//array for storing marker object
var mapflag =1;
var mapMarkers = [];
//array for storing window content for display for each marker
var mapMarkerHtmls = []; 
var activedivid="";
var mapZoom = 10;


//Function to open a map popup when we click on the "Show On Map" icon on the listings.
function markerOnGoogleMap(markerNum,divid)
{ 
  changeColorOfDiv(divid);  
  //document.getElementById('search_title').scrollIntoView(true); //Set window focus on top part of the map.
  mapMarkers[markerNum].openInfoWindowHtml(mapMarkerHtmls[markerNum]);  
} 

//Function for adding listener with given HTML content on given marker
function markerAddListener(marker, content)
{
  GEvent.addListener(marker, "click", function()
  {
   marker.openInfoWindowHtml(content);
   changeColorOfDiv(document.getElementById("Listing"+marker.zam_pos));
    } );
}

//Function to change color of a div when we click on show map link of that div 
function changeColorOfDiv(divid)
{
  if(activedivid != divid)
  {      
    activedivid.className= "marker_close";
  }        
  divid.className="marker_on";     
  activedivid=divid; 
}

//Function called onload of sherwoods pages to load map
//Will center the map on given latlong and create a marker
//Map's container div ID is passed.
//No other functionality required.
function sherwoodsMap(mapDivId, latitude, longitude) {

  var mapDiv = $(mapDivId);
  window.gmap = new GMap2(mapDiv);
  gmap.addControl(new GSmallMapControl());
  //gmap.addControl(new GMapTypeControl());   

  latlong = new GLatLng(latitude, longitude);
  gmap.setCenter(latlong, 11); //Initialize map center - necessary.

  gmap.addOverlay(new GMarker(latlong));

}


