﻿var myMap = null; //la carte objet
var mgr; //manager de marqueurs
var icons = {};
var allmarkers = [];
var zoom_min = 6;
var zoom_max = 13;

// ******** Initialisation ********* //
window.onload = function() {
 
//on affcihe map si le mode cacher carte n'est pas active !
if (document.getElementById("map") && globals.display_map!=0) { displayMap();}
                
//autocomplete 
var oSuggestionProvider = new SuggestionProvider();

var oAutoSuggestControl = new AutoSuggestControl(document.getElementById("dest"), oSuggestionProvider);  

//alert(globals.loc_id);
oAutoSuggestControl.hideSuggestions();
//remplissage de filtres
stringToCombo(); 


//calendrier
$("#datego").datepicker($.extend({}, $.datepicker.regional[""+globals.lang+""], {showStatus: true, showOn: "both", 
minDate: new Date(),
yearRange: '-1:+1',
dateFormat: 'dd-mm-yy',
buttonImage: globals.server+"/anyimages/global/pict_calendrier.gif", buttonImageOnly: true })).attr("readonly", "readonly");
	
//popups initialization
/*
    jQuery(document).ready(function($) {
      $('a[rel*=popups]').popups() 
    });
    */
 document.getElementById("dest").onclick = function()
 { 
     
     mydestValue = document.getElementById("dest").value;
     //test si carac interdits
     if(mydestValue==globals.langs_indifferent)
     {	  	  	
        document.getElementById("dest").value='';
        document.getElementById("dest").focus();
    	
     }
     //alert("id:"+globals.loc_id);
	 //alert("name:"+globals.location_name);
	 
	 if((globals.location_name != '') && (globals.location_name != globals.langs_indifferent))
	 {
		if(document.getElementById("dest").value != globals.location_name)
		{
			oAutoSuggestControl.setUsertext(document.getElementById("dest").value);
			oSuggestionProvider.requestSuggestions(oAutoSuggestControl,true);
		}
	 }
	 else
	 {
		oAutoSuggestControl.setUsertext(document.getElementById("dest").value);
		oSuggestionProvider.requestSuggestions(oAutoSuggestControl,true);
	 }
	       
 }
  
}//end onload

//Fonctions de gestion des cookies
function setCookie(name,value,expires,path,domain,secure)
{   //alert(name+":"+value+":"+expires+":"+path+":"+domain+":"+secure);
//alert(expires.toGMTString());alert(escape(value));

    cookieProperties = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires.toGMTString(): "")
    + ((path) ? ";path=" + path : "")
    + ((domain) ? ";domain=" + domain : "")
    + ((secure) ? ";secure" : "");
    //alert(cookieProperties);
    document.cookie = cookieProperties;
}

function getCookie(name)
{
    if(document.cookie)
    {//Un cookie a-t-il été créé?
    
        index = document.cookie.indexOf(name);
        if(index != -1)
        {
            startPos = (document.cookie.indexOf("=",index)+1);
            endPos = document.cookie.indexOf(";",index);
            if(endPos==-1){
                endPos = document.cookie.length;
            }
            return unescape(document.cookie.substring(startPos,endPos));
        }
    }
    return null;
}

//Fonction utilisée pour ne plus afficher le message
//en cas de grand nombre de destinations trouvées
function no_more_display_message()
{   
    var echeance = new Date();
    var oneDayDuration = echeance.getTime() + (1 * 24 * 60 * 60 * 1000);
    echeance.setTime(oneDayDuration);
    
    jQuery.popups.close();
    
    setCookie("nmdm","1",echeance,"/","","");
    //alert(getCookie("nmdm"));
}

//***** Module GO ******////
                   
//Button cacher filtres "go"
function show_filters(){
  if(navigator.appName == 'Microsoft Internet Explorer')
    {
        //var ar = document.getElementById("ar_recherche_avancee").getAttribute("style").display;
        var ar = $("#ar_recherche_avancee").css("display");
    }
    else
    {
        var ar = document.getElementById("ar_recherche_avancee").style.display;
    }
      
        
    switch (ar) 
    { 
        case 'block':
           case '':
      
            document.getElementById("ar_recherche_avancee").style.display = 'none';
           
           globals.display_ref_listing = 0;
 		    globals.display_filters = 0;
 	
            break;
        case 'none':
     
            document.getElementById("ar_recherche_avancee").style.display = 'block';
            document.getElementById("ar_recherche_refannonce").style.display = 'none';
            document.getElementById("ar_go_center").style.display = 'none';
            
           globals.display_ref_listing = 0;
 		    globals.display_filters = 1;
            break; 
        default: 
            break; 
    }
 }
 
  
 //button cacher reference "go"
 function show_ref(){
  if(navigator.appName == 'Microsoft Internet Explorer')
    {
        //var ar = document.getElementById("ar_recherche_refannonce").getAttribute("style").display;
        var ar = $("#ar_recherche_refannonce").css("display");
    }
    else
    {
        var ar = document.getElementById("ar_recherche_refannonce").style.display;
    }
          
        
    switch (ar) 
    { 
        case 'block':
           case '':
            document.getElementById("ar_recherche_refannonce").style.display = 'none';
            break;
        case 'none':
            document.getElementById("ar_recherche_avancee").style.display = 'none';
            document.getElementById("ar_recherche_refannonce").style.display = 'block';
            document.getElementById("ar_go_center").style.display = 'none';
            globals.display_ref_listing = 1;
     		globals.display_filters = 0;
            break; 
        default: 
            break; 
    } 
 }


 
