//global variables
var abs_path = "http://www.realitynamape.sk/";
var abs_path_img = "http://www.realitynamape.sk/images/";

/**************** START : v3.js ******************/


$(document).ready(function(){
  $("form#form_newsletter_subscribe #news_email").click(function() {
    if($(this).val() == get_trad_champ("your_email")) {
      $(this).val("");
    }
  });
  $("form#form_newsletter_subscribe #news_email").blur(function() {
    if($(this).val() == "") {
      $(this).val(get_trad_champ("your_email"));
    }
  });
  //newsletter subscribe on homepage
  $("form#form_newsletter_subscribe").submit(function(){
     if($("input#news_email").val() != '' && validemail("news_email") ){
      //$("p#form_message").html("<img src='"+abs_path_img+"ajax_loader_transparent.gif' alt='Loading' />");
      $.ajax({
    	 	type: "GET",
    	 	data: "email="+$("input#news_email").val(),
    	 	url: abs_path+"ajax/ajax_newsletter_subscribe.php",
    	 	success: function(msg){
    	 		if(msg != "ERROR"){
    	 		  $("#form_newsletter_subscribe input").hide("medium");
    	 		  $("#form_newsletter_subscribe div").append("<span>"+get_trad_champ("email_added_ok")+".</span>");
    	 		}
    	 	}
      });

    }
    return false;
  });

  $("form#rnm_form_contact").submit(function(){

  	if($("#name").val() == ""){
			alert(get_trad_champ("prenom"));
			return false;
		}
		if($("#message").val() == ""){
			alert(get_trad_champ("message"));
			return false;
		}
		if(!validemail("email")) {
			return false;
		}

    $.ajax({
  	 	type: "GET",
  	 	data: "email="+$("input#email").val()+"&name="+$("input#name").val()+"&message="+$("#message").val(),
  	 	url: abs_path+"ajax/ajax_contact.php",
  	 	success: function(msg){
  	 		if(msg != "ERROR"){
  	 		  $("#rnm_form_contact").html(get_trad_champ("msg_sent_ok"));
  	 		}
  	 	}
    });

    return false;

  });

	//filling onchange property name in search_basic.tpl - for nice urls in search
	$(".fill_property_nice_url").change(function() {
		$("#property_nice_url").val($(this).children("option:selected").text());
	} );
	$(".fill_property_commercial_nice_url").change(function() {
		$("#commercial_nice_url").val($(this).children("option:selected").text());
	} );

	$(".insert_offer_container #type_habitation").change(function() {
		if($(this).children("option:selected").val() == 13) {
			$("#type_commercial").parent().show();
			if( $("#type_offre").containsOption("3")) {
				$("#type_offre").removeOption("3");
			}
		} else {
			$("#type_commercial").parent().hide();
			if( !$("#type_offre").containsOption("3")) {
				$("#type_offre").addOption({"3":get_trad_champ("Spolubývajúci")},false);
			}
		}
	});

  $(".dropdown_container").bind("mouseenter", function(){
//    $(this).children(".dropdown").show();
    $(this).children(".dropdown").css('display', 'block');
  });

//  $(".dropdown").bind("mouseleave", function(){
//    $(this).slideUp("fast");
//  });

  $(".dropdown_container").bind("mouseleave", function(){
    //$(this).children(".dropdown").hide();
    $(this).children(".dropdown").css('display', 'none');
  });

  $(".tab_search_basic").click(function(){
    $(this).addClass("tab_search_basic_active");
    $(".tab_add_offer").removeClass("tab_add_offer_active");
    $("#add_offer").hide();
    $("#quick_search").show();
  });
  $(".tab_add_offer").click(function(){
    $(this).addClass("tab_add_offer_active");
    $(".tab_search_basic").removeClass("tab_search_basic_active");
    $("#quick_search").hide();
    $("#add_offer").show();
    if($("#ville").selectedValues() == "choose") {
    	$("#ville").empty();
	    $("#ville").ajaxAddOption(abs_path+"ajax/loadCityList.php",false,false,function(param){
		    	$("#ville").selectOptions("276",true);
		    	$("#ville").selectOptions("1");
		    	$("#ville").trigger("change");
	    });
	  }

  });

  //offer tabs controls
  $(".offer_description .content .block").css('display','block'); //show active tab content

  $("ul.offer_tabs li").click(function(){
    $("ul.offer_tabs li").removeClass("active");
    $(this).addClass("active");
    $(".content > div").hide();
    $(".hp_mag_content > div").hide();
  });

  //offer tabs
  $("#tab_offer_description").click(function(){
    $("#description").show();
  });
  $("#tab_offers_all").click(function(){
    $("#offers_all").show();
  });
   $("#tab_offers_smartvisite").click(function(){
    $("#offers_sm").show();
  });
  $("#tab_offer_3d").click(function(){
    $("#smart_visit").show();
    $("#smart_visit div").show();
  });
  $("#tab_offer_details").click(function(){
    $("#details").show();
    $("#details *").show();
  });
  $("#tab_offer_price").click(function(){
    $("#price_evolution").show();
//    $("#price_evolution *").show();
    loadZoneInfo($("#last_zone_id").val(), $("#last_zone_level").val());
  });
  $("ul.offer_tabs li").click(function(){
    $(".vip_contact").parent().removeClass("vip_contact_parent");
  });
  $("#tab_offer_contact").click(function(){
    $("#contact").show();
    $("#contact *").show();
    $(".vip_contact").parent().addClass("vip_contact_parent");
  });
  $("#tab_offer_project_offers").click(function(){
    $("#project_offers").show();
    $("#contact *").show();
  });
  $("#tab_offer_discussion").click(function(){
    $("#discussion_main_container").show();
    $("#discussion_main_container *").show();
//    $("#comments_form_container").hide();
    $("#general_rules").hide();
  });
  $("#tab_my_offers").click(function(){
    $("#my_offers").show();
    $("#my_offers *").show();
  });
  $("#tab_manage_credits").click(function(){
    $("#credits_overview").show();
  });
  $("#tab_general_stats").click(function(){
    $("#general_stats").show();
    showGeneralStats($("#general_stats_time_period").val());
//    $("#general_stats div").show();
  });

  $("#general_stats_time_period").change(function(){
    showGeneralStats($("#general_stats_time_period").val());
  });

//  homepage magazine tabs
  $("#tab_mag_newest").click(function(){
    $("#mag_newest").show();
  });
  $("#tab_mag_real").click(function(){
    $("#mag_real").show();
  });
  $("#tab_mag_living").click(function(){
    $("#mag_living").show();
  });
  $("#tab_mag_technology").click(function(){
    $("#mag_technology").show();
  });
  $("#tab_mag_lifestyle").click(function(){
    $("#mag_lifestyle").show();
  });
  $("#tab_mag_video").click(function(){
    $("#mag_video").show();
  });

  //virtual visists page
  $("#tab_rk").click(function(){
    $("#vv_rk").show();
  });
  $("#tab_individual").click(function(){
    $("#vv_individual").show();
  });
  $("#tab_developer").click(function(){
    $("#vv_developer").show();
  });

  $(".block_carousel").jCarouselLite({
        btnNext: "#articles_next",
        btnPrev: "#articles_prev",
        scroll: 3,
        visible: 3,
        circular: false,
        mouseWheel: true,
        vertical: true
    });
  $("#obedovat_carousel_container").jCarouselLite({
        scroll: 1,
        visible: 1,
        circular: true,
        mouseWheel: true,
        vertical: false,
        auto: 5000,
        speed: 1000

    });


//  $(".block_carousel_job").jCarouselLite({
//        btnNext: "#articles_next",
//        btnPrev: "#articles_prev",
//        scroll: 4,
//        visible: 4,
//        circular: false,
//        mouseWheel: true,
//        vertical: true,
//    });

  $(".last_search_results_carousel.offer_details").jCarouselLite({
        btnNext: ".last_search_results_control.right, .hp_carousel_control_right",
        btnPrev: ".last_search_results_control.left, .hp_carousel_control_left",
        scroll: 2,
        visible: 4,
        circular: true,
        mouseWheel: true
    });
    
    $(".last_search_results_carousel.map_seach").jCarouselLite({
        btnNext: ".last_search_results_control.right, .hp_carousel_control_right.map_seach_control",
        btnPrev: ".last_search_results_control.left, .hp_carousel_control_left.map_seach_control",
        scroll: 2,
        visible: 2,
        circular: true,
        mouseWheel: true
    });
    
    $(".last_search_results_carousel.newest_offers").jCarouselLite({
        btnNext: ".last_search_results_control.right, .hp_carousel_control_right.newest_offers_control",
        btnPrev: ".last_search_results_control.left, .hp_carousel_control_left.newest_offers_control",
        scroll: 2,
        visible: 2,
        circular: true,
        mouseWheel: true
    });
    
    
  $(".last_search_results_carousel.estimation").jCarouselLite({
        btnNext: ".last_search_results_control.right",
        btnPrev: ".last_search_results_control.left",
        scroll: 3,
        visible: 6,
        circular: false,
        mouseWheel: true
    });
    
    $("#reg_form_individual select#type").change(function(){
      if($(this).val() == 1){
        $("#professional_reg_info").hide('fast');
      } else {
        $("#professional_reg_info").show('fast');
      }
    })
    

    $("div.discussion_rules a").click(function(){
      $("#general_rules").slideToggle('fast');
      return false;
    });

    $('.rk_registration tr.header:first').find('.description').show("fast");
	  $('.rk_registration tr.header:first').find('td[class!=first]').css('background','#f5f5f5');

    $('.rk_registration tr.header').hover(
	  function () {
	  	$('.rk_registration tr.header').find('td[class!=first]').css('background','#FFFFFF');
	  	$('.rk_registration tr.header').find('.description').fadeOut("fast");
	    $(this).find('.description').fadeIn("fast");
	    $(this).find('td[class!=first]').css('background','#f5f5f5');
	  },
	  function () {
	    //$(this)
	    //$(this).find('td[class!=first]').css('background','#FFFFFF');
	  });

  $("form#discussion").submit(function(){

    if($("input#nickname").val() != '' && $("textarea#message").val() != ''){
      $("p#form_message").html("<img src='"+abs_path_img+"ajax_loader_transparent.gif' alt='Loading' />");
      $.ajax({
    	 	type: "GET",
    	 	data: "nickname="+$("input#nickname").val()+"&email="+$("input#email").val()+"&item_id="+$("input#item_id").val()+"&comment_type="+$("input#comment_type").val()+"&message="+$("textarea#message").val()+"&captcha="+$("input#captcha").val(),
    	 	url: abs_path+"ajax/ajax_add_comment_new.php",
    	 	success: function(msg){
    	 		if(msg != "ERROR"){
    	 		  $("input#nickname").val("");
    	 		  $("input#email").val("");
    	 		  $("textarea#message").val("");
    	 		  $("input#captcha").val("");
    	 		  $("p#form_message").html(get_trad_champ("msg_saved"));
    	 		  $("div#no_comments").hide();

    	 		  var data = msg.split("##");
    	 		  var new_html =
    	 		    "<div class='comment'>" +
              "  <span class='comment_name'>" + data[0] + "</span>" +
              "   <span class='comment_date'>(" + data[1] + ")</span>" +
              "   <span class='comment_date'>" + data[2] + "</span>" +
              "  <p>" + data[3] + "</p>" +
              "</div>";
    	 		  var old_html = $("div#comments").html();
    	 		  $("div#comments").html(new_html + old_html);

    	 		}else{
    	 		  $("p#form_message").html(get_trad_champ("err_captcha"));
    	 		}
    	 	}
      });
    } else {
      $("p#form_message").html(get_trad_champ("fill_name_and_msg"));
    }
    return false;
  });

  //disable autocomplete
  if(document.getElementById('ville')){
    document.getElementById('ville').setAttribute("autocomplete","off");
  }

  //offer detail photo navigation

  $(".photo_controls_right").click(function(){
    if(active < photos_count){
      active++;
    } else {
      active = 1;
    }
    showPhoto(active);
  });
  $(".photo_controls_left").click(function(){
    if(active > 1){
      active--;
    } else {
      active = photos_count;
    }
    showPhoto(active);
  });

  $("#comments_form_container_controller").click(function(){
      $(this).hide();
      $("#comments_form_container").show('fast');
      return false;
  });

  $("#hypo_button").click(function(){
    $("#unicredit_hypo").show('fast');
    $("#hypo_close").show('fast');
  });
  $("#hypo_close").click(function(){
    $("#unicredit_hypo").hide('fast');
    $("#hypo_close").hide('fast');
  });

  $("#toggle_services").click(function(){
    InitializeServices(500);
    return false;
  });
  $("#map_projects").click(function(){
    InitializeProjects();
    return false;
  });
  $("#services_bar img").click(function(){
    var addr = $(this).attr('src');
    if(addr.indexOf("active") != -1){
      addr = addr.replace("services/active", "services");
    } else {
      addr = addr.replace("services", "services/active");
    }
    $(this).attr('src', addr);
  });



  function statusMessage(){
    setTimeout("resetStatus()", 1);
  }
  if(document.getElementById('hidestatus')){
    statusMessage();
  }

  $(".select_tabs h3").click(function() {
  	$(".tabs_content").html($(this).next().html());
  	$(this).siblings().removeClass("active");
  	$(this).addClass("active");
  });

  $('.map_controls_icons li a').click(function() {
  	$(this).parent().addClass("active").siblings().removeClass("active");
  	return false;
  });
  $('.fav_comment').focus(function(){
    if($(this).hasClass("fav_comment_empty")){
      $(this).val("");
      $(this).removeClass("fav_comment_empty");
    }
  });

  $("form#architecture_request").submit(function(){
	  if($("input#email").val() != '' && $("textarea#message").val() != ''){
	    $("form#architecture_request >div >div:last").html("<img src='"+abs_path_img+"ajax_loader_transparent.gif' id='loader' alt='Loading' style='display:block; margin:2em auto 0;'/>");
	    $.ajax({
	  	 	type: "GET",
	  	 	data: "name="+$("input#name").val()+"&email="+$("input#email").val()+"&message="+$("textarea#message").val(),
	  	 	url: abs_path+"ajax/ajax_send_design_request.php",
	  	 	success: function(msg){
	  	 		if(msg != "ERROR"){
	  	 		  $("input#name").val("");
	  	 		  $("input#email").val("");
	  	 		  alert(get_trad_champ("msg_sent_ok2"));
	  	 		  $("form#architecture_request >div >div:last").html('<input type="submit" style="margin:25px 0 0 10px;" class="button_big big" value="'+get_trad_champ("send")+'" name="submit"/>');
	  	 		}else{
	  	 		  alert(get_trad_champ("msg_sent_err"));
	  	 		  $("form#architecture_request >div >div:last").html('<input type="submit" style="margin:25px 0 0 10px;" class="button_big big" value="'+get_trad_champ("send")+'" name="submit"/>');
	  	 		}
	  	 	}
	    });
	  } else {
	    alert(get_trad_champ("fill_email_and_msg"));
	  }

	  return false;
	});

	//maxitip creation sample update
	$("#mt_headline").keyup(function(){
	   $("#mt_sample_headline").html($(this).val());
	});
	$("#mt_line_1").keyup(function(){
	   $("#mt_sample_line1").html($(this).val());
	});
	$("#mt_line_2").keyup(function(){
	   $("#mt_sample_line2").html($(this).val());
	});
	$("#mt_link").keyup(function(){
	   $("#mt_sample_link").html($(this).val());
	});

	$(".double_tab li").click(function(){
	  if($(this).hasClass('left_tab')){
	    $(".double_tabs_content_container .right_tab_content").hide();
	    $(".double_tabs_content_container .left_tab_content").show();
	    $(this).parent().removeClass('inversed');
	  } else {
	    $(".double_tabs_content_container .left_tab_content").hide();
	    $(".double_tabs_content_container .right_tab_content").show();
	    $(this).parent().addClass('inversed');
	  }

	});
	
	$("#advanced_search_controller").click(function(){
	  $("#advanced_search_container").slideToggle('fast');
	  return false;
	});
});

function resetStatus(){
  window.status = get_trad_champ("rnm_title");
  setTimeout("resetStatus()", 200);
}

function showPhoto(index){
  $("#largeImg").attr('src', photos[index-1]);
  $("#active_photo").html(index);
}

function setActive(elem){
  $(elem).parent().addClass("active").siblings().removeClass("active");
  hideInfo();
}

function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;

  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";

  if(typeof(arr) == 'object') { //Array/Hashes/Objects
   for(var item in arr) {
    var value = arr[item];

    if(typeof(value) == 'object') { //If it is an array,
     dumped_text += level_padding + "'" + item + "' ...\n";
//     dumped_text += dump(value,level+1);
    } else {
     dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
    }
   }
  } else { //Stings/Chars/Numbers etc.
   dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}

function check_1st_step(){
  var check = true;
  check = check && ($("#ville").val() != 0);
  check = check && (trim($("input[name=nom_rue]").val()) != "");

  if(!check){
    alert(get_trad_champ("fill_mandatory"));
  }
  return check;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function set_credits(e, c){
  $("#nb_credit").val(c);
  $(".assign_credits").attr('src', abs_path_img+'v3/checkbox2_off.png');
  $(e).attr('src', abs_path_img+'v3/checkbox2_on.png');
}

function confirmDelete(delUrl) {
  if (confirm(get_trad_champ("really_wanna_del"))) {
    document.location = delUrl;
  }
}

function deleteFavorite(id){
  if(confirm(get_trad_champ("really_wanna_del_fav"))){
    $.ajax({
  	 	type: "GET",
  	 	data: "remove=1&oid="+id,
  	 	dataType: 'json',
  	 	url: abs_path+"ajax/ajax_favorites.php",
  	 	success: function(data){
	 		  $("#favrow_"+id).hide();
	 		  map.clearOverlays();
	 		  loadFavorites();
	 		  if(!data){
	 		    data = "0";
	 		  }
	 		  if(data == '0'){
	 		    $("#favorites_table").hide();
	 		    $("#no_favorites").show();
	 		  }
	 		  $("#favorites_count").html(data);
  	 	}
    });
  }
}

function deleteFavoriteSimple(id){
    $.ajax({
  	 	type: "GET",
  	 	data: "remove=1&oid="+id,
  	 	dataType: 'json',
  	 	url: abs_path+"ajax/ajax_favorites.php",
  	 	success: function(data){
	 		  if(!data){
	 		    data = "0";
	 		  }
        $("#favstar_"+id).attr('src', abs_path_img+'v3/ico/ico_fav.png');
        $("#favstar_"+id).attr('title', get_trad_champ("add_to_fav"));
        $("#fav_detail_link span").html(get_trad_champ("add_to_fav"));
	 		  $("#favorites_count").html(data);
  	 	}
    });
}

function saveFavorite(id, show_message){
  var comment = "";
  if ($("#favcom_"+id).val() != 'undefined'){
    comment = $("#favcom_"+id).val();
  }
  $.ajax({
	 	type: "GET",
	 	data: "save=1&oid="+id+"&comment="+comment,
	 	dataType: 'json',
	 	url: abs_path+"ajax/ajax_favorites.php",
	 	success: function(data){
	 		if(show_message){
	 		  alert(get_trad_champ("changes_saved"));
	 		}
	 		$("#favstar_"+id).attr('src', abs_path_img+'v3/ico/ico_fav_active.png');
	 		$("#favstar_"+id).attr('title', get_trad_champ("del_fav"));
	 		$("#fav_detail_link span").html(get_trad_champ("del_fav"));
	 		$("#favorites_count").html(data);
	 	}
  });
}

function manageFavorite(id){
  if(readCookie("favorites["+id+"]")){
    deleteFavoriteSimple(id);
  } else {
    saveFavorite(id, false);
  }
}

function loadFavorites(){
  var min_lat = 999;
  var min_lon = 999;
  var max_lat = 0;
  var max_lon = 0;
  GEvent.addListener(map, "dragstart", function() {
  		hideInfo();
	});
  $.ajax({
	 	type: "GET",
	 	data: "get_favorites",
	 	dataType: 'json',
	 	url: abs_path+"ajax/ajax_favorites.php",
	 	success: function(data){
	 	  for(var i in data){
	 	    var html = '<dl onclick="location.href = \''+ data[i].url+'\'">' +
 '        <dt class="fl">' +
 '          <a onclick="return false;" class="check_visited" title="" href="'+ data[i].url+'">' +
 '            <img alt="" src="'+ data[i].photo+'">' +
 '          </a>' +
 '        </dt>' +
 '        <dd class="fl result-item-heading">' +
 '          <h2>' +
 '            <a onclick="return false;" title="" href="'+ data[i].url+'">'+ data[i].property_type+' '+ data[i].address+', '+ data[i].city+'</a>' +
 '          </h2>' +
 '        </dd>' +
 '        <dd class="prix fl">' +
 '          <a onclick="return false;" title="" href="'+ data[i].url+'" class="base-red header-size bold">' +
 '            '+ data[i].price+'€' +
 '          </a>' +
 '        </dd> ' +
 '     </dl>';
	 	    create_google_point(data[i].latitude, data[i].longitude, html, 0);
	 	    if(data[i].latitude < min_lat){
	 	      min_lat = data[i].latitude;
	 	    }
	 	    if(data[i].latitude > max_lat){
	 	      max_lat = data[i].latitude;
	 	    }
	 	    if(data[i].longitude < min_lon){
	 	      min_lon = data[i].longitude;
	 	    }
	 	    if(data[i].longitude > max_lon){
	 	      max_lon = data[i].longitude;
	 	    }
	 	  }
	 	  center_google_map(min_lat, min_lon, max_lat, max_lon);
	 	}
  });

}

/**************** END : v3.js ******************/

/*----------- Variables globales -----------*/
var G_scroll    = 0;
var G_scroll_detail = 0;
var G_stop_anim = 0;
var G_nb_vignette = 0;
var G_nb_annonce = 0;
var G_max_annonce = 0;
var G_nb_search_detail = 0;
var G_max_search_detail = 0;
var G_liste_triable = -1;
var G_offers = new Array();
var G_agencies = new Array();
var G_timer = null;

var map_offers = true;
var map_pricemap = false;
var map_services = false;
var map_rea = false;
var map_projects = false;

var lastScroll = 0;
/*----------- ------------------ -----------*/

function restart_form_timer(paging_changed) {
	if(!paging_changed) { //if other than page have been chenged, restore default page
		$("#main_search_form > input#page").remove();
	}
	clearTimeout(G_timer);
	var timer = 1000;
	if(document.getElementById('search_within_map')){
	  timer = 1000;
	}
	G_timer = setTimeout("load_search()", timer);
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
	if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
		document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
		else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
		if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// verifie la validite d'un email
function validemail(champ)
{


	var email = document.getElementById(champ);
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email.value))
	{
		alert(get_trad_champ("email"));
		email.focus;
		return false;
	}
	else
	{
		return true;
	}
}