// Function for create Google Map in SRP.
function agentGoogleMap()
{ 
  mapflag=1;
  mapMarkers = [];
  mapMarkerHtmls = [];    
  
  var map = document.getElementById('map');
  map.style.display = "block";  
  
  window.gmap = new GMap2(map);
  gmap.addControl(new GSmallMapControl());
  gmap.addControl(new GMapTypeControl());   
  
  defaultLatlong = new GLatLng(28.635308, 77.22496); //New Delhi is the default   
  gmap.setCenter(defaultLatlong, mapZoom); //Initialize map center - necessary.
  
  //Click event listener. Marks the property and picks up its longitude latitude.
  var marker = null; 
  
  // Set up Geocoder
  var tries = 0;
  var area = document.getElementById('area').value;
  var city = document.getElementById('city').value;
  if(area != null && area != ""&& area != "Please Enter Locality") {
    address = area + "," + city;
  } else {
    address = city;
  }
  
  address = address + ",India";
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(address, function addToMap(latlong) {
    
    //In case the geocoding fails, try again without area
    if(latlong == null) {
      
      if(tries == 0) { //Try it again with only city if area search fails. Test case - Sancoale,Panaji fails.
        address = city + ",India";
        geocoder.getLatLng(address, addToMap);
        tries++;
      } else { //Failed second time? then center to New Delhi
        latlong = defaultLatlong;
      }
    }    
    gmap.setCenter(latlong, mapZoom);
  });


  //Element.show('map');
  
  if (GBrowserIsCompatible()) {
  // Add map markers for each listing
  var nl = document.getElementById("num_l").getAttribute("value");  
    for (var i = 0;i<=nl; i++)
    {        
      var llat = document.getElementById("llat" + i);
            
      if (llat != null)
      {
        llat = llat.innerHTML;
      }
      var llong = document.getElementById("llong" + i);
      if (llong != null)
      {
        llong = llong.innerHTML;
      }      
      if (llat != null && llong != null)
      {
        var content;
        var point = new GLatLng(llat, llong);
        var marker = new GMarker(point);
        marker.zam_pos = i;
        marker.map = map;           
        gmap.addOverlay(marker);
        var pc =document.getElementById("pc" + i).innerHTML;
        var lt = document.getElementById("lt" + i).innerHTML;
        var p = marker.zam_pos;
        var lid = document.getElementById("lid" + p).innerHTML;
        var area = document.getElementById("lar" + p).innerHTML;
        var city = document.getElementById("lct" + p).innerHTML;
        var zip = document.getElementById("lzp" + p);        
        if (zip != null)
        {
          zip = zip.innerHTML;
        }
        else
        {
          zip = "";
        }
        var address = area + ", " + city + " " + zip;
        var price = document.getElementById("lp" + p).innerHTML;
        var prop_type = document.getElementById("lpt" + p).innerHTML;
        var beds = document.getElementById("lbeds" + p);
        var baths = document.getElementById("lbaths" + p);
        if(pc=="Commercial" || prop_type=='Land' || prop_type == 'Office')
        {
        	beds='';
        	baths='';        	
        }else
        {
        	
        if (beds != null || beds != '')
        {
          beds = beds.innerHTML + " bed ";
        }
        else
        {
          beds = "";
        }
        
        if (baths != null || baths != "")
        {
          baths = " " + baths.innerHTML + " bath";
        }
        else
        {
          baths = "";
        }
        	
        }    
        
        
        var cov_area = document.getElementById("lca" + p);
        if (cov_area != null || cov_area != '')
        {
          cov_area = " " + cov_area.innerHTML + "<br/>";
        }
        else
        {
          cov_area = "<br/>";
        }        
        
        // create a variable for getting thumb photo for new listing in SRP.      
        var thumbphoto =  document.getElementById('thumburl'+i).innerHTML;
        if(thumbphoto=="" || thumbphoto == null)
        {
        	thumbphoto="images/photo-ph-small.gif";
        }
        
        
        //Content of popup which opens when we click on markerOnMap link 
           
        content="<table cellspacing='5' cellpadding='0' class='marginR'><td><span class='bld'>" +
         pc + " | " + lt + " | " + prop_type + "</span><br/>" +
         "<span class='priceRed bld'>" + price + "</span><br/>" +
         beds + baths + cov_area +
         "<a href='/property/"+ pc.toLowerCase() + '/' + lt.toLowerCase() + '/' + prop_type.toLowerCase() + '/' +city+'/'+area+'/'+lid+".html"+ "'>"+address+"</a>" +
         "</td><td class='paddingR'><a href='/property/"+pc.toLowerCase()+'/'+lt.toLowerCase()+'/'+prop_type.toLowerCase()+'/'+city+'/'+area+'/'+lid+".html" + "'>" + "<img border='0' height='70' width='70' src ='"+ thumbphoto +"'></a></td></table>";
                      
         
        //Add listener to the marker
        markerAddListener(marker,content);
        
        //Store the marker object for each listing in a array
        mapMarkers.push(marker);
    
        //Store the content of map popup for each listing in a array
        //which opens when we click on markerOnMap link
        mapMarkerHtmls.push(content);
      }            
    }   
  }
}