//button cacher carte "go"
function show_map(){

    if (document.getElementById("hide_map")){
         if (!document.getElementById('map') || document.getElementById('map').style.display == 'none'){

            globals.display_map = 1;
            //pour eviter bug affichage carte incomplete : si on arrive sur la page ou la carte est caché, et on ouvre la carte sans redirect en affichant le div, on a un bug : la carte est incomplete et la destination trouve mais pas centree
            redirect();

        } //end if 
        else {
            //document.getElementById('map').style.display = 'none';

            globals.display_map = 0;
            redirect();
        }

    }//end if 

} 



 //***** end Module GO ******////
 
 
 //***** Module MAIN Home page ******////

 //afficher filtres home page
 function show_filters_home()
 {
    if(navigator.appName == 'Microsoft Internet Explorer')
    {
        //var ar = document.getElementById("ar_recherche_avancee").getAttribute("style").display;
        var ar = $("#ar_recherche_avancee").css("display");
    }
    else
    {
        var ar = document.getElementById("ar_recherche_avancee").style.display;
    }
        
        
    switch (ar) 
    { 
        case 'block':
        case '':
            document.getElementById("ar_recherche_avancee").style.display = 'none';
            globals.display_ref_listing = 0;
     		globals.display_filters = 0;
            break;
        case 'none':
            document.getElementById("ar_recherche_avancee").style.display = 'block';
            document.getElementById("ar_carte").style.display = 'none';
            document.getElementById("ar_recherche_refannonce").style.display = 'none';
            globals.display_ref_listing = 0;
     		globals.display_filters = 1;
            break; 
        default: 
            break; 
    } 
 }
 
 //afficher map "home"
  function show_map_home(){
    if(navigator.appName == 'Microsoft Internet Explorer')
    {
        //var ar = document.getElementById("ar_carte").getAttribute("style").display;
        var ar = $("#ar_carte").css("display");
    }
    else
    {
        var ar = document.getElementById("ar_carte").style.display;
    }
       
    switch (ar) 
    { 
        case 'block':
        case '':
            document.getElementById("ar_carte").style.display = 'none';
            break;
        case 'none':
            document.getElementById("ar_recherche_avancee").style.display = 'none';
            document.getElementById("ar_carte").style.display = 'block';
            document.getElementById("ar_recherche_refannonce").style.display = 'none';
            break; 
        default: 
            break; 
    } 
 }
 
 //afficher ref annonce "home"
  function show_ref_home(){
   if(navigator.appName == 'Microsoft Internet Explorer')
    {
        //var ar = document.getElementById("ar_recherche_refannonce").getAttribute("style").display;
        var ar = $("#ar_recherche_refannonce").css("display");
    }
    else
    {
        var ar = document.getElementById("ar_recherche_refannonce").style.display;
    }
      
    switch (ar) 
    { 
        case 'block':
        case '':
            document.getElementById("ar_recherche_refannonce").style.display = 'none';
            globals.display_ref_listing = 0;
     		globals.display_filters = 0;
            break;
        case 'none':
            document.getElementById("ar_recherche_avancee").style.display = 'none';
            document.getElementById("ar_carte").style.display = 'none';
            document.getElementById("ar_recherche_refannonce").style.display = 'block';
            globals.display_ref_listing = 1;
     		globals.display_filters = 0;
            break; 
        default: 
            break; 
    } 
}



//***** end Module MAIN ******////
 

 
 
 //**** GENERAL ALL MODULES go, main... ***//
 
 
//lancement de la recherche
function search_button_go() {

        if((document.getElementById("dest").value == '') || (document.getElementById("dest").value == globals.langs_indifferent) || ( document.getElementById("dest").value != globals.location_name ) )
		{
			globals.loc_id = 0;
			globals.location_name='';
		}

        if (globals.loc_id!=0 && (typeof globals.loc_id != "undefined") && globals.location_name!='' && globals.location_name!=globals.langs_indifferent && (typeof globals.location_name != "undefined"))	{
	        location_ = document.getElementById("dest").value;
	        //nuller tout
	        document.getElementById("ref_listing").value = '';  globals.display_ref_listing=0; 
	      globals.zone_ne_lng=0; globals.zone_ne_lat=0; globals.zone_sw_lng=0; globals.zone_sw_lat=0;
        		
        } else {
	        jQuery.popups(js_popup_message_destination_bad);
	        return;
        }

 	  	
            go_location(location_, 'yes');    	
      
       


}


//lancement de la recherche reference "go"
function search_reference(){

if (document.getElementById("button_ref_annonce") && document.getElementById("ref_listing")){
	
       if (document.getElementById("ref_listing").value!='' && (typeof globals.ref_listing != "undefined"))	{
	        globals.ref_listing = document.getElementById("ref_listing").value;
	 	        redirect();
        } else {
	        jQuery.popups(js_chose_ref);
	        document.getElementById("ref_listing").focus();
	        return;
        }

    }

}





	
		
// ******* Afficher la carte ******* //
function displayMap() {
	
if (GBrowserIsCompatible()) {

	
//creation de l'objet carte + controls
  myMap = new GMap2(document.getElementById("map")); 
  point = new GLatLng(globals.center_location_lat, globals.center_location_lng);
  myMap.setCenter(point, globals.map_zoom);   
  myMap.addOverlay( new GMarker(point, {title: globals.location_name}) );  
  myMap.addControl(new GOverviewMapControl());
  myMap.addControl(new GSmallMapControl());
  myMap.addControl(new GMapTypeControl());
 
//zoom limit
  GEvent.addDomListener(
  myMap, "zoomend", function() 
  {
  cur_zoom = myMap.getZoom();

  if (cur_zoom > zoom_max) {
  
  myMap.setZoom(zoom_max);
  
  } else if (cur_zoom < zoom_min){
  myMap.setZoom(zoom_min);
  }
  
  }
  );
  

//button voir annonces sur la carte
function MapButtonControl() {
}
MapButtonControl.prototype = new GControl();
MapButtonControl.prototype.initialize = function(myMap) {
  var container = document.createElement("div");
  var reloaddiv = document.createElement("div");
  this.setButtonStyle_(reloaddiv);
  container.appendChild(reloaddiv);
  reloaddiv.innerHTML = (js_refresh_map_listings);
 
  GEvent.addDomListener(reloaddiv, "click", function() {
	  

 //zone rectanguliere visible de la carte pour faire marcher recherche actualiser annonces sur la carte
bounds = myMap.getBounds();
southWest = bounds.getSouthWest();
northEast = bounds.getNorthEast();

globals.zone_ne_lat = northEast.lat();
globals.zone_ne_lng = northEast.lng();
globals.zone_sw_lat = southWest.lat();
globals.zone_sw_lng = southWest.lng();
  
setWaitOverlay();

$.ajax({
  type: "GET",
  url: globals.server+globals.lang+"/go/loc/"+compose_url_redirect(true)+"~geosearch/",
  dataType: "script",
  cache: false,
 success: function(){
 if (typeof MLayer != "undefined"){
if (mgr){
 mgr.clearMarkers();  
 }
mgr = new MarkerManager(myMap, {trackMarkers:true});
setupMarkers();
//removeWaitOverlay();



 } 
     
   },
 complete: function(){
	removeWaitOverlay();
 }

  
});

   
  });// end GEvent.addDomListener(reloaddiv, "click", function() 

  myMap.getContainer().appendChild(container);
  return container;
}


MapButtonControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

MapButtonControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "none";
  button.style.color = "#000000";
  button.style.backgroundColor = "#FFFFFF";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.textAlign = "center";
  button.style.width = "70px";
  button.style.height = "58px";
  button.style.cursor = "pointer";
  button.style.fontsize = "1";
    button.style.opacity = "0.85";
  button.style.filter = "alpha(opacity=85)";
}
var bottomleft = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(3,35));
myMap.addControl(new MapButtonControl(), bottomleft);
//fin bouton voir  sur la carte
  




