function str_replace( search, replace, subject ){
    while( subject.match( search ) !== null )
        subject = subject.replace( search, replace );

    return subject;

}

function isset(variable_name){
    try{
        if (typeof(eval(variable_name)) != 'undefined')
            if (eval(variable_name) != null)
                return true;
            } catch(e) { }

        return false;
        }

function loadModels2()
{

	var mark = jQuery("#mark2").val();


  jQuery.post("/doska/announce/carmodels/", { mark: mark }, function(data) {
    jQuery('#model2').empty();
    var j = 1;
    for ( var i in data ) {
      jQuery("#model2").append('<option value="' + i + '">' + data[i]);
      j++;
    }
  }, 'json');
}
function check_del()
{
  var link = document.location.toString().replace('/edit', '/delete');
  confirm_66("Вы уверены, что хотите удалить это объявление?", null, "function", "window.location = '" + link + "'" );
}

function swap_price(){

	if (jQuery('#price').attr('disabled')) {
		jQuery('#price').removeAttr("disabled");
		jQuery('#currency').removeAttr("disabled");
	}else{
		jQuery('#price').attr("disabled", true);
		jQuery('#currency').attr("disabled", true);

	}
}
function loadRaions()
{
	var city = jQuery("#city").val();
	if( city == 2 ) {
	 	document.getElementById('raion_caption').innerHTML='Направление';
	 	document.getElementById('raion_other_caption').innerHTML='указать другое направление';
    }
    if( city == 11){
    	document.getElementById('raion_caption').innerHTML='Город';
    	document.getElementById('raion_other_caption').innerHTML='указать другой город';
    }
    if( city == 1 ) {
    	document.getElementById('raion_caption').innerHTML='Район';
    	document.getElementById('raion_other_caption').innerHTML='указать другой район';
    }

		if( city == 1 ) jQuery("#other_r").hide();
		else if( city == 2 ) jQuery("#other_r").hide();
		else jQuery("#other_r").show();

  jQuery.post("/doska/announce/raions/", { city: city }, function(data) {
    jQuery('#raion').empty();
    var j = 1;
    for ( var i in data ) {
      jQuery("#raion").append('<option value="' + i + '">' + data[i]);
      j++;
    }
  }, 'json');
}

function realty_filter_city_swap(){
	if( typeof(raions_selecded) != 'undefined' ){
		for (var raion in raions_selecded){
			raions_click(raion,1);
		}
	}
	raions_selecded = [];
	jQuery('#raions_text').empty();


	if( jQuery('#city').val() == 2 ){
		jQuery('#change_r_butt').empty();
		jQuery('#change_r_butt').append('указать направление');
	}

	if( jQuery('#city').val() == 11 ){
		jQuery('#change_r_butt').empty();
		jQuery('#change_r_butt').append('указать город');
	}

	if( jQuery('#city').val() == 1){
		jQuery('#change_r_butt').empty();
		jQuery('#change_r_butt').append('указать район');
	}

	if (jQuery('#city').val() != '1'){
		jQuery('#eburg_map').hide();
		jQuery('#other_map').show();
		jQuery('#city_name').attr('innerHTML', '');
		jQuery.post("/doska/announce/raions/", { city: jQuery('#city').val() },
		function(data) {
		    jQuery('#other_map').empty();

		    var j = 1;
		    for ( var i in data ) {
		      jQuery("#other_map").append('<input onclick="other_r_click(this);" type="checkbox" value="' + i + '" id="other_r_'+i+'"><label for="other_r_'+i+'"><span id="other_title_r_'+i+'">' + data[i]+'</span></label><br />');
		      j++;
	    	}
	  }, 'json');

	}else{
		jQuery('#eburg_map').show();
		jQuery('#other_map').hide();
		jQuery('#city_name').attr('innerHTML', 'Екатеринбург');
	}
}

