var search_in_progress = false;
var listings = {};
var pre_images = new Array();
var img_path = '/default/images/property_search/search/images/';
var cbo = new CallBackObject();


if (/msie/i.test (navigator.userAgent)) //only override IE
{
  document.nativeGetElementById = document.getElementById; 
  document.getElementById = function(id)
  {
    var elem = document.nativeGetElementById(id);
    if(elem)
    {
      //make sure that it is a valid match on id
      if(elem.attributes['id'].value == id)
      {
        return elem;
      }
      else
      {
        //otherwise find the correct element
        for(var i=1;i<document.all[id].length;i++)
        {
          if(document.all[id][i].attributes['id'].value == id)
          {
            return document.all[id][i];
          }
        }
      }
    }
    return null;
  }
} 

function el(id) {
    return document.getElementById(id);
}


function load_images(){    
    if (document.images)
    {  
        searchBttn = new Image(); searchBttn.src = img_path + "searchbutton_o.gif";        
        recommBttn = new Image(); recommBttn.src = img_path+"search_recomm_o.gif";        
        backBttn = new Image();  backBttn.src = img_path+"back_recomm_o.gif";     
        saveFHU = new Image(); searchBttn.src = img_path+"savefhu_o.gif";        
        updateFHU = new Image(); recommBttn.src = img_path+"updatefhu_o.gif"; 
        collapseBttn = new Image(); collapseBttn.src = img_path+"collapseform.gif"; 
        expandBttn = new Image(); expandBttn.src = img_path+"expandform.gif";         
        
        /* template buttons */
        calculateBttn = new Image(); calculateBttn.src = img_path+"templates/calculate_over.gif";        
        compareBttn = new Image(); compareBttn.src = img_path+"templates/compare_over.gif";        
        contactBttn = new Image(); contactBttn.src = img_path+"templates/contact_over.gif";                
        detailsBttn = new Image();  detailsBttn.src = img_path+"templates/details_over.gif";     
        detailsSmallBttn = new Image();  detailsSmallBttn.src = img_path+"templates/details_small_over.gif";     
        flyerBttn = new Image();  flyerBttn.src = img_path+"templates/flyer_over.gif";     
        mapBttn = new Image();  mapBttn.src = img_path+"templates/map_over.gif";     
        nvBttn = new Image();  nvBttn.src = img_path+"templates/neighborhood_over.gif";     
        rateBttn = new Image(); rateBttn.src = img_path+"templates/rate_over.gif";     
        saveBttn = new Image(); saveBttn.src = img_path+"templates/save_over.gif";   
        scheduleBttn = new Image(); scheduleBttn.src = img_path+"templates/schedule_over.gif";   
        slideshowBttn = new Image(); slideshowBttn.src = img_path+"templates/slideshow_over.gif";   
        tourBttn = new Image(); tourBttn.src = img_path+"templates/tour_over.gif";   
    }    
}
 

function getData(obj) {
    var data = {};
    
    for (i = 0; i < obj.elements.length ; i++) {
        if (!obj.elements[i].disabled){         
            
            if (obj.elements[i].name == 'scope' && obj.elements[i].value == '') {
                data[obj.elements[i].name] = 'ALL';
            }
    
            if (obj.elements[i].type == 'checkbox'){
                if(obj.elements[i].checked )
                    data[obj.elements[i].name] = obj.elements[i].value;
            }
            else if (obj.elements[i].type == 'radio') {
                if(obj.elements[i].checked )
                    data[obj.elements[i].name] = obj.elements[i].value;
            }
            else if (obj.elements[i].type == 'select-multiple') {
                var k = 0;                    
                for (var j = 0; j < obj.elements[i].length; j++){    
                    optElem = obj.elements[i].options[j];    
                    if (optElem.selected == true){    
                        if(typeof(data[obj.elements[i].name]) == 'undefined') {
                            data[obj.elements[i].name] = new Array();
                        }
                        data[obj.elements[i].name][k] = optElem.value;                                
                        k++;
                    }                    
                }                                               
                
            }
            else if (obj.elements[i].type == 'select-one') { 
                for (var j = 0; j < obj.elements[i].length; j++){    
                    optElem = obj.elements[i].options[j];    
                    if (optElem.selected == true){                            
                        data[obj.elements[i].name] = optElem.value;                        
                    }
                }    
            }
            else if (obj.elements[i].value != '') {                
                data[obj.elements[i].name] = obj.elements[i].value;
            }
        }
    }

    return data;
}