//***div mise en attente de resultats de recherhce sur la carte
function MapWaitControl() {
}
MapWaitControl.prototype = new GControl();
MapWaitControl.prototype.initialize = function(myMap) {
  var container = document.createElement("div");
  var waitdiv = document.createElement("div");
  
  this.setButtonStyle_(waitdiv);
  container.appendChild(waitdiv);
  waitdiv.appendChild(document.createTextNode(js_searching));
  
  myMap.getContainer().appendChild(container);
  return container;
}


MapWaitControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

MapWaitControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "blink";
  button.style.color = "red";
  button.style.background = "#B0C3E1 url('/anyimages/loadingAnimation.gif') no-repeat center";
  button.style.font = "16px Arial";
  button.style.border = "1px solid white";
  button.style.padding = "0px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = document.getElementById("map").style.width;
  button.style.height = document.getElementById("map").style.height;
  button.style.opacity = "0.85";
  button.style.filter = "alpha(opacity=85)";
  

}

var myWaitControl = new MapWaitControl();


 function setWaitOverlay() 

{

var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0));

	myMap.addControl(myWaitControl, topRight);


}

function removeWaitOverlay()

{

	myMap.removeControl(myWaitControl);
	

}
//end div wait annones
  
  

   //zone locator
      /* first set of options is for the visual overlay.*/
        var boxStyleOpts = {
          opacity: .35,
          border: "2px solid Gray",
          filter: "alpha(opacity=35)"
        }

        /* second set of options is for everything else */
        var otherOpts = {
          buttonHTML: js_start_map_search,
          buttonZoomingHTML: js_start_map_search_validate,
          buttonStartingStyle: {width: '70px', height: '58px', filter: 'alpha(opacity=85)', opacity: '.85', border: "1px solid #000000"},
          stickyZoomEnabled: false
        };

        /* third set of options specifies callbacks */
        var callbacks = {
           dragend: function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){

            var str_ne=new String(ne);
            var str_sw=new String(sw);
            
            str_ne = str_ne.replace(/ /, "");
            str_sw = str_sw.replace(/ /, "");           
            
            str_ne = str_ne.replace(/\(/, ""); 
            str_sw = str_sw.replace(/\(/, ""); 
            
            str_ne = str_ne.replace(/\)/, ""); 
            str_sw = str_sw.replace(/\)/, ""); 
            
            splited_ne = str_ne.split(",");
            splited_sw = str_sw.split(",");
            
            var num_ne_lat = new Number(splited_ne[0]);
            var num_ne_lng = new Number(splited_ne[1]);              
            str_ne_lat =  num_ne_lat.toFixed(6);
            str_ne_lng =  num_ne_lng.toFixed(6);
            
            
            var num_sw_lat = new Number(splited_sw[0]);
            var num_sw_lng = new Number(splited_sw[1]);             
            str_sw_lat =  num_sw_lat.toFixed(6);
            str_sw_lng =  num_sw_lng.toFixed(6);  
     
     //changer le centre de la map pour affichage
            var str_center = new String(myMap.getCenter());
            str_center = str_center.replace(/ /, "");
            str_center = str_center.replace(/\(/, ""); 
            str_center = str_center.replace(/\)/, ""); 
            str_center_splited = str_center.split(",");
       
    //popup    
    url_redirect = globals.server+globals.lang+'/go/loc/'+globals.langs_indifferent+'~'+str_center_splited[0]+'~'+str_center_splited[1]+'~~'+myMap.getZoom()+'~0~~7~3~0~~1~0~1~1~0~0~'+str_ne_lat+'~'+str_ne_lng+'~'+str_sw_lat+'~'+str_sw_lng+'~0~0~~~~~~~.htm';
    jQuery.popups(js_display_map_listings);
          
          
          
                   
           }
        };
  //ajout control sur la carte
 myMap.addControl(new DragZoomControl(boxStyleOpts, otherOpts, callbacks));
 //zone locator end
 
 
  

// ******** Marker Manager ********* //
  function setupMarkers() {
      allmarkers.length = 0;
      var k = new Number;
      for (var i in MLayer) {
      	
    
        var layer = MLayer[i];
        
        var markers = [];
        
        for (var j in layer["places"]) {
        	
          var place = layer["places"][j];         
          
          var title = place["name"];
          
           var offres = place["offres"];
           
           var url = place["url"];
           
           
           var icon = getIcon(place["icon"],offres);
           var posn = new GLatLng(place["posn"][0], place["posn"][1]);
            
          var marker = createMarker(posn,title,icon,offres,url); 
          markers.push(marker);
          allmarkers.push(marker);    
          
         k++;
          
          
        }
        
        mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
      }
      
      mgr.refresh();
//trop d'annonces trouvees
      if (k >= 50 ) {
        no_more_display_messageCookieValue = getCookie("nmdm");
        if(no_more_display_messageCookieValue != "1")
            jQuery.popups(js_too_many_listings_found); 
      }
     
    }
    

  
  function getIcon(images,offres) {
      var icon = null;  
          icon = new GIcon();
          //icon.image = globals.server+"anyimages/marker.php?n="+offres; 
          if (offres>=100){
          icon.image = globals.server+"anyimages/markers/markeur100.gif";
          }else{
           icon.image = globals.server+"anyimages/markers/markeur"+offres+".gif";
          }
          icon.iconSize = new GSize(20, 34);
          icon.iconAnchor = new GPoint(20, 20);
      return icon;
    }

  
     
    
 function createMarker(posn, title, icon, offres, url) {
    	
  var marker = new GMarker(posn, {title: title+' ('+offres+')', icon: icon});
  
    GEvent.addListener(marker, 'click', function() { 
       
document.location.href=globals.server+globals.lang+url;        

         
  } ); 

      return marker;
    }
  
           

    function deleteMarker() {
      var markerNum = parseInt(document.getElementById("markerNum").value);
      mgr.removeMarker(allmarkers[markerNum]);
    }

    function clearMarkers() {
      mgr.clearMarkers();
    }
   
    function reloadMarkers() {
      setupMarkers();
    }
    


     
	
	
	
	
	