function realty_filter_city_swap_new(){
	if( typeof(raions_selecded) != 'undefined' ){
		for (var raion in raions_selecded){
			raions_click(raion,1);
		}
	}
	raions_selecded = [];
	jQuery('#raions_text').empty();

	if( jQuery('#city').val() == 2 ){
		jQuery('#change_r_butt').empty();
		jQuery('#change_r_butt').append('указать направление');
	}

	if( jQuery('#city').val() == 11 ){
		jQuery('#change_r_butt').empty();
		jQuery('#change_r_butt').append('указать город');
	}

	if( jQuery('#city').val() == 1){
		jQuery('#change_r_butt').empty();
		jQuery('#change_r_butt').append('указать район');
	}

	if (jQuery('#city').val() != '1'){
		jQuery('#eburg_map').hide();
		jQuery('#other_map').show();
		jQuery('#city_name').attr('innerHTML', '');
		jQuery.post("/doska/announce/raions/", { city: jQuery('#city').val(), new_: true },
		function(data) {
		    jQuery('#other_map').empty();
		    for ( var i in data )
		      jQuery("#other_map").append('<span class="district-opt"><input onclick="other_r_click(this);" type="checkbox" value="' + i + '" id="other_r_'+data[i].id+'"><label for="other_r_'+data[i].id+'"><span id="other_title_r_'+data[i].id+'">' + data[i].name +'</span></label></span>');
	  }, 'json');

	}else{
		jQuery('#eburg_map').show();
		jQuery('#other_map').hide();
		jQuery('#city_name').attr('innerHTML', 'Екатеринбург');
	}
}

function realty_filter_obj_type_swap(){
	if(parseInt(jQuery('#f_obj_t').val()) != 1 && jQuery('#f_obj_t').val() != 2){
		jQuery('#span_no_kr').hide();
		jQuery('#span_rooms').hide();
	}else{
		jQuery('#span_no_kr').show();
		jQuery('#span_rooms').show();
	}
}


function other_r_click(elm){
	var val = elm.id.substr(8);
	if(elm.checked){
		//jQuery("#raions_text").append('<input id="filter[raion][]_'+elm.value+'" type="hidden" value="'+elm.value+'" name="filter[raion][]"/><span id="filter[raion][]_info_'+elm.value+'">'+jQuery("#other_title_r_"+elm.id.substr(8)).attr('innerHTML')+' <a href="#" onclick="other_r_unclick('+elm.value+')">X</a></span>')
		jQuery("#raions_text").append('<input id="filter[raion][]_'+val+'" type="hidden" value="'+val+'" name="filter[raion][]"/><span id="filter[raion][]_info_'+val+'">'+jQuery("#other_title_r_"+val).attr('innerHTML')+' <a href="#" onclick="other_r_unclick('+val+')">X</a></span>')
	}else{
		other_r_unclick(val);
	}
}

function other_r_unclick(id){
	input = document.getElementById('filter[raion][]_'+id);
	span = document.getElementById('filter[raion][]_info_'+id);

	input.parentNode.removeChild(input);
	span.parentNode.removeChild(span);

	jQuery("#other_r_"+id).removeAttr( 'checked' );
}

function report_to_moderator(adv_id)
	{
	window_create('alert_x',310,1);
	window_setupcontent('alert_x','Сообщить модератору');

	$("alert_x_mf").innerHTML = $("alert_x_mf").innerHTML + ""
		  +"<div id='forchange'>"
			+"<table cellspacing='0' cellpadding='0' border='0' width='100%' style='border-collapse: collapse;'>"
				+"<tr>"
					+"<td style='padding: 10px; font-size: 12px; color: #000000;'>Хотите, чтобы эта информация была просмотрена модератором?</td>"
				+"</tr>"

				+"<tr>"
					+"<td style='padding: 10px;'>"
						+"<textarea id='report_to_moderator_text' style='color: #808080; width: 100%;' onClick='input_rechange(\"подробности, если считаете нужным...\",\"report_to_moderator_text\",\"click\");' onBlur='input_rechange(\"подробности, если считаете нужным...\",\"report_to_moderator_text\",\"blur\");'>подробности, если считаете нужным...</textarea>"
					+"</td>"
				+"</tr>"
				+"<tr>"
					+"<td style='padding: 10px; font-size: 12px; color: #000000;' align='center'>"
						+"<img src='http://img.66.ru/dez/button_yes.gif' width='68' height='16' alt='Отправить' title='Отправить' border='0' onClick=\"report_to_moderator_save('"+adv_id+"');\" style='cursor: pointer;'>"
						+"&nbsp; &nbsp; &nbsp;"
						+"<img src='http://img.66.ru/dez/cancel.gif' width='68' height='16' alt='Отменить' title='Отменить' border='0' onClick=\"window_close(0);\" style='cursor: pointer;'>"
					+"</td>"
				+"</tr>"
			+"</table>"
		   +"</div><br>";
	}

