$(function(){
	$('select#city').selectmenu({
		style:'dropdown',
		maxHeight: 205
	});
	$("#squery").autocomplete({
		source: "http://www.obiavigo.com/qsearch.php",
		minLength: 2,
		select: function( event, ui ) {
			$("#squery").val(ui.item.value);
			document.search_form_get.submit();
		}
	});
});
	
var selectedCategory = '';
var selectedCategoryLabel = '';
var images = Array();
var price_type_var = 1;

function searchCategory(cat_id, accept_search) {
	document.getElementById('category_holder').style.display = '';
	document.getElementById('category_select').innerHTML = 'Зареждане на категориите...';
	var params = 'cat_id=' + cat_id;
	if(accept_search != 0) params += '&term=' + document.getElementById('category_search_term').value;
	var targetURL = 'http://www.obiavigo.com/?act=category_search_ajax';
	
	$.ajax({
	   type: "POST",
	   url: targetURL,
	   data: params,
	   success: function(msg){
		 document.getElementById('category_select').innerHTML = msg;
	   }
	 });
	
}

function changeCat() {
	document.getElementById('seach_cat_box').style.display = '';
	document.getElementById('category_holder').style.display = '';
	document.getElementById('category_selected').style.display = 'none';
	if(document.getElementById('category_select').innerHTML == '&nbsp;') {
		searchCategory(0,0);
	}
}

function selectCategory(id, path) {
	document.getElementById('seach_cat_box').style.display = 'none';
	document.getElementById('category_holder').style.display = 'none';
	document.getElementById('category_selected').innerHTML = '<strong>' + path + '</strong> - <a href="javascript:void(0)" onclick="changeCat()" style="color:#8fcc23">Промени</a>';	
	selectedCategory = id;
	selectedCategoryLabel = path;
	document.getElementById('category_selected').style.display = '';
	loadCategorySpecification(id);
}

var RightClick = {
	init: function () {
		this.FlashObjectID = "uploader_swf";
		this.FlashContainerID = "uploader";
		this.Cache = this.FlashObjectID;
		if(window.addEventListener){
			 window.addEventListener("mousedown", this.onGeckoMouse(), true);
		} else {
			document.getElementById(this.FlashContainerID).onmouseup = function() {document.getElementById(RightClick.FlashContainerID).releaseCapture();}
			document.oncontextmenu = function(){if(window.event.srcElement.id == RightClick.FlashObjectID) {return false;} else {RightClick.Cache = "nan";}}
			document.getElementById(this.FlashContainerID).onmousedown = RightClick.onIEMouse;
		}
	},
	UnInit: function () { 
		if(window.RemoveEventListener){
			alert('Un init is called for GECKO' );			
			window.addEventListener("mousedown", null, true);
			window.RemoveEventListener("mousedown",this.onGeckoMouse(),true);
			 //w//indow.releaseEvents("mousedown");
		} else {
			//alert('Un init is called for IE' );							
			document.getElementById(this.FlashContainerID).onmouseup = "" ;
			document.oncontextmenu = "";
			document.getElementById(this.FlashContainerID).onmousedown = "";
		}
	},
	killEvents: function(eventObject) {
		if(eventObject) {
			if (eventObject.stopPropagation) eventObject.stopPropagation();
			if (eventObject.preventDefault) eventObject.preventDefault();
			if (eventObject.preventCapture) eventObject.preventCapture();
	   		if (eventObject.preventBubble) eventObject.preventBubble();
		}
	},
	onGeckoMouse: function(ev) {
	  	return function(ev) {
	    if (ev.button != 0) {
			RightClick.killEvents(ev);
			if(ev.target.id == RightClick.FlashObjectID && RightClick.Cache == RightClick.FlashObjectID) {
	    		RightClick.call();
			}
			RightClick.Cache = ev.target.id;
		}
	  }
	},
	onIEMouse: function() {
	  	if (event.button > 1) {
			if(window.event.srcElement.id == RightClick.FlashObjectID && RightClick.Cache == RightClick.FlashObjectID) {
				RightClick.call(); 
			}
			document.getElementById(RightClick.FlashContainerID).setCapture();
			if(window.event.srcElement.id)
			RightClick.Cache = window.event.srcElement.id;
		}
	},
	call: function() {
		
	}
}