//afficher marquers si coordonees geo sont precisees
if (globals.zone_ne_lat!=0 && globals.zone_ne_lng!=0  && globals.zone_sw_lat!=0  && globals.zone_sw_lng!=0 ){	
setWaitOverlay();



//lancer affichage de marqeurs
$.ajax({
  type: "GET",
  url: globals.server+globals.lang+"/go/loc/"+compose_url_redirect(true)+"~geosearch/",
  dataType: "script",
  cache: false,
 success: function(){
 if (typeof MLayer != "undefined"){
mgr = new MarkerManager(myMap, {trackMarkers:true});
setupMarkers();
//removeWaitOverlay();
 } 
     
   },
 complete: function(){
	removeWaitOverlay();
 }
   

  
});


}//if
	
	
	} //end if Browsrer compatible
	
}//end display map




              
// ******** Resourdre les coordonnees en temps reel ********* //      
function go_location(location_name, redirection){      	

    var geocoder = null;
    
     if (location_name!='' && location_name!=globals.langs_indifferent){
 
    	geocoder = new GClientGeocoder();   

      if (geocoder) {
    
        geocoder.getLatLng(location_name,function(point) {
                
        globals.location_name=location_name;     	  
     	globals.center_location_lat = (point!=null) ? point.lat() : 48.77;
     	globals.center_location_lng = (point!=null) ? point.lng() : 2.39; 
     	globals.map_zoom=(point!=null) ? 10 : 1;
     	
           if(globals.loc_id.length == 2 ) {
               globals.map_zoom = 6;
	        }
	        if(globals.loc_id.length  == 5 ) {
               globals.map_zoom = 7;
	        }
	         if(globals.loc_id.length  == 7 ) {
               globals.map_zoom = 10;
	        }
	        
//afficher la dest trouver sur la carte sans redirect
if (redirection=='no'){
 
	        if(globals.loc_id.length == 2 ) {
               globals.map_zoom = 6;
	        }
	        if(globals.loc_id.length  == 5 ) {
               globals.map_zoom = 7;
	        }
	         if(globals.loc_id.length  == 7 ) {
               globals.map_zoom = 10;
	        }
	        
 //pas de carte donc de div de la carte dans certaines modules comme myanyresa ou content mais le moteur doit fonctionner
 if (myMap){
	 myMap.clearOverlays();
 point = new GLatLng(globals.center_location_lat, globals.center_location_lng);
 myMap.setCenter(point, globals.map_zoom);           
 myMap.addOverlay( new GMarker(point));
 }
 
 } else {

 redirect();
 }
 
           
          }
        );
      }
    	
    	//cas sinon 
     } else { //if 
   
     	//on affche touts les pays avec le centre france
     	globals.location_name=globals.langs_indifferent;     	  
     	globals.center_location_lat=48.77;
     	globals.center_location_lng=2.39; 
     	globals.map_zoom=1;

//afficher la dest trouvée sur la carte sans redirect
if (redirection=='no'){
	myMap.clearOverlays();
 point = new GLatLng(globals.center_location_lat, globals.center_location_lng);
 myMap.setCenter(point, globals.map_zoom);           
 myMap.addOverlay( new GMarker(point));
 
 } else {

 redirect();
 }
 
 
     }

    
         	
         }//end function
         
       
//redirect url principal de recherche module go : soit var est fournie en param, soit on prend la valeur du containeur  globals ou champ d'un controle html
function redirect(){
	
document.location.href=compose_url_redirect(false);
document.getElementById("button_go").focus(); 

}

//redirect, partial = parametre si true la version courte de l'url, speciale pour geo recherche ajax est retournee sinon false = redirect normal 
function compose_url_redirect(partial) {

//nom de destination et donc point centrale sur la carte
var location_name = document.getElementById("dest") && globals.location_name!=globals.langs_indifferent ? document.getElementById("dest").value : globals.langs_indifferent;


//lat de destination et donc point centrale sur la carte
var center_location_lat = (typeof globals.center_location_lat != "undefined") ? globals.center_location_lat : 48.77;

//lng de destination et donc point centrale sur la carte
var center_location_lng = (typeof globals.center_location_lng != "undefined") ? globals.center_location_lng : 2.39;

//location id
var loc_id = (typeof globals.loc_id != "undefined") ? globals.loc_id : 0;

//zoom de la carte
var map_zoom= (typeof globals.map_zoom != "undefined") ? globals.map_zoom : 1;

//zone de recherche (en select)
var e_search_zone = document.getElementById("search_zone");
var search_zone = e_search_zone ? e_search_zone.value : 15000;

//date de depart
var date_go = (document.getElementById("datego") && document.getElementById("datego").value!='') ? document.getElementById("datego").value : '';


//duree de location
var period= document.getElementById("period") ? document.getElementById("period").value : 0;

//type d'offre
var listing_type= get_radio_value_type() ? get_radio_value_type() : 1;

//afficher filtres  (0 = non, 1 = oui)
var display_filters= (typeof globals.display_filters != "undefined") ? globals.display_filters : 0;

//ref annonce
var e_ref_listing = document.getElementById("ref_listing");
var ref_listing = e_ref_listing ? jQuery.trim(e_ref_listing.value) : '';


//afficher carte (0 = non, 1 = oui)
var display_map= (typeof globals.display_map != "undefined") ? globals.display_map : 0;

//format de resultats en mosaic (0 = non, 1 = oui)
var display_mosaic= (typeof globals.display_mosaic != "undefined") ? globals.display_mosaic : 0;

//numero de la page de resultats
var page_number= (typeof globals.page_number != "undefined") ? globals.page_number : 1;

//trier par (code numerique)
var sort_by =  document.getElementById("order_by") ? document.getElementById("order_by").value : 1;

//offres avec photo ?  (0 = non, 1 = oui)
var with_photos = (document.getElementById("ar_with_photos") && document.getElementById("ar_with_photos").checked==true) ? 1 : 0;

//mode carte etenue ? (0 = non, 1 = oui)
var big_map = (typeof globals.big_map != "undefined") ? globals.big_map : 0;

//coordonees north east de la zone rectanguliere definie par l'utilisateur
var zone_ne_lat = (typeof globals.zone_ne_lat != "undefined") ? globals.zone_ne_lat : 0;
var zone_ne_lng = (typeof globals.zone_ne_lng != "undefined") ? globals.zone_ne_lng : 0;

//coordonees south west de la zone rectanguliere definie par l'utilisateur
var zone_sw_lat = (typeof globals.zone_sw_lat != "undefined") ? globals.zone_sw_lat : 0;
var zone_sw_lng = (typeof globals.zone_sw_lng != "undefined") ? globals.zone_sw_lng : 0;

//si affiche div ref annonce
var display_ref_listing = (typeof globals.display_ref_listing != "undefined") ? globals.display_ref_listing : 0;

//nombre de personnes
var e_filter_number = document.getElementById("filter_number");
var filter_number = e_filter_number ? e_filter_number.value : 0;

//appliquer filtres multichoix sauf le cas recherche ajax geo - ne pas remplir 2 eme fois les fintres
if (!partial){
comboToString();
}

f_4 = (typeof globals.f_4 != "undefined") ? globals.f_4 : 0;
f_13 = (typeof globals.f_13 != "undefined") ? globals.f_13 : 0;
f_5 = (typeof globals.f_5 != "undefined") ? globals.f_5 : 0;
f_6 = (typeof globals.f_6 != "undefined") ? globals.f_6 : 0;
f_8 = (typeof globals.f_8 != "undefined") ? globals.f_8 : 0;
f_7 = (typeof globals.f_7 != "undefined") ? globals.f_7 : 0;

if (typeof globals.tfc != "undefined") {
	
	
	f_1 = globals.tfc;
	
} else {
	
	f_1 = (typeof globals.f_1 != "undefined") ? globals.f_1 : 0;
}


//pour recherche geo
if (partial){
url = encodeURI(location_name)+'~'+center_location_lat+'~'+center_location_lng+'~'+loc_id+'~'+map_zoom+'~'+search_zone+'~'+date_go+'~'+period+'~'+listing_type+'~'+display_filters+'~'+ref_listing+'~'+display_map+'~'+display_mosaic+'~'+page_number+'~'+sort_by+'~'+with_photos+'~'+big_map+'~'+zone_ne_lat+'~'+zone_ne_lng+'~'+zone_sw_lat+'~'+zone_sw_lng+'~'+display_ref_listing+'~'+filter_number+'~'+f_4+'~'+f_13+'~'+f_5+'~'+f_6+'~'+f_8+'~'+f_7+'~'+f_1;  

	return url;
}


//pour recherche normal
url = globals.server+globals.lang+'/go/loc/'+encodeURI(location_name)+'~'+center_location_lat+'~'+center_location_lng+'~'+loc_id+'~'+map_zoom+'~'+search_zone+'~'+date_go+'~'+period+'~'+listing_type+'~'+display_filters+'~'+ref_listing+'~'+display_map+'~'+display_mosaic+'~'+page_number+'~'+sort_by+'~'+with_photos+'~'+big_map+'~'+zone_ne_lat+'~'+zone_ne_lng+'~'+zone_sw_lat+'~'+zone_sw_lng+'~'+display_ref_listing+'~'+filter_number+'~'+f_4+'~'+f_13+'~'+f_5+'~'+f_6+'~'+f_8+'~'+f_7+'~'+f_1+'.htm';  


return url;

}