//this function is being used on loadListProperty page
// set marker for property on map 
function markPropertyOnAgentMap(prop_area,prop_city,latitude,longitude,map,latlng)
{
  var mapDiv = document.getElementById(map);
  mapDiv.style.display = "block";
  var latlngDiv = document.getElementById(latlng);
  latlngDiv.style.display = "block";
  
  window.gmap = new GMap2(mapDiv);
  gmap.addControl(new GSmallMapControl());
  gmap.addControl(new GMapTypeControl());
  latSpan = document.getElementById(latitude);    
  lngSpan = document.getElementById(longitude);
  //defaultLatlong = new GLatLng(28.635308, 77.22496); //New Delhi is the default   
 // gmap.setCenter(defaultLatlong, 13); //Initialize map center - necessary.
  
  //Click event listener. Marks the property and picks up its longitude latitude.
  var marker = null;
  GEvent.addListener(gmap, "click", function(overlay,  latlng) {
    
    //Want to handle only the case when user clicks on the map
    //If user clicks on the marker itself, do nothing...
    if(latlng == null) return;
    
    latSpan.value = latlng.lat();
    lngSpan.value = latlng.lng();      
    
    if(marker != null) {
       gmap.removeOverlay(marker);
     }
    
     marker = new GMarker(latlng);
     marker.map = gmap;
     gmap.addOverlay(marker);
   });
  if(document.getElementById(latitude).value !='' && document.getElementById(latitude).value !=null){  	
     var latlng = new GLatLng(document.getElementById(latitude).value, document.getElementById(longitude).value);
    if(latlng == null) return;
    if(marker != null) {
       gmap.removeOverlay(marker);
     }
     
     marker = new GMarker(latlng);
    
     
     marker.map = gmap;
     gmap.addOverlay(marker);   
  
  // Set up Geocoder
  var tries = 0;
  var area = document.getElementById('prop_area_resale').value;
  var city = document.getElementById('prop_city_resale').value;
  if(area != null && area != ""&& area != "Please Enter Locality") {
    address = area + "," + city;
  } else {
    address = city;
  }
  
  address = address + ",India";
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(address, function addToMap(latlong) {
    
    //In case the geocoding fails, try again without area
    if(latlong == null) {
      
      if(tries == 0) { //Try it again with only city if area search fails. Test case - Sancoale,Panaji fails.
        address = city + ",India";
        geocoder.getLatLng(address, addToMap);
        tries++;
      } else { //Failed second time? then center to New Delhi
        latlong = defaultLatlong;
      }
    }
    
    gmap.setCenter(latlong, 13);
  });
  }
  else{ 
  
  // Set up Geocoder
  var tries = 0;
  var area = document.getElementById(prop_area).value;
  var city = document.getElementById(prop_city).value;
  if(area != null && area != ""&& area != "Please Enter Locality") {
    address = area + "," + city;
  } else {
    address = city;
  }
  
  address = address + ",India";
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(address, function addToMap(latlong) {
    
    //In case the geocoding fails, try again without area
    if(latlong == null) {
      
      if(tries == 0) { //Try it again with only city if area search fails. Test case - Sancoale,Panaji fails.
        address = city + ",India";
        geocoder.getLatLng(address, addToMap);
        tries++;
      } else { //Failed second time? then center to New Delhi
        latlong = defaultLatlong;
      }
    }
    
    gmap.setCenter(latlong, 13);
  });}
}


  // this function use to submit post requirment form
  function submitPostRequirementForm()
  { 
    document.postRequirement.submit();
  }

  // switch visiblity of passed DIV elements 
  function expandCollapse(id, id1)
  {
    var e = document.getElementById(id);
    var m = document.getElementById(id1);
    
    if(e.style.display == 'none') {
      e.style.display = 'block';
      m.style.background = '#FBFBFB url(/images/slidingDivTagColapse.gif) repeat-y top right';
    }
    else {
      e.style.display = 'none';
      m.style.background = '#FBFBFB url(/images/slidingDivTagExpand.gif) repeat-y top right';
    }
  }

  //Function to set link in google analytics tool and Zamanzar trackAnalytics 
  function trackAnalytics(str){
    urchinTracker("/custom/" + str);
    // This check analytics on/off switch    
    if(analytics)
    {
     new Ajax.Request('/home/analytics?type='+str, 
     {
       method: 'get',
     
       onSuccess: function(transport) {
       },         
   
     onFailure: function() { 
     },
     
     onLoading: function(){
     }
    });  // ajax finish
    }
  }
  
  //success callback in login user in myzamanzar and home page.