function startUpload() {
	
}

function cancelUpload() {
	
}

function uploadComplete(file) {
	var s = explode('_', file, 2);
	var name = s[0] + '_' + md5(s[1]);;
	addToImageList(name);
}

function addToImageList(file) {
	images.push(file);
	document.getElementById('images_content').innerHTML += '<div class="upPic" id="uppic_' + file + '"><img src="phpThumb.php?src=pics/original/'+file+'&w=130&h=100&zc=1&aoe=1"><br><a href="javascript:void(0)" onclick="removePic(\'' + file +'\')">Премахни</a></div>';
	if(images.length >= 5) {
		document.getElementById('uploader_swf').style.display = 'none';
	}
	if(images.length > 0) document.getElementById('images_content').style.display = '';
}

function removePic(f) {
	var d = document.getElementById('images_content');
	var olddiv = document.getElementById('uppic_' + f);
	d.removeChild(olddiv);
	for(i = 0; i < images.length; i++) {
		if(images[i] == f) {
			images.splice(i, 1);
			break;
		}
	}
	
	if(images.length < 5) {
		document.getElementById('uploader_swf').style.display = '';
	}
	if(images.length < 1) document.getElementById('images_content').style.display = 'none';
}

function tryPublish() {
	if(selectedCategory == '') {
		document.getElementById('error_message_p').innerHTML = 'Трябва да изберете <a href="#category_h3" onclick="$(\'#dialog\').dialog(\'close\');">категория</a> на обявата!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	/*else if(document.getElementById('city_id').value == 0) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да изберете <a href="#city_id_h3" onclick="$(\'#dialog\').dialog(\'close\');">местоположение</a> на обявата!';
		showDialog();
		$("#dialog").dialog('open');
	}*/
	
	else if(checkEmail(document.getElementById('email').value) == false) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете валиден <a href="javascript:void(0)" onclick="document.getElementById(\'email\').focus(); $(\'#dialog\').dialog(\'close\');">e-mail адрес</a> на подел!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if(document.getElementById('phone').value.length < 5) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете правилен <a href="javascript:void(0)" onclick="document.getElementById(\'phone\').focus(); $(\'#dialog\').dialog(\'close\');">телефонен номер</a> на подел!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if(document.getElementById('ad_title').value.length < 5) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете <a href="javascript:void(0)" onclick="document.getElementById(\'ad_title\').focus(); $(\'#dialog\').dialog(\'close\');">заглавие</a> на обявата поне 5 символа!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if(price_type_var == 1 && (document.getElementById('price').value == '' || parseFloat(document.getElementById('price').value) <= 0)) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете <a href="javascript:void(0)" onclick="document.getElementById(\'price\').focus(); $(\'#dialog\').dialog(\'close\');">цена</a> не по малка от 1!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if($("#description").val().length < 15) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете <a href="javascript:void(0)" onclick="document.getElementById(\'description\').focus(); $(\'#dialog\').dialog(\'close\');">описание</a> на обявата поне 15 символа!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if ($("#buy_online").attr('checked') == true && isUrl($("#shop_address").val()) == false) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете валиден<a href="javascript:void(0)" onclick="document.getElementById(\'shop_address\').focus(); $(\'#dialog\').dialog(\'close\');">интернет адрес</a> на продукта в електронния Ви магазин!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if($("#promo_section").attr('checked') == true && (document.getElementById('promo_price').value == '' || parseFloat(document.getElementById('promo_price').value) <= 0)) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете <a href="javascript:void(0)" onclick="document.getElementById(\'promo_price\').focus(); $(\'#dialog\').dialog(\'close\');">нова промоционална цена</a> не по малка от 1!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else if($("#promo_section").attr('checked') && parseFloat($("#price").val()) <= parseFloat($("#promo_price").val())) {
		document.getElementById('error_message_p').innerHTML = 'Трябва да въведете по-ниска <a href="javascript:void(0)" onclick="document.getElementById(\'promo_price\').focus(); $(\'#dialog\').dialog(\'close\');">промоционална цена</a> от старата цена!';
		showDialog();
		$("#dialog").dialog('open');
	}
	
	else {
		var this_pics = '';
		for(i = 0; i<images.length; i++) {
			this_pics += images[i] + '|';
		}
		document.getElementById('pics_string').value = this_pics;
		document.getElementById('input_cat_id').value = selectedCategory;
		document.getElementById('input_cat_label').value = selectedCategoryLabel;
		if(document.getElementById('specification_content')) executePublishExternal();
		else document.getElementById('add_form').submit();
		
	}
}

