<!--
function getItems(el, func) {
	$('#waitMessage').show();
	var unlock =  (window.location.href.indexOf('admin') > -1) ? '&unlock=1': '';		
	//alert("func="+func+"&current_id="+el.value+unlock);
	$.ajax({
       type: "POST",
       dataType: "json",
       url: "/controllers/offers.php",
       data: "func="+func+"&current_id="+el.value+unlock,
       success: successToGetCategories,
       error: failureToGetCategories
    });
	
}

function updateCategories(aCategories, func) {
    $('#oCategories').html('').removeAttr('onchange').unbind();
    $('#oCategories').bind("change", function (){ getItems(this, func.next); });
    
    $('#oCategories').append('<option value="0">Выберите раздел</>');

	for (var i = 0, n = aCategories.length; i < n; i ++) {
		 $('#oCategories').append('<option value="'+aCategories[i].id+'">'+aCategories[i].title+'</option>');
	}
}

function replaceAnchorBySelect(_this, func){
	$(_this).nextAll().remove();
	
	var parent_id = getParentFromURL('/step1',_this.href);
	
	$.ajax({
       type: "POST",
       dataType: "json",
       url: "/controllers/offers.php",
       data: "func="+func+"&current_id="+parent_id,
       success: function(res, options) {
			     if (res && !res.errors  && res.data.length>0) {
				   updateCategories(res.data, res.func);
			     } else {
				   alert('Ошибка связи. Попробуйте повторить позже.');
			     }},
       error: failureToGetCategories
    });
    
    $(_this).remove();
    $('#oCategories').show();
    
}

function successToGetCategories(res, options) {
	$('#waitMessage').hide();

	if (res && !res.errors && res.current_title) {
		
	    $('#categoriesNavigation').append('<A href="/offers/add/step1/'+res.parent_id+'" >'+res.current_title+'</A> ');
	    
	    $("#categoriesNavigation > A:last").bind("click", function (){ replaceAnchorBySelect(this, res.func.prev); return false;});
		if (res.data.length>0){
			$('#categoriesNavigation').append('<span class="blue">»</span>');
			updateCategories(res.data, res.func);
		} else {
		    $('#oCategories').hide();
		    url =  (window.location.href.indexOf('admin') > -1) ? '/admin/?module=offers&action=add&step=2&section=' + res.section : '/offers/add/step2/' + res.section;
			goTo(url);
			$('#waitMessage').show();
			return true;
		}
	} else {
		alert('Ошибка связи. Попробуйте повторить позже.');
	}
}
  
function failureToGetCategories() {
	$('#waitMessage').hide();
	alert('Ошибка связи. Попробуйте повторить позже.');
} 

function getRegions(el, func) {
	$('#waitMessageRegions').show();
	$.ajax({
       type: "POST",
       dataType: "json",
       url: "/controllers/offers.php",
       data: "func="+func+"&current_id="+el.value,
       success: successToGetRegions,
       error: failureToGetRegions
    });
	
}

function updateRegions(aRegions, func) {
    $('#oRegions').html('').removeAttr('onchange').unbind();
    $('#oRegions').bind("change", function (){ getRegions(this, func.next); });
 
    $('#oRegions').append('<option value="0">-- Выберите из списка --</option><option disabled="disabled">----------------------------</option>');
  
	for (var i = 0, n = aRegions.length; i < n; i ++) {
		  $('#oRegions').append('<option value="'+aRegions[i].id+'">'+aRegions[i].title+'</option>');
		  if (aRegions[i].sw != aRegions[i+1].sw)
		     $('#oRegions').append('<option disabled="disabled">----------------------------</option>');
		
	}
}

function replaceAnchorBySelectRegions(_this, func) {
	
	$(_this).nextAll().remove();
	
	var parent_id = getParentFromURL('/region',_this.href);
	$.ajax({
       type: "POST",
       dataType: "json",
       url: "/controllers/offers.php",
       data: "func="+func+"&current_id="+parent_id,
       success: function(res, options) {
			     if (res && !res.errors  && res.data.length>0) {
				   updateRegions(res.data, res.func);
			     } else {
				   alert('Ошибка связи. Попробуйте повторить позже.');
			     }},
       error: failureToGetRegions
    });
    
    $(_this).remove();
    $('#oRegions').show();
    
}