function get_radio_value_type()
{
	if(document.moteurform.listing_type){
		
	
for (var i=0; i < document.moteurform.listing_type.length; i++)
   {
   if (document.moteurform.listing_type[i].checked)
      {
      return document.moteurform.listing_type[i].value;
      }
   }
	}
   return false;
}






//redirection vers une page
function gotopage(page){

	globals.page_number = page;
	
	redirect();
}

//Fonction à revoir avant utilisation
function check_login_fields()
{
	email=document.getElementById("ar_login_myemail").value;
	
	password=document.getElementById("ar_login_mypass").value;
	
	if(email=='' || password=='')
	{
		alert("Veuillez entrer vos identifiants de connexion");
		return;
				
	}
	else
	{	
		login_url='http://'+window.location.hostname+window.location.pathname+'myaction/login';
		document.forms['ar_login_form'].method="POST";
		document.forms['ar_login_form'].action=login_url;
		
	}
}

// Fonction gérant la fermeture des composant myComboBox & mySelectBox
function MyClickHandler(oEvent)	{	

    oEvent = oEvent || window.event;
    oTarget = oEvent.target || oEvent.srcElement;
		
    for(var i in MyComboBox_Instances_Array)
    {
        
        var aCombo = MyComboBox_Instances_Array[i];
		if (!((oTarget.id) && (oTarget.id.indexOf(aCombo.familyName+aCombo.numericId) > -1)))
			aCombo.hideContent();
            
	} 
							
    for(var i in MySelectBox_Instances_Array)
    {
        
        var aSelect = MySelectBox_Instances_Array[i];
		if (!((oTarget.id) && (oTarget.id.indexOf(aSelect.familyName+aSelect.numericId) > -1)))
			aSelect.hideContent();
            
	}
	 
 }
 
 // Classe de détection du navigateur utilisée pour mycomboxbox et myselectbox