// verifie les champs obligatoire d'un formulaire
valider_formulaire = function () {
	var tab = valider_formulaire.arguments;

	taille = tab.length;

	for (i=0;i<taille;i++) {
		if (tab[i]=="email") {
			if (!validemail(tab[i])) {
				return 0;
			}
		}else{
			if ((document.formulaire.elements[tab[i]].value=="") || (document.formulaire.elements[tab[i]].value==" ")) {
				str_temp = tab[i].replace(/_/g," ");
				alert(get_trad_champ(str_temp));
				return 0;
			}
		}
	}

	document.formulaire.submit();
}

function empechechar()
{
	if( event.keyCode < 48 || event.keyCode > 57 )
	{
		alert(get_trad_champ("numeric") );
		event.returnValue = false;
	}
}

// fonction qui fait apparaitre le sablier sur soumission de formulaire un peu long..

// Variable t�moin de la validation effectu�e ou pas
var deja = 0;

function valider(nom_form) {
	// Si on n'a pas d�j� valid�
	if ( deja == 0 ) {

		// On marque qu'on valide
		deja = 1;

		// On affecte le style 'sablier' au corps de la page
		document.body.className = 'sablier';

		// On lance la soumission du formulaire
		eval('document.'+nom_form+'.submit()');
	} /*else {
	alert('Le formulaire est d�j� valid�, veuillez patienter.'); */
}

function show_sablier()
{
	document.body.className = 'sablier';
}



// verifie les champs obligatoire d'un formulaire
verif_formulaire_nom = function () {
	var tab = verif_formulaire_nom.arguments;
	var nom_form = "formulaire";

	taille = tab.length;

	if (taille>0)
	{
		nom_form = tab[0];
	}

	for (i=1;i<taille;i++) {
		if (tab[i]=="email") {
			if (!validemail(tab[i])) {
				return 0;
			}
		}else{

			if ((document.getElementById(tab[i]).value=="")  || (document.getElementById(tab[i]).value==" ")) {
				//str_temp = tab[i].replace(/_/g," ");
				str_temp = tab[i];
				alert(get_trad_champ(str_temp));
				return 0;
			}
		}
	}

	return true
}



function valid_form_particulier(){

	if ((document.getElementById("nom").value=="")) {
		alert(get_trad_champ("nom"));
		return 0;
	}

	if ((document.getElementById("email").value=="")) {
		alert(get_trad_champ("email"));
		return 0;
	}

	if ((document.getElementById("login_inscription").value=="")) {
		alert(get_trad_champ("login"));
		return 0;
	}

	if ((document.getElementById("passe_inscription").value=="")) {
		alert(get_trad_champ("passe"));
		return 0;
	}

	if ((document.getElementById("passe_verif").value=="")) {
		alert(get_trad_champ("passe_verif"));
		return 0;
	}
	if ((document.getElementById("strcode").value=="")) {
		alert(get_trad_champ("strcode"));
		return 0;
	}

	if (document.getElementById("cgv").checked == false) {
		alert(get_trad_champ("cgv"));
		return 0;
	}
	if ((document.getElementById("passe_verif").value!=document.getElementById("passe_inscription").value)) {
		alert(get_trad_champ("passe_not_equal"));
		return 0;
	}

	// Test login
	var texte = document.getElementById("login_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_login"));
		return 0;
	}

	// Test passe
	var texte = document.getElementById("passe_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_passe"));
		return 0;
	}





	document.getElementById("form_particulier").submit();

}

function valid_form_agence(etape){

	// Premiere etape du form agence //
	if(etape==1){
		if ((document.getElementById("nom_agence").value=="")) {
			alert(get_trad_champ("nom_agence"));
			return 0;
		}

		if ((document.getElementById("siret").value=="")) {
			alert(get_trad_champ("siret"));
			return 0;
		}

		if ((document.getElementById("adresse_agence").value=="")) {
			alert(get_trad_champ("adresse_agence"));
			return 0;
		}

		if ((document.getElementById("cp").value=="")) {
			alert(get_trad_champ("cp"));
			return 0;
		}
		if ((document.getElementById("ville").value=="")) {
			alert(get_trad_champ("ville_agence"));
			return 0;
		}

		if ((document.getElementById("pays").value==0)) {
			alert(get_trad_champ("pays_agence"));
			return 0;
		}



	}else{

		// Deuxieme etape du form agence //

		if ((document.getElementById("nom_contact").value=="")) {
			alert(get_trad_champ("nom_contact"));
			return 0;
		}
		if ((document.getElementById("email_contact").value=="")) {
			alert(get_trad_champ("email_contact"));
			return 0;
		}
		if ((document.getElementById("login_inscription").value=="")) {
			alert(get_trad_champ("login"));
			return 0;
		}


		// Test login
		var texte = document.getElementById("login_inscription").value;
		var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
		if ( ! exp.test(texte) ){
			alert(get_trad_champ("caractere_interdit_login"));
			return 0;
		}

		if ((document.getElementById("passe_inscription").value=="")) {
			alert(get_trad_champ("passe"));
			return 0;
		}
		if ((document.getElementById("passe_verif").value=="")) {
			alert(get_trad_champ("passe_verif"));
			return 0;
		}


		if ((document.getElementById("passe_verif").value!=document.getElementById("passe_inscription").value)) {
			alert(get_trad_champ("passe_not_equal"));
			return 0;
		}

		// Test passe
		var texte = document.getElementById("passe_inscription").value;
		var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
		if ( ! exp.test(texte) ){
			alert(get_trad_champ("caractere_interdit_passe"));
			return 0;
		}

		if ((document.getElementById("strcode").value=="")) {
			alert(get_trad_champ("strcode"));
			return 0;
		}
		if (document.getElementById("cgv").checked == false) {
			alert(get_trad_champ("cgv"));
			return 0;
		}

	}


	document.getElementById("form_agence").submit();
}
function valid_form_agence_modif(etape){

	// Premiere etape du form agence //
	if(etape==1){
		if ((document.getElementById("nom_agence").value=="")) {
			alert(get_trad_champ("nom_agence"));
			return 0;
		}

		if ((document.getElementById("siret").value=="")) {
			alert(get_trad_champ("siret"));
			return 0;
		}

		if ((document.getElementById("adresse_agence").value=="")) {
			alert(get_trad_champ("adresse_agence"));
			return 0;
		}


		if ((document.getElementById("ville").value=="")) {
			alert(get_trad_champ("ville_agence"));
			return 0;
		}

		if ((document.getElementById("pays").value==0)) {
			alert(get_trad_champ("pays_agence"));
			return 0;
		}
	}else{
		// Deuxieme etape du form agence //
		if ((document.getElementById("nom_contact").value=="")) {
			alert(get_trad_champ("nom_contact"));
			return 0;
		}
		if ((document.getElementById("email_contact").value=="")) {
			alert(get_trad_champ("email_contact"));
			return 0;
		}

		//		if ((document.getElementById("passe_inscription").value!="" && (document.getElementById("passe_verif").value=="" || document.getElementById("nouveau_passe").value=="") )) {
		//			alert(get_trad_champ("passe"));
		//			return 0;
		//		}
		//
		//		if ((document.getElementById("passe_verif").value!="" || document.getElementById("nouveau_passe").value!="") && (document.getElementById("passe_inscription").value=="")) {
		//			alert(get_trad_champ("passe"));
		//			return 0;
		//		}

		if (document.getElementById("passe_verif").value != "" && (document.getElementById("passe_verif").value!=document.getElementById("nouveau_passe").value)) {
			alert(get_trad_champ("passe_not_equal"));
			return 0;
		}
		// Test passe
		var texte = document.getElementById("passe_inscription").value;
		var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
		if ( ! exp.test(texte) ){
			alert(get_trad_champ("caractere_interdit_passe"));
			return 0;
		}
	}
	document.getElementById("form_agence").submit();
}

function login_user(){

	var page = document.getElementById('page_login').value;

	var login = document.getElementById("login").value;
	var pass = document.getElementById("motdepasse").value;
	if(document.getElementById("body_login") && document.getElementById("body_login").value != '' &&
	 document.getElementById("body_password") && document.getElementById("body_password").value != ''
	){
	  login = document.getElementById("body_login").value;
	  pass = document.getElementById("body_password").value;
	}

	$.ajax({
		type: "GET",
		data: "login="+login+"&passe="+pass,
		url: abs_path+"ajax/ajax_login.php",
		success: function(msg){
			var tableau=msg.split('|');
			if(tableau[1] == "ko"){
				alert(get_trad_champ("mauvais_login"));
				document.getElementById("login").value="";
				document.getElementById("motdepasse").value="";
				if(document.getElementById("body_login")){
				  document.getElementById("body_login").value="";
  				document.getElementById("body_password").value="";
				}
			}else{

				//	 			document.getElementById('DivLogin').innerHTML = "<span class='login_nom'>"+tableau[1]+"</span>";
				//	 			document.getElementById('DivLogin').style.display='block';
				//	 			document.getElementById('DivLogout').style.display='block';
				//	 			document.getElementById('DivForm').style.display='none';
				window.location=page;
			}
		} });
}

function checkKey(evennement) {


	if (!evennement) var evennement = window.event;
	if (evennement)
	{
		if (evennement.keyCode) {

			code = evennement.keyCode;
		}
		else if (evennement.which) {

			code = evennement.which;
		}
		if (code == 13 && document.getElementById('login').value != "" && document.getElementById('motdepasse').value != "")
		{
			login_user();
		}
	}
}

function logout(page){
	$.ajax({
		type: "GET",
		data: "",
		url: abs_path+"ajax/ajax_logout.php",
		success: function(){
			//	 			var tab = msg.split('|');
			//	 			document.getElementById('DivLogin').style.display='none';
			//	 			document.getElementById('DivLogout').style.display='none';
			//	 			document.getElementById('DivForm').style.display='block';
			//	 			document.getElementById("login").value=tab[0];
			//	 			document.getElementById("motdepasse").value=tab[1];
			window.location=page;
		} });
}


function valid_form_compte_particulier(){

	if ((document.getElementById("nom").value=="")) {
		alert(get_trad_champ("nom"));
		return 0;
	}


	if ((document.getElementById("email").value=="")) {
		alert(get_trad_champ("email"));
		return 0;
	}

	if (! validemail("email")) {
		return 0;
	}


	if ((document.getElementById("passe_verif").value!=document.getElementById("nouveau_passe").value)) {
		alert(get_trad_champ("passe_not_equal"));
		return 0;
	}


	// Test passe
	var texte = document.getElementById("passe_verif").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_passe"));
		return 0;
	}


	document.getElementById("form_particulier").submit();
}

function valid_form_oubli_passe(){

	if (! validemail("email")) {
		return 0;
	}

	/*if (! validemail("email_suite")) {
	return 0;
	}*/

	if ((document.getElementById("email").value=="")) {
		alert(get_trad_champ("email"));
		return 0;
	}

	/*if ((document.getElementById("email_suite").value=="")) {
	alert(get_trad_champ("email_suite"));
	return 0;
	}*/

	/*if ((document.getElementById("email_suite").value!=document.getElementById("email").value)) {
	alert(get_trad_champ("email_not_equal"));
	return 0;
	}*/
	document.getElementById("form_oubli_passe").submit();
}


function load_quartier(){

//	document.getElementById("D_ville_S").style.display = 'none';
//	document.getElementById("D_ville_S").value = '';

	$.ajax({
		type: "GET",
		data: "id_ville="+document.getElementById('ville').value,
		url: abs_path+"ajax/ajax_quartier.php",
		success: function(msg){

			document.getElementById("div_quartier").options.length = 0;
			var tab = msg.split('|');

			if(tab[1] == "ko"){
				//document.getElementById("div_quartier_select").style.display='none';
			}else{
				var tab = msg.split('|');
				var lgn = tab.length;
				var values;
				for(var i=0;i<lgn;i++){

					values = tab[i].split(';');
					document.getElementById("div_quartier").options[i] = new Option(values[0],values[1]);
					//document.getElementById("div_quartier_select").style.display='block';
				}
			}

		} });
}






function valid_form_promoteur(etape){

	// Premiere etape du form agence //
	if(etape==1){
		if ((document.getElementById("nom_promoteur").value=="")) {
			alert(get_trad_champ("nom_promoteur"));
			return 0;
		}

		if ((document.getElementById("siret").value=="")) {
			alert(get_trad_champ("siret"));
			return 0;
		}

		if ((document.getElementById("adresse_promoteur").value=="")) {
			alert(get_trad_champ("adresse_promoteur"));
			return 0;
		}

		if ((document.getElementById("cp").value=="")) {
			alert(get_trad_champ("cp"));
			return 0;
		}
		if ((document.getElementById("ville").value=="")) {
			alert(get_trad_champ("ville_promoteur"));
			return 0;
		}

		if ((document.getElementById("pays").value==0)) {
			alert(get_trad_champ("pays_promoteur"));
			return 0;
		}



	}else{

		// Deuxieme etape du form agence //

		if ((document.getElementById("nom_contact").value=="")) {
			alert(get_trad_champ("nom_contact"));
			return 0;
		}
		if ((document.getElementById("email_contact").value=="")) {
			alert(get_trad_champ("email_contact"));
			return 0;
		}
		if ((document.getElementById("login_inscription").value=="")) {
			alert(get_trad_champ("login"));
			return 0;
		}


		// Test login
		var texte = document.getElementById("login_inscription").value;
		var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
		if ( ! exp.test(texte) ){
			alert(get_trad_champ("caractere_interdit_login"));
			return 0;
		}

		if ((document.getElementById("passe_inscription").value=="")) {
			alert(get_trad_champ("passe"));
			return 0;
		}
		if ((document.getElementById("passe_verif").value=="")) {
			alert(get_trad_champ("passe_verif"));
			return 0;
		}


		if ((document.getElementById("passe_verif").value!=document.getElementById("passe_inscription").value)) {
			alert(get_trad_champ("passe_not_equal"));
			return 0;
		}

		// Test passe
		var texte = document.getElementById("passe_inscription").value;
		var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
		if ( ! exp.test(texte) ){
			alert(get_trad_champ("caractere_interdit_passe"));
			return 0;
		}

		if ((document.getElementById("strcode").value=="")) {
			alert(get_trad_champ("strcode"));
			return 0;
		}
		if (document.getElementById("cgv").checked == false) {
			alert(get_trad_champ("cgv"));
			return 0;
		}

	}


	document.getElementById("form_promoteur").submit();
}