function report_to_moderator_new(adv_id)
	{
	window_create('alert_x',310,1);
	window_setupcontent('alert_x','Сообщить модератору');

	$("alert_x_mf").innerHTML = $("alert_x_mf").innerHTML + ""
		  +"<div id='forchange'>"
			+"<table cellspacing='0' cellpadding='0' border='0' width='100%' style='border-collapse: collapse;'>"
				+"<tr>"
					+"<td style='padding: 10px; font-size: 12px; color: #000000;'>Хотите, чтобы эта информация была просмотрена модератором?</td>"
				+"</tr>"
				+"<tr>"
					+"<td style='padding: 10px; font-size: 12px; color: #000000;'>"
					+"<input value=\"1\" type=\"radio\" name=\"what\" id=\"ne_tot_razdel\" checked=\"checked\" onclick=\"document.getElementById('report_to_moderator_text').disabled=true\"> <label style=\"position:relative;top:-3px;\" for=\"ne_tot_razdel\">не тот раздел</label><br />"
					+"<input value=\"2\" type=\"radio\" name=\"what\" id=\"moshen\" onclick=\"document.getElementById('report_to_moderator_text').disabled=true\"> <label style=\"position:relative;top:-3px;\" for=\"moshen\">мошенничество</label><br />"
					+"<input value=\"3\" type=\"radio\" name=\"what\" id=\"ne_korr\" onclick=\"document.getElementById('report_to_moderator_text').disabled=true\"> <label style=\"position:relative;top:-3px;\" for=\"ne_korr\">некорректно составлено</label><br />"
					+"<input value=\"4\" type=\"radio\" name=\"what\" id=\"zapr_pred\" onclick=\"document.getElementById('report_to_moderator_text').disabled=true\"> <label style=\"position:relative;top:-3px;\" for=\"zapr_pred\">запрещенные предметы</label><br />"
					+"<br /><input value=\"0\" type=\"radio\" name=\"what\" id=\"drugaya\" onclick=\"document.getElementById('report_to_moderator_text').disabled=false\"> <label style=\"position:relative;top:-3px;\" for=\"drugaya\">Укажите свою</label><br />"
					+"</td>"
				+"</tr>"
				+"<tr>"
					+"<td style='padding: 10px;'>"
						+"<textarea disabled=\"disabled\" id='report_to_moderator_text' style='color: #808080; width: 100%;' onClick='input_rechange(\"подробности, если считаете нужным...\",\"report_to_moderator_text\",\"click\");' onBlur='input_rechange(\"подробности, если считаете нужным...\",\"report_to_moderator_text\",\"blur\");'>подробности, если считаете нужным...</textarea>"
					+"</td>"
				+"</tr>"
				+"<tr>"
					+"<td style='padding: 10px; font-size: 12px; color: #000000;' align='center'>"
						+"<img src='http://img.66.ru/dez/button_yes.gif' width='68' height='16' alt='Отправить' title='Отправить' border='0' onClick=\"report_to_moderator_save('"+adv_id+"');\" style='z-index: 999;cursor: pointer;'>"
						+"&nbsp; &nbsp; &nbsp;"
						+"<img src='http://img.66.ru/dez/cancel.gif' width='68' height='16' alt='Отменить' title='Отменить' border='0' onClick=\"window_close(0);\" style='cursor: pointer;'>"
					+"</td>"
				+"</tr>"
			+"</table>"
		   +"</div><br>";
	}