function BrowserDetect () {
	this.init = function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	}
	this.searchString = function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	}
	this.searchVersion = function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	}
	this.dataBrowser = [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	]
	this.dataOS = [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function autoFillPseudoField(){
    document.getElementById('ar_mypseudo').value = document.getElementById('ar_myemail').value;
}

//Fonctions de co-registration LSF
// These three functions must be included in your page.

// validatePublisherForm() is called before processing offers form.
// This is where you validate data from your own form, and if necessary, returns error.
// If this function returns false, offers won't be processed.
function validatePublisherForm(){
    return true;
}

// submitPublisherForm() is called by the LSF scripts after processing the coreg offers sending data to the LSF server.
// This function must be the only way to submit the form.
function submitPublisherForm() { document.ar_register_form1.submit(); }

// This is a security wrapper, used to call the two previous functions.
function LSFaction(action){
    switch (action) {
        case 0: if (window.display_LSF_offers) display_LSF_offers(); break;
        case 1: if (window.LSF_submit) LSF_submit(); else if (validatePublisherForm()) submitPublisherForm(); break;
    }
}

function isLSFValid()
{
  var myLSF = document.LSF_form;
  
  var nbMyLSFRadioButtons = myLSF.elements.length;
  
  var emptyChoiceIdentified = false;
    
  for(var i=0;i<nbMyLSFRadioButtons-1;i+=2)
  {
       if((!myLSF.elements[i].checked) && (!myLSF.elements[i+1].checked))
           emptyChoiceIdentified = true;
  }
  if(emptyChoiceIdentified)
        delete bob; 
  
}



//pour parsing json en autosujjestion et autres modules
var JSON = {
    org: 'http://www.JSON.org',
    copyright: '(c)2005 JSON.org',
    license: 'http://www.crockford.com/JSON/license.html',
    stringify: function (arg) {
        var c, i, l, s = '', v;

        switch (typeof arg) {
        case 'object':
            if (arg) {
                if (arg.constructor == Array) {
                    for (i = 0; i < arg.length; ++i) {
                        v = this.stringify(arg[i]);
                        if (s) {
                            s += ',';
                        }
                        s += v;
                    }
                    return '[' + s + ']';
                } else if (typeof arg.toString != 'undefined') {
                    for (i in arg) {
                        v = arg[i];
                        if (typeof v != 'undefined' && typeof v != 'function') {
                            v = this.stringify(v);
                            if (s) {
                                s += ',';
                            }
                            s += this.stringify(i) + ':' + v;
                        }
                    }
                    return '{' + s + '}';
                }
            }
            return 'null';
        case 'number':
            return isFinite(arg) ? String(arg) : 'null';
        case 'string':
            l = arg.length;
            s = '"';
            for (i = 0; i < l; i += 1) {
                c = arg.charAt(i);
                if (c >= ' ') {
                    if (c == '\\' || c == '"') {
                        s += '\\';
                    }
                    s += c;
                } else {
                    switch (c) {
                        case '\b':
                            s += '\\b';
                            break;
                        case '\f':
                            s += '\\f';
                            break;
                        case '\n':
                            s += '\\n';
                            break;
                        case '\r':
                            s += '\\r';
                            break;
                        case '\t':
                            s += '\\t';
                            break;
                        default:
                            c = c.charCodeAt();
                            s += '\\u00' + Math.floor(c / 16).toString(16) +
                                (c % 16).toString(16);
                    }
                }
            }
            return s + '"';
        case 'boolean':
            return String(arg);
        default:
            return 'null';
        }
    },
    parse: function (text) {
        var at = 0;
        var ch = ' ';

        function error(m) {
            throw {
                name: 'JSONError',
                message: m,
                at: at - 1,
                text: text
            };
        }

        function next() {
            ch = text.charAt(at);
            at += 1;
            return ch;
        }

        function white() {
            while (ch) {
                if (ch <= ' ') {
                    next();
                } else if (ch == '/') {
                    switch (next()) {
                        case '/':
                            while (next() && ch != '\n' && ch != '\r') {}
                            break;
                        case '*':
                            next();
                            for (;;) {
                                if (ch) {
                                    if (ch == '*') {
                                        if (next() == '/') {
                                            next();
                                            break;
                                        }
                                    } else {
                                        next();
                                    }
                                } else {
                                    error("Unterminated comment");
                                }
                            }
                            break;
                        default:
                            error("Syntax error");
                    }
                } else {
                    break;
                }
            }
        }

        function string() {
            var i, s = '', t, u;

            if (ch == '"') {
outer:          while (next()) {
                    if (ch == '"') {
                        next();
                        return s;
                    } else if (ch == '\\') {
                        switch (next()) {
                        case 'b':
                            s += '\b';
                            break;
                        case 'f':
                            s += '\f';
                            break;
                        case 'n':
                            s += '\n';
                            break;
                        case 'r':
                            s += '\r';
                            break;
                        case 't':
                            s += '\t';
                            break;
                        case 'u':
                            u = 0;
                            for (i = 0; i < 4; i += 1) {
                                t = parseInt(next(), 16);
                                if (!isFinite(t)) {
                                    break outer;
                                }
                                u = u * 16 + t;
                            }
                            s += String.fromCharCode(u);
                            break;
                        default:
                            s += ch;
                        }
                    } else {
                        s += ch;
                    }
                }
            }
            error("Bad string");
        }

        function array() {
            var a = [];

            if (ch == '[') {
                next();
                white();
                if (ch == ']') {
                    next();
                    return a;
                }
                while (ch) {
                    a.push(value());
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad array");
        }

        function object() {
            var k, o = {};

            if (ch == '{') {
                next();
                white();
                if (ch == '}') {
                    next();
                    return o;
                }
                while (ch) {
                    k = string();
                    white();
                    if (ch != ':') {
                        break;
                    }
                    next();
                    o[k] = value();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad object");
        }

        function number() {
            var n = '', v;
            if (ch == '-') {
                n = '-';
                next();
            }
            while (ch >= '0' && ch <= '9') {
                n += ch;
                next();
            }
            if (ch == '.') {
                n += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    n += ch;
                }
            }
            if (ch == 'e' || ch == 'E') {
                n += 'e';
                next();
                if (ch == '-' || ch == '+') {
                    n += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
            }
            v = +n;
            if (!isFinite(v)) {
                ////error("Bad number");
            } else {
                return v;
            }
        }

        function word() {
            switch (ch) {
                case 't':
                    if (next() == 'r' && next() == 'u' && next() == 'e') {
                        next();
                        return true;
                    }
                    break;
                case 'f':
                    if (next() == 'a' && next() == 'l' && next() == 's' &&
                            next() == 'e') {
                        next();
                        return false;
                    }
                    break;
                case 'n':
                    if (next() == 'u' && next() == 'l' && next() == 'l') {
                        next();
                        return null;
                    }
                    break;
            }
            error("Syntax error");
        }

        function value() {
            white();
            switch (ch) {
                case '{':
                    return object();
                case '[':
                    return array();
                case '"':
                    return string();
                case '-':
                    return number();
                default:
                    return ch >= '0' && ch <= '9' ? number() : word();
            }
        }

        return value();
    }
};




/***********************************************
 Fool-Proof Date Input Script with DHTML Calendar
 by Jason Moon - http://calendar.moonscript.com/dateinput.cfm
 ************************************************/

// Customizable variables
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 3; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var UnselectedMonthText = ''; // Text to display in the 1st month list item when the date isn't required
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var ImageURL = '/anyimages/global/pict_calendrier.gif';
var NextURL = '/anyimages/global/next.gif';
var PrevURL = '/anyimages/global/prev.gif';
var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightgrey';

// Global variables
var ZCounter = 100;
var Today = new Date();
var WeekDays = new Array('S','M','T','W','T','F','S');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//var MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var MonthNames = new Array('01','02','03','04','05','06','07','08','09','10','11','12');

// Write out the stylesheet definition for the calendar
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('</style>');
}

// Only allows certain keys to be used in the date field
function YearDigitsOnly(e) {
   var KeyCode = (e.keyCode) ? e.keyCode : e.which;
   return ((KeyCode == 8) // backspace
        || (KeyCode == 9) // tab
        || (KeyCode == 37) // left arrow
        || (KeyCode == 39) // right arrow
        || (KeyCode == 46) // delete
        || ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
   );
}

// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

// Is the specified select-list behind the calendar?
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY) {
   var ListLeftX = GetTagPixels(SelectList, 'LEFT');
   var ListRightX = ListLeftX + SelectList.offsetWidth;
   var ListBottomY = ListTopY + SelectList.offsetHeight;
   return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}

// For IE, hides any select-lists that are behind the calendar
function FixSelectLists(Over) {
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var CalDiv = this.getCalendar();
      var CalLeftX = CalDiv.offsetLeft;
      var CalRightX = CalLeftX + CalDiv.offsetWidth;
      var CalTopY = CalDiv.offsetTop;
      var CalBottomY = CalTopY + (CellHeight * 9);
      var FoundCalInput = false;
      formLoop :
      for (var j=this.formNumber;j<document.forms.length;j++) {
         for (var i=0;i<document.forms[j].elements.length;i++) {
            if (typeof document.forms[j].elements[i].type == 'string') {
               if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName)) {
                  FoundCalInput = true;
                  i += 3; // 3 elements between the 1st hidden field and the last year input field
               }
               if (FoundCalInput) {
                  if (document.forms[j].elements[i].type.substr(0,6) == 'select') {
                     ListTopY = GetTagPixels(document.forms[j].elements[i], 'TOP');
                     if (ListTopY < CalBottomY) {
                        if (BehindCal(document.forms[j].elements[i], CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY)) {
                           document.forms[j].elements[i].style.visibility = (Over) ? 'hidden' : 'visible';
                        }
                     }
                     else break formLoop;
                  }
               }
            }
         }
      }
   }
}