function valid_form_modif_annonce(etape,param){
	var erreur=0;
	if(etape == 3){

		var tab = param.split('|');
		var lgn = tab.length;
		for(var i=0;i<lgn;i++){

			if(erreur == 0)
			{
				var temp = tab[i].split(';');
				if(temp[1] == "select"){
					var select = document.getElementById(temp[0]);
					var index_select = select.options[select.selectedIndex].value;
					if ((index_select==0) && erreur==0) {
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
				}
				else if(temp[1] == "select_multiple"){

					var div = document.getElementById('div_'+temp[0]);
					var checkboxes = div.getElementsByTagName("input");
					var checked = false;
					for(var j = 0; j < checkboxes.length ; j++)
					{
						if(checkboxes[j].checked)
						{
							checked = true;
						}
					}

					if(!checked)
					{
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
				}
				else if(temp[1] == "text"){

					if(document.getElementById(temp[0]).value == "" && erreur==0){
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
					if(temp[2] != ""){
						if(temp[2] == "int"){

							var reg1=new RegExp(" ", "g");
							var reg2=new RegExp(",", "g");
							document.getElementById(temp[0]).value = document.getElementById(temp[0]).value.replace(reg1,"");
							document.getElementById(temp[0]).value = document.getElementById(temp[0]).value.replace(reg2,".");

							if(isNaN(document.getElementById(temp[0]).value) == true){
								alert(get_trad_champ("Nan",get_trad_champ(temp[0])));
								erreur=1;
							}
						}
					}

				}else if(temp[1] == "file"){

					if( (document.getElementById(temp[0]).value == "" && document.getElementById('H_'+temp[0]).value == "" ) && erreur==0){
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}

				}else if(temp[1] == "textarea"){
					if(document.getElementById(temp[0]).value == "" ||  document.getElementById(temp[0]).value == document.getElementById('H_'+temp[0]).value){
						var temp = get_trad_champ(temp[0]).split('_');
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
				}
			}
		}
	}
	if(erreur != 1)
	document.getElementById("form_annonce").submit();
}


function valid_form_annonce(etape,param,pays){
	var erreur=0;
	if(etape == 1){
		var select_type_offre = document.forms['form_annonce'].type_offre;
		var number_type_offre = select_type_offre.options[select_type_offre.selectedIndex].value;
		if ((number_type_offre==0)) {
			alert(get_trad_champ("type_offre"));
			return 0;
		}
		var select_type_hab = document.forms['form_annonce'].type_habitation;
		var number_type_hab  = select_type_hab.options[select_type_hab.selectedIndex].value;
		if ((number_type_hab==0)) {
			alert(get_trad_champ("type_hab"));
			return 0;
		}
		var select_ville = document.forms['form_annonce'].ville;
		var number_ville = select_ville.options[select_ville.selectedIndex].value;
		if (number_ville==0) {
			alert(get_trad_champ("ville"));
			return 0;
		}

		if ((document.getElementById("nom_rue").value=="")) {
			alert(get_trad_champ("nom_rue"));
			return 0;
		}
		if ((document.getElementById("reference").value=="")) {
			alert(get_trad_champ("reference"));
			return 0;
		}
		if ( ($("#type_commercial").children("option:selected").val() == 0) && number_type_hab == 13) {
			alert(get_trad_champ("type_commercial"));
			return 0;
		}

	}else if(etape == 3){

		var tab = param.split('|');
		var lgn = tab.length;
		for(var i=0;i<lgn;i++){

			if(erreur == 0)
			{

				var temp = tab[i].split(';');
				if(temp[1] == "select"){
					var select = document.getElementById(temp[0]);
					var index_select = select.options[select.selectedIndex].value;
					if ((index_select==0) && erreur==0) {
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
				}
				else if(temp[1] == "select_multiple"){

					var div = document.getElementById('div_'+temp[0]);
					var checkboxes = div.getElementsByTagName("input");
					var checked = false;
					for(var j = 0; j < checkboxes.length ; j++)
					{
						if(checkboxes[j].checked)
						{
							checked = true;
						}
					}

					if(!checked)
					{
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
				}


				else if(temp[1] == "text"){

					if(document.getElementById(temp[0]) && document.getElementById(temp[0]).value == "" && erreur==0){
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
					if(temp[2] != ""){
						if(temp[2] == "int"){

							var reg1=new RegExp(" ", "g");
							var reg2=new RegExp(",", "g");
							document.getElementById(temp[0]).value = document.getElementById(temp[0]).value.replace(reg1,"");
							document.getElementById(temp[0]).value = document.getElementById(temp[0]).value.replace(reg2,".");

							if(isNaN(document.getElementById(temp[0]).value) == true){

								alert(get_trad_champ("Nan",get_trad_champ(temp[0])));
								erreur=1;
							}
						}
					}






				}else if(temp[1] == "file"){
					//ROBO: commented out because on step 3, no file input is mandatory (if no picture is inserted, it is replaced bt CoC logo)
					/*if( (document.getElementById(temp[0]).value == "" && document.getElementById("H_"+temp[0]).value == "" ) && erreur==0){
					alert(get_trad_champ(temp[0]));
					erreur=1;
					}*/
				}else if(temp[1] == "textarea"){
					if(document.getElementById(temp[0]).value == "" ||  document.getElementById(temp[0]).value == document.getElementById('H_'+temp[0]).value){
						var temp = get_trad_champ(temp[0]).split('_');
						alert(get_trad_champ(temp[0]));
						erreur=1;
					}
				}
			}
		}
//		if(document.getElementById('mail')) {
//			if(!validemail("mail")) {
//				erreur = 1;
//			}
//		}
	}
	if(erreur != 1)
	document.getElementById("form_annonce").submit();
}


function zoom_vignette(img){
	if(G_stop_anim == 0){
		G_stop_anim=1;
		var tab = img.split("|");
		$("#largeImg").animate({opacity: "0"}, "fast")
		.attr({ src: tab[0], alt: tab[1] })
		.animate({opacity: "1"}, "fast", function(){
			G_stop_anim=0;
		});
	}
}

function scroll_right(contener,nb){
	if(nb>3){
		if(G_stop_anim == 0){
			if(G_nb_vignette < (nb-3)){
				G_nb_vignette++;
				G_stop_anim=1;
				$('#'+contener).animate({
					marginLeft: G_scroll-102}, "slow", function(){
						G_scroll -=102;
						G_stop_anim=0;
					});
			}
		}

	}
}

function scroll_left(contener,nb){
	if(nb>3){
		if(G_stop_anim == 0){
			if(G_nb_vignette > 0){
				G_nb_vignette--;
				G_stop_anim=1;
				$('#'+contener).animate({
					marginLeft: G_scroll+102}, "slow", function(){
						G_scroll +=102;
						G_stop_anim=0;
					});
			}
		}
	}
}

function scroll_top(contener,nb){
	if(G_stop_anim == 0){
		if(G_nb_vignette > 0){
			G_nb_vignette--;
			G_stop_anim=1;
			$('#'+contener).animate({
				marginTop: G_scroll+290}, "normal", function(){
					G_scroll +=290;
					G_stop_anim=0;
				});
		}
	}
}

function scroll_bottom(contener,nb){
	if(G_stop_anim == 0){

		if(G_nb_vignette < nb){
			G_nb_vignette++;
			G_stop_anim=1;
			$('#'+contener).animate({
				marginTop: G_scroll-290}, "normal", function(){
					G_scroll -=290;
					G_stop_anim=0;
				});
		}
	}
}


function scroll_search_top(contener){
	if(G_stop_anim == 0){
		if(G_nb_annonce > 0){
			G_nb_annonce--;
			G_stop_anim=1;

			var window = document.getElementById('gmap_volets_resultats-liste').offsetHeight;
			var div = document.getElementById(contener).offsetHeight;

			/*by default the scroll is the half of the window*/
			var scroll = window / 2;

			/*if the scroll is more than the rest of total scroll the we reduce the scroll */
			if(scroll + G_scroll > 0)
			{
				scroll = - G_scroll;
			}



			$('#'+contener).animate({
				marginTop: G_scroll+scroll}, "normal", function(){
					G_scroll +=scroll;
					G_stop_anim=0;
				});
		}
	}
}

function scroll_search_bottom(contener){
	if(G_stop_anim == 0){
		if(G_nb_annonce < G_max_annonce){
			G_nb_annonce++;
			G_stop_anim=1;

			var window = document.getElementById('gmap_volets_resultats-liste').offsetHeight;
			var div = document.getElementById(contener).offsetHeight;

			/*by default the scroll is the half of the window*/
			var scroll = window / 2;

			/*if the scroll is more than the difference between the div and the total scroll + 1 window the we reduce the scroll */
			if(scroll > div + G_scroll - window){
				scroll = div + G_scroll - window;
			}

			$('#'+contener).animate({
				marginTop: G_scroll-scroll}, "normal", function(){
					G_scroll -=scroll;
					G_stop_anim=0;
				});
		}
	}
}

function general_scroll_down(contener){
	if(G_stop_anim == 0){
		var window = $('.' + contener).parent().height();
		var div = $('.' + contener).height();
		/*by default the scroll is the half of the window*/
		var scroll = window / 3 * 2;

		/*if the scroll is more than the difference between the div and the total scroll + 1 window the we reduce the scroll */
		if(scroll > div + G_scroll - window)
		{
			scroll = div + G_scroll - window;
		}
		$('.'+contener).animate({
			marginTop: G_scroll-scroll}, "normal", function(){
				G_scroll -=scroll;
				G_stop_anim=0;
			});
	}
}

function general_scroll_up(contener){
	if(G_stop_anim == 0){
		var window = $('.' + contener).parent().height();
		var div = $('.' + contener).height();
		/*by default the scroll is the half of the window*/
		var scroll = window / 3 * 2;

		/*if the scroll is more than the difference between the div and the total scroll + 1 window the we reduce the scroll */
		if(scroll + G_scroll > 0){
			scroll = - G_scroll;
		}
		$('.'+contener).animate({
			marginTop: G_scroll+scroll}, "normal", function(){
				G_scroll +=scroll;
				G_stop_anim=0;
			});
	}
}

function general_scroll_right(contener){
	if(G_stop_anim == 0){
		var window = $('.' + contener).parent().width();
		var div = $('.' + contener).width();
		/*by default the scroll is the half of the window*/
		var scroll = window / 3 * 3;

		/*if the scroll is more than the difference between the div and the total scroll + 1 window the we reduce the scroll */
		if(scroll > div + G_scroll - window)
		{
			//scroll = div + G_scroll - window;
			scroll = (window / 3 * 3)/2;
			$('.' + contener).siblings(".scroll_right").addClass("invisible");
		} else {
			$('.' + contener).siblings(".scroll_left").removeClass("invisible");
		}
		$('.'+contener).animate({
			marginLeft: G_scroll-scroll}, "normal", function(){
				G_scroll -=scroll;
				G_stop_anim=0;
			});
	} else {
	}
}

function general_scroll_left(contener){
	if(G_stop_anim == 0){
		var window = $('.' + contener).parent().width();
		var div = $('.' + contener).width();
		/*by default the scroll is the half of the window*/
		var scroll = window / 3 * 3;

		/*if the scroll is more than the difference between the div and the total scroll + 1 window the we reduce the scroll */
		if(scroll + G_scroll > 0){
			//scroll = - G_scroll;
			scroll = (window / 3 * 3)/2;
			$('.' + contener).siblings(".scroll_left").addClass("invisible");
		} else {
			$('.' + contener).siblings(".scroll_right").removeClass("invisible");
		}
		$('.'+contener).animate({
			marginLeft: G_scroll+scroll}, "normal", function(){
				G_scroll +=scroll;
				G_stop_anim=0;
			});
	}
}


function scroll_search_detail_top(contener){
	if(G_stop_anim == 0){
		if(G_nb_search_detail > 0){
			G_nb_search_detail--;
			G_stop_anim=1;
			$('#'+contener).animate({
				marginTop: G_scroll_detail+85}, "normal", function(){
					G_scroll_detail +=85;

					G_stop_anim=0;
				});
		}
	}
}

function scroll_search_detail_bottom(contener){
	if(G_stop_anim == 0){
		if(G_nb_search_detail < G_max_search_detail){
			G_nb_search_detail++;
			G_stop_anim=1;
			$('#'+contener).animate({
				marginTop: G_scroll_detail-85}, "normal", function(){
					G_scroll_detail -=85;

					G_stop_anim=0;
				});
		}
	}
}


function Show_div(obj){
	document.getElementById('Div_'+obj).style.display='block';
	document.getElementById(obj+'_txt').style.display='none';
}

function Show_div_file(obj,num){
	document.getElementById('Div_'+obj).style.display='block';
	document.getElementById(obj+'_txt').style.display='none';
	if( parseInt(num) > 0){
		var tab = obj.split('_');
		document.getElementById(tab[0]+'_'+num+'_txt').style.display='block';
	}


}

function Show_simple_div(obj){
	document.getElementById(obj).style.display='none';
}

function Show_div_ville(obj,obj2,num){
	document.getElementById(obj).style.display='block';
	document.getElementById(obj2).style.display='none';
	if(num == "1"){
		document.getElementById('div_quartier_select').style.display='none';
	}else{

	}
}

function changeTown (town)
{
	document.getElementById("checkbox_ville").style.display='none';
	document.getElementById('ville').value = town;

	if(document.getElementById('geo_place') != null)
	{
		document.getElementById('geo_place').value = town;
		get_geo_map(false);
	}

}

function changeTownCatalog (town)
{
	document.getElementById("checkbox_ville_catalog").style.display='none';
	document.getElementById('city').value = town;

	if(document.getElementById('geo_place') != null)
	{
		document.getElementById('geo_place').value = town;
		get_geo_map(false);
	}

}

function changeTown_multi (town)
{
	document.getElementById("checkbox_ville").style.display='none';
	document.getElementById('ville').value = town;
	//document.getElementById("etat_bien").style.visibility='visible';

	if(document.getElementById('geo_place') != null)
	{
		document.getElementById('geo_place').value = town;
		get_geo_map(false);
	}

}

function load_villes_multi(){

	$.ajax({
		type: "GET",
		data: "id_ville="+document.getElementById('ville').value+"&univers="+document.getElementById('univers').value,
		url: abs_path+"ajax/ajax_villes.php",
		success: function(msg){

			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				document.getElementById("checkbox_ville").style.display='none';
			}
			else
			{

				document.getElementById("checkbox_ville").style.display='block';
				//document.getElementById('etat_bien').style.visibility = 'hidden';
				var lgn = tab.length;
				var inner_html = "";
				for(var i=1;i<lgn;i++){
					inner_html += "<a href=\"javascript:void(0);\" onclick=\"changeTown_multi(\'" + tab[i] + "\');\">" + tab[i] + "</a><br />";
				}
				document.getElementById("checkbox_ville-inner").innerHTML = inner_html;
			}
		}


	});
}

function load_villes(){

	$.ajax({
		type: "GET",
		data: "id_ville="+document.getElementById('ville').value+"&univers="+document.getElementById('univers').value,
		url: abs_path+"ajax/ajax_villes.php",
		success: function(msg){

			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				document.getElementById("checkbox_ville").style.display='none';
			}
			else
			{

				document.getElementById("checkbox_ville").style.display='block';
				var lgn = tab.length;
				var inner_html = "";
				for(var i=1;i<lgn;i++){
					inner_html += "<a href=\"javascript:void(0);\" onclick=\"changeTown(\'" + tab[i] + "\');\">" + tab[i] + "</a><br />";
				}
				document.getElementById("checkbox_ville-inner").innerHTML = inner_html;
			}
		}


	});
}

function load_villes_catalog(){
	$.ajax({
		type: "GET",
		data: "city="+document.getElementById('city').value,
		url: abs_path+"ajax/ajax_villes_catalog.php",
		success: function(msg){
			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				document.getElementById("checkbox_ville_catalog").style.display='none';
			}
			else
			{
				document.getElementById("checkbox_ville_catalog").style.display='block';
				var lgn = tab.length;
				var inner_html = "";
				for(var i=1;i<lgn;i++){
					inner_html += "<a href=\"javascript:void(0);\" onclick=\"changeTownCatalog(\'" + tab[i] + "\');\">" + tab[i] + "</a><br />";
				}
				document.getElementById("checkbox_ville-inner").innerHTML = inner_html;
			}
		},
		error: function(msg){
		}


	});
}

function load_villes_city_map(){
	$.ajax({
		type: "GET",
		data: "city="+document.getElementById('city').value,
		url: abs_path+"ajax/ajax_villes_city_map.php",
		success: function(msg){
			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				document.getElementById("checkbox_ville_catalog").style.display='none';
			}
			else
			{
				document.getElementById("checkbox_ville_catalog").style.display='block';
				var lgn = tab.length;
				var inner_html = "";
				for(var i=1;i<lgn;i++){
					inner_html += "<a href=\"javascript:void(0);\" onclick=\"changeTownCatalog(\'" + tab[i] + "\');\">" + tab[i] + "</a><br />";
				}
				document.getElementById("checkbox_ville-inner").innerHTML = inner_html;
			}
		},
		error: function(msg){
		}


	});
}

// verifie la validite de la recherche
function valideSearch()
{
	var div = document.getElementById("checkbox_type");
	var tab = div.getElementsByTagName("Input");
	for (i=0; i<tab.length; i++) {

		if(tab[i].checked) {

			document.form_recherche_simple.submit();
			return true;
		}
	}

	alert(get_trad_champ("type_bien"));
	return false;
}
function parse_loaded_search() {

	GEvent.addListener(map, "dragstart", function() {
		hideInfo();
	});
	
	GEvent.clearListeners(map,"moveend");
	GEvent.clearListeners(map,"zoomend");
	
	for(j in G_offers) {
		map.removeOverlay(G_offers[j]);
	}
	G_offers = null;
	G_offers = new Array();
	//document.getElementById("loading").style.display = "none";

	if(($("#search_status").val() == "ko") && (!document.getElementById("search_within_map"))) //nothing found and we want to go
	{
		country = "Slovensko"; //tab[2]
		geocoder = new GClientGeocoder();
		search_geocode(country,6,"Country Not Found");
		if($('input#page').size() != 0) { //if the page might be the problem, reload with no page set
			$('input#page').remove();
			load_search();
		}
	}
	else
	{
		var min_lat = -1;
		var min_long = -1;
		var max_lat = -1;
		var max_long = -1;
		var points = new Array();
		var nb_content = new Array();
		var left_col  = "";

		$("#result_list dl" ).each(
			// for each row, run this, intIndex being the pointer to current element
			function( intIndex ){
				var gps = $(this).children("dd:first-child").children(".gps_coords").val().split("_");
				var top_offer = $(this).hasClass("top-offer");
				var lat = parseFloat(gps[0]);
				var lon = parseFloat(gps[1]);

				if(lat < min_lat || min_lat == -1)
				{
					min_lat = lat;
				}
				if(lat > max_lat || max_lat == -1)
				{
					max_lat = lat;
				}
				if(lon < min_long || min_long == -1)
				{
					min_long = lon;
				}
				if(lon > max_long || max_long == -1)
				{
					max_long = lon;
				}

				var html = '<li><dl onclick="location.href = \''+$(this).children("dt").children("a").attr("href") + '\'">' + $(this).html() + '</dl></li>';
				var index = lat + "_" + lon;

				if(G_offers[index] != null) {
					G_offers[index]["html"] += html;
					G_offers[index]["count"]++;
					if(!G_offers[index]["top_offer"]) { G_offers[index]["top_offer"] = top_offer; }
				} else {
					G_offers[index] = new Array();
					G_offers[index]["html"] = html;
					G_offers[index]["count"] = 1;
					G_offers[index]["top_offer"] = top_offer;
				}
			}
		);

		if(!document.getElementById("search_within_map") && !document.getElementById('map_update_disable')) {
			center_google_map(min_lat,min_long,max_lat,max_long);
		}
		$('#map_update_disable').remove();

		if(($("#main_search_form > input#search_within_map").size() != 0)) {
			$(".search_within_map").addClass("active");

			var centerLat = $("#main_search_form > input#centerLat").val();
			var centerLng = $("#main_search_form > input#centerLng").val();
			var zoom_level = $("#main_search_form > input#zoom_level").val();

			map.setCenter(new GLatLng(centerLat, centerLng), parseInt(zoom_level));

			GEvent.addListener(map,"moveend", function(point) { update_input_map_coords(); restart_form_timer(); });
			GEvent.addListener(map,"zoomend", function(point) { update_input_map_coords(); restart_form_timer(); });
			$("#main_search_form > input#first_load").remove();
		}


		for (i in G_offers) {
			var gps = i.split('_');
			var type = "0";
			if(G_offers[i]["top_offer"]) {
				type = "1";
			}
			create_google_point(gps[0],gps[1],G_offers[i]["html"],G_offers[i]["count"],type);
		}
	}
}

function load_search(){
	//	var limit = 20;
	hideInfo();

	$("#main_search_form > input#first_load").remove(); //remove first load flag, if present

	$(".loader").show();
	
	var call_data = "";

	$("#main_search_form > input").each(function(i) {
		call_data = call_data + "&" + $(this).attr("id") + "=" + $(this).val();
	});
	
	if(document.getElementById('map_only_seach')){
	  refreshMapSearch();
	  $.ajax({
		type: "GET",
		data: "",
		url: abs_path+"ajax/ajax_get_search_phrases.php",
		success: function(msg) {
			$("#search_phrases").html(msg);
			$("#search_phrases > span").not(".search_phrases_noclick").bind("click",click_search_phrase);
			refresh_AS(); //refreshes Advanced search
		}

	});
	  
	  
	  return false;
	} else {
	  scroll(0,0); // go to top of the page
	}

	//alert(call_data);

	$.ajax({
		type: "GET",
		data: call_data,
		url: abs_path+"ajax/ajax_search.php",
		success: function(msg) {
			chunks = msg.split("#|#");
			$(".results_num").html(chunks[0]);

			if(chunks[0] == 0) { // set search status field, so parse_loaded_search can proceed.
				$("#search_status").val("ko");
				$(".th_list").hide();
				//$(".pagination-selectbox").hide();
				$('.results_control_wrap').hide();
			} else {
				$("#search_status").val("ok");
				$(".th_list").show();
				//$(".pagination-selectbox").show();
				$('.results_control_wrap').show();
			}

			$("#result_list dl").unbind('mouseenter',hover_offer_on);
			$("#result_list dl").unbind('mouseleave',hover_offer_off);
			$("#result_list").html(chunks[1]).fadeIn();
			$("#result_list dl").bind('mouseenter',hover_offer_on);
			$("#result_list dl").bind('mouseleave',hover_offer_off);

			var search_phrases = chunks[2].replace(/^\s+|\s+$/g, '')
			if(search_phrases != "") {
				$('#search_phrases').add('#search_phrases-bottom').show();
				$("#search_phrases").html(chunks[2]);
				$("#search_phrases > span").not(".search_phrases_noclick").bind("click",click_search_phrase);
			} else {
				$('#search_phrases').add('#search_phrases-bottom').hide();
			}


			$(".search_results-heading").html(chunks[3]);
			//$("body").append(chunks[5]);
			$(".pagination-line a").unbind("click",click_page);
			$(".pagination-line").empty().html(chunks[4]);
			$(".pagination-line a").not(".off").not(".page-current").bind("click",click_page);

			$('#search_phrases > a.offers_rss').attr("href",chunks[5]);

			refresh_AS(); //refreshes Advanced search
			parse_loaded_search(); //and shows results on the map
			$(".loader").hide();
		},
		error: function() {
			$(".loader").hide();
		}
	});


}

function load_publicite(){

//	document.getElementById('gmap').style.visibility = 'hidden';
//	document.getElementById('control_haut').style.visibility = 'hidden';
//	document.getElementById('control_bas').style.visibility = 'hidden';
//	document.getElementById('control_droite').style.visibility = 'hidden';
//	document.getElementById('control_gauche').style.visibility = 'hidden';
//	document.getElementById('publicite').style.display = 'block';
}

function unload_publicite(){


//	document.getElementById('publicite').style.display = 'none';
//	document.getElementById('control_haut').style.visibility = 'visible';
//	document.getElementById('control_droite').style.visibility = 'visible';
//	document.getElementById('control_gauche').style.visibility = 'visible';
//	document.getElementById('control_bas').style.visibility = 'visible';
//	document.getElementById('gmap').style.visibility = 'visible';

}


function load_selection(){
  if(map_offers && reload_offers){
    map.closeInfoWindow();
    var bounds = map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var link = "&top="+ne.lat()+"&right="+ne.lng()+"&bottom="+sw.lat()+"&left="+sw.lng()+"";
    link = link + "&is_commercial=" + $("#is_commercial").val();
    link = link + "&offer_type=" + document.getElementById('map_offer_type').value;
    link = link + "&price_max=" + $("#map_price_max").val();
    link = link + "&Rub=" + $("input[name=Rub]").val();
  	$.ajax({
  		type: "GET",
  		data: "&univers="+document.getElementById('univers').value + link,
  		url: abs_path+"ajax/ajax_map_cities.php",
  		success: function(msg){
  		  if(!map_offers){
  		    return false;
  		  }
  		  try{
  			 map.clearOverlays();
  		  } catch(err){
          map.closeInfoWindow();
  		  }

  		  GEvent.addListener(map, "dragstart", function() {
		    		hideInfo();
		  	});

  			$("#offer_results").html("");
  			var tab = msg.split('|');
  			if(tab[1] == "ko")
  			{
  				document.getElementById("offer_results").innerHTML = "<strong>"+tab[2]+"</strong>";
  				$("#result_page_redirect span").html("0");
  				$("#result_page_redirect").fadeOut();
  			}
  			else
  			{
  				var left_col = "";
  				var points = new Array();
  				var nb_content = new Array();
  				var top_offers = new Array();
  				var count = 0;
  				var link = "";
  				var count_list = tab.length-1;

  				for(var i = 1; i < tab.length; i++)
  				{
  					var point = tab[i].split('##');

  					point[2] = "<li>"+point[2]+"</li>"

  					var latlng = point[1] + "_" + point[0];

  					if((top_offers[latlng] == null) || top_offers[latlng] == 0) {
  						top_offers[latlng] = point[5];
  					}
  					if(points[latlng] != null)
  					{
  						points[latlng] += point[2];
  						nb_content[latlng]++;
  					}
  					else
  					{
  						points[latlng] = point[2];
  						nb_content[latlng] = 1;
  					}

  					left_col += point[3];
  					count = point[6];
  					link = point[7];

  				}
  				//center_google_map(min_lat,min_long,max_lat,max_long);
//  				alert(points);
  				for ( i in points) {
  					var point = i.split('_');
//  					alert(top_offers[i]);
  					create_google_point(point[0],point[1],points[i],nb_content[i],top_offers[i]);
  				}

  				if(count_list > 50) {
  					count_list = 50;
  				}

  				$("#result_page_redirect span:last").html(count);
  				$("#result_page_redirect span:first").html(count_list);

  				if(left_col.length > 0)
  				{
  				  $("#offer_results").html(left_col);
  //					document.getElementById("offer_results").innerHTML = left_col;
  				}

  				if($("#is_commercial").val()=='1') { var prop_type = 13; } else { prop_type = 1; }

  				link += "&maxLat="+ne.lat()+"&maxLng="+ne.lng()+"&minLat="+sw.lat()+"&minLng="+sw.lng()+'&property_type='+prop_type+'&offer_type='+$("#map_offer_type").val();
  				link += '&centerLat='+map.getCenter().lat()+'&centerLng='+map.getCenter().lng()+'&zoom_level='+(map.getZoom()-1)+'&search_within_map=1&first_search=1';

  				if(prop_type == 13) {
  					link += '&commercial_type=1';
  				}

  				$("#result_page_redirect a").attr("href",link);

  				$("#result_page_redirect").fadeIn("medium");
  			}
  		}

  	});
  }
  load_services_home();
}


function load_detail(id){
  var id = "";
  if(document.getElementById('id')){
    id = document.getElementById('id').value;
  }
  var pid = "";
  if(document.getElementById('project_id')){
    pid = document.getElementById('project_id').value;
  }
	$.ajax({
		type: "GET",
		data: "annonce="+id+"&project_id="+pid,
		url: abs_path+"ajax/ajax_detail.php",
		success: function(msg){

			//Charge l'annonce courante sur la map
			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				if(tab[2] != "")
				{
					country = tab[2];
					geocoder = new GClientGeocoder();
					search_geocode(country,6,"Country Not Found");

				}
				else
				{
					center_google_map(0,0,15);
				}
			}
			else
			{
			  var point = tab[1].split('##');

      	var point_location = new GLatLng(point[1], point[0]);
      	var marker = createSimpleMarker(point_location);
      	map.setCenter(point_location);
      	map.setZoom(15);
      	map.addOverlay(marker);

      	//We save the point to be able to delete the overlays of the map except this point
      	detail_point = marker;

			}

		}

	});
}

function load_detail_agency(){

	$.ajax({
		type: "GET",
		data: "annonce="+document.getElementById('id').value,
		url: abs_path+"ajax/ajax_detail_agency.php",
		success: function(msg){

			//Charge l'annonce courante sur la map
			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				center_google_map(0,0,15);
			}
			else
			{
				var point = tab[1].split('##');
				var point_location = new GLatLng(point[1], point[0]);
		      	var marker = createSimpleMarker(point_location,point[2]);
		      	map.setCenter(point_location);
		      	map.setZoom(15);
		      	map.addOverlay(marker);
			}

		}

	});
}


function city_map_goto(){
	var location = document.getElementById("city").value + " " +document.getElementById("street").value+", Slovensko";
	geocoder = new GClientGeocoder();
	search_geocode(location, 16, "Place not found");
	load_services_city_map();
}

function map_search_goto(){
	var location = document.getElementById("ville").value + ", Slovensko";
	geocoder = new GClientGeocoder();
	search_geocode(location, 13, "Place not found");
}

function manage_service(id_type_service)
{
  var reg = new RegExp("[,]+", "g");
	var list = document.getElementById("service_types").value.split(reg);
  var check = true;
	for(var i = 0; i < list.length; i++)
	{
		if(list[i] == id_type_service)
		{
			check = false;
			break;
		}
	}

	if(document.getElementById("service_types"))
	{
		if(check)
		{
			if(document.getElementById("service_types").value != "")
			{
				document.getElementById("service_types").value += ",";
			}
			document.getElementById("service_types").value += id_type_service;
//			load_service(id_type_service);
		}
		else
		{
			var new_list  = "";
			var reg = new RegExp("[,]+", "g");
			var list = document.getElementById("service_types").value.split(reg);

			for(var i = 0; i < list.length; i++)
			{
				if(list[i] != id_type_service)
				{
					if(new_list != "")
					{
						new_list += ",";
					}
					new_list += list[i];
				}
			}

			document.getElementById("service_types").value = new_list;
//			unload_service(id_type_service);
		}
	}
  load_services_home();
	//load_services();
}

function load_services()
{
	//We remove all the overlays of the map except the offer point
	//map.clearOverlays();
	//map.addOverlay(detail_point);

	//We get all the service types checked
	if(map_services) {
  	//alert('preslo');
  	if(document.getElementById("service_types"))
  	{
  		var list = document.getElementById("service_types").value;
  		var news_services = '';
  		if(document.getElementById("news_services")){
  			var news_services = document.getElementById("news_services").value;
  		}

  		//We get the map limits
  		var map_limits = map.getBounds();
  		var sw = map_limits.getSouthWest();
  		var ne = map_limits.getNorthEast();

  		var minLat = ne.lat() < sw.lat() ? ne.lat() : sw.lat();
  		var maxLat = ne.lat() < sw.lat() ? sw.lat() : ne.lat();
  		var minLng = ne.lng() < sw.lng() ? ne.lng() : sw.lng();
  		var maxLng = ne.lng() < sw.lng() ? sw.lng() : ne.lng();

  		//We load all the services information on the map
  		$.ajax({

  			type: "GET",
  			data: "types="+document.getElementById("service_types").value+"&minLat="+minLat+"&maxLat="+maxLat+"&minLng="+minLng+"&maxLng="+maxLng+"&news_services="+news_services,
  			url: abs_path+"ajax/ajax_load_services.php",
  			success: function(msg){
  				map.clearOverlays();
  				map.addOverlay(detail_point);
  				var tab = msg.split('|');

  				if(tab[1] != "ko")
  				{
  					for(var i = 1; i < tab.length; i++)
  					{

  						var point = tab[i].split('##');
  						if(point.length == 6)
  						{
  							create_google_service(point[0],point[1],point[2],point[3],point[4],point[5]);
  						}
  					}

  				}
  			}

  		});
  	}
	}
}

function load_services_city_map()
{
	//We get all the service types checked
	//	alert('cm');
	if(document.getElementById("service_types"))
	{
		var list = document.getElementById("service_types").value;
		var news_services = document.getElementById("news_services").value;
		//We get the map limits
		var map_limits = map.getBounds();
		//		if(map_limits){
		var sw = map_limits.getSouthWest();
		var ne = map_limits.getNorthEast();

		var minLat = ne.lat() < sw.lat() ? ne.lat() : sw.lat();
		var maxLat = ne.lat() < sw.lat() ? sw.lat() : ne.lat();
		var minLng = ne.lng() < sw.lng() ? ne.lng() : sw.lng();
		var maxLng = ne.lng() < sw.lng() ? sw.lng() : ne.lng();
		//We load all the services information on the map
		$.ajax({
			type: "GET",
			data: "types="+document.getElementById("service_types").value+"&minLat="+minLat+"&maxLat="+maxLat+"&minLng="+minLng+"&maxLng="+maxLng+"&news_services="+news_services,
			url: abs_path+"ajax/ajax_load_services.php",
			success: function(msg){
				//    	map.addOverlay(detail_point);
				var tab = msg.split('|');
				if(tab[1] != "ko")
				{
					//  	 		  map.clearOverlays();
					unload_services();
					for(var i = 1; i < tab.length; i++)
					{
						var point = tab[i].split('##');
						if(point.length == 6)
						{
							create_google_service(point[0],point[1],point[2],point[3],point[4],point[5]);
						}
					}
				}
			}
		});
	}
}

function load_realestate()
{
	if(map_rea) {

		var map_limits = map.getBounds();
		var sw = map_limits.getSouthWest();
		var ne = map_limits.getNorthEast();

		var minLat = ne.lat() < sw.lat() ? ne.lat() : sw.lat();
		var maxLat = ne.lat() < sw.lat() ? sw.lat() : ne.lat();
		var minLng = ne.lng() < sw.lng() ? ne.lng() : sw.lng();
		var maxLng = ne.lng() < sw.lng() ? sw.lng() : ne.lng();

			//We load all the services information on the map
			$.ajax({

				type: "GET",
				data: "minLat="+minLat+"&maxLat="+maxLat+"&minLng="+minLng+"&maxLng="+maxLng,
				url: abs_path+"ajax/ajax_load_rea.php",
				success: function(msg){
				  map.clearOverlays();
					var tab = msg.split('|');
	        var html = "";
					if(tab[1] != "ko"){
//					  var html = "";
						for(var i = 1; i < tab.length; i++){
							var point = tab[i].split('##');
							create_google_agency(point[2],point[1], "<li>"+point[0]+"</li>", 1,point[3]);
							html += point[0];
						}
					} else {
					  html = "<p>"+get_trad_champ("no_rk_in_area")+"</p>";
					}
					$("#services_results").html(html);
				}
		});
	}
}

function load_services_home()
{
	if(map_services || document.getElementById('offer_id')) {

//		  var bounds = map.getBounds();
//		  var sw = bounds.getSouthWest();
//		  var ne = bounds.getNorthEast();
			//We remove all the overlays of the map except the offer point
			//map.clearOverlays();
			//map.addOverlay(detail_point);

			//We get all the service types checked
			if(document.getElementById("service_types"))
			{
				var list = document.getElementById("service_types").value;
				//We get the map limits
				var map_limits = map.getBounds();
				var sw = map_limits.getSouthWest();
				var ne = map_limits.getNorthEast();

				var minLat = ne.lat() < sw.lat() ? ne.lat() : sw.lat();
				var maxLat = ne.lat() < sw.lat() ? sw.lat() : ne.lat();
				var minLng = ne.lng() < sw.lng() ? ne.lng() : sw.lng();
				var maxLng = ne.lng() < sw.lng() ? sw.lng() : ne.lng();

				//We load all the services information on the map
				$.ajax({

					type: "GET",
					data: "types="+document.getElementById("service_types").value+"&minLat="+minLat+"&maxLat="+maxLat+"&minLng="+minLng+"&maxLng="+maxLng,
					url: abs_path+"ajax/ajax_load_services.php",
					success: function(msg){
						var tab = msg.split('|');
						map.clearOverlays();
						if(detail_point){
						  map.addOverlay(detail_point);
						}
						if(tab[1] != "ko")
						{
						  var html = "";
							for(var i = 1; i < tab.length; i++)
							{

								var point = tab[i].split('##');
								if(point.length == 6)
								{
									create_google_service("<li>"+point[0]+"</li>",point[1],point[2],point[3],point[4],point[5]);
									html += point[0];
								}
							}
//		          $("#services_results").html(html);
						}
						if(document.getElementById('GM_type') && document.getElementById('GM_type').value == 'favorites'){
						  loadFavorites();
						}
					}

				});
			}
	}
}

function load_service(id_type_service)
{
	//We get all the service types checked
	if(document.getElementById("service_types"))
	{
		var list = document.getElementById("service_types").value;

		//We get the map limits
		var map_limits = map.getBounds();
		var sw = map_limits.getSouthWest();
		var ne = map_limits.getNorthEast();

		var minLat = ne.lat() < sw.lat() ? ne.lat() : sw.lat();
		var maxLat = ne.lat() < sw.lat() ? sw.lat() : ne.lat();
		var minLng = ne.lng() < sw.lng() ? ne.lng() : sw.lng();
		var maxLng = ne.lng() < sw.lng() ? sw.lng() : ne.lng();

		//We load all the services information on the map
		$.ajax({

			type: "GET",
			data: "types="+id_type_service+"&minLat="+minLat+"&maxLat="+maxLat+"&minLng="+minLng+"&maxLng="+maxLng,
			url: abs_path+"ajax/ajax_load_services.php",
			success: function(msg){

				var tab = msg.split('|');

				if(tab[1] != "ko")
				{
					for(var i = 1; i < tab.length; i++)
					{

						var point = tab[i].split('##');
						if(point.length == 6)
						{
							create_google_service(point[0],point[1],point[2],point[3],point[4],point[5]);
						}
					}

				}
			}

		});
	}
}

function load_one_service(id_service)
{
	if(document.getElementById("news_services").value != "")
	{
		document.getElementById("news_services").value += ",";
	}
	document.getElementById("news_services").value += id_service;

	//      load_services_city_map();

	//We load all the services information on the map
	$.ajax({

		type: "GET",
		data: "id="+id_service,
		url: abs_path+"ajax/ajax_load_one_service.php",
		success: function(msg){

			var tab = msg.split('|');

			if(tab[1] != "ko")
			{
				for(var i = 1; i < tab.length; i++)
				{

					var point = tab[i].split('##');
					if(point.length == 6)
					{
						create_google_service(point[0],point[1],point[2],point[3],point[4],point[5]);
						map.setCenter(new GLatLng(point[3],point[4]), 16);
					}
				}

			}
		}

	});
}

function unload_service(id_type_service)
{
	//We get all the service types checked
	if(services[id_type_service])
	{
		var list = services[id_type_service];

		for(var i = 0; i < list.length; i++)
		{
			map.removeOverlay(list[i]);
		}
	}
}

function unload_services()
{
	//We get all the service types checked
	for(var j in services){
		if(services[j])
		{
			var list = services[j];

			for(var i = 0; i < list.length; i++)
			{
				map.removeOverlay(list[i]);
			}
		}
	}
}


function Hide_div_modif_annonce(obj){


	document.getElementById('Div_'+obj).style.display='none';
	document.getElementById(obj+'_txt').style.display='block';

	document.getElementById('H_'+obj).value= "";
	document.getElementById('I_'+obj).innerHTML = "";
}

function display_password()
{
	document.getElementById('motdepasse').style.display = 'block';
	document.getElementById('motdepasse').focus();
	document.getElementById('motdepasse').value = '';
}

function hide_password()
{
	if(document.getElementById('motdepasse').value == '')
	{
		document.getElementById('motdepasse').style.display = 'none';
		document.getElementById('init_motdepasse').style.display = 'block';
	}
}

function alert_puis_redirect(message,url){

	if(confirm(get_trad_champ(message))){
		window.location=url;
	}
}

function alert_puis_redirect_form(message,form){

	if(confirm(get_trad_champ(message))){
		document.getElementById(form).submit();
	}
}

function Form_ajout_credit(form){

	var credit_user = parseFloat(document.getElementById('nb_credit_user').value);
	var credit_TA 	= parseFloat(document.getElementById('nb_credit').value);
	var credit_clic = parseFloat(document.getElementById('prix_clic').value);
	var credit_maximum = parseFloat(document.getElementById('maximum').value);
	var erreur 		= 0;

//	var i = isNaN(credit_TA);
//	if(i == 1 && erreur==0){
//		alert(get_trad_champ("nombre_credit_mauvais"));
//		erreur=1;
//	}
//
//	i = isNaN(credit_clic);
//	if(i == 1 && erreur==0){
//		alert(get_trad_champ("CreditClic_negatif"));
//		erreur=1;
//	}
//
//
//
//	if(credit_TA > credit_user && erreur==0){
//		erreur=1;
//		alert(get_trad_champ('CreditTA_sup_CreditUser'));
//
//	}
//
//	if(credit_TA > credit_maximum && erreur==0){
//		erreur=1;
//		alert(get_trad_champ('CreditTA_sup_CreditMaximum'));
//
//	}

//	if(credit_TA < 0 && erreur==0){
//		erreur=1;
//		alert(get_trad_champ('CreditTA_negatif'));
//	}




//	if(parseFloat(credit_TA) < parseFloat(credit_clic) && erreur==0){
//		erreur=1;
//		alert(get_trad_champ('CreditTA_inf_CreditClic'));
//	}

//	if(credit_clic < 0 && erreur==0){
//		erreur=1;
//		alert(get_trad_champ('CreditClic_negatif'));
//	}

	if(erreur==0){

		document.getElementById(form).submit();
	}



}


//SCRIPTS POUR LA REPONSE A UNE ANNONCE
function valider_reponse_annonce()
{
	var valid_form = true;

	if(document.getElementById("lastname").value.length == 0)
	{
		document.getElementById("ec1").style.display = "block";
		valid_form = false;
	}
	else
	{
		document.getElementById("ec1").style.display = "none";
	}

	if(document.getElementById("message").value.length == 0)
	{
		document.getElementById("ec5").style.display = "block";
		valid_form = false;
	}
	else
	{
		document.getElementById("ec5").style.display = "none";
	}

	if(document.getElementById("email").value.length != 0 && !validemail("email"))
	{
		document.getElementById("ec4").style.display = "block";
		valid_form = false;
	}
	else
	{
		document.getElementById("ec4").style.display = "none";
	}

	if(document.getElementById("email").value.length == 0 && document.getElementById("phone").value.length == 0)
	{
		document.getElementById("ec2").style.display = "block";
		document.getElementById("ec3").style.display = "block";
		valid_form = false;
	}
	else
	{
		document.getElementById("ec2").style.display = "none";
		document.getElementById("ec3").style.display = "none";
	}

	if(valid_form)
	{
		document.getElementById("validation").value = 1;
		document.form_reponse_annonce.submit();
	}
	else
	{
		return false;
	}
}

function cache_erreur_serveur()
{
	document.getElementById('erreur_serveur').style.display = "none";
}


function Show_googlemap(obj){
	if(document.getElementById(obj).style.display == "none"){
		document.getElementById(obj).style.display ='block';
		document.getElementById(obj).style.visibility ='visible';
	}else{
		document.getElementById(obj).style.display ='none';
	}
}

function afficher_form()
{
	document.getElementById('div_form_conseil').style.display = 'block';
	document.getElementById('lien_affiche_form').style.display = 'none';

}


function valid_form_envoi_ami(){


	if ((document.getElementById("nom").value=="")) {
		alert(get_trad_champ("prenom"));
		return 0;
	}

	if (! validemail("email")) {
		return 0;
	}


	if (! validemail("email_ami")) {
		return 0;
	}

	document.getElementById("form_envoi_ami").submit();
}


function valide_alert_mail()
{
	var alert_name = document.getElementById("alert_name").value;

	if  (alert_name == "" )
	{
		alert(get_trad_champ("alert_name_obligatoire"));
		return false;
	}


	var ids = "";

	var div = document.getElementById("checkbox_type");
	var tab = div.getElementsByTagName("Input");

	for (i=0; i<tab.length; i++) {
		if(tab[i].checked) {
			ids += tab[i].value + ",";
		}
	}

	ids = ids.substr(0,ids.lastIndexOf(','));

	if (ids != "")
	{
		document.getElementById("type_bien").value = ids;
	}
	else
	{
		alert(get_trad_champ("type_bien"));
		return false;
	}

	if (document.getElementById('select_type_offre').value == "-1")
	{
		alert(get_trad_champ("type_offre"));
		return false;
	}
	else
	{
		document.getElementById("type_offre").value = document.getElementById('select_type_offre').value;
	}


	document.form_create_agent.envoi.value = "1";
	document.form_create_agent.submit();
	//return true;

}

function select_univers(param,adresse)
{

	var url = adresse + '&univers=' + param
	//alert(url);
	document.getElementById('postback').value = "1";
	document.getElementById('univers').value = param;


	if (document.getElementById('alert_name').value != "" )
	{
		url = url + "&an=" + document.getElementById('alert_name').value;
	}

	url += "&postback=1";

	var ids = "";
	var div = document.getElementById("type_bien_span");
	var tab = div.getElementsByTagName("input");


	for (i=0; i<tab.length; i++) {

		if(tab[i].checked) {
			ids += tab[i].value + ",";
		}
	}

	ids = ids.substr(0,ids.lastIndexOf(','));

	//alert(document.getElementById('nb_piece1').className);

	var idp = "";

	for ( i = 1 ; i <= 5 ; i++ )
	{
		if (document.getElementById('nb_piece' + i + '').className == "pce_bg_etat_on")
		{
			//alert(i + ' = ' + document.getElementById('nb_piece' + i + '').className);
			idp += i + ",";
		}
	}

	idp = idp.substr(0,idp.lastIndexOf(','));

	//id="a_particulier" class="ann_bg_etat_on"
	//id="a_agence" class="ann_bg_etat_on"

	//particulier
	var tp = "-1";
	//agence
	var ta = "-1";

	if (document.getElementById("a_particulier").className == "ann_bg_etat_on")
	{
		tp = "1";
	}

	if (document.getElementById("a_agence").className == "ann_bg_etat_on")
	{
		ta = "1";
	}

	var ville = "";

	if (document.getElementById("ville").value != "")
	{
		ville = document.getElementById("ville").value;
	}

	window.location.href = url + "&id_tb=" + ids + '&idp=' + idp + "&tp=" + tp + "&ta=" + ta + "&tw=" + ville;

}


function load_villes_quartiers()
{

	$.ajax({
		type: "GET",
		data: "id_ville="+document.getElementById('ville').value+"&univers="+document.getElementById('univers').value,
		url: abs_path+"ajax/ajax_villes.php",
		success: function(msg){

			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				document.getElementById("checkbox_ville").style.display='none';
			}
			else
			{

				document.getElementById("checkbox_ville").style.display='block';
				var lgn = tab.length;
				var inner_html = "";
				for(var i=1;i<lgn;i++){
					inner_html += "<a href=\"javascript:void(0);\" onclick=\"changeTown(\'" + tab[i] + "\');changeDistrict(\'" + tab[i] + "\');\">" + tab[i] + "</a><br>";
				}
				document.getElementById("checkbox_ville-inner").innerHTML = inner_html;
			}
		}


	});
}


