﻿//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Reno.LoadFirst Begin
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var $RenoBase = function()
{
    this.DocumentReady = false; // loaded in Reno.LoadLast.js
};

//================================================================
//  Initialize Base Class
//================================================================
var $Reno = new $RenoBase();

//================================================================
//  String.Format gives you C# style string formatting
//  However it will not replace a number more than once
//  You need to provide a key for each value
//================================================================
//  Example:    "one on one"
//  Use:        "{0} {1} {2}", "one", "on", "one"
//  Note:       "{0} {1} {0}", "one", "on"
//================================================================
//  Jim Conte - jim@conte.com
//================================================================
String.Format = function() 
{
    if (arguments.length < 2) 
    {
        throw ("String.Format requires at least 2 arguments");
    }
    var str = " " + arguments[0];
    for (var i = 1; i < arguments.length; i++) 
    {
        var re = new RegExp('([^\\{]{1})(\\{' + (i - 1) + '\\}(?!\\}))', 'gm');
        str = str.replace(re, '\$1' + arguments[i]);
    }
    str = str.replace(new RegExp('\\{\\{', 'gm'), "{");
    str = str.replace(new RegExp('\\}\\}', 'gm'), "}");
    return str.substring(1);
};

String.format = String.Format;

//================================================================
//  String.Trim() == standard trim function
//================================================================
//  Jim Conte - jim@conte.com
//================================================================
String.Trim = function(str) 
{
    if (str == null) { return ""; }
    return str.replace(/^\s*|\s*$/g, "");
};
function trim(str) 
{
    if (str==null) { return ""; }
    if (GetType(str) == "object") { return ""; }
	return str.replace(/^\s*|\s*$/g,"");
}
function Trim(str) { return trim(str); }


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Enable Background Image Caching for image backgrounds in CSS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
try
{
    document.execCommand("BackgroundImageCache",false,true);
}
catch(err){};


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Reload page if anchor tag exists with Query on results
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if (window.location.href.indexOf('#') > -1)
{
    var SEOPath = window.location.href.substring(window.location.href.indexOf('#')+1);
    if (SEOPath.indexOf("/") > -1 && SEOPath.length > 3)
    {
        window.location.href = "http://" + window.location.hostname + SEOPath;
    }
}