// Displays a message in the status bar when hovering over the calendar days
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   if (Over) {
      if ((this.yearValue == Today.getFullYear()) && (this.monthIndex == Today.getMonth()) && (HoveredDay == Today.getDate())) self.status = 'Click to select today';
      else {
         var Suffix = HoveredDay.toString();
         switch (Suffix.substr(Suffix.length - 1, 1)) {
            case '1' : Suffix += (HoveredDay == 11) ? 'th' : 'st'; break;
            case '2' : Suffix += (HoveredDay == 12) ? 'th' : 'nd'; break;
            case '3' : Suffix += (HoveredDay == 13) ? 'th' : 'rd'; break;
            default : Suffix += 'th'; break;
         }
         self.status = 'Click to select ' + this.monthName + ' ' + Suffix;
      }
   }
   else self.status = '';
   return true;
}

// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) { 
   this.show();
   var MonthList = this.getMonthList();
   var DayList = this.getDayList();
   var YearField = this.getYearField();
   FixDayList(DayList, GetDayCount(this.displayed.yearValue, this.displayed.monthIndex));
   // Select the month and day in the lists
   for (var i=0;i<MonthList.length;i++) {
      if (MonthList.options[i].value == this.displayed.monthIndex) MonthList.options[i].selected = true;
   }
   for (var j=1;j<=DayList.length;j++) {
      if (j == ClickedDay) DayList.options[j-1].selected = true;
   }
   this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
   // Change the year, if necessary
   YearField.value = this.picked.yearPad;
   YearField.defaultValue = YearField.value;
}

// Builds the HTML for the calendar days
function BuildCalendarDays() {
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:default">';
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               TextStyle = 'color:white;font-weight:bold;'
               BackColor = DayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) TextStyle += 'border:1px solid darkred;padding:0px;';
            HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
         }
         else HTML += '<td class="calendarDateInput" style="height:' + CellHeight + '">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}

// Determines which century to use (20th or 21st) when dealing with 2-digit years
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}

// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}

// Highlights the buttons
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}

// Mouse-over for the previous/next month buttons
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
      self.status = 'Click to view ' + DateObj.fullName;
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
      self.status = '';
   }
   return true;
}

// Adds/removes days from the day list, depending on the month/year
function FixDayList(DayList, NewDays) {
   var DayPick = DayList.selectedIndex + 1;
   if (NewDays != DayList.length) {
      var OldSize = DayList.length;
      for (var k=Math.min(NewDays,OldSize);k<Math.max(NewDays,OldSize);k++) {
         (k >= NewDays) ? DayList.options[NewDays] = null : DayList.options[k] = new Option(k+1, k+1);
      }
      DayPick = Math.min(DayPick, NewDays);
      DayList.options[DayPick-1].selected = true;
   }
   return DayPick;
}

// Resets the year to its previous valid value when something invalid is entered
function FixYearInput(YearField) {
   var YearRE = new RegExp('\\d{' + YearField.defaultValue.length + '}');
   if (!YearRE.test(YearField.value)) YearField.value = YearField.defaultValue;
}

// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isShowing()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}

// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.timerID + ')');
   eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}

// The timer for the calendar
function DoTimer(CancelTimer) {
   if (CancelTimer) eval('clearTimeout(' + this.timerID + ')');
   else {
      eval(this.timerID + '=null');
      this.resetTimer();
   }
}

// Show or hide the calendar
function ShowCalendar() {
   if (this.isShowing()) {
      var StopTimer = true;
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
      this.fixSelects(false);
   }
   else {
      var StopTimer = false;
      this.fixSelects(true);
      this.getCalendar().style.zIndex = ++ZCounter;
      this.getCalendar().style.visibility = 'visible';
   }
   this.handleTimer(StopTimer);
   self.status = '';
}

// Hides the input elements when the "blank" month is selected
function SetElementStatus(Hide) {
   this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
   if(this.getCalendarLink()) this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}

// Sets the date, based on the month selected
function CheckMonthChange(MonthList) {
   var DayList = this.getDayList();
   if (MonthList.options[MonthList.selectedIndex].value == '') {
      DayList.selectedIndex = 0;
      this.hideElements(true);
      this.setHidden('');
   }
   else {
      this.hideElements(false);
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-selected month
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var DayPick = FixDayList(DayList, GetDayCount(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value));
      this.setPicked(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value, DayPick);
   }
}

// Sets the date, based on the day selected
function CheckDayChange(DayList) {
   if (this.isShowing()) this.show();
   this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
}

// Changes the date when a valid year has been entered
function CheckYearInput(YearField) {
   //if ((YearField.value.length == YearField.defaultValue.length) && (YearField.defaultValue != YearField.value)) {
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-entered year
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var NewYear = GetGoodYear(YearField.value);
      var MonthList = this.getMonthList();
      var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
      this.setPicked(NewYear, this.picked.monthIndex, NewDay);
      YearField.defaultValue = YearField.value;
   //}
}

// Holds characteristics about a date
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
   ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}

// Keeps track of the date that goes into the hidden field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?((MON)|(MM?M?))/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
   }
   else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat)) {
      this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}

// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0){
     if(this.getDisplay()) this.getDisplay().innerHTML = this.fullName;
   }
}

// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
   (Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
   this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0){
     if(this.getButton()) this.getButton().title = this.monthName;
   }
}

// Sets the currently-displayed month object
function SetDisplayedMonth(DispYear, DispMonth) {
   this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
   // Creates the previous and next month objects
   this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
   this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   // Creates the HTML for the calendar
   if (this.formNumber >= 0){
    if(this.getDayTable()) this.getDayTable().innerHTML = this.buildCalendar();
   }
}

// Sets the current selected date
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
   this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
   this.setHidden(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}

// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate) {

   /* Properties */
   this.hiddenFieldName = DateName;
   this.monthListID = DateName + '_Month_ID';
   this.dayListID = DateName + '_Day_ID';
   this.yearFieldID = DateName + '_Year_ID';
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;

   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.checkYear = CheckYearInput;
   this.fixYear = FixYearInput;
   this.changeMonth = CheckMonthChange;
   this.changeDay = CheckDayChange;
   this.resetTimer = CalTimerReset;
   this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   this.handleTimer = DoTimer;
   this.iconHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.fixSelects = FixSelectLists;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   this.getMonthList = new Function('return document.getElementById(this.monthListID)');
   this.getDayList = new Function('return document.getElementById(this.dayListID)');
   this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isShowing = new Function('if(this.getCalendar()) return !(this.getCalendar().style.visibility != \'visible\')');

   /* Constructor */
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos<MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
      if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
   }
   // Main part of the constructor
   if (DefaultDate != '') {
      if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate))) this.setPicked(RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
      else {
         // Get the year
         if ((this.format.substr(0,2) == 'YY') && (/^(\d{2,4})(-|\/)/.test(DefaultDate))) { // Year is at the beginning
            var YearPart = GetGoodYear(RegExp.$1);
            // Determine the order of the months and days
            if (/(-|\/)(\w{1,3})(-|\/)(\w{1,3})$/.test(DefaultDate)) {
               var MidPart = RegExp.$2;
               var EndPart = RegExp.$4;
               if (/D$/.test(this.format)) { // Ends with days
                  var DayPart = EndPart;
                  var MonthPart = MidPart;
               }
               else {
                  var DayPart = MidPart;
                  var MonthPart = EndPart;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/(-|\/)(\d{2,4})$/.test(DefaultDate)) { // Year is at the end
            var YearPart = GetGoodYear(RegExp.$2);
            // Determine the order of the months and days
            if (/^(\w{1,3})(-|\/)(\w{1,3})(-|\/)/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'D') { // Starts with days
                  var DayPart = RegExp.$1;
                  var MonthPart = RegExp.$3;
               }
               else { // Starts with months
                  var MonthPart = RegExp.$1;
                  var DayPart = RegExp.$3;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else SetGoodDate(this, true);
      }
   }
}

// Main function that creates the form elements
function DateInput(DateName, Required, DateFormat, DefaultDate) {
   if (arguments.length == 0) document.writeln('<span style="color:red;font-size:' + FontSize + 'px;font-family:' + FontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      // Handle DateFormat
      if (arguments.length < 3) { // The format wasn't passed in, so use default
         DateFormat = DefaultDateFormat;
         if (arguments.length < 2) Required = false;
      }
      else if (/^(Y{2,4}(-|\/)?)?((MON)|(MM?M?)|(DD?))(-|\/)?((MON)|(MM?M?)|(DD?))((-|\/)Y{2,4})?$/i.test(DateFormat)) DateFormat = DateFormat.toUpperCase();
      else { // Passed-in DateFormat was invalid, use default format instead
         var AlertMessage = 'WARNING: The supplied date format for the \'' + DateName + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         DateFormat = DefaultDateFormat;
         if (arguments.length == 4) { // DefaultDate was passed in with an invalid date format
            var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
            AlertMessage += '\n\nThe supplied date (' + DefaultDate + ') cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
            DefaultDate = CurrentDate.formatted;
         }
         alert(AlertMessage);
      }
      // Define the current date if it wasn't set already
      if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
      // Handle DefaultDate
      if (arguments.length < 4) { // The date wasn't passed in
         DefaultDate = (Required) ? CurrentDate.formatted : ''; // If required, use today's date
      }
      // Creates the calendar object!
      eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
      // Determine initial viewable state of day, year, and calendar icon
      if ((Required) || (arguments.length == 4)) {
         var InitialStatus = '';
         var InitialDate = eval(DateName + '_Object.picked.formatted');
      }
      else {
         var InitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
         eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDate() + ')');
      }
      // Create the form elements
      with (document) {
         writeln('<input type="hidden" name="' + DateName + '" value="' + InitialDate + '">');
         // Find this form number
         for (var f=0;f<forms.length;f++) {
            for (var e=0;e<forms[f].elements.length;e++) {
               if (typeof forms[f].elements[e].type == 'string') {
                  if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
                     eval(DateName + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
         writeln('<select' + InitialStatus + ' class="calendarDateInput" id="' + DateName + '_Day_ID" onChange="' + DateName + '_Object.changeDay(this)">');
         for (var j=1;j<=eval(DateName + '_Object.picked.dayCount');j++) {
            DaySelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.day') == j)) ? ' selected' : '';
            writeln('<option' + DaySelected + '>' + j + '</option>');
         }
         writeln('</select>');
         
         writeln('<select class="calendarDateInput" id="' + DateName + '_Month_ID" onChange="' + DateName + '_Object.changeMonth(this)">');
         if (!Required) {
            var NoneSelected = (DefaultDate == '') ? ' selected' : '';
            writeln('<option value=""' + NoneSelected + '>' + UnselectedMonthText + '</option>');
         }
         for (var i=0;i<12;i++) {
            MonthSelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.monthIndex') == i)) ? ' selected' : '';
            writeln('<option value="' + i + '"' + MonthSelected + '>' + MonthNames[i] + '</option>');
         }
         writeln('</select>');
                                    
         writeln('<select' + InitialStatus + ' class="calendarDateInput" id="' + DateName + '_Year_ID" onKeyUp="' + DateName + '_Object.checkYear(this)" onChange="' + DateName + '_Object.checkYear(this)">');
         for (var k=1918;k<=1992;k++) {
            YearSelected = ((DefaultDate != '') && (eval(DateName + '_Object.displayed.yearValue') == k.toString())) ? ' selected' : '';
            writeln('<option value="' + k + '"' + YearSelected + '>' + k + '</option>');
         }
         writeln('</select>');
                 
      }
   }
}





