/* *****************************************************************
Following methods are used to plot map using YAHOO Ajax libraries. 
******************************************************************/

//YAHOO CONSTANTS USED FOR SETTING COOKIES
var YRE_COOKIE_MAP_SIZE = 'mapsize';
var YRE_COOKIE_MAP_TYPE = 'maptype';
var YRE_COOKIE_MAP_SHOW = 'mapshow';
var YRE_COOKIE_SEARCH_OPTIONS = 'op';

//function to set cookie values for map.
function SetCookieforMap(name,value) { 
	var expiration_date = new Date ();
	expiration_date.setTime (expiration_date.getTime() + (24 * 60 * 60 * 1000 * 365)); // 1 year from now 

	FixCookieDate (expiration_date);
	SetCookie ( name , value ,expiration_date ,"/");
}

//function to retreive cookie values
function GetCookie(name) { 
	   var start = document.cookie.indexOf(name+"="); 
	   var len = start+name.length+1; 
	   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
	   if (start == -1) return null; 
	   var end = document.cookie.indexOf(";",len); 
	   if (end == -1) end = document.cookie.length; 
	   return unescape(document.cookie.substring(len,end)); 
}

function getZoomLevel( minLat, maxLat, minLon, maxLon, mpoint )
{
	if ( maxLat < mpoint.LatMax  && maxLon < mpoint.LonMax  &&  minLat > mpoint.LatMin && minLon > mpoint.LonMin )
	{
		return true;
	}
	else
	{
		return false;
	}
}	

var yreMap = {
    id        : null,
    mapObj    : null,
    zoomLevel : 6,
    centerPt  : null,
    width     : null,
    height    : null,
    expWidth  : null,
    expHeight : null,
    openExpand: 0,
    mapType   : null,
    mapSize   : null,
    currSize  : null,
    rendered  : false,

    init : function(id, width, height, expWidth, expHeight, zoomLevel, openExpand, mapSize ) {
		this.id = id;
        this.width = width;
        this.height = height;
        this.expWidth = expWidth;
        this.expHeight = expHeight;
        this.zoomLevel = zoomLevel;
        this.openExpand = openExpand;
		this.mapSize = mapSize;
		var mt = GetCookie(YRE_COOKIE_MAP_TYPE);
        this.mapType = (mt=='') ? YAHOO_MAP_REG : mt; 
        this.currSize = (this.mapSize=='L') ? 'expand' : 'default';
        
        document.getElementById('yreMapSizeLnk').onclick = function() { yreMap.resize(); return false; };
        if (document.getElementById('yreMapHideLnk')) {
            document.getElementById('yreMapHideLnk').onclick = function() { yreMap.hideMap(); return false; };
        }
        if (document.getElementById('yreMapShowLnk')) {
            document.getElementById('yreMapShowLnk').onclick = function() { yreMap.showMap(); return false; };
        }
    },

    createMarker : function(geoPoint, label, autoExpand, smartWin, icon, iconSize, color) {
        var bubble = new YImage();
        bubble.src = icon;
        bubble.size = iconSize;
        bubble.offsetSmartWindow = new YCoordPoint(0, 0);
        var marker = new YMarker(geoPoint, bubble);
        marker.addLabel("<div class=mapLabel>" + label + "</div>");
        marker.addAutoExpand(autoExpand);
        marker.setSmartWindowColor(color);
        YEvent.Capture(marker, EventsList.MouseClick,
          function() { marker.openSmartWindow(smartWin); });
        return marker;
    },

    display : function(points) {
		var size = (this.mapSize=='L') ? new YSize(this.expWidth, this.expHeight) : new YSize(this.width, this.height);
        var map = new YMap(document.getElementById(this.id), this.mapType, size);
        map.removeZoomScale();
        map.addTypeControl();
        map.addPanControl();
        map.addZoomLong();
        map.disableKeyControls();
        
        YEvent.Capture(map, EventsList.changeMapType,
          function() { yreMap.changeMapType(); return true; });

        var geoPoints = [];
        var first = null;
        for (var i = 0; i < points.length; i++) {
            var p = points[i];
            var geoPoint = new YGeoPoint(p.lat, p.lon);
            geoPoints[geoPoints.length] = geoPoint;
            var marker = this.createMarker(geoPoint, p.label, p.popupS, p.popupL, p.icon.url, new YSize(p.icon.w, p.icon.h), p.popupColor);
            map.addOverlay(marker);
            if (i == 0) { first = marker; }
        }
		
		if (1 /* DYNAMIC_ZOOM_AND_CENTER */ && geoPoints.length > 0) {
            var zoomCenter = map.getBestZoomAndCenter(geoPoints);
            map.drawZoomAndCenter(zoomCenter.YGeoPoint, zoomCenter.zoomLevel);
        } 
        
        if (this.openExpand && first != null) { first.openAutoExpand(); }
        this.rendered = true;
        this.mapObj = map;
    },

    resize : function() {
        var lnk = document.getElementById("yreMapSizeLnk");
        if (this.currSize == 'default') {
            this.mapObj.resizeTo(new YSize(this.expWidth, this.expHeight));
            lnk.innerHTML = 'Reduce Map Size';
            this.currSize = 'expand';
            SetCookieforMap(YRE_COOKIE_MAP_SIZE, 'L');
        } else {
            this.mapObj.resizeTo(new YSize(this.width, this.height));
            lnk.innerHTML = 'Expand Map Size';
            this.currSize = 'default';
            SetCookieforMap(YRE_COOKIE_MAP_SIZE, 'S');
        }
    },

    hideMap : function() {
        document.getElementById("pnlMap").className = "yreMapView1";
        SetCookieforMap(YRE_COOKIE_MAP_SHOW, 'N');
    },

    showMap : function() {
        document.getElementById("pnlMap").className = "yreMapView2";
        SetCookieforMap(YRE_COOKIE_MAP_SHOW, 'Y');
        if (!this.rendered) {
            this.display(mapPoints);
        }
    },

    changeMapType : function() {
        var type = this.mapObj.getCurrentMapType();
        SetCookieforMap(YRE_COOKIE_MAP_TYPE, type);
    }
};