function showDialog() {
	$(function() {
		$("#dialog").dialog({
			bgiframe: true,
			modal: true,
			resizable: false,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
	});		
}


function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) return false;
	else return true;
}

function isNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if(charCode == 46) return true;
	else if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
	else return true;
}

function errorMessage(err) {
	document.getElementById('error_message_p').innerHTML = err;
	showDialog();
	$("#dialog").dialog('open');	
}

function navigateTo(url) {
	window.location = url;	
}

function switchImage(img, big) {
	document.getElementById('big_pic').src = img;
	$("#big_pic_holder a").attr("href", big);
}

function loadCategorySpecification(id) {
	var params = 'cat_id=' + id;
	var targetURL = 'http://www.obiavigo.com/?act=specification_ajax';

	var loc_ad_id = $("#ad_loc_id").val();
	if(loc_ad_id != '') params += '&ad_id=' + loc_ad_id;

	$.ajax({
	   type: "POST",
	   url: targetURL,
	   data: params,
	   success: function(msg){
		 $('#specification_content').html(msg);
	   }
	 });
}

function ajaxSelectFill(from,id) {
    var select = document.getElementById('range_' + id);
	var l = select.options.length;
    for(i = 0; i < l; i++) {
        select.options[0] = null;
    }
    select.options[0] = new Option('Зареждане...',0,true,false);
    
    $(function(){
        $('select#range_'+id).selectmenu('destroy');
        $('select#range_'+id).selectmenu({
                style:'dropdown',
                maxHeight: 205
        });
    });

    var params = 'id=' + id + '&value=' + document.getElementById('range_' + from).value;
    var targetURL = 'http://www.obiavigo.com/?act=selectComponent';

    $.ajax({
       type: "POST",
       url: targetURL,
       data: params,
       success: function(msg){
			var l = select.options.length;
			for(i = 0; i < l; i++) {
                select.options[0] = null;
            }
            select.options[0] = new Option('--',0,true,false);
            var sep = msg.split('|');
            for(i = 0; i < sep.length; i++) {
                if(sep[i] != '') {
                    var row = sep[i].split('^');
                    var opt_index = i+1;
                    select.options[opt_index] = new Option(row[1],row[0],false,false);
                }
            }
            $(function(){
                $('select#range_'+id).selectmenu('destroy');
                $('select#range_'+id).selectmenu({
                        style:'dropdown',
                        maxHeight: 205
                });
            });
       }
     });
}

function ajaxSelectFill2(from,id, selected) {
	var select = document.getElementById('range_' + id);
	var params = 'id=' + id + '&value=' + document.getElementById('range_' + from).value;
    var targetURL = 'http://www.obiavigo.com/?act=selectComponent';

    $.ajax({
       type: "POST",
       url: targetURL,
       data: params,
       success: function(msg){
			var l = select.options.length;
			for(i = 0; i < l; i++) {
                select.options[0] = null;
            }
            select.options[0] = new Option('--',0,true,false);
            var sep = msg.split('|');
            for(i = 0; i < sep.length; i++) {
                if(sep[i] != '') {
                    var row = sep[i].split('^');
                    var opt_index = i+1;
					if(row[0] == selected) select.options[opt_index] = new Option(row[1],row[0],true,true);
					else select.options[opt_index] = new Option(row[1],row[0],false,false);
                }
            }


			$(function(){
				if(document.getElementById('extendFilter')) {
					document.getElementById('extendFilter').style.height = '1px';
					document.getElementById('extendFilter').style.overflow = 'hidden';
					document.getElementById('extendFilter').style.display = '';
				}
                $('select#range_'+id).selectmenu('destroy');
                $('select#range_'+id).selectmenu({
                        style:'dropdown',
                        maxHeight: 205
                });
				if(document.getElementById('extendFilter')) {
					document.getElementById('extendFilter').style.height = 'auto';
					document.getElementById('extendFilter').style.overflow = 'auto';
					document.getElementById('extendFilter').style.display = 'none';
				}
            });
       }

     });
}