function changeDistrict(ville)
{
	$.ajax({
		type: "GET",
		data: "id_ville="+document.getElementById('ville').value,
		url: abs_path+"ajax/ajax_quartier_bis.php",
		success: function(msg){

			var tab = msg.split('|');
			if(tab[1] == "ko")
			{
				tb_show(tab[3],tab[2], true);
			}
			else
			{
				document.getElementById("quartiers").style.display='block';

				var lng = tab.length;
				var inner_html = '<ul>';
				for(var i=1;i<lng;i++){

					var id_label = tab[i].split('_');
					var id = id_label[0];
					var label = id_label[1];

					inner_html += '<li style="float: left; width: 170px; padding-left: 20px;"><a href="#" onclick="toogleDistrict(\''+ id + '\',\'' + i +'\');" id="quartier_'+ i +'" class="ann_bg_etat_off">' + label + '</a></li>';
				}

				inner_html += '</ul>';
				document.getElementById("inner_quartiers").innerHTML = inner_html;
			}
		}


	});
}

function changer_etat(url,id_etat)
{
	//alert(url + '&id_etat=' + id_etat);
	window.location.href = url + '&id_etat=' + id_etat;
}


function change_prix_credits()
{
	var div;
	for(var i = 0; i < document.getElementById('credits').options.length; i++)
	{
		div = document.getElementById('prix_credits_' + document.getElementById('credits').options[i].value);
		if(div != null)
		{
			div.style.display = 'none';
		}
	}
	var index = document.getElementById('credits').value;
	div = document.getElementById('prix_credits_' + index);
	if(div != null)
	{
		div.style.display = 'block';
	}
}