function yreStartMap(e, o) {
	yreMap.display(o);
}

// Legacy Map arrays
var arrHouseData = new Array();
var arrMenu = new Array();

// open VOW detail page and close current window
function openDetail( strUrl, hindex )
{
	//var strOptions = "scrollbars=yes,status=yes,toolbar=yes,menubar=yes,resizable=yes,location=yes,left=0,top=0";
	//DetailWindow = window.open( strUrl,"Detail" + hindex,strOptions );
	window.document.location.href = strUrl.replace( "~" , "'" );
}


/* ***************************************************************************************************
Following methods are used to Set and Get elements from cookies and to turn on/off history cookies. 
******************************************************************************************************/

function historyOn()
{
    DeletehistoryCookie("RecentSearch", "/");
    DeletehistoryCookie("RecentView", "/");
    document.getElementById('tdOn').className = 'sl2';
    document.getElementById('tdOff').className = 'sl1';
}

function historyOff()
{
    document.getElementById('divRecentSearches').style.visibility = "hidden";
    document.getElementById('divRecentSearches').style.position = "absolute";
    document.getElementById('divRecentViews').style.visibility = "hidden";
    document.getElementById('divRecentViews').style.position = "absolute";
    setCookieStatus();
    document.getElementById('tdOn').className = 'sl1';
    document.getElementById('tdOff').className = 'sl2';
}

function setCookieStatus()
{
    var expdate = new Date ();
    FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
    expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000 * 365)); // 1 year from now 
    SetCookie ("RecentSearch", "StatusOff",expdate ,"/");
    SetCookie ("RecentView", "StatusOff",expdate ,"/");
}

//  Function to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//

function DeletehistoryCookie (name,path,domain) 
{
	var expdate = new Date ();
    FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
    expdate.setTime (expdate.getTime() - (24 * 60 * 60 * 1000) ); // to previous day 
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
     "; expires="+expdate.toGMTString();
}


//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}


/* **************************************************************************
Following methods are used in ajaxing/client callback refine search control. 
*****************************************************************************/