function switchPriceType(type) {
	price_type_var = type;
	if(type == 1) {
		document.getElementById('addefinitionsdetails').style.display = '';
		document.getElementById('price').style.display = '';
		document.getElementById('currency').style.display = '';
		$(function(){
			$('select#currency').selectmenu('destroy');
			$('select#currency').selectmenu({
					style:'dropdown',
					maxHeight: 205
			});
        });
	}
	else {
		$(function(){
			$('select#currency').selectmenu('destroy');
        });
		document.getElementById('price').style.display = 'none';
		document.getElementById('currency').style.display = 'none';
		document.getElementById('addefinitionsdetails').style.display = 'none';
	}
}

function expandFilter() {
	var div = document.getElementById('extendFilter');
	var lnk = document.getElementById('expandLink');
	if(div.style.display == 'none') {
		div.style.display = '';
		lnk.innerHTML = 'Скрии подробния филтър';
	}
	else {
		div.style.display = 'none';
		lnk.innerHTML = 'Покажи подробен филтър';
	}
}

function sendFriend(ad_id, firm) {
	var youremail = $("#youremail").val();
	var toemail = $("#toemail").val();
	var yourname = $("#yourname").val();
	var send_message = $("#send_message").val();

	if(checkEmail(youremail) == false) {
		sendFriendError('Моля посечете ваш валиден e-mail адрес!');
	}

	else if(checkEmail(toemail) == false) {
		sendFriendError('Моля посечете валиден e-mail адрес на получателя!');
	}
	else {
		document.getElementById('send_fields_holder').style.display = 'none';
		document.getElementById('send_message_holder').style.display = '';

		var params = 'ad_id=' + ad_id + '&from_email=' + youremail + '&to_email=' + toemail + '&from_name=' + yourname + "&text=" +send_message;
		if(firm != '') params += '&firm=true';
		var targetURL = 'http://www.obiavigo.com/?act=sendFriend_post';
		$.ajax({
		   type: "POST",
		   url: targetURL,
		   data: params,
		   success: function(msg){
				$("#send_message_holder").html('Съобщението е изпратено!');
			}
		 });
	}

}