function valider_paiement_credit()
{
	/*
	if(!document.getElementById('cgv').checked)
	{
	alert(get_trad_champ('cgv'));
	}
	else
	{
	document.getElementById('gestion_credit').submit();
	}
	*/
	document.getElementById('gestion_credit').submit();
}

function alert_search()
{
	document.getElementById("form_alert_search").submit();
}

function search_alert(index)
{
	var rooms = document.getElementById("rooms_"+index).value;
	var min_price = document.getElementById("min_price_"+index).value;
	var max_price = document.getElementById("max_price_"+index).value;
	var offerer_types = document.getElementById("offerer_types_"+index).value;
	var item_type = document.getElementById("item_type_"+index).value;
	var city = document.getElementById("city_"+index).value;
	var url = document.getElementById("url_"+index).value;

	var reg=new RegExp("[ ,;]+", "g");

	if(rooms.length > 0)
	{

		var tab_rooms=rooms.split(reg);
		for (var i=0; i<tab_rooms.length; i++)
		{
			document.getElementById("agent_rooms"+tab_rooms[i]).value = "on";
		}
	}

	var tab_offerer_types=offerer_types.split(reg);
	for (var i=0; i<tab_offerer_types.length; i++) {


		if(tab_offerer_types[i] == 1)
		{
			document.getElementById("agent_annonce_part").value = "on";
		}

		if(tab_offerer_types[i] == 2)
		{
			document.getElementById("agent_annonce_agence").value = "on";
		}
		if(tab_offerer_types[i] == 3)
		{
			document.getElementById("agent_annonce_promo").value = "on";
		}
	}

	document.getElementById("agent_slider1").value = min_price;
	document.getElementById("agent_slider2").value = max_price;
	document.getElementById("agent_type_bien").value = item_type;
	document.getElementById("agent_ville").value = city;

	document.getElementById("form_recherche_simple").action = url;
	document.getElementById("form_recherche_simple").submit();
}



function decremente_TA(id,url){
	$.ajax({
		type: "GET",
		data: "id_annonce="+id,
		url: abs_path+"ajax/ajax_decremente_TA.php",
		success: function(msg){
			window.location=url;

		}


	});
}

function decremente_TA_external(id,url){
	$.ajax({
		type: "GET",
		data: "id_annonce="+id,
		url: abs_path+"ajax/ajax_decremente_TA.php",
		success: function(msg){
			self.parent.location=url;

		}


	});
}

function recherche_quartiers()
{
	var city = document.getElementById('ville').value;
	var url_quartier = document.getElementById('url_quartier');

	var url_quartier_exist = document.getElementById('url_quartier_exist').value;
	var url_no_quartier_exist = document.getElementById('url_no_quartier_exist').value;

	//Si aucune ville n'est entr�e
	if(city == "")
	{
		self.parent.tb_show(url_quartier.title,url_no_quartier_exist,false);return false;

	}
	else
	{
		$.ajax({
			type: "GET",
			data: "id_ville="+document.getElementById('ville').value,
			url: abs_path+"ajax/ajax_quartier_bis.php",
			success: function(msg){

				var tab = msg.split('|');
				if(tab[1] == "ko")
				{
					tb_show(tab[3],tab[2], true);
				}
				else
				{
					document.getElementById("form_recherche_simple").action = url_quartier_exist;
					document.getElementById("form_recherche_simple").submit();
				}
			}


		});
	}

}

function addCheckedValue(id_div_ext,id_lbl,default_lbl,is_span)
{
	//id_div_ext = 'checkbox_type', id_lbl = 'type_bien'
	var div_ext = document.getElementById(id_div_ext);
	var checkboxes = div_ext.getElementsByTagName("Input");

	var lbl = "";
	for(var i = 0; i < checkboxes.length; i++)
	{

		if(checkboxes[i].checked)
		{
			if(lbl.length > 0)
			{
				lbl += ", ";
			}

			var span = checkboxes[i].parentNode.getElementsByTagName("span")[0];
			lbl += 	span.innerHTML;
		}
	}

	if(lbl == "")
	{
		lbl = default_lbl;
	}

	if(is_span)
	{
		document.getElementById(id_lbl).innerHTML=lbl;
	}
	else
	{
		document.getElementById(id_lbl).value=lbl;
	}


}

function isNumeric(sText){

	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++){

		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;
}

function isInteger(sText){

	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++){

		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;
}