function loginSuccess(request,analyticText)
{ 
  if(request.responseText=='success')
  {     
    trackAnalytics(analyticText);
    document.getElementById('loginUserFeedback').style.display='none';
    var sURL = unescape(window.location.href);
    window.location.href = sURL;
  }
  else
  {   
    document.getElementById('loginUserFeedback').style.display='block';
    document.getElementById('loginUserFeedback').innerHTML=request.responseText;
  }
}

// This function is use to delete property form listing table
function deleteProperty(listing_id)
{
	new Ajax.Request('/agent/deleteProperty?id='+listing_id, 
   {
     method: 'get',
   
     onSuccess: function(transport) {
     	var response = transport.responseText;     	
     	if(response == 'Successfully')
     	{    		
		    var sURL = unescape(window.location.href);		    
		    window.location.href = sURL;     		
     	}
     },         
 
   onFailure: function() { 
   },
   
   onLoading: function(){
   }
  });  // ajax finish	
}
  
  
//show reset password pop up    
function resetAgentPasswordPopup(event, div,email, width, height, fixedTopPos, fixedLeftPos)
{
  var windowWidth, windowHeight, scrollTop, scrollLeft, top_pos, left_pos;
  var IE = document.all?true:false;  
  if (IE)
  {  
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
    scrollLeft = document.documentElement.scrollLeft;
    scrollTop = document.documentElement.scrollTop;
    top_pos = scrollTop + ((windowHeight - height) / 2);
    left_pos = scrollLeft + ((windowWidth - width) / 2);
    if(email)
      {                     
        document.getElementById('resetDiv').innerHTML="<table width='100%'><tr>"+                              
        "<td colspan='2' width='200'>&nbsp;</td>"+
        "<td><input class='allTextBoxes' style='width: 150px;' maxlength='100' type='hidden' name='email' id='resetPasswordEmail' value=''/>"+
        "</td><td align='right'><span id='resetPasswordIndicator' style='display:none;margin-right:10px;height:20px'>"+
        "<input type='image' name='submit' src='/images/indicator.gif'/>"+             
        "</span><input class='allButtons' style='width: 150px;' type='submit' id='resetPasswordSubmit' onclick="+'trackAnalytics("RESET_PASSWORD_CLICK");'+" value='RESET PASSWORD'/>"+
        "</td></tr><tr><td colspan='2' height='15'></td></tr></table>"
        document.getElementById('emailValue').innerHTML=email+".";   
        document.getElementById('resetPasswordEmail').value = email;                
      }       
      else
      {
        document.getElementById('emailValue').innerHTML="given mail id.";
        document.getElementById('resetDiv').innerHTML="<table width='100%'><tr>"+        
         "<td id='emailTd'>Email:</td>"+
         "<td><input class='allTextBoxes' style='width: 150px;' maxlength='100' type='text' name='email' id='resetPasswordEmail'/></td>"+        
         "<td colspan='2' width='200'>&nbsp;</td>"+             
         "</td><td align='right'><span id='resetPasswordIndicator' style='display:none;margin-right:10px;height:20px'>"+
         "<input type='image' name='submit' src='/images/indicator.gif'/>"+  
          "</span><input class='allButtons' style='width: 150px;' type='submit' id='resetPasswordSubmit' onclick="+'trackAnalytics("RESET_PASSWORD_CLICK");'+" value='RESET PASSWORD'/>"+
         "</td></tr><tr><td colspan='2' height='15'></td></tr></table>"             
         
      }       
    
  }
  else
  {
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
    scrollLeft = window.pageXOffset;
    scrollTop = window.pageYOffset;
    top_pos = scrollTop + ((windowHeight - height) / 2);
    left_pos = scrollLeft + ((windowWidth - width) / 2);
    if(email)
      {                     
        document.getElementById('resetDiv').innerHTML="<table width='100%'><tr>"+                              
        "<td colspan='2' width='200'>&nbsp;</td>"+
        "<td><input class='allTextBoxes' style='width: 150px;' maxlength='100' type='hidden' name='email' id='resetPasswordEmail' value=''/>"+
        "</td><td align='right'><span id='resetPasswordIndicator' style='display:none;margin-right:10px;height:20px'>"+
        "<input type='image' name='submit' src='/images/indicator.gif'/>"+             
        "</span><input class='allButtons' style='width: 150px;' type='submit' id='resetPasswordSubmit' onclick="+'trackAnalytics("RESET_PASSWORD_CLICK");'+" value='RESET PASSWORD'/>"+
        "</td></tr><tr><td colspan='2' height='15'></td></tr></table>"
        document.getElementById('emailValue').innerHTML=email+".";   
        document.getElementById('resetPasswordEmail').value = email;                
      }       
      else
      {
        document.getElementById('emailValue').innerHTML="given mail id.";
        document.getElementById('resetDiv').innerHTML="<table width='100%'><tr>"+        
         "<td id='emailTd'>Email:</td>"+
         "<td><input class='allTextBoxes' style='width: 150px;' maxlength='100' type='text' name='email' id='resetPasswordEmail'/></td>"+        
         "<td colspan='2' width='200'>&nbsp;</td>"+             
         "</td><td align='right'><span id='resetPasswordIndicator' style='display:none;margin-right:10px;height:20px'>"+
         "<input type='image' name='submit' src='/images/indicator.gif'/>"+  
          "</span><input class='allButtons' style='width: 150px;' type='submit' id='resetPasswordSubmit' onclick="+'trackAnalytics("RESET_PASSWORD_CLICK");'+" value='RESET PASSWORD'/>"+
         "</td></tr><tr><td colspan='2' height='15'></td></tr></table>"             
         
      }       
  }

  if (fixedTopPos != -1)
  {
    top_pos = scrollTop + fixedTopPos;
  }       

  if (fixedLeftPos != -1)
  {
    left_pos = scrollLeft + fixedLeftPos;
  }
    
  div.style.top = top_pos.toString() + "px";
  div.style.left = left_pos.toString() + "px";
  div.style.display = "block";
}  