function sendFriendError(error) {
	$(function() {
		$("#error_message_p_send").html(error);
		$("#error_dialog_send").dialog('destroy');
		$("#error_dialog_send").dialog({
			autoOpen: true,
			modal: true,
			resizable: false,
			title : 'Грешка!',
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
	});
}


function submit_note(ad_id, is_firm) {
	if($("#note_area").val() != '') {
		$("#note_area").attr("disabled","disabled");
		$("#note_submit_btn").attr("disabled","disabled");

		$("#note_area").addClass("disabled");
		$("#note_submit_btn").addClass("disabled");

		//send data
		var params = 'ad_id='+ad_id+'&text=' + $("#note_area").val();
		if(is_firm != '') params += '&firm=true';
		var targetURL = 'http://www.obiavigo.com/?act=notes_ajax_manipulation';
		$.ajax({
		   type: "POST",
		   url: targetURL,
		   data: params,
		   success: function(msg){
				if(msg == '1') {
					var firm_str = '';
					if(is_firm != '') firm_str = '&firm=true';
					$('#notes').load(load_str);
					$('#notes').load('http://www.obiavigo.com/?act=notes_ajax&dialog=notes&ad_id='+ad_id + firm_str);
					var childs = $("#notes_div > div").size();
					childs += 1;
					if(childs < 1) {
						$("#no_notes").attr("style","display:inherit");
						$("#notes_btn").text('Бележки');
						$("#notes_btn").attr('style', 'font-weight:normal');
					}
					else {
						$("#notes_btn").text('Бележки ('+childs+')');
						$("#notes_btn").attr('style', 'font-weight:bold');
					}
				}
				else openDialog('В момента бележката неможе да бъде запазена. Моля опитайте отново!');
				$("#note_area").removeAttr("disabled");
				$("#note_submit_btn").removeAttr("disabled");

				$("#note_area").removeClass("disabled");
				$("#note_submit_btn").removeClass("disabled");
			}
		 });
	}
	else {
		openDialog('Моля въведете текст на бележката!');
	}
}
function openDialog(error) {
	$(function() {
		$("#error_message_p").html(error);
		$("#error_dialog").dialog('destroy');
		$("#error_dialog").dialog({
			autoOpen: true,
			modal: true,
			resizable: false,
			title : 'Грешка!',
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
	});
}

function editNote(id) {
	var val = $("#html_note_" + id).text();
	$("#textarea_note_" + id).val(val);
	document.getElementById('display_note_' + id).style.display = 'none';
	document.getElementById('edit_note_' + id).style.display = '';
}

function cancelEditNote(id) {
	document.getElementById('display_note_' + id).style.display = '';
	document.getElementById('edit_note_' + id).style.display = 'none';
}

function editNoteReq(id, ad_id, firm) {
	if($("#textarea_note_" + id).val() != '') {
		$("#textarea_note_" + id).attr("disabled","disabled");
		$("#note_edit_s_btn_" + id).attr("disabled","disabled");

		$("#textarea_note_" + id).addClass("disabled");
		$("#note_edit_s_btn_" + id).addClass("disabled");

		//send data
		var params = 'ad_id=' + ad_id + '&text=' + $("#textarea_note_" + id).val() + '&note_id='+id;
		if(firm != '') params += '&firm=true';
		var targetURL = 'http://www.obiavigo.com/?act=notes_ajax_manipulation';
		$.ajax({
		   type: "POST",
		   url: targetURL,
		   data: params,
		   success: function(msg){
				if(msg == '1') {
					var val = $("#textarea_note_" + id).val();
					$("#html_note_" + id).html(htmlspecialchars(val));
					cancelEditNote(id);
				}
				else openDialog('В момента бележката неможе да бъде запазена. Моля опитайте отново!');

				$("#textarea_note_" + id).removeAttr("disabled");
				$("#note_edit_s_btn_" + id).removeAttr("disabled");

				$("#textarea_note_" + id).removeClass("disabled");
				$("#note_edit_s_btn_" + id).removeClass("disabled");
			}
		 });
	}
	else {
		openDialog('Моля въведете текст на бележката!');
	}
}

function deleteNote(id, ad_id, firm) {
	var params = 'ad_id=' + ad_id + '&del_id=1&note_id='+id;
	if(firm != '') params += '&firm=true';
	var targetURL = 'http://www.obiavigo.com/?act=notes_ajax_manipulation';
	$.ajax({
	   type: "POST",
	   url: targetURL,
	   data: params,
	   success: function(msg){
			if(msg == '1') {
				$("#note_" + id).remove();
				var childs = $("#notes_div > div").size();
				if(childs < 1) {
					$("#no_notes").attr("style","display:inherit");
					$("#notes_btn").text('Бележки');
					$("#notes_btn").attr('style', 'font-weight:normal');
				}
				else {
					$("#notes_btn").text('Бележки ('+childs+')');
					$("#notes_btn").attr('style', 'font-weight:bold');
				}
			}
			else openDialog('В момента бележката неможе да бъде изтрита!');
		}
	 });
}


function sendReport(ad_id, firm) {
	var reporter_email = $("#reporter_email").val();
	var reporter_name = $("#reporter_name").val();
	var problem_message = $("#problem_message").val();

	if(checkEmail(reporter_email) == false) {
		sendReportError('Моля посечете ваш валиден e-mail адрес!');
	}

	else if(problem_message == '') {
		sendReportError('Моля опишете естеството на проблема!');
	}
	else {
		document.getElementById('report_fields_holder').style.display = 'none';
		document.getElementById('report_message_holder').style.display = '';

		var params = 'ad_id=' + ad_id + '&from_email=' + reporter_email + '&from_name=' + reporter_name + "&text=" + problem_message;
		if(firm != '') params += '&firm=true';
		var targetURL = 'http://www.obiavigo.com/?act=report_ajax_post';
		$.ajax({
		   type: "POST",
		   url: targetURL,
		   data: params,
		   success: function(msg){
				$("#report_message_holder").html('Съобщението е изпратено!');
			}
		 });
	}

}

function sendReportError(error) {
	$(function() {
		$("#error_message_p_report").html(error);
		$("#error_dialog_report").dialog('destroy');
		$("#error_dialog_report").dialog({
			autoOpen: true,
			modal: true,
			resizable: false,
			title : 'Грешка!',
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
	});
}


function favoriteFromList(id, ad_id, firm) {
	document.getElementById('fav_loader_'+id).style.display = '';
	$("#favorites_btn_" + id).attr('style','display:none');
	var params = 'ad_id=' + ad_id;
	if(firm != '') params += '&firm=true';
	var targetURL = 'http://www.obiavigo.com/?act=favorite_ajax';
	$.ajax({
	   type: "POST",
	   url: targetURL,
	   data: params,
	   success: function(msg){
		   document.getElementById('fav_loader_' + id).style.display = 'none';
		   $("#favorites_btn_" + id).attr('style','display:inherit');
			if(msg == '2') {
				$("#favorites_btn_" + id).text('Премахни от любими');
				$("#favorites_btn_" + id).removeClass('bold');
			}
			else {
				$("#favorites_btn_" + id).text('Добави отново в любими');
				$("#favorites_btn_" + id).addClass('bold');

			}
		}
	 });
}

function showHide(ele) {
   var elm = document.getElementById(ele);
   if(elm.style.display == 'none') elm.style.display = '';
   else elm.style.display = 'none';
}

function msgError(error) {
	$(function() {
		$("#msg_error_text").html(error);
		$("#msg_error").dialog('destroy');
		$("#msg_error").dialog({
			autoOpen: true,
			modal: true,
			resizable: false,
			title : 'Грешка!',
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
	});
}

function feedBackSend(ad_id) {
	var from = $("#sendRfrom").val();
	var txt = $("#sendRtext").val();
	var code = $("#sendRcode").val();

	if(checkEmail(from) == false) {
		msgError('Моля въведете валиден e-mail!');
	}

	else if (txt == '') {
		msgError('Моля въведете съобщение!');
	}

	else if(code.length != 5) {
		msgError('Моля попилнете коректно кода за сигурност!');
	}
	
	else {
		$("#sendRfrom").attr("disabled","disabled");
		$("#sendRtext").attr("disabled","disabled");
		$("#codeGenBtn").attr("disabled","disabled");
		$("#sendRcode").attr("disabled","disabled");
		$("#sendRbtn").attr("disabled","disabled");

		$("#sendRbtn").val('Изпраща...');
		$("#sendRbtn").addClass("spinner");

		$("#sendRfrom").addClass("disabled");
		$("#sendRtext").addClass("disabled");
		$("#codeGenBtn").addClass("disabled");
		$("#sendRcode").addClass("disabled");
		$("#sendRbtn").addClass("disabled");

		var params = 'ad_id=' + ad_id + '&from=' + from + '&text=' + txt + '&code=' + code;
		var targetURL = 'http://www.obiavigo.com/?act=sendFeedback_ajax';
		$.ajax({
		   type: "POST",
		   url: targetURL,
		   data: params,
		   success: function(msg){
			   $("#sendRfrom").removeAttr("disabled","disabled");
			   $("#sendRtext").removeAttr("disabled","disabled");
			   $("#codeGenBtn").removeAttr("disabled","disabled");
			   $("#sendRcode").removeAttr("disabled","disabled");
			   $("#sendRbtn").removeAttr("disabled","disabled");
			   $("#sendRbtn").val('Изпрати');
			   $("#sendRbtn").removeClass("spinner");
			   $("#sendRfrom").removeClass("disabled");
			   $("#sendRtext").removeClass("disabled");
			   $("#codeGenBtn").removeClass("disabled");
			   $("#sendRcode").removeClass("disabled");
			   $("#sendRbtn").removeClass("disabled");

			   if(msg == '1') {
				   msgError('Не може да изпращате запитване към невалидна обява!');
			   }

			   else if(msg == '2') {
				   msgError('Моля въведете валиден e-mail!');
			   }

			   else if(msg == '3') {
				   msgError('Моля въведете текст на вашето запитване!');
			   }

			   else if(msg == '4') {
				   msgError('Моля въведете правилен код за сигурност!');
			   }

			   else {
					$("#sendRfrom").val('');
					$("#sendRtext").val('');
					$("#sendRcode").val('');
					document.getElementById('sendRform').style.display = 'none';
					document.getElementById('sendRsuccess').style.display = '';
			   }
			}
		 });
	}
}

function newFbf() {
	document.getElementById('sendRform').style.display = '';
	document.getElementById('sendRsuccess').style.display = 'none';
}

function deleteConfirm(ad_id) {
	$(function() {
		$("#msg_delete").dialog('destroy');
		$("#msg_delete").dialog({
			autoOpen: true,
			modal: true,
			resizable: false,
			title : 'Потвърждение!',
			buttons: {
				'Изтрий': function() {
					$(this).dialog('close');
					window.location.href = 'http://www.obiavigo.com/?act=published&delete_id='+ad_id;
				},
				'Отказ': function() {
					$(this).dialog('close');
				}
			}
		});
	});
}

function extendExpire(id, periode) {
	//alert(ad_id + ' ' + periode)
	document.getElementById('link_ex_bar_' + id).style.display = 'none';
	document.getElementById('spinner_bar_' + id).style.display = '';

	var params = 'ad_id=' + id + '&periode=' + periode;
	var targetURL = 'http://www.obiavigo.com/?act=extendExpire_ajax';
	$.ajax({
	   type: "POST",
	   url: targetURL,
	   data: params,
	   success: function(msg){
		   if(msg != '') {
			   $("#expired_icon_" + id).remove();
			   $("#expired_red_" + id).remove();
			   $("#expire_label_" + id).html('Изтича');
			   $("#expire_content_" + id).html(msg);
			   document.getElementById('ad_expire_box_' + id).style.backgroundColor = '#f1f1f1';
			   document.getElementById('ad_expire_box_' + id).style.border = 'solid 1px #dadada';
			   document.getElementById('link_ex_bar_' + id).style.display = '';
			   document.getElementById('spinner_bar_' + id).style.display = 'none';
		   }
		}
	 });
}

var load_str = '<img src="http://www.obiavigo.com/images/default/spinner.gif" class="vam" alt="" /> Зареждане... Моля изчакайте.';

function makeVip(ad_id) {
	$("#vip_top_dialog").dialog('open');
	$('#vip_top_dialog').html(load_str);
	$('#vip_top_dialog').load('http://www.obiavigo.com/?act=vip_ajax&ad_id=' + ad_id);
}

function makeTop(ad_id) {
	$("#vip_top_dialog").dialog('open');
	$('#vip_top_dialog').html(load_str);
	$('#vip_top_dialog').load('http://www.obiavigo.com/?act=top_ajax&ad_id=' + ad_id);
}

function loadVipTop(prex, ad_id) {
	$('#premium_type').html(load_str);
	$('#premium_type').load('http://www.obiavigo.com/?act='+prex+'_ajax&ad_id=' + ad_id);
}

function changeLocation() {
	var firm_prefix = '';
	if(document.getElementById('refresh_type').value == '2') firm_prefix = 'firms/'
	var id = document.getElementById('city').value;
	if(id == '') window.location = 'http://obiavigo.com'
	else window.location = 'http://'+id+'.obiavigo.com/' + firm_prefix;
}

function deleteFirmConfirm(id) {
	$(function() {
		$('#dialog').dialog('destroy');
		$("#dialog").dialog({
			bgiframe: true,
			modal: true,
			resizable: false,
			buttons: {
				'Изтрии': function() {
					$(this).dialog('close');
					window.location = 'http://www.obiavigo.com/?act=profile&page=firmprofile&delete_id=' + id;
				},
				'Отказ': function() {
					$(this).dialog('close');
				}
			}

		});
	});
}

function showAdDetails() {
	document.getElementById('warn_message').style.display = 'none';
	document.getElementById('adViewHolder').style.display = '';	
}

function voteIt(poll_id) {
	
	var answer_id = 0;
	for (var i=0; i < document.poll_form.poll.length; i++) {
		if (document.poll_form.poll[i].checked) {
			answer_id = document.poll_form.poll[i].value;
		}
	}

	if(answer_id == 0) alert('Моля изберете отговор!');
	else {
		$('#poll_holder').html(load_str);
		var params = 'poll_id=' + poll_id + '&answer_id=' + answer_id;
		var targetURL = 'http://www.obiavigo.com/?act=poll_vote';
		$.ajax({
		   type: "POST",
		   url: targetURL,
		   data: params,
		   success: function(msg){
			   if(msg != '') {
				   //alert(msg);
				   $('#poll_holder').html(msg);
				   //hide vote form
				   //show result form
			   }
			}
		 });
	}
}

function newsletterAds() {
	if(selectedCategory == '') {
		alert('Моля изберете категория!');
	}
	else {
		document.getElementById('input_cat_id').value = selectedCategory;
		document.newsletter_ads_form.submit();
	}
}

var openedMap = 0;
function showMap() {
	if(openedMap == 1) {
		$('#locs').fadeOut();
		openedMap = 0;
	}
	
	else {
		$('#locs').fadeIn();
		openedMap = 1;
	}
	
	$('#geoLocation').slideToggle('slow');
}

function showCategories() {
	$('#categoryList').slideToggle('slow');
}

var qfilter_str = '';
var qfilter_open = false;
function showAllFilters() {
	if(qfilter_open == false) {
		qfilter_str = $("#quickFilter").html();
		$("#quickFilter").html(unescape(afilters_base));
		$("#expand_filter_link").attr("title", "Скрии разширените филтри");
		$("#expand_filter_link").text("Скрии разширените филтри");
		qfilter_open = true;
	}
	else {
		 $("#quickFilter").html(qfilter_str);
		 $("#expand_filter_link").attr("title", "Разширени филтри");
		 $("#expand_filter_link").text("Покажи всички филтри");
		 qfilter_open = false;
		 jQuery('html, body').animate( { scrollTop: 0 }, 'slow' );
	}
}

var ohsfilter = true;
function showHideFilters() {
	$('#filtersUL').slideToggle('slow');
	if(ohsfilter == true) {
		 $("#showHideFiltersLink").attr("title", "Покажи");
		 $("#showHideFiltersLink").text("Покажи");
		 $("#showhideFiltersImg").attr("src", "http://www.obiavigo.com/images/default/bullet_toggle_plus.png");
		 ohsfilter = false;
	}
	else {
		$("#showHideFiltersLink").attr("title", "Скрии");
		$("#showHideFiltersLink").text("Скрии");
		$("#showhideFiltersImg").attr("src", "http://www.obiavigo.com/images/default/bullet_toggle_minus.png");
		 ohsfilter = true;

	}
}

function changeAmount() {
	var val = $("#price").val();
	var curren = $("#currency option:selected").text();
	$("#old_price").val(val);
	$("#currency_label").text(curren);
	$("#currency_label_new").text(curren);
}

function isUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}