function compute_credits()
{
	var nb = document.getElementById("nb_packages").value;
	if(!isInteger(nb) || nb == "")
	{
		nb = 1;
		document.getElementById("nb_packages").value = "1";
	}
	var prix_total = document.getElementById("prix_total_hidden").value.replace(',','.');
	var conversion_total = document.getElementById("conversion_total_hidden").value.replace(',','.');

	var nb_package = document.getElementById("nb_hidden").value;

	document.getElementById("nb_total_credits").innerHTML = Math.round(nb * nb_package * 100)/100;
	document.getElementById("prix_total_credits").innerHTML = Math.round(nb * prix_total * 100)/100;
	document.getElementById("conversion_total_credits").innerHTML = Math.round(nb * conversion_total * 100)/100;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function update_input_map_coords() {

	var bound_names = new Array('minLat','maxLat','minLng','maxLng','centerLat','centerLng','zoom_level');
	var bounds = map.getBounds();
	var center = map.getCenter();
	var centerLat = center.lat();
	var centerLng= center.lng();
	var zoom_level = map.getZoom();
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
	var coords = new Array(sw.lat(),ne.lat(),sw.lng(),ne.lng(),centerLat,centerLng,zoom_level);

	if($("#main_search_form > input#"+bound_names[0]).size() != 0) {
		for(var i in bound_names) {
			$("#main_search_form > input#"+bound_names[i]).val(coords[i]);
		}
	} else {
		for(var i in bound_names) {
			$("#main_search_form").append("<input id='"+bound_names[i]+"' name='"+bound_names[i]+"' value='"+coords[i]+"' type='hidden' />");
		}
	}

}

$(document).ready(function(){
	//adding offer city form	
	$("#D_ville #ville").selectOptions("276",true);
	$("#D_ville #ville").selectOptions("1");
	$("#D_ville #ville").trigger("change");
	
	//Search within map only - functionality
	//refresh_AS();
	$('#AS_keyword').click(function() {
		if($(this).val() == get_trad_champ('AS_keyword_hint')) {
			$(this).val('');
		}
	});

	$(".search_within_map").click(function() {
		var bound_names = new Array('minLat','maxLat','minLng','maxLng');
		var fields_to_remove = new Array("city_id","quartier","district","city_text");

		var bound_names = new Array('minLat','maxLat','minLng','maxLng','centerLat','centerLng','zoom_level');
		var bounds = map.getBounds();
		var center = map.getCenter();
		var centerLat = center.lat();
		var centerLng= center.lng();
		var zoom_level = map.getZoom();
	  var sw = bounds.getSouthWest();
	  var ne = bounds.getNorthEast();
		var coords = new Array(sw.lat(),ne.lat(),sw.lng(),ne.lng(),centerLat,centerLng,zoom_level);

		if(!$(this).hasClass("active")) {

			//set GMAP event listeners
			GEvent.addListener(map,"moveend", function(point) { update_input_map_coords(); restart_form_timer(); });
		  GEvent.addListener(map,"zoomend", function(point) { update_input_map_coords(); restart_form_timer(); });

			$(this).addClass("active");

			//set field that indicate that we search within map only
			if($("#main_search_form > input#search_within_map").size() == 0) {
				$("#main_search_form").append("<input id='search_within_map' name='search_within_map' value='1' type='hidden' />");
			}

			if($("#main_search_form > input#"+bound_names[0]).size() != 0) {
				for(var i in bound_names) {
					$("#main_search_form > input#"+bound_names[i]).val(coords[i]);
				}
			} else {
				for(var i in bound_names) {
					$("#main_search_form").append("<input id='"+bound_names[i]+"' name='"+bound_names[i]+"' value='"+coords[i]+"' type='hidden' />");
				}
			}

			//remove input fields that interfere with searching within map
			for(var i in fields_to_remove) {
				$("#main_search_form > input#"+fields_to_remove[i]).remove();
			}

			$("#gmap").css({"border" : "1px solid #901e2f","width" : "298px", "height" : "298px"});

		} else {

			$("#gmap").css("border","1px solid #bababa");

			GEvent.clearListeners(map,"moveend");
			GEvent.clearListeners(map,"zoomend");

			$(this).removeClass("active");

			//remove field that indicate that we search within map only
			$("#main_search_form > input#search_within_map").remove();

			for(var i in bound_names) {
				$("#main_search_form > input#"+bound_names[i]).remove();
			}

			$("#search-map_block form").append("<input id='map_update_disable' name='map_update_disable' value='1' type='hidden' />");
		}

		//$("#main_search_form > input#"+bound_names[i]).remove();
//		load_search();
//		restart_form_timer();
	});

	$("#add_offer select#ville").change(function() {
		load_quartier();
	});

	$("#result_list .check_visited").each(function(i) {
			if(($("#is_office").val() == 1) && (parseInt($(this).css('opacity')) < 0)) {
				alert("visited");
			}
	});

	$("#agent_submit").click(function(){
			if(validemail("agent_email")) {
	    	$.ajax({
					type: "GET",
					data: "email="+$("#agent_email").val(),
					url: abs_path+"ajax/ajax_createAgent.php",
					success: function(msg){
						var message = msg.split('|');
						$("#search_phrases-bottom span").html(message[1]);
						$("#search_phrases-bottom").css("background-image","url("+abs_path_img+"v3/bkg/SP_background-down-success.png)");
						$("#search_phrases-bottom").css("padding","10px 0 0 50px");
						$("#search_phrases-bottom input").remove();
					},
					error: function(msg){
						var message = msg.split('|');
						alert(message[1]);
		      }
				});
    	} else {

    	}
	});

	$('.description_select_bar label').click(function() {
		$("div[id^=Div_description]").hide();
		$(this).siblings().removeClass("description_active");
		//alert($(this).attr("for"));
		$("div[id=Div_"+$(this).attr("for")+"]").show();
		$(this).addClass("description_active");
	});

	$('#civilite').val($(".input_radio[checked=checked]").val());
	AS_change_visibility($("#AS_property_type").children("option:selected").val());
	AS_change_visibility_commercial($("#AS_commercial_type").children("option:selected").val());

	$("div.help").mouseover(function () {
		$(this).parent().children("div.help_bubble").show();
	});
	$("div.help").mouseout(function () {
		$(this).parent().children("div.help_bubble").hide();
	});
	$(".civ_option").click(function() {
		$('.chkbox_civ_on').attr('class','chkbox_civ');
		$(this).children('div').attr('class','chkbox_civ_on');
		$("#civilite").val($(this).children('.input_radio').val());
	});

	$("#cgv_box").click(function() {
		if($(this).hasClass('cgv_box_on')) {
			$(this).removeClass('cgv_box_on');
			$(this).addClass('cgv_box_off');
			$('#cgv').removeAttr('checked');
		} else {
			$(this).removeClass('cgv_box_off');
			$(this).addClass('cgv_box_on');
			$('#cgv').attr('checked','checked');
		}
	});

	$(".cm_detail").click(function(){
		//    alert($(this).html());
		$("#city").val($(this).html());
	});
	$(".city_example span").click(function(){
		$("#ville").val($(this).html());
	});

	$('#reg_form input, .form_registration input').focus(function() {
		$('.reg_hint').hide('fast');
		$(this).siblings('.reg_hint').show('fast');
	});

	//home-page: simple research
	$('#reg_form input, .form_registration input').focus(function() {
		$('.reg_hint').hide('fast');
		$(this).siblings('.reg_hint').show('fast');
	});

	$(".detail_right_block_top h2").click(function(){
		$(this).parent().children().removeClass('active');
		$(this).addClass('active');
		if($(this).hasClass('right')){3
		$("#offer_description").hide();
		$("#offer_properties").show();
		} else {
			$("#offer_properties").hide();
			$("#offer_description").show();
		}
	})

	$(".competition .contact_form input").blur(function(){
		if($(this).val() == ''){
			$(this).addClass('empty');
		}
	});

	$(".competition .contact_form input").focus(function(){
		$(this).removeClass('empty');
	});

	$(".corners").corner({
		tl: { radius: 5 },
		tr: { radius: 5 },
		bl: { radius: 5 },
		br: { radius: 5 }});
		$(".corners_no_bottom").corner({
			tl: { radius: 5 },
			tr: { radius: 5 },
			bl: { radius: 0 },
			br: { radius: 0 }});


	$("#result_list dl").bind('mouseenter',hover_offer_on);
	$("#result_list dl").bind('mouseleave',hover_offer_off);

	/**** SEARCH PHRASES & ADVANCED SEARCH FUNCTIONALITY ****/

	if($('#search_phrases').html() == "") { $('#search_phrases').add('#search_phrases-bottom').hide(); }
	$("#search_phrases > span").not(".search_phrases_noclick").bind("click",click_search_phrase);

	//text type handling
	$("#advanced_search_form input[type=text]").not("#AS_city_text").keyup(function () {
		var input_val = $(this).val();
		var input_name = $(this).attr("id").split("AS_");
		input_name = input_name[1];

		if(input_val == "") {
			$("#main_search_form > input#"+input_name).remove();
		} else {
			if($("#main_search_form > input#"+input_name).size() != 0) {
				$("#main_search_form > input#"+input_name).val(input_val);
			} else {
				$("#main_search_form").append("<input id='"+input_name+"' name='"+input_name+"' value='"+input_val+"' type='hidden' />");
			}
		}

		restart_form_timer();
	});

	$("#advanced_search_form #AS_city_text").keyup(function () {
		process_city_text();
	});
	$("#advanced_search_form .city_text").blur(function () {
		$("#city_text-suggestions-box").hide();
	});

	//select type handling
	$("#advanced_search_form select").change(function () {
		var input_val = $(this).children("option:selected").add($(this).children("optgroup").children("option:selected")).val();
		var input_name = $(this).attr("id").split("AS_");
		input_name = input_name[1];

		if(input_val == -1) {
			$("#main_search_form > input#"+input_name).remove();
		} else {
			if($("#main_search_form > input#"+input_name).size() != 0) {
				$("#main_search_form > input#"+input_name).val(input_val);
			} else {
				$("#main_search_form").append("<input id='"+input_name+"' name='"+input_name+"' value='"+input_val+"' type='hidden' />");
			}

			if(input_name == 'district') { //if district is being set, remove city_text or other city inputs
				$("#main_search_form > input#city_text").remove();
				$("#main_search_form > input#city_id").remove();
				$("#main_search_form > input#quartier").remove();
				disable_search_within_map();
			}
		}

		restart_form_timer();
	});

	//checkbox type handling
	$("#advanced_search_form input[type=checkbox]").change(function () {
		//alert("čejndž");
		var input_name = $(this).attr("class");
		var input_vals = "";

		$("#advanced_search_form input[class="+input_name+"]:checked").each(function(i) {
			input_vals += $(this).val() + ",";
		});

		if(input_vals.charAt(input_vals.length-1) == ",") {
			input_vals = input_vals.substr(0,input_vals.length-1);
		}

		var clear_input_name = input_name.split(" ");
		clear_input_name = clear_input_name[0].split("chkgrp_");
		clear_input_name = clear_input_name[1];

		//alert(clear_input_name + " - " + input_vals);

		if(input_vals == "") {
			$("#main_search_form > input#"+clear_input_name).remove();
		} else {
			if($("#main_search_form > input#"+clear_input_name).size() != 0) {
				$("#main_search_form > input#"+clear_input_name).val(input_vals);
			} else {
				$("#main_search_form").append("<input id='"+clear_input_name+"' name='"+clear_input_name+"' value='"+input_vals+"' type='hidden' />");
			}
		}

		restart_form_timer();
	});

	$("#AS_property_type").change(function () {
		AS_change_visibility($(this).children("option:selected").val());
	});

	$("#AS_commercial_type").change(function () {
		AS_change_visibility_commercial($(this).children("option:selected").val());
	});

	//sorting fucntionality
	$(".sort-btn").click(function() {
		var cls_grp = $(this).attr("class").split(" ");
		var cls_data = cls_grp[1].split("-");

		if(cls_data[2] != "ON") {

			var img_src = $(this).attr("src");
			img_src = img_src.replace("OFF","ON");
			$(this).attr("src",img_src);

			cls_data[2] = "ON";

			//alert("id="+cls_data[0]+" | direction = "+cls_data[1]+" | status = "+cls_data[2]);
			$(".sort-btn").not("."+cls_grp[1]).each(function() {
				var cls_grp2 = $(this).attr("class").split(" ");
				$(this).removeClass(cls_grp2[1]);

				var img_path = $(this).attr("src");
				img_path = img_path.replace("ON","OFF");
				$(this).attr("src",img_path);

				var cls_data2 = cls_grp2[1].split("-");
				cls_data2[2] = "OFF";
				cls_data2 = cls_data2.join("-");

				$(this).addClass(cls_data2);

			});

			if($("#main_search_form > input#sorting").size() == 0) {
				$("#main_search_form").append("<input id='sorting' name='sorting' value='"+cls_data[0]+"-"+cls_data[1]+"' type='hidden' />");
			} else {
				$("#main_search_form > input#sorting").val(cls_data[0]+"-"+cls_data[1]);
			}

			$(this).removeClass(cls_grp[1]);
			cls_data = cls_data.join("-");
			$(this).addClass(cls_data);

			restart_form_timer();
		}

	});

	$(".pagination-line.ajax a").not(".off").not(".page-current").bind("click",click_page);

	$(".pagination-selectbox select").change(function() {
		var data = $(this).children("option:selected").val();

		$(".pagination-selectbox select").children("option:selected").removeAttr("selected");
		$(".pagination-selectbox select").children("option[value="+data+"]").attr("selected","selected");

		if($("#main_search_form > input#paging").size() == 0) {
			$("#main_search_form").append("<input id='paging' name='paging' value='"+data+"' type='hidden' />");
		} else {
			$("#main_search_form > input#paging").val(data);
		}
		restart_form_timer();

	});

	$(".checkbox_switch").click(function () {
        var data = $(this).attr("class").split(" ");
        data = data[1].split("-");

      	if($(this).hasClass("chkbox-on")) {
        	$(this).removeClass("chkbox-on").addClass("chkbox-off");
        	$(".AS_"+data[0]).each(function(){
        		if($(this).val() == data[1]) {
        			$(this).removeAttr("checked");
        			$(this).trigger("change");
        		}
        	});

        } else {
        	$(this).removeClass("chkbox-off").addClass("chkbox-on");
        	$(".AS_"+data[0]).each(function(){
        		if($(this).val() == data[1]){
        			$(this).attr("checked","checked");
        			$(this).trigger("change");
        		}
        	});
        }
      }
    );

    $(".conditions").hover(
       	  function () {
    	  	$(".popup_conditions").fadeIn(100);
	      },
	      function () {
	        $(".popup_conditions").fadeOut(100);
	      }
    );

    $(".get_advice #input_submit").click(function () {
    	if(($("#input_email").val() != "")) {
	    	$.ajax({
				type: "GET",
				data: "mail="+$("#input_email").val()+"&message="+$("#input_text").val()+"&type="+$("#form_type").val(),
				url: abs_path+"ajax/ajax_request_advisory.php",
				success: function(msg){
					var message = msg.split('|');
					alert(message[1]);
					$("#input_email").val('');
					$("#input_text").val(' ');
					$("#input_text").text(' ');
				},
				error: function(msg){
					var message = msg.split('|');
					alert(message[1]);
	      	 	}
			});
    	} else {
    		alert(get_trad_champ("fill_it_right"));
    	}
    	return false;
    });
	//catalogue flag selector
	$(".search_container.flags div").click(function() {
		$(this).children("input").attr("checked","checked");
	});

	//positioning map block from search reasults
	if(document.getElementById('search-map_block')) {
		setMapOffset.initialPos = getStyle('search-map_block','top');
		window.onscroll = document.documentElement.onscroll = setMapOffset;
		setMapOffset();
	}
});

function getStyle(el,styleProp) {
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

function setMapOffset() {
	$("#search-map_block").queue( [ ] );
	listHeight = document.getElementById('search-results_block').offsetHeight;
	var map = document.getElementById('search-map_block');
	if (!map) return;
	var desiredOffset = 0;
	var currentOffset = document.documentElement.scrollTop || document.body.scrollTop; // body for Safari
	var startPos = parseInt(setMapOffset.initialPos); //160

	if($('.top_leaderboard').length) { //if top leaderboard is in place
		currentOffset = currentOffset - $('.top_leaderboard').height();
	}

	if(currentOffset < (listHeight - $('#search-map_block').height() + 120)) {
		desiredOffset = currentOffset + 10;
	} else {
		desiredOffset = listHeight - $('#search-map_block').height() + 120;
	}

	if(desiredOffset < startPos) {
		desiredOffset = startPos;
	}

	if (desiredOffset != parseInt(map.style.top)) {
		$("#search-map_block").animate(
					{ top: desiredOffset },
					{ duration: 'medium',
            easing: 'jswing' });
	}
}

function click_page() {
	var cls_grp = $(this).attr("class").split(" ");
	var cls_data = cls_grp[1].split("-");

	if($("#main_search_form > input#page").size() == 0) {
		$("#main_search_form").append("<input id='page' name='page' value='"+cls_data[1]+"' type='hidden' />");
	} else {
		$("#main_search_form > input#page").val(cls_data[1]);
	}
	restart_form_timer(true);

	return false;
}

function AS_change_visibility(id) {
	if(id > -1) {
		var arr_field_defines = new Array();
		//flat
		arr_field_defines[1] = new Array("property_status","equipped","rooms","surface","floor","elevator","balcony","terasse","cellar","parking","garage","type_construction");
		//cottage - recreational object
		arr_field_defines[2] = new Array("recreation_type","property_status","rooms","floor_cnt","floor","electricity","water","gas","canalisation","heating_type","type_construction");

		//house
		arr_field_defines[4] = new Array("property_status","equipped","rooms","surface","floor","floor_cnt","elevator","balcony","terasse","cellar","pool","type_construction");
		//farm
		arr_field_defines[5] = new Array("property_status","floor","floor_cnt","electricity","water","gas","canalisation","type_construction");

		//historical object
		arr_field_defines[6] = new Array("property_status","rooms","floor_cnt","electricity","water","gas","canalisation","type_construction");

		//land
		arr_field_defines[7] = new Array("property_status","land_type","surface","electricity","water","gas","canalisation","type_construction");

		//garage
		arr_field_defines[10] = new Array("electricity","electric_gate","type_construction");

		//all custom criteria
		var arr_all_fields = new Array("property_status","land_type","surface","networks","type_construction","id_warehouse_type","overall_capacity","free_capacity","minimal_sell_space_max","warehouse_equipment","manipulation","property_status","hotel_type","rooms","floor","heating_type","features","floor_cnt","recreation_type");
		var arr_all_field_items = new Array("property_status","land_type","surface","electricity","water","gas","canalisation","type_construction","id_warehouse_type","overall_capacity","free_capacity","minimal_sell_space_max","warehouse_equipment","manipulation","property_status","hotel_type","rooms","floor","heating_type","elevator","equipped","electric_gate","cellar","pool","terasse","balcony","floor_cnt","recreation_type","parking","garage");

		$("#custom_criteria > div").each(function (i) {
				var xclass = $(this).attr('class').split(" ");
				if(xclass.length > 1)
					xclass = xclass[1];
				else
					xclass = xclass[0];

				if(arr_field_defines[id].join().indexOf(xclass) != -1) {
					$(this).show("medium");
				} else {
					$(this).hide("medium");
				}
			}
		);
	}
}

function AS_change_visibility_commercial(id) {
	if(id > -1) {
		var arr_field_defines = new Array();

		//offices
		arr_field_defines[1] = new Array("property_status","equipped","rooms","surface","floor","elevator","type_construction","cafe_inside","market_inside","restaurant_inside","reception_nonstop","windows_openable","isdn_line","conference_inside");

		//hotels/restaurants...
		arr_field_defines[2] = new Array("property_status","hotel_type","rooms","floor","heating_type","type_construction");

		//warehouse/offices
		arr_field_defines[3] = new Array("id_warehouse_type","overall_capacity","free_capacity","minimal_sell_space_max","warehouse_equipment","manipulation");

		//land...
		arr_field_defines[4] = new Array("property_status","land_type","surface","electricity","water","gas","canalisation","type_construction");

		//all custom criteria
		var arr_all_fields = new Array("property_status","land_type","surface","networks","type_construction","id_warehouse_type","overall_capacity","free_capacity","minimal_sell_space_max","warehouse_equipment","manipulation","property_status","hotel_type","rooms","floor","heating_type","features");
		var arr_all_field_items = new Array("property_status","land_type","surface","electricity","water","gas","canalisation","type_construction","id_warehouse_type","overall_capacity","free_capacity","minimal_sell_space_max","warehouse_equipment","manipulation","property_status","hotel_type","rooms","floor","heating_type","elevator","equipped","cafe_inside","market_inside","restaurant_inside","reception_nonstop","windows_openable","isdn_line","conference_inside");

		$("#custom_criteria > div").each(function (i) {
				var xclass = $(this).attr('class').split(" ");
				if(xclass.length > 1)
					xclass = xclass[1];
				else
					xclass = xclass[0];

				if(arr_field_defines[id].join().indexOf(xclass) != -1) {
					$(this).show("medium");
				} else {
					$(this).hide("medium");
				}
			}
		);
	}
}

function process_city_text() {
		var input_val = $("#advanced_search_form #AS_city_text").val();
		var input_name = $("#advanced_search_form #AS_city_text").attr("id").split("AS_");
		input_name = input_name[1];

		if(input_val == "") {
			$("#main_search_form > input#"+input_name).remove();
		} else {
			if($("#main_search_form > input#"+input_name).size() != 0) {
				$("#main_search_form > input#"+input_name).val(input_val);
			} else {
				$("#main_search_form").append("<input id='"+input_name+"' name='"+input_name+"' value='"+input_val+"' type='hidden' />");
				//alert(input_val + input_name);
			}

		}

		$("#main_search_form > input#city_id").remove();
		$("#main_search_form > input#quartier").remove();
		$("#main_search_form > input#district").remove();
		disable_search_within_map();

		restart_form_timer();
}

function refresh_AS() { //refreshes all fields from Advanced Search, e.g. initialisation or search has been redefined by search-phrase
	$("#advanced_search_form select").not(".property_type").each(function(i) {
		var name = $(this).attr("id").split("AS_");
		name = name[1];

		if($("#" + name).size() == 0) {
			$(this).children("option:selected").add($(this).children("optgroup").children("option:selected")).removeAttr("selected");
			$(this).children("option[value=-1]").add($(this).children("optgroup").children("option[value=-1]")).attr("selected","selected");
		}
	});

	$("#advanced_search_form input[type=checkbox]").each(function(i) {
		var name = $(this).attr("name").split("AS_");
		name = name[1];
		//alert("i am in "+name);
		var name_grp = new Array();
		if($("#" + name).size() != 0) {
			name_grp = $("#" + name).val().split(",");
		}
		//alert($("#" + name).val().split(","));

		if(name_grp.length == 0) {
			$("input.chkgrp_"+name).each(function(i) {
				$(this).removeAttr("checked");
				$(this).siblings("div.checkbox_switch").removeClass("chkbox-on").addClass("chkbox-off");
			});
		} else {
			var val = $(this).val();
			var in_array = false;

			for (var i in name_grp) {
				if(val == name_grp[i]) in_array = true;
//				alert(name_grp[i]+" / "+val);
			}

			if(!in_array) {
				$(this).removeAttr("checked");
				$(this).siblings("div.checkbox_switch."+name+"-"+val).removeClass("chkbox-on").addClass("chkbox-off");
//				alert("div.checkbox_switch."+name+"-"+val);
			}
		}

	});

	$("#advanced_search_form input[type=text]").each(function(i) {
		var name = $(this).attr("id").split("AS_");
		name = name[1];

		if($("#" + name).size() == 0) {
			$(this).val('');
		} else {
			$(this).val($("#" + name).val());
		}

	});
	if($('#AS_keyword').val() == '') {
		$('#AS_keyword').val(get_trad_champ('AS_keyword_hint'));
	}
	//alert("refreshing");
}

function disable_search_within_map() {
	var items_to_remove = new Array('minLat','maxLat','minLng','maxLng','centerLat','centerLng','zoom_level','search_within_map');
	for(i in items_to_remove) {
		$("#"+items_to_remove[i]).remove();
	}

	$("#gmap").css("border","1px solid #bababa");

	GEvent.clearListeners(map,"moveend");
	GEvent.clearListeners(map,"zoomend");
	$(".search_within_map").removeClass("active");
}

function click_search_phrase() {
	$(this).children("input").each(
	function() {
		var cur_class = $(this).attr("class");
		var cur_val = $(this).val();

		if(cur_val == 'disable') {
			$("#" + cur_class).remove();
		} else {
			$("#" + cur_class).val($(this).val());
		}

		if(cur_class == "search_within_map") { //search within map is somehow special ;)
			disable_search_within_map();
		}
	});

	//$("#result_list").fadeOut("slow");
	//$(this).hide();
	$(this).unbind("click",click_search_phrase).remove();

	restart_form_timer();

	return false;
}

function hover_offer_on() {
	hideInfo();
	$(this).addClass("result-item-on");
	var gps = $(this).children("dd:first-child").children(".gps_coords").val();

	if($(this).children("dd:first-child").children(".gps_coords").val() != '') {
		if(!G_offers[gps]) { return 0; }
		var gps_split = $(this).children("dd:first-child").children(".gps_coords").val().split("_");
		var current_gps = new GLatLng(gps_split[0],gps_split[1]);
		var curr_pt = G_offers[gps];
		map.removeOverlay(G_offers[gps]);
		G_offers[gps] = curr_pt;
		map.addOverlay(G_offers[gps]);

		if(!document.getElementById("search_within_map")) {
			map.panTo(current_gps);
		}

		var top = "-project";
		if(G_offers[gps].dataset.type == 1) {
			top = "-project-gold";
		}
		G_offers[gps].setImage(abs_path_img+"googlemap/picto"+top+"-on.png");
	}
}
function hover_offer_off() {
	$(this).removeClass("result-item-on");
	var gps = $(this).children("dd:first-child").children(".gps_coords").val();
	if(!G_offers[gps]) { return 0; }

	var top = "-project";
	if(G_offers[gps].dataset.type == 1) {
		top = "-project-gold";
	}
	if(G_offers[gps]) {
		G_offers[gps].setImage(abs_path_img+'googlemap/picto'+top+'.png');
	}
}

function valid_form_arrange_meeting(){

	if (! validemail("email")) {
		return 0;
	}

	document.getElementById("form_arrange_meeting").submit();
}

$(document).ready(function(){
	$("#nb_credit,#prix_clic").keyup( function() {
		$.ajax({
			type: "GET",
			data: "cpc="+document.getElementById("prix_clic").value+"&budget="+document.getElementById("nb_credit").value,
			url: abs_path+"ajax/ajax_TA_position.php",
			success: function(msg){
				$("#pos_box").html(msg+'.');

			}


		});
	});

	$("#nb_credit,#prix_clic").trigger("keyup");
});

function valid_form_particulier_reg(){

	if ((document.getElementById("email").value=="")) {
		alert(get_trad_champ("email"));
		return 0;
	}

	if ((document.getElementById("login_inscription").value=="")) {
		alert(get_trad_champ("login"));
		return 0;
	}

	if ( (document.getElementById("passe_inscription").value).length < 6 ) {
		alert(get_trad_champ("passe"));
		return 0;
	}

	if ((document.getElementById("passe_verif").value=="")) {
		alert(get_trad_champ("passe_verif"));
		return 0;
	}
//	if ((document.getElementById("strcode").value=="")) {
//		alert(get_trad_champ("strcode"));
//		return 0;
//	}

	if (document.getElementById("cgv").checked == false) {
		alert(get_trad_champ("cgv"));
		return 0;
	}
	if ((document.getElementById("passe_verif").value!=document.getElementById("passe_inscription").value)) {
		alert(get_trad_champ("passe_not_equal"));
		return 0;
	}

	// Test login
	var texte = document.getElementById("login_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_\.]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_login"));
		return 0;
	}

	// Test passe
	var texte = document.getElementById("passe_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_passe"));
		return 0;
	}
	if($("#reg_form_individual select#type").val() == 2 || $("#reg_form_individual select#type").val() == 3){
	  valid_form_agence_reg();
	} else {
	  document.getElementById("form_particulier").submit();
	}
	


}

function valid_form_agence_reg(){

	if ((document.getElementById("nom_agence").value=="")) {
		alert(get_trad_champ("nom_agence"));
		return 0;
	}

	if ((document.getElementById("siret").value=="")) {
		alert(get_trad_champ("siret"));
		return 0;
	}

	if ((document.getElementById("adresse_agence").value=="")) {
		alert(get_trad_champ("adresse_agence"));
		return 0;
	}

	if ((document.getElementById("cp").value=="")) {
		alert(get_trad_champ("cp"));
		return 0;
	}
	if ((document.getElementById("ville").value=="")) {
		alert(get_trad_champ("ville_agence"));
		return 0;
	}

	if ((document.getElementById("pays").value==0)) {
		alert(get_trad_champ("pays_agence"));
		return 0;
	}

	if ((document.getElementById("login_inscription").value=="")) {
		alert(get_trad_champ("login"));
		return 0;
	}


	// Test login
	var texte = document.getElementById("login_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_login"));
		return 0;
	}

	if ((document.getElementById("passe_inscription").value=="")) {
		alert(get_trad_champ("passe"));
		return 0;
	}
	if ((document.getElementById("passe_verif").value=="")) {
		alert(get_trad_champ("passe_verif"));
		return 0;
	}


	if ((document.getElementById("passe_verif").value!=document.getElementById("passe_inscription").value)) {
		alert(get_trad_champ("passe_not_equal"));
		return 0;
	}

	if (document.getElementById("cgv").checked == false) {
		alert(get_trad_champ("cgv"));
		return 0;
	}
	document.getElementById("form_particulier").submit();
}
function valid_form_promoteur_reg(){


	if ((document.getElementById("nom_promoteur").value=="")) {
		alert(get_trad_champ("nom_promoteur"));
		return 0;
	}

	if ((document.getElementById("siret").value=="")) {
		alert(get_trad_champ("siret"));
		return 0;
	}

	if ((document.getElementById("adresse_promoteur").value=="")) {
		alert(get_trad_champ("adresse_promoteur"));
		return 0;
	}

	if ((document.getElementById("cp").value=="")) {
		alert(get_trad_champ("cp"));
		return 0;
	}
	if ((document.getElementById("ville").value=="")) {
		alert(get_trad_champ("ville_promoteur"));
		return 0;
	}

	if ((document.getElementById("pays").value==0)) {
		alert(get_trad_champ("pays_promoteur"));
		return 0;
	}


	if ((document.getElementById("nom_contact").value=="")) {
		alert(get_trad_champ("nom_contact"));
		return 0;
	}
	if ((document.getElementById("email_contact").value=="")) {
		alert(get_trad_champ("email_contact"));
		return 0;
	}
	if ((document.getElementById("login_inscription").value=="")) {
		alert(get_trad_champ("login"));
		return 0;
	}

	var texte = document.getElementById("login_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_login"));
		return 0;
	}

	if ((document.getElementById("passe_inscription").value=="")) {
		alert(get_trad_champ("passe"));
		return 0;
	}
	if ((document.getElementById("passe_verif").value=="")) {
		alert(get_trad_champ("passe_verif"));
		return 0;
	}


	if ((document.getElementById("passe_verif").value!=document.getElementById("passe_inscription").value)) {
		alert(get_trad_champ("passe_not_equal"));
		return 0;
	}

	var texte = document.getElementById("passe_inscription").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_passe"));
		return 0;
	}

	if ((document.getElementById("strcode").value=="")) {
		alert(get_trad_champ("strcode"));
		return 0;
	}
	if (document.getElementById("cgv").checked == false) {
		alert(get_trad_champ("cgv"));
		return 0;
	}
	document.getElementById("form_promoteur").submit();
}
function validate_create_agent()
{
	var alert_name = document.getElementById("alert_name").value;

	if  (alert_name == "" )
	{
		alert(get_trad_champ("alert_name_obligatoire"));
		return 0;
	}


	var ids = "";

	var div = document.getElementById("checkbox_type");
	var tab = div.getElementsByTagName("input");

	/*
	for (i=0; i<tab.length; i++) {
	if(tab[i].checked) {
	document.creation_alerte_form.envoi.value = "1";
	document.creation_alerte_form.submit();
	return true;
	}
	}
	*/

	for (i=0; i<tab.length; i++) {
		if(tab[i].checked) {
			ids += tab[i].value + ",";
		}
	}

	ids = ids.substr(0,ids.lastIndexOf(','));

	if (ids != "")
	{
		document.getElementById("type_bien").value = ids;
	}
	else
	{
		alert(get_trad_champ("type_bien"));
		return 0;
	}

	if (document.getElementById('select_type_offre').value == "-1")
	{
		alert(get_trad_champ("type_offre"));
		return 0;
	}
	else
	{
		document.getElementById("type_offre").value = document.getElementById('select_type_offre').value;
	}

	if ((document.getElementById("nom").value=="")) {
		alert(get_trad_champ("nom"));
		return 0;
	}

	if ((document.getElementById("email").value=="")) {
		alert(get_trad_champ("email"));
		return 0;
	}

	if ((document.getElementById("reg_login").value=="")) {
		alert(get_trad_champ("login"));
		return 0;
	}

	if ((document.getElementById("reg_pass").value=="")) {
		alert(get_trad_champ("passe"));
		return 0;
	}

	if ((document.getElementById("passe_verif").value=="")) {
		alert(get_trad_champ("passe_verif"));
		return 0;
	}
	if ((document.getElementById("strcode").value=="")) {
		alert(get_trad_champ("strcode"));
		return 0;
	}

	if (document.getElementById("cgv").checked == false) {
		alert(get_trad_champ("cgv"));
		return 0;
	}
	if ((document.getElementById("passe_verif").value!=document.getElementById("reg_pass").value)) {
		alert(get_trad_champ("passe_not_equal"));
		return 0;
	}

	// Test login
	var texte = document.getElementById("reg_login").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_login"));
		return 0;
	}

	// Test passe
	var texte = document.getElementById("reg_pass").value;
	var exp=new RegExp("^[a-zA-Z0-9\-_]*$","g");
	if ( ! exp.test(texte) ){
		alert(get_trad_champ("caractere_interdit_passe"));
		return 0;
	}


	document.form_create_agent.envoi.value = "1";
	document.form_create_agent.submit();
	//return true;

}