function successToGetRegions(res, options) {
	$('#waitMessageRegions').hide();

	if (res && !res.errors && res.current_title) {
	
	    $('#regionsNavigation').append('<A href="/region/'+res.parent_id+'" >'+res.current_title+'</A>');
	    $('#regionsNavigation').append('<input type="hidden" name="data['+res.current_name+']" id='+res.current_name+' value="'+res.current_id+'" >');
	   
	    $("#regionsNavigation > A:last").bind("click", function (){ replaceAnchorBySelectRegions(this, res.func.prev); return false;});
		if (res.data.length>0){
			$('#regionsNavigation').append('<span class="arrow">»</span>');
			updateRegions(res.data, res.func);

		} else {
			$('#oRegions').html('');
		    $('#oRegions').hide();
			return true;
		}
	} else {
		alert('Ошибка связи. Попробуйте повторить позже.');
	}
}

function failureToGetRegions() {
	$('#waitMessageRegions').hide();
	alert('Ошибка связи. Попробуйте повторить позже.');
} 

function getParentFromURL(step, str){
	 urlChunk = str.split(step);
	if(!urlChunk[1]) return false;
	 gets=urlChunk[1].split('/');
	 return gets[gets.length-1];

}

function goTo(url) {
	window.location = url;
}

function saveOffer(){
    var params = $("input[name^='uploads'], input[name^='photoDesc'], input[name^='mainfoto'], input[name^='hhhh'], select[name^='data'], input[name^='data'], textarea[name^='data']").serialize();
    var ref = $("input[name^='return_path']").val();
  
    var oldValue = $("#submitButton").val();
	lockSendButton("submitButton");
	    
    $.ajax({
          type: "POST",
          dataType: "json",
          url: "/controllers/offers.php",
          data: "func=saveOffer&"+params,
          success: function (res, options) {
          	  
          	    if (res.error_db){  
          	      $(".messageserror").html('<li>Ошибка сохранения данных! Попробуйте повторить попытку.</li>').show();
          	    } else if(res.error_login){
          	      $(".messageserror").html('<li>Пройдите авторизацию</li>').show();
          	      $('#email-block').show(); 
          	    } else if(res.error_notice){
          	      $(".messageserror").html('<li>Вы уже подавали очень похожее объявление, обновите старое или измените заголовок.</li>').show();
          	    } else if(res.error_price){
          	      $(".messageserror").html('<li>Цена слишком мала или не указана.</li>').show();
          	    } else if(res.error_phone){
          	      $(".messageserror").html('<li>Телефон введен неверно.</li>').show();
          	    } else if(res.error_flat){
          	      $(".messageserror").html('<li>Укажите количество комнат.</li>').show();
          	    } else if(res.error_ppchars){
          	      $(".messageserror").html('<li>Вы оплатили это объявление для подачи в журнал, пока оно не выйдет Вы не можете превысить ограничение по символам в ' + res.error_ppchars + ' символов.</li>').show();
          	    } else if(res.mainfoto){
          	    	$(".messageserror").html('<li>MAIN: ' + res.mainfoto + '</li>').show();
          	    } else if(res.hhhh){
          	    	$(".messageserror").html('<li>HHHH: ' + res.hhhh + '</li>').show();
          	    } else if(res.id){
          	    	//url =  (window.location.href.indexOf('edit') > -1) ? '/offers/editlist' : '/offers/add/step3/'+res.id;
          	    	url =  (ref) ? ref : ((window.location.href.indexOf('edit') > -1) ? '/offers/editlist' : '/offers/add/step3/'+res.id);
          	    	goTo(url);
          	    }
          	    unlockSendButton("submitButton", oldValue);
          },
          error: function (){
          	   alert('Ошибка связи. Попробуйте повторить позже.');
          	   unlockSendButton("submitButton", oldValue);
          }
         });   
}