//========================================================
//   shorthand for document.getElementById with null check
//========================================================
function gE(objId)
{
    if (document.getElementById(objId))
    {
        return document.getElementById(objId);
    }
    return null;
}


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	Extends the javascript Array object to include the method
//	indexOf(x), which returns the index of the first 
//	occurrent of x in the array. (One-dimensional Arrays only)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (!Array.prototype.indexOf)
{
	Array.prototype.indexOf = function(elt /*, from*/)
	{
		var len = this.length;
		
		var from = Number(arguments[1]) || 0;
		from = (from < 0) ? Math.ceil(from) : Math.floor(from);
		if (from < 0)
		{
			from += len;
		}
		for (; from < len; from++)
		{
			if (from in this && this[from] === elt)
			{
				return from;
			}
		}
		return -1;
	};
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	Extends the javascript Array object to include the method
//	count() which will return the number of items if the 
//	array object is used as an associative array ie.
//
//	var MyArray = new Array();
//		MyArray["key"] = value;
//
//	MyArray.length // == 0
//	MyArray.count  // == 1
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (!Array.prototype.count)
{
	Array.prototype.count = function () 
	{
		var cnt = 0;
		for (var k in this) 
		{
			cnt++;
		}
		return cnt;
	};
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	Extends the javascript Array object to include the method
//	keys() which will return the keys of items as an array if the 
//	array object is used as an associative array ie.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (!Array.prototype.keys)
{
	Array.prototype.keys = function() 
	{
		var keys = new Array();
		for (var k in this) 
		{
			if (k != "count" && k != "keys")
			{
				keys.push(k);
			}
		}
		return keys;
	};
}

//========================================================
//   FormatNumber
//========================================================
function FormatNumber(NumberString)
{
	NumberString += '';
	Parts = NumberString.split('.');
	Number1 = Parts[0];
	Number2 = Parts.length > 1 ? '.' + Parts[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(Number1)) 
	{
		Number1 = Number1.replace(rgx, '$1' + ',' + '$2');
	}
	return Number1 + Number2;
}

//========================================================
//   NormalizeSEOQuery
//========================================================
function NormalizeSEOQuery(SEOQuery, Suffix, boolRemove)
{
	SEOQuery = SEOQuery.toLowerCase();
	if (Suffix != undefined)
	{	
		Suffix = Suffix.toLowerCase();
	}
    var QS = null;
    if (SEOQuery.indexOf('?') > -1)
    {
        QS = SEOQuery.substring(SEOQuery.indexOf('?')+1);
        SEOQuery = SEOQuery.substring(0, SEOQuery.indexOf('?'));
    }
    SEOQuery = SEOQuery.replace(/^(.+?)\/?$/, '$1'); // remove trailing slash
    SEOQuery = SEOQuery.replace(/^\/?(.+?)$/, '$1'); // remove leading slash
    SEOQuery = "/" + SEOQuery;
    if (boolRemove != undefined && 
		boolRemove == true &&
		Suffix != undefined)
    {
		SEOQuery = SEOQuery.replace(Suffix, "");
    }
    else if (Suffix != undefined)
    {
		Suffix = Suffix.replace(/^\/?(.+?)$/, '$1'); // remove leading slash
		SEOQuery = SEOQuery + "/" + Suffix;
    }
    SEOQuery = SEOQuery.replace("///", "/").replace("//", "/");
    if (QS != null)
    {
        SEOQuery = SEOQuery + "?" + QS;
    }
    return SEOQuery;
}





function DoReportArray(ArrayReportData, EventCode) // typically for search results, 10 listings
{
    for(var x=0;x<ArrayReportData.length;x++)
    {
        DoReport(ArrayReportData[x], EventCode);
    }
}

function DoReportIndex(arr, index, EventCode) // typically for any search result listing
{
    if ($.isArray(arr) &&
        arr.length > 0 &&
        arr.length-1 >= index &&
        arr[index] != null &&
        arr[index] != '')
    {
        //alert(arr[index] + ":" + arr[index].replace("ReplaceWithEvent", EventCode) + ":" + index);
        
        DoReport(arr[index], EventCode);
    }
}

var reporting_index = 0;

function DoReport(data, EventCode)
{
	reporting_index++;
    if (reporting_index > 19) 
    {
		reporting_index = 0; // there are 20 DoReport pages
	}
    data = data.replace("ReplaceWithEvent", EventCode);
    $.get("/reno/reporting/doreport" + reporting_index + ".aspx", { data: escape(data) });
//    if (DEBUG==true)
//    {
//		$.log(data);
//		alert("Reported: " + data + "\n\n...\n\nDisable this debug alert in \n/Reno/GlobalResources/Javascript/Reno.LoadFirst.js");
//    }
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  GoLst event fired when user clicks listing link to detail 
//  Updates results cookies and reports click
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function GoLst(pageIndex, resultIndex, page, EventCode, url)
{
    //alert("here1");
    var Opts = { hoursToLive: 1 };
    $.cookies.set("SearchDetailIndex", resultIndex, Opts);
    $.cookies.set("SearchPage", page, Opts);
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //  this function is defined differently depending on the context
    //  wrap in try to exclude any errors
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//    try
//    {
//        DisplayReloaderOnly();
//    }
    //    catch(ex){}
    Report(pageIndex, EventCode);
    //alert(index + ":" + page);
    //alert("here2");
    if (url != undefined && document.all) {
        window.location.href = url;
    }
    return true;
}



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  this function reports listing click events
//  ListingReporting array reused on results and detail
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Report(index, EventCode) 
{
    //alert(EventCode);
    DoReportIndex(ListingReporting, index, EventCode);
}


//========================================================
//  Capture MouseMove event X, Y, stores it in the MousePosition object
//  Mouse position is globally available in the  object
//========================================================

// Global variables
var MousePosition = new Object();
    MousePosition.X = 0;
    MousePosition.Y = 0;

    //========================================================
    //  captureMousePosition
    //========================================================
    function captureMousePosition(e) 
    {
        if (document.layers) 
        {
            MousePosition.X = e.pageX + 25;
            MousePosition.Y = e.pageY - 25;
        } 
        else if (document.all) 
        {
            MousePosition.X = window.event.x + document.body.scrollLeft + 25;
            MousePosition.Y = window.event.y + document.body.scrollTop - 25;
        } 
        else if (document.getElementById) 
        {
            MousePosition.X = e.pageX + 25;
            MousePosition.Y = e.pageY - 25;
        }
    }

    //========================================================
    //  CaptureMouseXY
    //========================================================
    function CaptureMouseXY() 
    {
	    // Set Netscape up to run the "captureMousePosition" function whenever
	    // the mouse is moved. For Internet Explorer and Netscape 6, you can capture
	    // the movement a little easier.
	    if (document.layers) { // Netscape -6
	        document.captureEvents(Event.MOUSEMOVE);
	        document.onmousemove = captureMousePosition;
	    } else if (document.all) { // Internet Explorer
	        document.onmousemove = captureMousePosition;
	    } else if (document.getElementById) { // Mozilla
	        document.onmousemove = captureMousePosition;
	    }
    }


//========================================================
//  RecurseOffset(object)
//  returns true cross-browser offsetLeft and offsetTop of an object.
//  offsetWidth and offsetHeight are included for 
//  ease of use.
//--------------------------------------------------------
//  ex. var Left = RecurseOffset(obj).offsetLeft;
//========================================================
function RecurseOffset(obj)
{
    if (GetType(obj)=="string")
    {
        if (gE(obj)==null)
        {
            alert("RecurseOffset requires a valid DOM object");
        }
        else
        {
            obj = gE(obj);
        }
    }
   var ROO = new RecurseOffsetObject(obj);
   var Offsets = new Object();
       Offsets.offsetLeft   = ROO.GetOffsetLeft();
       Offsets.offsetTop    = ROO.GetOffsetTop();
       Offsets.offsetWidth  = ROO.GetOffsetWidth();
       Offsets.offsetHeight = ROO.GetOffsetHeight();
   
   return Offsets;
}


//========================================================
//  RecurseOffsetObject(object) used in RecurseOffset(object)
//  This can be called directly
//========================================================
function RecurseOffsetObject(obj)
{
	this.ParentObj = null;
	this.CurrentObj = obj;
    this.offsetLeft = obj.offsetLeft;
    this.offsetTop = obj.offsetTop;
    this.offsetWidth = obj.offsetWidth;
    this.offsetHeight = obj.offsetHeight;
    
	RecurseOffsetObject.prototype.Init = function()
	{
	    if (this.CurrentObj.offsetParent != null)
	    {
	        do
		    {
                this.ParentObj = this.CurrentObj.offsetParent;
                this.offsetLeft += this.ParentObj.offsetLeft;
                this.offsetTop += this.ParentObj.offsetTop;
                this.CurrentObj = this.ParentObj;
		    }
		    while (this.CurrentObj.offsetParent != null);
	    }
	};
	RecurseOffsetObject.prototype.GetOffsetLeft = function(){ return this.offsetLeft; };
	RecurseOffsetObject.prototype.GetOffsetTop = function(){ return this.offsetTop; };
	RecurseOffsetObject.prototype.GetOffsetWidth = function(){ return this.offsetWidth; };
	RecurseOffsetObject.prototype.GetOffsetHeight = function(){ return this.offsetHeight; };
	this.Init();
}



//===============================================
//	System Types are caught with GetType()
//	Or, any custom type built with a constructor
//===============================================
function GetType(Element)
{
	if (Element==null)
	{
		return "null";
	}
	if (Element.constructor == null)
	{
		return "object";
	}
	else
	{
		var Catches = Element.constructor.toString().toLowerCase().match(/([a-z0-9]+)(\(\))/i);
		if (Catches != null)
		{
			return Catches[1];
		}
		else
		{
			return "unknown";
		}
	}
}



//================================================================
//  UrlGen
//  Mimics functionality of Endeca "UrlGen"
//================================================================
function UrlGen(strQueryString)
{
    this.Parameters = new Array();
    
    UrlGen.prototype.Init = function(strQueryString)
    {with(this){
        Parameters = new Array();
        var QueryString = strQueryString.replace(/&amp;/gi,'&');
            QueryString = QueryString.replace('%7c','|');
            QueryString = unescape(QueryString);
        
        var _tempParams = QueryString.split('&');
        for (var i=0; i < _tempParams.length; i++)
        {
            var _Param = _tempParams[i].split('=');
            Parameters.push(_Param);
        }
    }};
    
    UrlGen.prototype.RemoveParam = function(strKey)
    {with(this){
        var _tempParams = new Array();
        for (var i=0; i<Parameters.length; i++)
        {
            if (Parameters[i][0].toLowerCase() != strKey.toLowerCase())
            {
                _tempParams.push(Parameters[i]);
            }
        }
        Parameters = _tempParams;
    }};
    
    UrlGen.prototype.RemoveParams = function(arrParams)
    {with(this){
        for (var p=0; p<arrParams.length; p++)
        {
            RemoveParam(arrParams[p]);
        }
    }};
    
    UrlGen.prototype.AddParam = function(strKey, strValue)
    {with(this){
        Parameters.push(new Array(strKey, strValue));
    }};
    
    UrlGen.prototype.GetParam = function(strKey)
    {with(this){
        for (var i=0; i<Parameters.length; i++)
        {
           if (Parameters[i][0].toLowerCase() == strKey.toLowerCase())
           {
                return Parameters[i][1];
           }
        }
        return "";
    }};

    UrlGen.prototype.AddNValue = function(EndecaId)
    {with(this){
        var NValues = unescape(GetParam('N')).split(' ');
            NValues.push(EndecaId);
            RemoveParam('N');
            AddParam('N', NValues.join('+'));
    }};
    
    UrlGen.prototype.GetNValues = function()
    {with(this){
        return unescape(GetParam('N')).split(' ');
    }};
    
    UrlGen.prototype.AddNavFilter = function(strFilterName, strFilterValue)
    {with(this){
        var NavFilters = new NavFilterCollection(GetParam("Nf"));
            NavFilters.AddFilter(strFilterName, strFilterValue);
            RemoveParam('Nf');
            AddParam('Nf', NavFilters.ToString());
    }};
    
    UrlGen.prototype.RemoveNavFilter = function(strNavFilterName)
    {with(this){
        var NavFilters = new NavFilterCollection(GetParam("Nf"));
            NavFilters.RemoveFilter(strNavFilterName);
            RemoveParam('Nf');
            if (NavFilters.ToString() != '')
            {
                AddParam('Nf', NavFilters.ToString());
            }
    }};
    
    UrlGen.prototype.GetNavFilters = function(strNavFilterNamePattern)
    {with(this){
        var NavFilters = new NavFilterCollection(GetParam("Nf"));
            return NavFilters.GetFilters(strNavFilterNamePattern);
    }};
    
    UrlGen.prototype.ToString = function()
    {with(this){
        var _tempParams = new Array();
        for (var i=0; i<Parameters.length; i++)
        {
            if (trim(Parameters[i][0]) != "")
            {
                _tempParams.push(Parameters[i].join('='));
            }
        }
        return _tempParams.join('&');
    }};
    
    this.Init(strQueryString);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  ClickToCall 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function ClickToCall(id, value) //'cc-{@id}', '{agent/phone}')
{
    //window.location.href = "/reno/utility/clicktocall.aspx?r=txt&a=decrypt&v=" + escape(value);
    
    $.get("/reno/utility/clicktocall.aspx?r=txt&a=decrypt&v=" + escape(value), function(data)
    {
		if ($("#cc-"+id+"").length > 0)
		{
			$("#cc-"+id+"").html(data);
		}
		else
		{
			alert(data);
		}
    });
}

var AbsoluteWebRoot = "/";

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Function to fade carousel images on rollover.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var miniResultShow = function(el){

    if(el.firstChild.className=="this")return;
    
    var s = this;

    this.el = $(el);
    this.img = $("img", el);
    this.con = $(".photo", el);
    this.offset = this.img.offset()
    this.width = this.img.width();
    this.height = this.img.height();
    
    this.el.bind('mouseenter.mr', function(){
 
        s.con.css({'z-index':10});
        $("#mini_result_carousel_wrap img").not(this).trigger('mouseleave');
        s.con.siblings().css({color:"#0F2F4F",backgroundColor:"#ddd",textAlign:"center"});
        $(".price,.locality", el).css({border:"1px solid #ddd",borderTop:"none",marginTop:'-1px'})
        $(".price", el).css('borderBottom','none');
        s.con.stop(true,true).css('z-index','10');
        s.img.css('border','1px solid #ddd');
        s.img.stop(true, true).animate({'width':s.width*2,'left':-s.width/2, 'height' : s.height*2, 'top':-s.height, opacity:1} ,200);
        
    });
    
    this.el.bind('mouseleave.mr',function(){
        s.con.stop(true,true).css({'z-index':0});
        s.con.siblings().attr("style","");
        s.img.css({border:'none'});
        s.img.stop(true, true).animate({'width':s.width,'left':0, 'height' : s.height, 'top':0, opacity:.5 },200);
    });
    
    
//    //return if element is current detail
//    if(el.firstChild.className=="this")return;
//    
//    //store vars locally
//    var s = this;
//    this.offset = $(el).offset()
//    this.width = el.clientWidth;
//    this.height = el.clientHeight;
//    this.left = this.offset.left;
//    this.top = this.offset.top;
//    
//    //clone mini detail
//    this.clone = el.cloneNode(true);
//    this.clone.id = "mr-clone";
//    
//    //bind mouseenter with to element
//    $(el).bind('mouseenter.mr', function(){

//        //remover previous clone
//        $("#mr-clone").remove();
//        
//        //append set styles and animate to desired postion
//        $(s.clone).css({top:s.top, left:s.left}).appendTo('body');
//        $('span.photo', s.clone).stop(true,true).fadeTo(250, 1);
//        $('img', s.clone).css({width:s.width*2});
//        $(s.clone).css({'width':s.width*2,'left':s.left-s.width/2, height : s.height*1.75, top:s.top-s.height/2});
//        
//        //bind mouseleave to clone
//        $(s.clone).bind('mouseleave.mr', function(){
//            $('span.photo', s.clone).stop(true,true).fadeTo(250, .5);
//            $(this).attr('style','');
//            $(this).remove();
//        });
//    
//    });

}

function CaourselFadeHovers(rollover_item, faded_item, stopper_class) {
    
    
    $(function() {

        //var $rolloverItem = $(rollover_item); // Set obj.
        //var $fadedItem = $(faded_item);  // Set obj.

        $(rollover_item).each(function(){
            new miniResultShow(this)
        });
        
        
        

        /*$rolloverItem.each(function(index) {

            // See if the object has class "this" on it. If not, animate it.
            
           if (!$(this).children().hasClass(stopper_class)) {

                $(this).hover(function() {

                    $fadedItem.eq(index).animate({"opacity":"1"}, 50);

                },function() {

                    $fadedItem.eq(index).animate({"opacity":".5"}, 50);

                });
            }
        });*/
    });
}

function jTrigger(id, event)
{
    $("#" + id).trigger(event);
}

//TODO: Joey Temp
function swap_flash(obj)
{
    //return;
    $obj = $(obj);

    if ($obj.css('visibility') == 'hidden')
    {
        $obj.css('visibility','visible');
        $('.GL_flashPlayer').css('visibility','visible');
    }
    else
    {
        $obj.css('visibility','hidden');
        $('.GL_flashPlayer').css('visibility','hidden');
     }
}

function Go(url, callback)
{
    window.location.href = url;
    if (callback != undefined)
    {
        callback();
    }
}



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	Exec - executes any parameterless delegate function
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function Exec(callback)
{
	if (callback != undefined && callback != null && $.isFunction(callback))
    {
		callback.apply();
    }
}


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Reno.LoadFirst End
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