// Click sur nombre de pieces : passage de la valeur et changement d etat
function togglerooms1(){
	if(document.getElementById('rooms1').value=='on'){
		document.getElementById('rooms1').value='off';
		document.getElementById("nb_piece1").className="pce_bg_etat_off";
	}
	else{
		document.getElementById('rooms1').value='on';
		document.getElementById("nb_piece1").className="pce_bg_etat_on";
	}
}
function togglerooms2(){
	if(document.getElementById('rooms2').value=='on'){
		document.getElementById('rooms2').value='off';
		document.getElementById('nb_piece2').className="pce_bg_etat_off";
	}
	else{
		document.getElementById('rooms2').value='on';
		document.getElementById('nb_piece2').className="pce_bg_etat_on";
	}
}
function togglerooms3(){
	if(document.getElementById('rooms3').value=='on'){
		document.getElementById('rooms3').value='off';
		document.getElementById('nb_piece3').className="pce_bg_etat_off";
	}
	else{
		document.getElementById('rooms3').value='on';
		document.getElementById('nb_piece3').className="pce_bg_etat_on";
	}
}
function togglerooms4(){
	if(document.getElementById('rooms4').value=='on'){
		document.getElementById('rooms4').value='off';
		document.getElementById('nb_piece4').className="pce_bg_etat_off";
	}
	else{
		document.getElementById('rooms4').value='on';
		document.getElementById('nb_piece4').className="pce_bg_etat_on";
	}
}
function togglerooms5(){
	if(document.getElementById('rooms5').value=='on'){
		document.getElementById('rooms5').value='off';
		document.getElementById('nb_piece5').className="pce_bg_etat_off";
	}
	else{
		document.getElementById('rooms5').value='on';
		document.getElementById('nb_piece5').className="pce_bg_etat_on";
	}
}

// Meme chose mais pour le nombre d etage
function toggleetgrc(){
	if(document.getElementById('etagerc').value=='on'){
		document.getElementById('etagerc').value='off';
		document.getElementById("nb_etagerc").className="etg_bg_etat_off";
	}
	else{
		document.getElementById('etagerc').value='on';
		document.getElementById("nb_etagerc").className="etg_bg_etat_on";
	}
}
function toggleetg1(){
	if(document.getElementById('etage1').value=='on'){
		document.getElementById('etage1').value='off';
		document.getElementById("nb_etage1").className="etg_bg_etat_off";
	}
	else{
		document.getElementById('etage1').value='on';
		document.getElementById("nb_etage1").className="etg_bg_etat_on";
	}
}
function toggleetg2(){
	if(document.getElementById('etage2').value=='on'){
		document.getElementById('etage2').value='off';
		document.getElementById('nb_etage2').className="etg_bg_etat_off";
	}
	else{
		document.getElementById('etage2').value='on';
		document.getElementById('nb_etage2').className="etg_bg_etat_on";
	}
}
function toggleetg3(){
	if(document.getElementById('etage3').value=='on'){
		document.getElementById('etage3').value='off';
		document.getElementById('nb_etage3').className="etg_bg_etat_off";
	}
	else{
		document.getElementById('etage3').value='on';
		document.getElementById('nb_etage3').className="etg_bg_etat_on";
	}
}
function toggleetg4(){
	if(document.getElementById('etage4').value=='on'){
		document.getElementById('etage4').value='off';
		document.getElementById('nb_etage4').className="etg_bg_etat_off";
	}
	else{
		document.getElementById('etage4').value='on';
		document.getElementById('nb_etage4').className="etg_bg_etat_on";
	}
}
function toggleetg5(){
	if(document.getElementById('etage5').value=='on'){
		document.getElementById('etage5').value='off';
		document.getElementById('nb_etage5').className="etg_bg_etat_off";
	}
	else{
		document.getElementById('etage5').value='on';
		document.getElementById('nb_etage5').className="etg_bg_etat_on";
	}
}

// Meme chose mais pour les commobox
function tooglecommobox1(){
	if(document.getElementById('commobox1').value=='on'){
		document.getElementById('commobox1').value='off';
		document.getElementById("nb_commobox1").className="commo_box_off";
	}
	else{
		document.getElementById('commobox1').value='on';
		document.getElementById("nb_commobox1").className="commo_box_on";
	}
}
function tooglecommobox2(){
	if(document.getElementById('commobox2').value=='on'){
		document.getElementById('commobox2').value='off';
		document.getElementById("nb_commobox2").className="commo_box_off";
	}
	else{
		document.getElementById('commobox2').value='on';
		document.getElementById("nb_commobox2").className="commo_box_on";
	}
}
function tooglecommobox3(){
	if(document.getElementById('commobox3').value=='on'){
		document.getElementById('commobox3').value='off';
		document.getElementById("nb_commobox3").className="commo_box_off";
	}
	else{
		document.getElementById('commobox3').value='on';
		document.getElementById("nb_commobox3").className="commo_box_on";
	}
}
function tooglecommobox4(){
	if(document.getElementById('commobox4').value=='on'){
		document.getElementById('commobox4').value='off';
		document.getElementById("nb_commobox4").className="commo_box_off";
	}
	else{
		document.getElementById('commobox4').value='on';
		document.getElementById("nb_commobox4").className="commo_box_on";
	}
}
function tooglecommobox5(){
	if(document.getElementById('commobox5').value=='on'){
		document.getElementById('commobox5').value='off';
		document.getElementById("nb_commobox5").className="commo_box_off";
	}
	else{
		document.getElementById('commobox5').value='on';
		document.getElementById("nb_commobox5").className="commo_box_on";
	}
}
function tooglecommobox6(){
	if(document.getElementById('commobox6').value=='on'){
		document.getElementById('commobox6').value='off';
		document.getElementById("nb_commobox6").className="commo_box_off";
	}
	else{
		document.getElementById('commobox6').value='on';
		document.getElementById("nb_commobox6").className="commo_box_on";
	}
}
function tooglecommobox7(){
	if(document.getElementById('commobox7').value=='on'){
		document.getElementById('commobox7').value='off';
		document.getElementById("nb_commobox7").className="commo_box_off";
	}
	else{
		document.getElementById('commobox7').value='on';
		document.getElementById("nb_commobox7").className="commo_box_on";
	}
}
function tooglecommobox8(){
	if(document.getElementById('commobox8').value=='on'){
		document.getElementById('commobox8').value='off';
		document.getElementById("nb_commobox8").className="commo_box_off";
	}
	else{
		document.getElementById('commobox8').value='on';
		document.getElementById("nb_commobox8").className="commo_box_on";
	}
}
function tooglecommobox9(){
	if(document.getElementById('commobox9').value=='on'){
		document.getElementById('commobox9').value='off';
		document.getElementById("nb_commobox9").className="commo_box_off";
	}
	else{
		document.getElementById('commobox9').value='on';
		document.getElementById("nb_commobox9").className="commo_box_on";
	}
}

// Meme chose mais pour le type d annonce
function toogleannonce1(){
	if(document.getElementById('annonce_part').value=='on' && (document.getElementById('annonce_agence').value=='on' || document.getElementById('annonce_promo').value=='on')){
		document.getElementById('annonce_part').value='off';
		document.getElementById('a_particulier').className="ann_bg_etat_off";
	}
	else{
		document.getElementById('annonce_part').value='on';
		document.getElementById('a_particulier').className="ann_bg_etat_on";
	}
}
function toogleannonce2(){
	if(document.getElementById('annonce_agence').value=='on' && (document.getElementById('annonce_promo').value=='on' || document.getElementById('annonce_part').value=='on')){
		document.getElementById('annonce_agence').value='off';
		document.getElementById('a_agence').className="ann_bg_etat_off";
	}
	else{
		document.getElementById('annonce_agence').value='on';
		document.getElementById('a_agence').className="ann_bg_etat_on";
	}
}
function toogleannonce3(){
	if(document.getElementById('annonce_promo').value=='on' && (document.getElementById('annonce_agence').value=='on' || document.getElementById('annonce_part').value=='on')){
		document.getElementById('annonce_promo').value='off';
		document.getElementById('a_promoteur').className="ann_bg_etat_off";
	}
	else{
		document.getElementById('annonce_promo').value='on';
		document.getElementById('a_promoteur').className="ann_bg_etat_on";
	}
}

// Affiche & cache la div contenant les checkbox type de bien
function affiche_checkbox_type(){
	/*
	if(document.getElementById('checkbox_type').style.display=='block'){
	document.getElementById('checkbox_type').style.display='none';
	document.getElementById('close_checkbox_type').style.display='none';
	//document.getElementById('select_ie_visible').style.visibility='visible';
	}
	else{

	document.getElementById('checkbox_type').style.display='block';
	document.getElementById('close_checkbox_type').style.display='block';
	//document.getElementById('select_ie_visible').style.visibility='hidden';
	}
	*/


	if(document.getElementById('checkbox_type').style.display=='none'){

		document.getElementById('checkbox_type').style.display='block';
		document.getElementById('type_bien_span').className='type_bien_on';
	}
	else{

		document.getElementById('checkbox_type').style.display='none';
		document.getElementById('type_bien_span').className='type_bien_off';
	}
}


function hide_checkbox_type(){

	if(document.getElementById('checkbox_type').style.display=='block' && display_checkbox_type == false){
		document.getElementById('checkbox_type').style.display='none';
		document.getElementById('type_bien_span').className='type_bien_off';
	}
	init_checkbox_type(false);

}


function hide_checkbox_type_alert(){

	if(document.getElementById('checkbox_type_alert').style.display=='block' && display_checkbox_type_alert == false){
		document.getElementById('checkbox_type_alert').style.display='none';
		document.getElementById('type_bien_alert').className='type_bien_off';
	}

	init_checkbox_type_alert(false);
}


function init_checkbox_type(val) {
	display_checkbox_type = val;
}

// Affiche & cache la div contenant les checkbox type de d'offre
function affiche_checkbox_type_offre(){
	if(document.getElementById('checkbox_type_offre').style.display=='block'){
		document.getElementById('checkbox_type_offre').style.display='none';
		document.getElementById('close_checkbox_type_offre').style.display='none';
		//document.getElementById('select_ie_visible').style.visibility='visible';
	}
	else{

		document.getElementById('checkbox_type_offre').style.display='block';
		document.getElementById('close_checkbox_type_offre').style.display='block';
		//document.getElementById('select_ie_visible').style.visibility='hidden';
	}
}

function hide_checkbox_type_offre(){

	if(document.getElementById('checkbox_type_offre').style.display=='block' && display_checkbox_type_offre == false){
		document.getElementById('checkbox_type_offre_offre').style.display='none';
		document.getElementById('close_checkbox_type_offre').style.display='none';
	}
	init_checkbox_type_offre(false);

}

function init_checkbox_type_offre(val) {

	display_checkbox_type_offre = val;
}


function display_price_versus_type_offre(ischecked, valeur, pays)
{




	var slovaquie = "1";
	var pologne   = "2";
	var hongrie   = "3";
	var tcheque   = "4";

	var vente      = "1";
	var location   = "2";
	var colocation = "3";

	var temp = valeur + '-' + pays;

	/*
	alert(ischecked);
	alert('val passee=' +  temp);
	alert('val calculee=' +  vente + '-' + slovaquie);
	*/


	if (ischecked)
	{

		var elt = document.getElementById('add_example');
		/*
		render = '<div class="ui-slider-handle" id="example_1" style="left: 14px;"><span class="slider-handle" id="ui_slider1"></span></div>';
		render += '<div class="ui-slider-handle" id="example_2" style="left: 188px;"><span class="slider-handle" id="ui_slider2"></span></div>';
		*/
		render = '<div class="ui-slide_borne">';
		render += '<span>0</span>';


		switch (temp)
		{
			case  vente + '-' + slovaquie :
			case  vente + '-' + tcheque :
			render += '<span>1 mil</span>';
			render += '<span>2 mil</span>';
			render += '<span>3 mil</span>';
			render += '<span>4 mil</span>';
			render += '<span>5 mil</span>';

			document.getElementById('slider_max').value = 5000000;
			document.getElementById('slider_unit').value = "mil";
			document.getElementById('slider_nb').value = 6;
			document.getElementById('ui_slider1').innerHTML = "2";
			document.getElementById('ui_slider2').innerHTML = "4";

			//alert('cas 1');
			break;

			case  location + '-' + slovaquie :
			case  location + '-' + tcheque :
			render += '<span>5 000</span>';
			render += '<span>10 000</span>';
			render += '<span>15 000</span>';
			render += '<span>20 000</span>';
			render += '<span>25 000</span>';
			document.getElementById('slider_max').value = 25000;
			document.getElementById('slider_unit').value = "mil";
			document.getElementById('slider_nb').value = 6;
			document.getElementById('ui_slider1').innerHTML = "10 000";
			document.getElementById('ui_slider2').innerHTML = "20 000";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";

			//alert('cas 2');
			break;

			case  colocation + '-' + slovaquie :
			case  colocation + '-' + tcheque :
			render += '<span>3 000</span>';
			render += '<span>6 000</span>';
			render += '<span>9 000</span>';
			document.getElementById('slider_max').value = 9000;
			document.getElementById('slider_unit').value = "mil";
			document.getElementById('slider_nb').value = 4;

			document.getElementById('ui_slider1').innerHTML = "4 500";
			document.getElementById('ui_slider2').innerHTML = "7 500";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";

			//alert('cas 3');
			break;

			case  vente + '-' + pologne :
			render += '<span>150 tis</span>';
			render += '<span>300 tis</span>';
			render += '<span>450 tis</span>';
			render += '<span>600 tis</span>';
			render += '<span>750 tis</span>';


			document.getElementById('slider_max').value = 750;
			document.getElementById('slider_unit').value = "tis";
			document.getElementById('slider_nb').value = 6;

			document.getElementById('ui_slider1').innerHTML = "300";
			document.getElementById('ui_slider2').innerHTML = "600";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";

			//alert('cas 4');
			break;

			case  location + '-' + pologne :
			render += '<span>1500</span>';
			render += '<span>3000</span>';
			render += '<span>4500</span>';
			render += '<span>6000</span>';
			render += '<span>75000</span>';

			document.getElementById('slider_max').value = 75000;
			document.getElementById('slider_unit').value = "";
			document.getElementById('slider_nb').value = 6;

			document.getElementById('ui_slider1').innerHTML = "3000";
			document.getElementById('ui_slider2').innerHTML = "6000";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";


			//alert('cas 5');
			break;

			case  colocation + '-' + pologne :
			render += '<span>1000</span>';
			render += '<span>2000</span>';
			render += '<span>3000</span>';


			document.getElementById('slider_max').value = 3000;
			document.getElementById('slider_unit').value = "";
			document.getElementById('slider_nb').value = 4;

			document.getElementById('ui_slider1').innerHTML = "1500";
			document.getElementById('ui_slider2').innerHTML = "2500";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";

			//alert('cas 6');
			break;

			case  vente + '-' + hongrie :
			render += '<span>20 mil</span>';
			render += '<span>40 mil</span>';
			render += '<span>60 mil</span>';
			render += '<span>80 mil</span>';
			render += '<span>100 mil</span>';

			document.getElementById('slider_max').value = 100;
			document.getElementById('slider_unit').value = "mil";
			document.getElementById('slider_nb').value = 6;

			document.getElementById('ui_slider1').innerHTML = "40";
			document.getElementById('ui_slider2').innerHTML = "80";

			//alert('cas 7');
			break;

			case  location + '-' + hongrie :
			render += '<span>150 000</span>';
			render += '<span>300 000</span>';
			render += '<span>450 000</span>';
			render += '<span>600 000</span>';
			render += '<span>750 000</span>';


			document.getElementById('slider_max').value = 150000;
			document.getElementById('slider_unit').value = "";
			document.getElementById('slider_nb').value = 6;

			document.getElementById('ui_slider1').innerHTML = "300 000";
			document.getElementById('ui_slider2').innerHTML = "600 000";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";

			//alert('cas 8');
			break;

			case  colocation + '-' + hongrie :
			render += '<span>15 000</span>';
			render += '<span>30 000</span>';
			render += '<span>45 000</span>';

			document.getElementById('slider_max').value = 45000;
			document.getElementById('slider_unit').value = "";
			document.getElementById('slider_nb').value = 4;

			document.getElementById('ui_slider1').innerHTML = "22 500";
			document.getElementById('ui_slider2').innerHTML = "37 500";

			document.getElementById('ui_slider1').style.width = "50px;";
			document.getElementById('ui_slider2').style.width = "50px;";


			//alert('cas 9');
			break;

			default:
			render += '<span>1 mil</span>';
			render += '<span>2 mil</span>';
			render += '<span>3 mil</span>';
			render += '<span>4 mil</span>';
			render += '<span>5 mil</span>';

			document.getElementById('slider_max').value = 5;
			document.getElementById('slider_unit').value = "mil";
			document.getElementById('slider_nb').value = 6;

			document.getElementById('ui_slider1').innerHTML = "2";
			document.getElementById('ui_slider2').innerHTML = "4";

			//alert('cas 10');
			break;
		}


		render += '<span>+</span>';
		render += '</div>';


		elt.innerHTML = render;

		document.getElementById('example_1').style.display = 'block';
		document.getElementById('example_2').style.display = 'block';

	}
}


// Affiche la partie photo dans la fiche detail
function affiche_detail_photo(lien){
	if(document.getElementById('detail_bloc_photo').style.display=='none'){
		window.location.href=lien;
	}
}

// Affiche la partie carte dans la fiche detail
function affiche_detail_carte(lien){

	if(document.getElementById('detail_bloc_carte').style.display=='none'){

		window.location.href=lien;
	}
}

// Affiche la partie financer dans la fiche detail
function affiche_detail_financer(lien){
	if(document.getElementById('detail_bloc_financer').style.display=='none'){

		window.location.href=lien;

	}
}

// Affiche la partie habiter dans la fiche detail
function affiche_detail_habiter(lien){
	if(document.getElementById('detail_bloc_habiter').style.display=='none'){

		window.location.href=lien;

	}
}

// Affiche la partie photo dans la fiche detail
function affiche_detail_repondre(lien){
	if(document.getElementById('detail_bloc_repondre').style.display=='none'){

		window.location.href=lien;

	}
}