function LookUpArea()
{		
    var form = document.forms[0];
    var arguments = "";
    var propertyTypeIndex = new String();
    var beds = "";
    var baths = "";
    var minPrice = "";
    var maxPrice = "";
    var miles = "";
    var SearchGeo = "";
    
    for (var  i = 0; i < form.elements.length; i++ )
    {
        if ( form.elements[i].type == "checkbox" )
        {
            if ( form.elements[i].id.indexOf( "cblPropertyTypes" ) != -1 )
            {
                if ( form.elements[i].checked )
                {
					var x = form.elements[i].name.indexOf( ":" );
					if( x != -1 && form.elements[i].name.length >= (x+2) )
					{
						id = new String( form.elements[i].name );
						id = id.slice( x + 1, x + 2 );
						propertyTypeIndex = propertyTypeIndex + id + ",";
                    }
                    else
                    {
						propertyTypeIndex = propertyTypeIndex + form.elements[i].name + ",";
                    }
                }
            }
        }
        
        if ( minPrice == "" )
        {
			if ( form.elements[i].type == "radio" )
			{
				if ( form.elements[i].id.indexOf( "Bed" ) != -1 )
				{
					if (  form.elements[i].checked )
					{
						beds = form.elements[i].value;
					}
				}
			}
        }
        
        if ( maxPrice == "" )
        {
			if ( form.elements[i].type == "radio" )
			{
				if ( form.elements[i].id.indexOf( "Bath" ) != -1 )
				{
					if (  form.elements[i].checked )
					{
						baths = form.elements[i].value;
					}
				}
			}
        }
        	        
    }

    // Clean up last comma in PropertyType
    if ( propertyTypeIndex.length > 1 )
    {
		propertyTypeIndex = propertyTypeIndex.slice( 0, propertyTypeIndex.length - 1 );
    }
    if( propertyTypeIndex.length > 0 )
    {
		if ( document.getElementById( 'lblRefineSearchError' ) != null )
		{
			document.getElementById( 'lblRefineSearchError' ).style.display = "none";
		}
	}
    
    if ( document.getElementById( 'ddlMinPrice' ) != null )
    {
		minPrice = document.getElementById( 'ddlMinPrice' ).options[document.getElementById( 'ddlMinPrice' ).selectedIndex].value;
    }
    
    if ( document.getElementById( 'ddlMaxPrice' ) != null )
    {
		maxPrice = document.getElementById( 'ddlMaxPrice' ).options[document.getElementById( 'ddlMaxPrice' ).selectedIndex].value;
    }
    
    if ( document.getElementById( 'txtSearchArea' ) != null )
    {
		SearchGeo = document.getElementById( 'txtSearchArea' ).value;
    }
    
    miles = "-1";    
        
    arguments = "propertytype=" + propertyTypeIndex + "&searchbedrooms=" + beds + "&searchbathrooms=" + baths + "&searchminprice=" + minPrice + "&searchmaxprice=" + maxPrice +
		"&miles=" + miles + "&txtsearch=" + SearchGeo;   
    
    CallServer( arguments, "" );
}

function ReceiveServerData( xml )
{   
	FillListingCounts( xml, "proptC", "<ptv>", "</ptv>", "<ptt>", "</ptt>" );
	FillListingCounts( xml, "bedsC", "<bedv>", "</bedv>", "<bedt>", "</bedt>" );
	FillListingCounts( xml, "bathsC", "<bathv>", "</bathv>", "<batht>", "</batht>" );	
}

function FillListingCounts( xml, countLabelPrefix, valTagOpenName, valTagCloseName, txtTagOpenName, txtTagCloseName )
{
	var valTagBegin = 0;
	var valTagEnd = 0;
	var txtTagBegin = 0;
	var txtTagEnd = 0;
	var flg = 0;
	var nodeText = ""; 
	var nodeId = "";
	var i = 0;
	
	while ( true )
	{
		valTagBegin = xml.indexOf( valTagOpenName, valTagBegin ) + valTagOpenName.length;
		if ( flg > valTagBegin )
		{
			return;
		}
		else
		{
			flg = valTagBegin;
		}
		valTagEnd = xml.indexOf( valTagCloseName, valTagBegin );
		txtTagBegin = xml.indexOf( txtTagOpenName, txtTagBegin ) + txtTagOpenName.length;
		txtTagEnd = xml.indexOf( txtTagCloseName, txtTagBegin );
		nodeId = xml.slice( valTagBegin, valTagEnd );
		nodeText = xml.slice( txtTagBegin, txtTagEnd );                  

		var labelId = countLabelPrefix + nodeId;
		
		if ( document.getElementById( labelId ) != null )
		{
			if ( nodeText == "" )
			{
				document.getElementById( labelId ).innerHTML = "";
			}
			else
			{
				document.getElementById( labelId ).innerHTML = nodeText ;
			}
		}
		i++;
	}
}

// due to differences in browsers, not every browser works with body onload
// and some browsers won't call the onload function when you click the "back" button.
// this function will always call the function on completion of the page download
function CrossBrowserOnload( callback )
{
    if (window.addEventListener) //DOM method for binding an event
        window.addEventListener("load", callback, false)
    else if (window.attachEvent) //IE exclusive method for binding an event
        window.attachEvent("onload", callback)
    else if (document.getElementById) //support older modern browsers
        window.onload=callback
}