function filterInteger(event) {
	var keyCode = (event.charCode) ? event.charCode : event.keyCode;
	return ((keyCode == 46) || (keyCode == 0) || (keyCode == 8) || (keyCode == 9) || (keyCode == 37) || (keyCode == 39) || (keyCode > 47 && keyCode < 58));
}

window.reEmail = /^([\w\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
window.reTel = /^(?:\+|00)[0-9]{11,12}$/;

function formAddSubmit(){
	
	var flagSend=true;
	
	$(".messageserror").html('').hide();
	$("input, select").removeClass( 'fillError' );
	
	if (necessaryFields && necessaryFields.length>0){
		jQuery.each(necessaryFields, function() {
          if ($("#" + this).val()==''){
          	$("#" + this).attr('class', 'fillError');
          	flagSend=false;
          }
        });
	}
	
	if (isNaN(parseInt($("#not_region").val())) ){
		$("#oRegions").attr('class', 'fillError');
		$(".messageserror").html('<li>Укажите регион</li>').show();
		flagSend = false
	}
	
	if (flagSend == false){
		$(".messageserror").append('<li>Не все обязательные поля заполнены!</li>').show();
		return false;
	}

	/*if ($('#email-block').css('display')=='none' 
           && $('#password-block').css('display')=='none' 
              && $('#register-block').css('display')=='none' ){
              	
    	saveOffer();
    	return true;
    }
    
	if (!reEmail.test($("#login_email").val())) {
		$("#login_email").attr('class', 'fillError');
        $(".messageserror").html('<li>Укажите корректный email</li>').show();
        return false;
    }*/
    
	if (!(window.location.href.indexOf('agencyoffice') > -1)) {
		if ($('#email-block').css('display')=='none' 
	           && $('#password-block').css('display')=='none' 
	              && $('#register-block').css('display')=='none' ){
	              	
	    	saveOffer();
	    	return true;
	    }
	    if (!reEmail.test($("#login_email").val())) {
			$("#login_email").attr('class', 'fillError');
	        $(".messageserror").html('<li>Укажите корректный email</li>').show();
	        return false;
	    }
	} else {
		saveOffer();
	    return true;
	}

	if (jQuery.trim($("#login_password").val())!=''){ //alert(jQuery.trim($("#login_password").val()))
		
		var params = $("#login_email, #login_password").serialize();

		var oldValue = $("#submitButton").val();
	    lockSendButton("submitButton");
	    //alert("func=checkUser&"+params);
		$.ajax({
          type: "POST",
          dataType: "json",
          url: "/controllers/users.php",
          data: "func=checkUser&"+params,
          success: function (res, options) {
          	    if (res.success){  
          	        $('#LoginBar').html(res.loginBar);
          	        $('#email-block').hide();
          	        $('#password-block').hide();
          	        $('#not_phone1').val(res.not_phone1);
          	        $('#not_phone2').val(res.not_phone2);
          	        $('#not_contact').val(res.not_contact);
          	        $('#not_url').val(res.not_url);
          	        draw();
          	        saveOffer();
          	    }else{
          	        $(".messageserror").html('<li>Пароль неверный!</li>').show();
          	    	flagSend = false;
          	    }
          	    
          	   unlockSendButton("submitButton", oldValue);
          },
          error: function (){
          	   alert('Ошибка связи. Попробуйте повторить позже.');
          	   unlockSendButton("submitButton", oldValue);
          }
         });
	} else {
		
		var oldValue = $("#submitButton").val();
	    lockSendButton("submitButton");
	  	   //alert("func=userExists&email="+$("#login_email").val());
		$.ajax({
          type: "POST",
          dataType: "json",
          url: "/controllers/users.php",
          data: "func=userExists&email="+$("#login_email").val(),
          success: function (res, options) {
          	    if (res){  
          	        $('#email_span_password').text($("#login_email").val());
          	        $('#email-block').hide();
          	        $('#password-block').fadeIn('slow');
          	    }else{
          	    	$('#submitButton').attr('onclick','').unbind().bind("click", function (){ userAddSubmit()});
          	       
          	    	$('#email_span_register').text($("#login_email").val());
          	    	$("input[name='user[email]']").val($("#login_email").val());
          	    	$('#email-block').hide();
          	    	$('#register-block').fadeIn('slow');
          	    }
          	    
          	    unlockSendButton("submitButton", oldValue);
	        
          },
          error: function (){
          	   alert('Ошибка связи. Попробуйте повторить позже.');
          	   unlockSendButton("submitButton", oldValue);
          }
         });
	}
}

function changePassword() {
	$('#submitButton').attr('onclick','').unbind().bind("click", function (){ formAddSubmit()});
    $(".messageserror, .messagesok").html('').hide();  
       	       
	$("#login_password, input[name='user[email]']").val('');
	$('#password-block').hide();
	$('#register-block').hide();
	$('#email-block').show();
	return false;
}

function getPassword() {
	
	var params = $("#login_email").serialize();
		
		var oldValue = $("#submitButton").val();
	    lockSendButton("submitButton");
	  
		$.ajax({
          type: "POST",
          dataType: "json",
          url: "/controllers/users.php",
          data: "func=getPassword&"+params,
          success: function (res, options) {
          	    if (res){  
          	        $(".messagesok").html('<li>Новый пароль отправлен вам на e-mail</li>').show();
          	    }else{
          	        $(".messageserror").html('<li>Ошибка! Попробуйте повторить еще раз</li>').show();
          	    }
          	    unlockSendButton("submitButton", oldValue);
          },
          error: function (){
          	   alert('Ошибка связи. Попробуйте повторить позже.');
          	   unlockSendButton("submitButton", oldValue);
          }
         });
	return false;
}

function sendXLS(){
	var params = $("#xls_params").attr('innerHTML');
//	params.replace("&amp;", "&");
	var search_params = $("#searchForm").serialize();
	
	var vars = '';
	if (params && params.length > 0) vars += '&'+params;
	if (search_params && search_params.length > 0) vars += '&'+search_params;
	
//	alert(vars);
	
	$.ajax({
       type: "POST",
       dataType: "json",
       url: "/controllers/offers.php",
       data: "func=getXLS"+vars,
       success: function(res, options) {
       		if (res && !res.errors/* && res.file>0*/) {
//   			   alert(res);
       		   goTo('/down.php?xls=1&file_xls='+res);
		     } else {
			   alert('Ошибка выполнения скрипта.');
	   }},
       error: function (){
          	   alert('Ошибкa связи. Попробуйте повторить позже.');
       }
    });
}

function userAddSubmit(){
	var flagSend=true;
	$("input[name^='user']").removeClass( 'fillError' );
	
	if (!$('#agree').attr('checked')) {
        alert('Для подачи объявления вы должны согласиться с нашими условиями');
        return false;
    }
    
    var oPassword = $("input[name='user[password]']");
    var oConfirm  = $("input[name='user[password2]']");
    //var oTel      = $("input[name='user[phone1]']");
    var oTel1      = $("input[name='user[tel1]']");
    var oTel2      = $("input[name='user[tel2]']");
    
    var reSymbols = /[^\w]/i;

    if (oPassword.val()=='' || reSymbols.test(oPassword.val()) ) {
    	    oPassword.attr('class', 'fillError');
            alert('Пароль может содержать буквы латинского алфавита, цифры и символ "_"');
            return false;
    }

    if (oPassword.val() != oConfirm.val()) {
            oConfirm.attr('class', 'fillError');
            alert('Подтвердите пароль');
            return false;
    }
    
    /*if (oTel.val() == '') {
     	    oTel.attr('class', 'fillError');
            alert('Не указан основной номер телефона');
            return false;
    }*/
    
    if (oTel1.val()=='') {
     	    oTel1.attr('class', 'fillError');
            alert('Не указан основной номер телефона');
            return false;
    }
    if (!reTel.test(oTel1.val())) {
    //if (  !oTel1.val().match (/^(?:\+|00)[0-9]{11,12}$/)  ){
			oTel1.attr('class', 'fillError');
            alert('Основной номер телефона указан в неверном формате');
            return false;
	    }
    if (oTel2.val()!='' && !reTel.test(oTel2.val())) {
    //if (oTel2.val()!='' && !oTel1.val().match (/^(?:\+|00)[0-9]{11,12}$/)) {
     	    oTel2.attr('class', 'fillError');
            alert('Дополнительный номер телефона указан в неверном формате');
            return false;
    }
    
    
    var params = $("input[name^='user'], select[name^='user']").serialize();
    alert(params);
    
    var oldValue = $("#submitButton").val();
	lockSendButton("submitButton");
	  
    $.ajax({
          type: "POST",
          dataType: "json",
          url: "/controllers/users.php",
          data: "func=addUser&"+params,
          success: function (res, options) {
          	    lockSendButton("submitButton");
          	    if (res){  
          	      $(".messagesok").append('<li>Ваши данные сохранены</li>').show();  
          	      $('#register-block').hide();
          	      saveOffer();
          	    }else{
          	      $(".messageserror").append('<li>Ошибка сохранения данных! Попробуйте повторить попытку.</li>').show();
          	    }
          	    
//          	    unlockSendButton("submitButton", oldValue);
          	
          },
          error: function (){
          	   alert('Ошибка связи. Попробуйте повторить позже.');
          	   unlockSendButton("submitButton", oldValue);
          }
         });   
	
	 
}

function setOfferType(offer_id){
	var product = $("input[name='product']:checked").val();
	if (isNaN(offer_id)) return false;
	
    goTo('/offers/add/step4/'+offer_id+'/'+product);
}

function lockSendButton(id){
	var btn = $('#'+id);
	btn.val('Ждите...');
	btn.attr('disabled', true);
	btn.parent().parent().removeClass("btn-a").addClass("btn-c");	   
}

function unlockSendButton(id, oldValue){
	var btn = $('#'+id);
	btn.val(oldValue);
	btn.attr('disabled', false);  
    btn.parent().parent().removeClass("btn-c").addClass("btn-a");	      
}

var map, placemark ;
        
function smallMap() {
	map = new YMaps.Map( document.getElementById("YMapsID") );          
	map.addControl(new YMaps.Zoom(), new YMaps.ControlPosition(YMaps.ControlPosition.TOP_LEFT, new YMaps.Size(5, 10)));
	
	var geoPoint = new YMaps.GeoPoint.fromString(coords);
	placemark = new YMaps.Placemark(geoPoint);
	placemark.disableBalloon();
	placemark.setIconContent("Здесь");  
	map.addOverlay(placemark);
	map.setCenter(geoPoint, (zoom==17) ? 16:zoom, YMaps.MapType.MAP);                    
};
        
function showYandexMap(){        	
	if (jQuery('#YMapsID').css('display')=='none'){
		jQuery('#YMapsID').html('Идет загрузка карты ...').show();
		YMaps.load(initYandexMap);

		jQuery('#YMapsLink').val('Скрыть карту');
		return true;
	}
	jQuery('#YMapsLink').val('Показать объект на карте');
	jQuery('#not_coord, #not_zoom').val('');
	jQuery('#YMapsID').hide();
};

function initYandexMap () {
	map = new YMaps.Map( document.getElementById("YMapsID") );          
	var typeControl = new YMaps.TypeControl();
	typeControl.removeType(YMaps.MapType.HYBRID);
	map.addControl(typeControl);
	map.addControl(new YMaps.Zoom());
	map.addControl(new YMaps.MiniMap());

	var s = new YMaps.Style();
	s.iconStyle = new YMaps.IconStyle("example#customPointIcon");
	s.iconStyle.offset = new YMaps.Point(-10, -32);
	s.iconStyle.href = "/img/extra/blue-pushpin.png";
	s.iconStyle.size = new YMaps.Point(32, 32);
	s.iconStyle.shadow = new YMaps.IconShadowStyle();
	s.iconStyle.shadow.offset = new YMaps.Point(-8, -32);
	s.iconStyle.shadow.href = "/img/extra/pushpin_shadow.png";
	s.iconStyle.shadow.size = new YMaps.Point(59, 32);
	YMaps.Styles.add("example#customPoint", s);

	var t = new YMaps.Template();
	t.text = "<div><img alt=\"123\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" src=\"$[style.iconStyle.href]\"\/></div>";
	YMaps.Templates.add("example#customPointIcon", t);

	if (jQuery('#not_coord').val()){
		var geoPoint = new YMaps.GeoPoint.fromString(jQuery('#not_coord').val())
		ShowPlacemark(geoPoint);
		map.setCenter(geoPoint, jQuery('#not_zoom').val(), YMaps.MapType.MAP );
	} else {
		getGeoLocation();
	}

	YMaps.Events.observe(map, map.Events.Click, function (mEvent) {
		ShowPlacemark(mEvent.getGeoPoint());
		map.panTo(mEvent.getGeoPoint());
	});

	YMaps.Events.observe(map, map.Events.Update, function () {
		jQuery('#not_zoom').val(map.getZoom());
	});
};
        
function getGeoLocation(){
	var params = jQuery("input[id='not_region'], input[id='not_district'], input[id='not_settle'], input[id='not_street'] ").serialize();
		
	jQuery.ajax({
		type: "POST",
		dataType: "json",
		url: "/controllers/offers.php",
		data: "func=getGeoLocation&"+params,
		success: function (res, options) {
			if (location)  showAddress(res.location);
		},
		error: function (){
			alert('Ошибка связи. Попробуйте повторить позже.');
		}
	});        
}
        
function showAddress (value) {
	var geocoder = new YMaps.Geocoder(value, { results: 4});

	YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
		if (this.length()) {
			var geoResult = this.get(0);
			ShowPlacemark(geoResult.getGeoPoint());
			map.setBounds(geoResult.getBounds());
			if (map.getZoom() <=9) map.setZoom(11);
			if (value =='Украина') map.setZoom(6);
				jQuery('#not_zoom').val(map.getZoom());
			} else {
				alert("Ничего не найдено")
			}
	});
}