//srp google map for custom agent site
function loadSrpMap()
{   
  mapflag=1;
  mapMarkers = [];
  mapMarkerHtmls = [];  
  Element.show('map');
  if (GBrowserIsCompatible()) {  
     
  var map = new GMap2(document.getElementById("map"));
  
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());  
  var lat = document.getElementById('map_lat').value; 
  var long = document.getElementById('map_long').value;  
  map.setCenter(new GLatLng(lat, long), 11);    
  // Add map markers for each listing
  var nl = document.getElementById("num_l").getAttribute("value");    
    for (var i = 0;i<nl; i++)
    {     
      var llat = document.getElementById("llat" + i);
            
      if (llat != null)
      {
        llat = llat.innerHTML;
      }
      var llong = document.getElementById("llong" + i);
      if (llong != null)
      {
        llong = llong.innerHTML;
      }
      if (llat != null && llong != null)
      {
        var content;
        var point = new GLatLng(llat, llong);
        var marker = new GMarker(point);
        marker.zam_pos = i;
        marker.map = map;           
        map.addOverlay(marker);
       
      var p = marker.zam_pos;      
     
      var pc = document.getElementById("pc"+ p).innerHTML;
      var lt = document.getElementById("lt"+ p).innerHTML;
      var lid = document.getElementById("lid" + p).innerHTML;
      var area = document.getElementById("lar" + p).innerHTML;
      var city = document.getElementById("lct" + p).innerHTML;
      var zip = document.getElementById("lzp" + p);
       var prop_type = document.getElementById("lpt" + p).innerHTML;
      if (zip != null)
      {
        zip = zip.innerHTML;
      }
      else
      {
        zip = "";
      }
      var address = area + ", " + city + " " + zip;
      var price = document.getElementById("lp" + p).innerHTML;
      var beds = document.getElementById("lbeds" + p);
      //document.getElementById('lead1').style.display=true;
      if (beds != null)
      {
        beds = beds.innerHTML + " bed ";
      }
      else
      {
        beds = "";
      }
      var baths = document.getElementById("lbaths" + p);
      if (baths != null)
      {
        baths = " " + baths.innerHTML + " bath";
      }
      else
      {
        baths = "";
      }
      
     // var plot_size = document.getElementById("lplot_size" + p);
      var cov_area = " "+document.getElementById("lca" + p).innerHTML;
            
      // create a variable for getting thumb photo for new listing in SRP.      
      var thumbphoto =  document.getElementById('thumburl'+i).src;      
      
      // Get builder project name for new listing in map popup.  
      if(document.getElementById('b_proj'+p)!=null && document.getElementById('b_proj'+p)!="undefined")   
      { 
        var b_proj = document.getElementById('b_proj'+p).innerHTML;      
      }
      // Get builder property name for new listing in map popup.
      if(document.getElementById('b_prop'+p)!=null && document.getElementById('b_prop'+p)!="undefined")
      {
        var b_prop = document.getElementById('b_prop'+p).innerHTML;
      }  
      // Get new listing for map popup in Srp.   
       var new_listing = document.getElementById('new_listing'+p).innerHTML;
          
      
      //Content of popup which opens when we click on markerOnMap link      
        
        if(new_listing)
        {           
           content="<table cellspacing='5' cellpadding='5'><tr><td><h4><b>" +
           prop_type + " | " + b_proj+"</b> ("+b_prop+")"+ "<br/>" +
           "<span class='price'>" + price + "</span></b><br/>" +
           beds + baths + cov_area +"<br/>"+
           "<a href='/property/"+pc.toLowerCase()+'/'+lt.toLowerCase()+'/'+prop_type.toLowerCase()+'/'+city+'/'+area+'/'+lid+".html"+ "'>" +address+"</a></h4>" +
           "</td><td><a href='/property/"+pc.toLowerCase()+'/'+lt.toLowerCase()+'/'+prop_type.toLowerCase()+'/'+city+'/'+area+'/'+lid+".html" + "'>" + "<img border='0' height='70' width='70' src ='"+ thumbphoto +"'></a></td></tr></table>";          
        }
        else
        {         
           content="<table cellspacing='5' cellpadding='5'><tr><td><h4><b>" +
           pc + " | " + lt + " | " + prop_type + "<br/>" +
           "<span class='price'>" + price + "</span></b><br/>" +
           beds + baths + cov_area +"<br/>"+
           "<a href='/property/"+pc.toLowerCase()+'/'+lt.toLowerCase()+'/'+prop_type.toLowerCase()+'/'+city+'/'+area+'/'+lid+".html"+ "'>" +address+"</a></h4>" +
           "</td><td><a href='/property/"+pc.toLowerCase()+'/'+lt.toLowerCase()+'/'+prop_type.toLowerCase()+'/'+city+'/'+area+'/'+lid+".html" + "'>" + "<img border='0' height='70' width='70' src ='"+ thumbphoto +"'></a></td></tr></table>";
         }       
      //Add listener to the marker
      markerAddListener(marker,content);       
      }
      //Store the marker object for each listing in a array
      mapMarkers.push(marker);
    
      //Store the content of map popup for each listing in a array
      //which opens when we click on markerOnMap link
      mapMarkerHtmls.push(content);
    }   
  }}  
  
// This function is use to delete property form listing table from sherwood site
function deletePropertySherwoods(listing_id) 
{
  new Ajax.Request('/sherwoods/deleteProperty?id='+listing_id, 
   {
     method: 'get',
   
     onSuccess: function(transport) {
      var response = transport.responseText;      
      if(response == 'Successfully')
      {       
        var sURL = unescape(window.location.href);        
        window.location.href = sURL;        
      }
     },         
 
   onFailure: function() { 
   },
   
   onLoading: function(){
   }
  });  // ajax finish 
}  