function report_to_moderator_save(adv_id)
	{
	warningText = $("report_to_moderator_text").value;
	var what;
	if( jQuery('input[name=what]:checked').length ) {
	    what = jQuery('input[name=what]:checked').val();
	}
	else
	    what = '';
	if (warningText == "подробности, если считаете нужным...") {warningText = "";}
	xhref = window.location.href;

	req.onreadystatechange = function()
		{
		if (req.readyState == 4)
			{
			if (req.responseJS.res == -1) {
				alert_66("Извините, Вы уже жаловались на это объявление. Модератор обязательно рассмотрит Вашу жалобу");
				} else {
				alert_66("Спасибо, сообщение будет рассмотрено модератором");
				}

			}
		}
	req.caching = false; //true
	req.open('POST', '/show/ajax_report_to_moderator.php', true);
	req.send({ usdie: usdie , warning_text: warningText, xhref: xhref, adv_id:adv_id, what: what});
	}

	function show( obj ){
        if( !getObj( obj ) )
            return false;

        getObj( obj ).style.display = '';
    }

    function hide( obj ){
        if( !getObj( obj ) )
            return false;

        getObj( obj ).style.display = 'none';
    }

    function showHide( obj ){

    	if( !( obj = getObj( obj ) ) )
    		return false;

    	var open = ( obj.style.display == 'none')	;

    	if( open )
    	   show( obj );
	    else
	       hide( obj );

    	return open;
    }

       function getObj( arg ){

        if( typeof( arg ) == 'object' )
            return arg;

        if( document.getElementById( arg ) )
            return document.getElementById( arg );

        return false;
    }


    function setDefText(field_id, connectWith, def_class, stopRecursion, colored){
        if( is_object(field_id) ) field_id = field_id.id;

        jQuery(document).ready(function(){
                jQuery("#"+field_id).focus(function(srcc){
                    if (jQuery(this).val() == jQuery(this)[0].title){

                        if(def_class){
                            jQuery(this).removeClass(def_class);
                        }
                        jQuery(this).val("");

                         if(connectWith ){
                        if(jQuery('#'+connectWith).val() == jQuery('#'+connectWith)[0].title ){
                            if(def_class)
                                jQuery('#'+connectWith).removeClass(def_class);
                            jQuery('#'+connectWith).val("");
                        }
                    }

                    }



                });

        jQuery(document).keypress(function(){});

        jQuery("#"+field_id).blur(function(){
                if (jQuery(this).val() == ""){
                    if(connectWith) {
                        if(jQuery('#'+connectWith).val() != "") return;
                    }
                    if(def_class)
                        jQuery(this).addClass(def_class);
                    jQuery(this).val(jQuery(this)[0].title);

                    if(connectWith){
                        if (jQuery('#'+connectWith).val() == ""){
                            if(def_class)
                                jQuery('#'+connectWith).removeClass(def_class);
                            jQuery('#'+connectWith).val(jQuery('#'+connectWith)[0].title);
                        }
                    }
                }

            });

        jQuery("#"+field_id).blur();
        });

        if(connectWith && !stopRecursion){setDefText(connectWith, field_id, def_class, 1, colored)};


    }
     function is_object( mixed_var ){
    // Returns true if variable is an object
    //
    // version: 810.114
    // discuss at: http://phpjs.org/functions/is_object
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

function my_adv(sentBy) {

	window_create('alert_x', 310, 1);
	window_setupcontent('alert_x', 'Это моё объявление');

	var html = '';

	html+= '<form action="" method="post" style="margin: 0; padding: 0 15px; zoom: 1;">' +
	        '<p style="font-size: 12px; margin: 0; padding: 10px 0;">' +
		     '<label for="my-key">Код для редактирования:</label><br />' +
			 (sentBy ? '<small>отправлен Вам с помощью ' + sentBy + '</small><br />': '') +
			 '<input type="text" name="my-key" id="my-key" style="margin: 4px 0;" /><br />' +
			 '<input type="submit" value="Редактировать" name="my-edit" style="height: auto !important; height: 1px; overflow: visible; padding: 2px 3px;" />' +
			 '<input type="submit" value="Напомнить код" name="my-repair" style="height: auto !important; height: 1px; overflow: visible; padding: 2px 3px;" />'
		    '</p>' +
	       '</form>';

	$('alert_x_mf').innerHTML = $('alert_x_mf').innerHTML = html;
}

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
  //alert('done');
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("body")[0].appendChild(fileref)
}