function ShowPlacemark(geoPoint){        	
	var coords = 0;
	jQuery('#not_coord').val(geoPoint.toString());
	map.removeOverlay(placemark);

	placemark = new YMaps.Placemark(geoPoint, { style: "example#customPoint" , draggable: true } );
	placemark.disableBalloon();
	map.addOverlay(placemark);

	YMaps.Events.observe(placemark, placemark.Events.DragEnd, function (mEvent) {
		placemark.setIconContent(null);
		jQuery('#not_coord').val(mEvent.getGeoPoint().toString());
		jQuery('#not_zoom').val(map.getZoom());
		map.panTo(mEvent.getGeoPoint());
	});
}

function loadYouTubeURL() {
	var url = jQuery("input[id='youtube_url']").val();
	
	var ptrn1 = /\s*((\S+\s*)*)/;
	var ptrn2 = /((\s*\S+)*)\s*/;
	var url = url.replace(ptrn1, "$1");
	url = url.replace(ptrn2, "$1");

	if (url=='Введите URL') return;
	
	$.ajax({
		type: "POST",
		dataType: "json",
		url: "/controllers/offers.php",
		data: "func=loadYouTubeURL&url="+url,
		success: function (res, options) {
			if (res.length) {
				jQuery('#resLoad').html('<img src="http://i1.ytimg.com/vi/'+res+'/default.jpg" border="0" style="margin-top:5px;">');
				jQuery('#not_embed').val(res);
			}
		},
		error: function (){
			alert('Ошибка связи. Попробуйте повторить позже.');
		}
	});
	
}

//-->