function addCommas(nStr)
{
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


function beforeSubmit(old_new){
   
    if(el('press_search_msg')) el('press_search_msg').style.display='none';

    if(search_in_progress) {       
       shownote('','Search already in progress. Please wait for the results and run a new search after.');
       return false;
    } 
        
    if(el('search_type').value == 'map'){          
        if(map && map.getZoom) {
            if(map.getZoom()<6) {               
               shownote('','Please zoom in before searching.');
               return false;
            }
        }
        
        if(el('mapResDiv')) el('display_style').value = 'map';
    }
    else if( el('search_type').value == 'zipcode' && el('zipcode').value == '') {                  
        shownote('','Please insert a zipcode or change the search type before submit.', 'Form error');
        return false;
    }
    else if( el('search_type').value == 'mls_id' && (
        el('listing_mls_id_1').value == '' && el('listing_mls_id_2').value == '' && el('listing_mls_id_3').value == '' &&
        el('listing_mls_id_4').value == '' && el('listing_mls_id_5').value == '' && el('listing_mls_id_6').value == '' )) {                  
        shownote('','Please insert a mls id or change the search type before submit.', 'Form error');
        return false;
    
    }
    el('ps_form_content').style.display='none';        
    if(el('ps_form_img')) { el('ps_form_img').src = img_path+ 'collapsed.gif'; }
    if(el('ps_form_msg')) { el('ps_form_msg').style.display = 'block'; }        
    if(el('ps_edit_msg')) { el('ps_edit_msg').style.display = 'block'; }
    
    //hide block divs
    if(el('_block_div_')) { el('_block_div_').style.display = 'none'; }
    if(el('_map_block_div_')) { el('_map_block_div_').style.display = 'none'; }
    
    el('recommendedDiv').innerHTML = '';        
    el('teaserDiv').style.display = 'none';        
    
    if(old_new == true) submitForm(true);
    else submitForm(); 
}


cbo.OnLoading = function() {}
cbo.OnAbort   = function(){alert('Request has been aborted');};

cbo.OnError   = function(status, statusText){
    alert('Error - ' + status + ' - ' + statusText); 
    search_in_progress = false; 
    el('workLoaderDiv').style.display = 'block';  
    el('preLoaderDiv').style.display = 'none';       
};


// Search button
function submitForm(old_new){
    formId = 'ps_form';
    search_in_progress=true;  
    
    if(old_new && old_new == true) { data = the_criteria; }        
    else { data = getData(el(formId)); }           
    
    cbo.OnLoading = function(){                        
        if(el('mapDiv')) el('mapDiv').style.display = 'none';
        if(el('mapResDiv')) el('mapResDiv').style.display = 'none';         
              
        el('workLoaderDiv').style.display = 'none';  
        el('resultsHeadertop').style.display = 'none';                
        if(el('resultsHeaderbottom'))el('resultsHeaderbottom').style.display = 'none';                
        el('preLoaderDiv').style.display = 'block'; 
        if(document.all && el('loading_image')){
            el('loading_image').style.visibility = "visible"; 
             setTimeout("el('loading_image').src=el('loading_image').src;",100);
            
        }
    }
    
    cbo.OnComplete = function(text, xml){                
        if(window.map){ map.clearOverlays(); }
        
        var loaderDiv = el('workLoaderDiv');
        loaderDiv.innerHTML = '';         
        loaderDiv.innerHTML = text;  
                 
        
        search_in_progress=false;
                
        if(el('search_type') == 'map' && el('mapDiv')){            
            if(el('mapDiv')) el('mapDiv').style.display = 'block';
            if(el('mapResDiv')) el('mapResDiv').style.display = 'block';                         
        }
        else {
            el('workLoaderDiv').style.display = 'block';  
        }     
        
        runInnerScripts(loaderDiv);
        //if(el('mapResDiv')) el('mapResDiv').style.height = '120px';
        el('preLoaderDiv').style.display = 'none';
		if(window.back2results && el('login_link')){ el('login_link').href='/login.htm?referer='+back2results;}
		if(window.back2results && el('register_link')){ el('register_link').href='/register.htm?purl=_vip_&referer='+back2results; }
      
    };

    var url = 'http://'+ servername +'/listing_search/index.php';
    cbo.DoCallBack(url, data);
    return true;
}


function _imagesLoaded(){    
    var flag = true;
    
    for(var i1=0; i1 < listings.length; i1++) { if(!pre_images[listings[i1].id].complete) flag = false;}
    if(!flag) { setTimeout('_imagesLoaded()', 500); }    
    else { get_images(); }
}

function preload_images() {         
    if(listings.length < 1 ) return;     
                                       
    for(var i=0; i < listings.length; i++) {                        
        pre_images[listings[i].id]= new Image();
        pre_images[listings[i].id].src = listings[i].photo_url;                           
    }      
         
    _imagesLoaded();
}   
    
function get_images() {     
    
    for(var idx = 0;  idx < listings.length; idx++) {        
        var id = listings[idx].id;
        var photo = pre_images[id];             
        
      
        if(el('thumbnail_' +id)) {
            el('thumbnail_'+id).src = photo.src;  
            el('thumbnail_'+id).width = 96;     
            el('thumbnail_'+id).height = 80;     
        }                
    
        if(el('detail_'+id)){
            el('detail_'+id).src = photo.src;     
            el('detail_'+id).width = 132;     
            el('detail_'+id).height = 90;     
        }                 

        if(el('map_'+id)){ 
            el('map_'+id).src = photo.src;
            el('map_'+id).width = 70;     
            el('map_'+id).height = 58;     
        }
        
        if(el('map_list_'+id)){ 
            el('map_list_'+id).src = photo.src;
            el('map_list_'+id).width = 48;
            el('map_list_'+id).height = 40;            
        }
    }
}


function getTeaser(obj, mls, nmbr, mls_name){            
    if(!search_in_progress){
        if(prev!= obj.id) { 
            el(prev).innerHTML = 'Display '+ teaser_nr; 
            prev=obj.id; 
            teaser_nr = number_format(nmbr, 0, '.', ','); 
            search_in_progress=true;
            obj.innerHTML = '<font color=green><b>'+ nmbr +'</b> displayed</font>';
            the_criteria.mls = mls;  
            the_criteria.mls_name = mls_name;  
            the_criteria.nrc = nmbr;
            the_criteria.show_teaser = 'off';  
            the_criteria.page = '1'; 
            submitForm(true);
        }
    }

       
}


function getPage(pg, nmbr){    
    the_criteria.page = pg; 
    the_criteria.nrc = nmbr; 
    the_criteria.show_teaser = 'off'; 
    submitForm(true);    
}


function getCustomPage(obj){        
    
    max_pg = Math.ceil( parseInt(the_criteria.nrc) / parseInt(the_criteria.res_on_page) ) ;   
    if( parseInt(obj.value) <= max_pg && parseInt(obj.value) > 0) {
        the_criteria.page = parseInt(obj.value); 
        the_criteria.show_teaser = 'off'; 
        submitForm(true);    
    }
    else {
        alert("Please insert a value larger than 0 and smaller than " + max_pg);
        return false;
    }
}


function getResOnPage(val){
    el('res_on_page').value = val;    
    the_criteria.res_on_page = val; 
    the_criteria.page = '1';     
    the_criteria.show_teaser = 'off'; 
    submitForm(true);    
}


function getOrderBy(val){    
    el('order_by').value = val;
    the_criteria.order_by = val; 
    the_criteria.page = '1';   
    the_criteria.show_teaser = 'off'; 
    submitForm(true);  
}


function showResults(display_tpl) {      
    
    var els = new Array('text', 'detail', 'map', 'thumbnail');
    
    // determine the view to display
    if(display_tpl == '') {     
        if(el('search_type') && el('search_type').value == 'map') display_tpl = 'map';  
        if(el('display_style') && el('display_style').value != '' ) display_tpl = el('display_style').value;            
    }  
    else {        
        el('display_style').value= display_tpl;
    }
    
    // set the view into the criteria 
    the_criteria.display_style = display_tpl;
    
    if(display_tpl == 'map') {                
        el('workLoaderDiv').style.display = 'none';        
        if(el('mapDiv')) el('mapDiv').style.display = 'block';
        if(el('_map_block_div_')) el('_map_block_div_').style.display = 'none';
        
        if(listings && listings.length) {
            if(!_map_loaded_){
                if(document.all) {  setTimeout("initMap();drawMapResults(listings);",3500);}
                else { initMap(); drawMapResults(listings); }
            }
            else {
                drawMapResults(listings);
            }
        }        
        
        if( el('mapResDiv') && el('mapResFake') && (el('mapResFake').innerHTML!= '')){                     
            el('mapResDiv').innerHTML=el('mapResFake').innerHTML;
            el('mapResFake').innerHTML='';
            _imagesLoaded();                
            el('mapResDiv').style.display = 'block';
            el('mapResDiv').parentNode.style.height='auto';
            //setTimeout("el('mapResDiv').style.height='90px';",200);
			setTimeout("el('mapResDiv').style.height=(el('mapResDiv').offsetHeight+(document.all?16:0))+'px';",200);            
        }           
        //added here in case map list is disabled
        if(el('mapResLnk')) {
            el('mapResLnk').className = 'ps_views_current';
            el('mapResLnk').onmouseout = function () { this.className = 'ps_views_current';}             
        }      
        
    }
    else {        
        if(el('mapDiv')) { 
            el('mapDiv').style.display = 'none'; 
            if(el('_map_block_div_')) el('_map_block_div_').style.display = 'none';
            //added here in case map list is disabled
            if(el('mapResLnk')) {
                el('mapResLnk').className = 'ps_views';
                el('mapResLnk').onmouseout = function () { this.className = 'ps_views';}             
            }      
        }        
        el('workLoaderDiv').style.display = 'block';                
    }
    
    
    // chage current link    
    for(var i3 = 0; i3 < els.length; i3++) if(el(els[i3]+'ResDiv')) {            
        if(els[i3] == display_tpl) { 
            el(els[i3]+'ResDiv').style.display = 'block';
            if(el(els[i3]+'ResLnk')) {
                el(els[i3]+'ResLnk').className = 'ps_views_current';
                el(els[i3]+'ResLnk').onmouseout = function () { this.className = 'ps_views_current';}             
            }                
                
        }
        else {
            el(els[i3]+'ResDiv').style.display='none';
            if(el(els[i3]+'ResLnk')) { 
                el(els[i3]+'ResLnk').className = 'ps_views';            
                el(els[i3]+'ResLnk').onmouseout = function () { this.className = 'ps_views';}
            }
        }
    }         
      

}