function toogleetage(id){

	if(document.getElementById('nb_etage'+id).className=='nb_etage etg_bg_etat_on'){

		var liste = "";
		var reg=new RegExp("[,]+", "g");
		var tab = document.getElementById('etage').value.split(reg);
		for(var i = 0; i < tab.length; i ++)
		{
			if(tab[i]!=id)
			{
				if(liste != "")
				{
					liste += ",";
				}
				liste += id;
			}
		}

		document.getElementById('etage').value = liste;
		document.getElementById('nb_etage'+id).className="nb_etage etg_bg_etat_off";
	}
	else{

		var liste = document.getElementById('etage').value;
		if(liste != "")
		{
			liste += ",";
		}
		liste += id;
		document.getElementById('etage').value = liste;
		document.getElementById('nb_etage'+id).className="nb_etage etg_bg_etat_on";
	}
}

function tooglecommobien(id){

	if(document.getElementById('nb_commobien'+id).className=='commo_box_on'){

		var liste = "";
		var reg=new RegExp("[,]+", "g");
		var tab = document.getElementById('commobien').value.split(reg);
		for(var i = 0; i < tab.length; i ++)
		{
			if(tab[i]!=id)
			{
				if(liste != "")
				{
					liste += ",";
				}
				liste += id;
			}
		}

		document.getElementById('commobien').value = liste;
		document.getElementById('nb_commobien'+id).className="commo_box_off";
	}
	else{

		var liste = document.getElementById('commobien').value;
		if(liste != "")
		{
			liste += ",";
		}
		liste += id;
		document.getElementById('commobien').value = liste;
		document.getElementById('nb_commobien'+id).className="commo_box_on";
	}
}



function tooglecommoimmeuble(id){

	if(document.getElementById('nb_commoimmeuble'+id).className=='commo_box_on'){

		var liste = "";
		var reg=new RegExp("[,]+", "g");
		var tab = document.getElementById('commoimmeuble').value.split(reg);
		for(var i = 0; i < tab.length; i ++)
		{
			if(tab[i]!=id)
			{
				if(liste != "")
				{
					liste += ",";
				}
				liste += id;
			}
		}

		document.getElementById('commoimmeuble').value = liste;
		document.getElementById('nb_commoimmeuble'+id).className="commo_box_off";
	}
	else{

		var liste = document.getElementById('commoimmeuble').value;
		if(liste != "")
		{
			liste += ",";
		}
		liste += id;
		document.getElementById('commoimmeuble').value = liste;
		document.getElementById('nb_commoimmeuble'+id).className="commo_box_on";
	}
}

function toogleDistrict(id, index)
{
	var add = false;
	var box = document.getElementById('quartier_'+index);


	if(box.className == 'ann_bg_etat_off')
	{
		box.className = 'ann_bg_etat_on';
		add = true;
	}
	else
	{
		box.className =	'ann_bg_etat_off';
	}

	var new_list = "";
	if(add)
	{
		new_list = document.getElementById('quartier_liste').value;
		if(new_list.length != 0)
		{
			new_list += ",";
		}
		new_list += id;
	}
	else
	{
		var list = document.getElementById('quartier_liste').value;
		var tab = list.split(',');


		for(var i = 0; i < tab.length; i++)
		{
			if(tab[i] != id)
			{
				if(new_list.length != 0)
				{
					new_list += ",";
				}
				new_list += tab[i];
			}
		}
	}

	document.getElementById('quartier_liste').value = new_list;
}

function toogleCodePostal()
{
	var radio = document.getElementById('mot_cle_cp');
	var codePostal = document.getElementById('codePostal');

	if(radio.className == 'ann_bg_etat_on')
	{
		radio.className = 'ann_bg_etat_off';
		codePostal.value = 0;
	}
	else
	{
		radio.className = 'ann_bg_etat_on';
		codePostal.value = 1;
	}
}

function toogleRue()
{
	var radio = document.getElementById('mot_cle_rue');
	var nomRue = document.getElementById('nomRue');

	if(radio.className == 'ann_bg_etat_on')
	{
		radio.className = 'ann_bg_etat_off';
		nomRue.value = 0;
	}
	else
	{
		radio.className = 'ann_bg_etat_on';
		nomRue.value = 1;
	}
}

function toogleQuartier()
{
	var radio = document.getElementById('mot_cle_quartier');
	var nomQuartier = document.getElementById('nomQuartier');

	if(radio.className == 'ann_bg_etat_on')
	{
		radio.className = 'ann_bg_etat_off';
		nomQuartier.value = 0;
	}
	else
	{
		radio.className = 'ann_bg_etat_on';
		nomQuartier.value = 1;
	}
}

/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "images/loadingAnimation.gif";
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
$(document).ready(function(){
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	//imgLoader = new Image();// preload image
	//imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
		var t = this.title || this.name || null;
		var a = this.href || this.alt;
		var g = this.rel || false;
		var c = $(this).hasClass('TB_individual');
		tb_show(t,a,g);
		if(c) { $("#TB_window").addClass('TB_individual'); }
		this.blur();
		return false;
	});
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link


	//try {

	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css("overflow","hidden");
		if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
			$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
			$("#TB_overlay").click(tb_remove);
		}
	}else{//all others
		if(document.getElementById("TB_overlay") === null){
			$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
			$("#TB_overlay").click(tb_remove);
		}
	}

	if(tb_detectMacXFF()){
		$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
	}else{
		$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
	}

	if(caption===null){caption="";}
	//$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
	$("body").append("<div id='TB_load'></div>");//add loader to the page
	$('#TB_load').show();//show loader

	var baseURL;
	if(url.indexOf("?")!==-1){ //ff there is a query string involved
		baseURL = url.substr(0, url.indexOf("?"));
	}else{
		baseURL = url;
	}

	var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	var urlType = baseURL.toLowerCase().match(urlString);
	if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

		TB_PrevCaption = "";
		TB_PrevURL = "";
		TB_PrevHTML = "";
		TB_NextCaption = "";
		TB_NextURL = "";
		TB_NextHTML = "";
		TB_imageCount = "";
		TB_FoundURL = false;
		if(imageGroup){
			TB_TempArray = $("a[@rel="+imageGroup+"]").get();
			for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
				var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
				if (!(TB_TempArray[TB_Counter].href == url)) {
					if (TB_FoundURL) {
						TB_NextCaption = TB_TempArray[TB_Counter].title;
						TB_NextURL = TB_TempArray[TB_Counter].href;
						TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
					} else {
						TB_PrevCaption = TB_TempArray[TB_Counter].title;
						TB_PrevURL = TB_TempArray[TB_Counter].href;
						TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
					}
				} else {
					TB_FoundURL = true;
					TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
				}
			}
		}
		imgPreloader = new Image();
		imgPreloader.onload = function(){
			imgPreloader.onload = null;

			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth);
				imageWidth = x;
				if (imageHeight > y) {
					imageWidth = imageWidth * (y / imageHeight);
					imageHeight = y;
				}
			} else if (imageHeight > y) {
				imageWidth = imageWidth * (y / imageHeight);
				imageHeight = y;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth);
					imageWidth = x;
				}
			}
			// End Resizing

			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src='"+abs_path_img+"home_recherche/fd_select_type_bien-close.gif' title='Close' /></a></div>");

			$("#TB_closeWindowButton").click(tb_remove);

			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;
				}
				$("#TB_prev").click(goPrev);
			}

			if (!(TB_NextHTML === "")) {
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);
					return false;
				}
				$("#TB_next").click(goNext);

			}
			document.onkeydown = function(e){
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}
			};

			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
		};

		imgPreloader.src = url;
	}else{//code to show html

		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = tb_parseQuery( queryString );


		TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
		TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
		ajaxContentW = TB_WIDTH - 30;
		ajaxContentH = TB_HEIGHT - 45;

		if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
			urlNoQuery = url.split('TB_');

			$("#TB_iframeContent").remove();

			if(params['modal'] != "true"){//iframe no modal

				$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src='"+abs_path_img+"home_recherche/fd_select_type_bien-close.gif' title='Close' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");

			}else{//iframe modal

				$("#TB_overlay").unbind();
				$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
			}
		}else{// not an iframe, ajax
			if($("#TB_window").css("display") != "block"){
				if(params['modal'] != "true"){//ajax no modal
					$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><img src='"+abs_path_img+"home_recherche/fd_select_type_bien-close.gif' title='Close' /></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
				}else{//ajax modal
					$("#TB_overlay").unbind();
					$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
				}
			}else{//this means the window is already up, we are just loading new content via ajax
				$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
				$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
				$("#TB_ajaxContent")[0].scrollTop = 0;
				$("#TB_ajaxWindowTitle").html(caption);
			}
		}


		$("#TB_closeWindowButton").click(tb_remove);

		if(url.indexOf('TB_inline') != -1){
			$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
			$("#TB_window").unload(function () {
				$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
			});
			tb_position();
			$("#TB_load").remove();
			$("#TB_window").css({display:"block"});
		}else if(url.indexOf('TB_iframe') != -1){
			tb_position();
			if($.browser.safari){//safari needs help because it will not fire iframe onload
				$("#TB_load").remove();
				$("#TB_window").css({display:"block"});
			}
		}else{
			$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
				tb_position();
				$("#TB_load").remove();
				tb_init("#TB_ajaxContent a.thickbox");
				$("#TB_window").css({display:"block"});
			});
		}

	}
	if(!params['modal']){
		document.onkeyup = function(e){
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			if(keycode == 27){ // close
				tb_remove();
			}
		};
	}

	//}
	/*
	catch(e) {

	}
	*/
	//nothing here
	//alert(e);

}

//helper functions below
function tb_showIframe(){


	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}
function tb_remove() {
	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}
function tb_position() {
	$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}
function tb_parseQuery ( query ) {
	var Params = {};
	if ( ! query ) {return Params;}// return empty object
	var Pairs = query.split(/[;&]/);
	for ( var i = 0; i < Pairs.length; i++ ) {
		var KeyVal = Pairs[i].split('=');
		if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
		var key = unescape( KeyVal[0] );
		var val = unescape( KeyVal[1] );
		val = val.replace(/\+/g, ' ');
		Params[key] = val;
	}
	return Params;
}
function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}
function tb_detectMacXFF() {
	var userAgent = navigator.userAgent.toLowerCase();
	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
		return true;
	}
}

function selectValue(elem, value, input){
	document.getElementById(input).value = value;
	$("#"+input).val(value);
	$("."+input).removeClass('checkbox_active');
	$(elem).addClass('checkbox_active');
	return true;
}

function CompanyInfo(status){
	if(status){
		$(".invoice_info .column_right").fadeIn('fast');
	} else {
		$(".invoice_info .column_right").fadeOut('fast');
	}
}

function selectCredits(eur, skk, credits){
	document.getElementById('prix_total_hidden').value = eur;
	document.getElementById('conversion_total_hidden').value = skk;
	document.getElementById('nb_hidden').value = credits;
}

function checkInvoiceInfo(){
	document.getElementById('order_credits').submit();
	return true;

	var organization = document.getElementById('organization').value;
	var check = true;

	var name = document.getElementById('nom').value;
	var surname = document.getElementById('prenom').value;
	var address = document.getElementById('address').value;
	var city = document.getElementById('city').value;
	var zip = document.getElementById('zip').value;

	check = (name != '' && surname != '' && address != '' && city != '' && zip != '');

	if(organization == 2){
		var company = document.getElementById('company').value;
		var ico = document.getElementById('ico').value;
		check &= (company != '' && ico != '');
	}
	if(!check){
		alert(get_trad_champ("fill_invoice"));
	} else {
		document.getElementById('order_credits').submit();
	}
	return check;
}

function submit_competition(){
	if($("#name").val() == '' || $("#phone").val() == '' || $("#email").val() == ''){
		alert(get_trad_champ("fill_contact"));
	} else {
		document.getElementById('competition').submit();
	}
}

function InitializeOffers(){
  map_offers = true;
  map_pricemap = false;
  map_services = false;
  map_rea = false;
  map.clearOverlays();

  $(".map_features_controls h2").fadeOut('medium',function() { $(this).html($("#offer_control_panel .gmap_title").html()); }).fadeIn();

  $("#result_page_redirect").show();
  $("#services_bar").slideUp("250");
  //localize('Bratislava', 15);
  $("div.control_panel").hide();
  $("#offer_control_panel").show();
  //get_selection();
  load_selection();
}

function InitializeServices(service_type){
  map_offers = false;
  map_pricemap = false;
  map_projects = false;
  map_rea = false;
  map_services = true;
  map.clearOverlays();

  $(".map_features_controls h2").fadeOut('medium',function(){$(this).html($("#services_control_panel .gmap_title").html()); }).fadeIn();

  $("#projects_bar").slideUp(250,function() { $("#services_bar").slideDown(500); });
  $("div.control_panel").hide();
  $("#result_page_redirect").hide();
  $("#services_bar").slideDown(500);

  $("#services_bar img").each(function() { //disable all service types
  	var addr = $(this).attr("src");
  	addr = addr.replace("services/active", "services");
  	$(this).attr("src",addr);
  });
  var addr1 = $("#services_bar img:first").attr("src"); //and make first one active
  addr1 = addr1.replace("services", "services/active");
  $("#services_bar img:first").attr("src",addr1);

  switch(service_type){
    case 25:
      $('#agencies_control_panel').show();
      break;
    case 26:
      $('#hotels_control_panel').show();
      break;
    default:
      $('#services_control_panel').show();
  }
  document.getElementById("service_types").value = service_type;
  load_services_home();
}

function InitializeRea(){
  map_offers = false;
  map_pricemap = false;
  map_services = false;
  map_rea = true;
  map.clearOverlays();

  GEvent.addListener(map,"moveend", function(point) {
    load_realestate();
  });
  GEvent.addListener(map,"zoomend", function(point) {
    load_realestate();
  });
  $("div.control_panel").hide();
  $('#agencies_control_panel').show();

  load_realestate();
}

function highlight_offer(key,type){
	var curr_pt = G_offers[key];
	map.removeOverlay(G_offers[key]);
	G_offers[key] = curr_pt;
	map.addOverlay(G_offers[key]);
	var picture = "-project-on";
	if(type) {
		switch(type) {
			case 1 : picture = "-project-on"; break;
			case 2 : picture = "-project-gold-on"; break;
		}
	}
  G_offers[key].setImage(abs_path_img+"googlemap/picto" + picture + ".png");
}
function dimm_offer(key,type){
	var picture = "-project";
	if(type) {
		switch(type) {
			case 1 : picture = "-project"; break;
			case 2 : picture = "-project-gold"; break;
		}
	}
  G_offers[key].setImage(abs_path_img+"googlemap/picto" + picture + ".png");
}
function highlight_rea(key){
  G_offers[key].setImage(abs_path_img+"googlemap/picto_agency-on.png");
}
function highlight_rea_pro(key){
  G_offers[key].setImage(abs_path_img+"googlemap/picto_agency-on.png");
}
function dimm_rea(key){
  G_offers[key].setImage(abs_path_img+"googlemap/picto_agency.png");
}
function dimm_rea_pro(key){
  G_offers[key].setImage(abs_path_img+"googlemap/picto_agency_gold.png");
}

function unload() {
	GUnload();
	if($("#GM_type").val() == "search") {
		SetCookie("scrollOffset",document.documentElement.scrollTop+'');
	}
}

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return "";
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length;
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function DeleteCookie(name) {
	document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}

function validate_step_2() {
	if ((document.getElementById("coord_y").value > 49.62027501307051) || (document.getElementById("coord_y").value < 47.66307516642836)) {
		alert(get_trad_champ("alert_offer_misplaced"));
		return 0;
	}
	if ((document.getElementById("coord_x").value > 22.58136749267578) || (document.getElementById("coord_x").value < 16.829467)) {
		alert(get_trad_champ("alert_offer_misplaced"));
		return 0;
	}

	document.getElementById('form_depot_annonce').submit();
}

/* Projects related script */

$(document).ready(function(){
	$('.showcase_carousel').fadeIn(1000, function() {
  	$('.showcase_carousel').cycle({
		    fx:     'fade',
		    speed:  2000,
		    timeout: 5000,
		    pause:	1,
		    fastOnEvent:	500,
		    pager:  '#showcase_controls'
		});
  })
  $('.showcase_controls_wrap').fadeIn(1000);

	$('.map_features_controls select').change(function () {
		load_projects();
	});
	$(".map_features_controls input").keyup(function () {
		clearTimeout(G_timer);
			G_timer = setTimeout("load_projects()", 1000);
	});
});

function load_projects(){
    $("#info_window").hide();
    $(".projects_search_carousel").css("left","-5000px").css("width","0px");
    $(".projects_loader").fadeIn();
    var bounds = map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var link = "";
    link = link + "&type=" + $('#project_types').val();
    link = link + "&city_id=" + $('#project_city_id').val();

    if(!$(".map_features_controls input").hasClass("disabled")) {
    	link = link + "&keyword=" + $("#project_keyword").val();
    }

  	$.ajax({
  		type: "GET",
  		data: "&univers="+document.getElementById('univers').value + link,
  		url: abs_path+"ajax/ajax_projects.php",
  		success: function(msg){
  		  try{
  			 map.clearOverlays();
  		  } catch(err){
          map.closeInfoWindow();
  		  }

  		  GEvent.addListener(map, "dragstart", function() {
		    		hideInfo();
		  	});

  			$(".projects_search_carousel").html("");
  			var tab = msg.replace(/^\s*/, "").replace(/\s*$/, "").split('|');
  			if(tab[0] == "ko")
  			{
  				$(".projects_search_carousel_left,.projects_search_carousel_right").hide();
  				$(".projects_search_carousel").css("left","-5000px");
  				$("#projects_bar span.no_offers").html(tab[1]);
  				$("#projects_bar").css("left","0").css("height","28px").slideDown("250");

  				mgr.clearMarkers();

  				/* Center map on Slovakia */
  				geocoder = new GClientGeocoder();
  				search_geocode("Slovakia", 7, "Place not found");
  			}
  			else
  			{
  				var result = "<ul>";
  				var points = new Array();
  				var top_points = new Array();
  				var count_list = tab.length-1;
  				var min_lat = -1;
					var min_lon = -1;
					var max_lat = -1;
					var max_lon = -1;

  				for(var i = 1; i < tab.length; i++)
  				{
  					var point = tab[i].split('##');
  					var lat = point[0];
  					var lon = point[1];
  					var latlng = lat + "_" + lon;
  					points[latlng] = point[2];
  					result += "<li>"+point[3]+"</li>";
  					if(point[4] == "1") {
  						top_points[latlng] = "1";
  					} else {
  						top_points[latlng] = "0";
  					}

  					if(lat < min_lat || min_lat == -1)
						{
							min_lat = lat;
						}
						if(lat > max_lat || max_lat == -1)
						{
							max_lat = lat;
						}
						if(lon < min_lon || min_lon == -1)
						{
							min_lon = lon;
						}
						if(lon > max_lon || max_lon == -1)
						{
							max_lon = lon;
						}
  				}

  				result += "</ul>";

  				G_offers = new Array();

  				for ( i in points) {
  					var point = i.split('_');
  					create_google_point(point[0],point[1],points[i],1,top_points[i]);
  				}

  				var batch = [];
  				var batch1 = [];
  				var batch2 = [];
  				var batch3 = [];

					for(id in G_offers) {
						batch.push(G_offers[id]);
					}

					mgr.clearMarkers();

  				mgr.addMarkers(batch, 1);
  				mgr.refresh();

  				center_google_map(min_lat,min_lon,max_lat,max_lon);

 				  $(".projects_search_carousel").html(result);

 				  $("#projects_bar span.no_offers").html("");

 				  if(count_list < 6) {
  					$(".projects_search_carousel_left,.projects_search_carousel_right").hide();
  					$(".projects_search_carousel").jCarouselLite({
					      visible: count_list
					  });
  				} else {
  					$(".projects_search_carousel_left,.projects_search_carousel_right").show();
  					$(".projects_search_carousel").jCarouselLite({
					      btnNext: ".projects_search_carousel_right",
					      btnPrev: ".projects_search_carousel_left",
					      scroll: 1,
					      visible: 6,
					      circular: false,
					      mouseWheel: true
					  });
  				}
  				$("#projects_bar").css("height","118px").css("left","0");
  			}
  			$(".projects_loader").fadeOut();
  		},
  		error: function(){
  			$(".projects_loader").fadeOut();
  		}
  	});
}

function InitializeProjects(){
	map_services = false;
	map_projects = true;
	map.clearOverlays();

	$("#services_bar").slideUp("250");
	load_projects();
	$("#projects_bar").slideDown("250");
}

/* END: Project related scripts */

tick = function() { }
