var savedListings;
function setGuid(){
    var cookieValues = new RegExp("visitor=([^;]+)").exec(document.cookie);
    var guid;
    if (cookieValues)
        guid = cookieValues[1];
    else{
        var expireDate = new Date();
        expireDate.setTime(expireDate.getTime()-(24*60*60*1000));
        document.cookie = "visitor=" + guid + ";expires=" + expireDate.toUTCString() + ";path=/;";    
        guid = newGuid();
        var date = new Date();
        date.setTime(date.getTime()+(365*24*60*60*1000));
        document.cookie = "visitor=" + guid + ";expires=" + date.toUTCString() + ";path=/;";
    }
    return guid;
}
var __v = setGuid();
function newGuid(){
    var g = "";
    for(var i = 0; i < 32; i++)
        g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 7 || i == 11 || i == 15 || i == 19 ? "-" : "");
    return g;
}
function geoScript(){
    var hasGid = /UserGeoAreaID=([^;]+)/.exec(document.cookie);
    var hasPGid = /UserParentGeoAreaID=([^;]+)/.exec(document.cookie);
    var hasCC = /Country_Code=([^;]+)/.exec(document.cookie);
    var hasSC = /Region_Code=([^;]+)/.exec(document.cookie);
    if(!(hasGid && hasPGid)){
        var expireDate = new Date();
        expireDate.setTime(expireDate.getTime()-(24*60*60*1000));   
        document.cookie = "UserGeoAreaID=35611;expires=" + expireDate.toUTCString() + ";path=/;domain=" + window.location.host;
        document.cookie = "UserParentGeoAreaID=226849;expires=" + expireDate.toUTCString() + ";path=/;domain=" + window.location.host;
        document.cookie = "Country_Code=US;expires=" + expireDate.toUTCString() + ";path=/;domain=" + window.location.host;
        document.cookie = "Region_Code=CA;expires=" + expireDate.toUTCString() + ";path=/;domain=" + window.location.host;       
        var date = new Date();
        date.setTime(date.getTime()+(365*24*60*60*1000)); 
        document.cookie = "UserGeoAreaID=35611;expires=" + date.toUTCString() + ";path=/;";
        document.cookie = "UserParentGeoAreaID=226849;expires=" + date.toUTCString() + ";path=/;";
        document.cookie = "Country_Code=US;expires=" + date.toUTCString() + ";path=/;";
        document.cookie = "Region_Code=CA;expires=" + date.toUTCString() + ";path=/;";
        return '<script type="text/javascript" src="/Origin/GeoLookup.ashx?visitor='+__v+'"></script>';
    } else if (!(hasCC && hasSC)) {
        var __g = hasGid[1];
        return '<script type="text/javascript" src="/Origin/GeoLookup.ashx?visitor='+__v+'&GeoAreaID='+__g+'"></script>';
    }
    return '';
}
document.write(geoScript());
function setSearchAction(form) {
	if(form.cx.options[form.cx.selectedIndex].value == 'map'){
		form.action = "/Listing/MapSearch.aspx";
}
}
function insertBannersWithDivs(name, itemCount, srcArray) {
    var summary = document.getElementById(name);
    var grid = summary.getElementsByTagName('table')[0];
    var numCols = grid.rows[2].cells.length;
    var i = 12;
    if (i > itemCount + 2) i = itemCount + 2;
    var row, cell;
    var srcIndex = 0;
    for (; i <= itemCount + 2; i += 16) {
        row = grid.insertRow(i);
        row.className = 'Item';
        cell = row.insertCell(0);
        cell.colSpan = numCols;
        cell.className = 'BannerCell';
        var div = document.getElementById(srcArray[srcIndex]);
        cell.appendChild(div);
        div.style.display = "block";
        srcIndex++;
    }
}
/**CookieUtils Start**/
function getCookie(name) {
    var cookieValues = new RegExp(name + "=([^;]+)").exec(document.cookie);
    if (cookieValues) {
        // unescape our values
        var value = cookieValues[1].replace(/%0a|%0d|%25|%3b/ig, function(str, offset, s) { return unescape(str); });
        if (value != unescape(cookieValues[1])) {
            return cookieValues[1]; //wasn't us that escaped it
        }
        return value;
    }
    return null;
}
function setCookie(name, value, expires, path, domain, secure) {
    value = value.replace(/[\n\r%;]+/g, function(str, offset, s) { return escape(str); }); //escape only special characters
    document.cookie = name + "=" + value
       + ((expires) ? ";expires=" + expires.toGMTString() : "")
       + ((path) ? ";path=" + path : "")
       + ((domain) ? ";domain=" + domain : "")
       + ((secure) ? ";secure" : "");
}
function deleteCookie(name, path, domain) {
    if (getCookie(name))
        setCookie(name, '', new Date(0, 0, 0), path, domain);
}
/**CookieUtils End**/
function formatCreatedDate(m, d) {
    var arMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    return (arMonths[m - 1] + " " + d);
}
function makeDate(y, m, d, h, mm, s) {
    dt = new Date();
    dt.setYear(y);
    dt.setMonth(m - 1); //setMonth is 0-based not 1-based
    dt.setDate(d);
    dt.setHours(h);
    dt.setMinutes(mm);
    dt.setSeconds(s);
    return dt;
}
/* DateFormat.js Formats a Date object into a human-readable string
* Copyright (C) 2001 David A. Lindquist (http://www.gazingus.org)*/
Date.MONTHS = [
  'January', 'February', 'March', 'April', 'May', 'June', 'July',
  'August', 'September', 'October', 'November', 'December'
];
Date.DAYS = [
  'Sunday', 'Monday', 'Tuesday', 'Wednesday',
  'Thursday', 'Friday', 'Saturday'
];
Date.SUFFIXES = [
  'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th',
  'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th',
  'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th',
  'st'
];
Date.prototype.format = function(mask) {
    var formatted = (mask != null) ? mask : 'DD-MMM-YY';
    var letters = 'DMYHdhmst'.split('');
    var temp = new Array();
    var count = 0;
    var regexA;
    var regexB = /\[(\d+)\]/;
    var day = this.getDay();
    var date = this.getDate();
    var month = this.getMonth();
    var year = this.getFullYear().toString();
    var hours = this.getHours();
    var minutes = this.getMinutes();
    var seconds = this.getSeconds();
    var formats = new Object();
    formats['D'] = date;
    formats['d'] = date + Date.SUFFIXES[date - 1];
    formats['DD'] = (date < 10) ? '0' + date : date;
    formats['DDD'] = Date.DAYS[day].substring(0, 3);
    formats['DDDD'] = Date.DAYS[day];
    formats['M'] = month + 1;
    formats['MM'] = (month + 1 < 10) ? '0' + (month + 1) : month + 1;
    formats['MMM'] = Date.MONTHS[month].substring(0, 3);
    formats['MMMM'] = Date.MONTHS[month];
    formats['Y'] = (year.charAt(2) == '0') ? year.charAt(3) : year.substring(2, 4);
    formats['YY'] = year.substring(2, 4);
    formats['YYYY'] = year;
    formats['H'] = hours;
    formats['HH'] = (hours < 10) ? '0' + hours : hours;
    formats['h'] = (hours > 12 || hours == 0) ? Math.abs(hours - 12) : hours;
    formats['hh'] = (formats['h'] < 10) ? '0' + formats['h'] : formats['h'];
    formats['m'] = minutes;
    formats['mm'] = (minutes < 10) ? '0' + minutes : minutes;
    formats['s'] = seconds;
    formats['ss'] = (seconds < 10) ? '0' + seconds : seconds;
    formats['t'] = (hours < 12) ? 'A' : 'P';
    formats['tt'] = (hours < 12) ? 'AM' : 'PM';
    for (var i = 0; i < letters.length; i++) {
        regexA = new RegExp('(' + letters[i] + '+)');
        while (regexA.test(formatted)) {
            temp[count] = RegExp.$1;
            formatted = formatted.replace(RegExp.$1, '[' + count + ']');
            count++;
        }
    }
    while (regexB.test(formatted)) {
        formatted = formatted.replace(regexB, formats[temp[RegExp.$1]]);
    }
    return formatted;
}
/*end DateFormat*/
/*LinkUtils start*/
function attribute(name, value) {
    this.name = name;
    this.value = value;
}
var FeaturedLink = new attribute("Featured", "T");
var SmartAaLink = new attribute("Aa", getCookie('visitor'));
/*
Iterate through the links on the page and apply appropriate attributes
based on the link class name(s)
*/
function AddLinkAttributes(attributes, startElement) {
    var links;
    if (startElement) {
        links = startElement.getElementsByTagName('a');
    } else {
        links = document.getElementsByTagName('a');
    }
    for (var i = 0; i < links.length; i++) {
        for (var j = 0; j < attributes.length; j++) {
            if ((links[i].className.indexOf(attributes[j].name) >= 0)) {
                Append(links[i], attributes[j]);
            }
        }
    }
}
function Append(link, attribute) {
    var l = link.innerHTML;
    if ((link.href).indexOf(attribute.name + "=" + attribute.value) == -1)
        link.href += Prefix(link.href) + attribute.name + "=" + attribute.value;
    link.innerHTML = l;
}
function Prefix(str) {
    var prefix = "?";
    if (str.indexOf("?") >= 0) prefix = "&";
    return prefix;
}
function showHide(show, hide, display) {
    document.getElementById(show).style.display = display;
    document.getElementById(hide).style.display = "none";
}
/*LinkUtils end*/
/*Default.js start*/
function loadFeatured(moo, src, dest) {
    if (!src) { src = 'featuredSource' };
    if (!dest) { dest = 'featuredDest' };
    var iFrame = window.frames["featuredFrame"];
    var dataSource = iFrame.document.getElementById(src);
    var dataDest = document.getElementById(dest);
    if (dataDest && dataSource) {
        dataDest.innerHTML = dataSource.innerHTML;
        if (moo) {
            if (dataDest.firstChild.firstChild.firstChild) {
                dataDest.style.display = 'block';
                if (typeof fx != 'undefined' && fx) {
                    dataDest.style.height = '15px';
                    var divOpen = new fx.Height(dataDest, { duration: 250 });
                    divOpen.custom(dataDest.offsetHeight, dataDest.firstChild.offsetHeight);
                    dataDest.style.paddingBottom = '10px';
                }
            }
        }
    }
}
function showFeatured(prefix, spots, vl, vlp) {
    if (!vl) vl = getCookie('UserGeoAreaID');
    if (!vlp) vlp = getCookie('UserParentGeoAreaID');
    var vls = "";
    if (vl) vls += "&GeoAreaID=" + vl;
    if (vlp) vls += "&ParentGeoAreaID=" + vlp;
    if (spots && spots != '') vls += "&Spots=" + spots;
    var f = doIFrame(prefix + '?' + vls, "featuredFrame");
    var d = document.getElementById('featuredFrameDiv');
    if (d) {
        d.appendChild(f);
    }
}
function doIFrame(source, fName) {
    var f = document.createElement('iframe');
    f.frameBorder = 0;
    f.scrolling = 'no';
    f.name = fName;
    f.id = fName;
    f.style.position = "absolute";
    f.style.visibility = "hidden";
    f.style.width = "0";
    f.style.height = "0";
    f.src = source;
    return f;
}
function switchMaps() {
    var country = getCookie('Country_Code');
    var region = getCookie('Region_Code');
    if ((country == 'US' || country == 'CA') && region != null) {
        var map;
        var src;
        if (country == 'US') {
            if (region == 'PR' || region == 'VI')
                region = 'US';

            map = document.getElementById('usMap');
            src = 'US/' + region + '.gif';
        }
        else if (country == 'CA') {
            map = document.getElementById('caMap');
            src = 'CA/' + region + '.gif';
        }
        if (map)
            map.src = src;
    }
}
/*Default.js end*/
/*CurrencyUtils start*/
var currency = new Currency();
function getCurrency() {
    return currency;
}
function Currency() {
    var xe = new Array();
    xe['USD'] = [1, '$'];
    var currencyID = getCookie('CurrencyID');
    var isDefault = false;
    var template = new Array();
    template[''] = '{Symbol}{Value}';
    var rate = 1;
    var symbol = '$';
    this.init = function(defaultID) {
        if (currencyID == null) {
            //at least set default for CA and US
            if (defaultID && (defaultID == 'CA' || defaultID == 'US'))
                defaultID += 'D';
            if (defaultID && defaultID != '' && xe[defaultID])
                currencyID = defaultID;
            else
                currencyID = 'USD'; // reste to USD
            isDefault = true;

        }
        rate = xe[currencyID][0];
        symbol = xe[currencyID][1];
    };
    this.setCurrencyID = function(value) {
        setCookie('CurrencyID', value);
        currencyID = value;
        isDefault = false;
        rate = xe[value][0];
        symbol = xe[value][1];
    };
    this.getCurrencyID = function() {
        return currencyID;
    };
    this.add = function(id, rate, symbol) {
        xe[id] = [rate, symbol];
    };
    this.addTemplate = function(id, value) {
        template[id] = value;
    };
    this.format = function(templateid, usdValue, originalValue, originalID) {
        var templateValues = new Array();
        templateValues["{ID}"] = currencyID;
        templateValues["{Symbol}"] = symbol;
        if (usdValue != null && originalID != currencyID)
            templateValues["{Value}"] = Math.round(usdValue / rate).toLocaleString().replace('.00', '');
        else if (originalValue != null && originalID == currencyID)
            templateValues["{Value}"] = Math.round(originalValue).toLocaleString().replace('.00', '');
        else
            templateValues["{Value}"] = '';
        if (usdValue != null)
            templateValues["{USDValue}"] = usdValue.toLocaleString();
        else if (originalValue != null && originalID != null)
            templateValues["{USDValue}"] = originalValue * xe[originalID][0];
        else
            templateValues["{USDValue}"] = '';
        if (originalID != null) {
            templateValues["{OrigID}"] = originalID;
            templateValues["{OrigSymbol}"] = xe[originalID][1];
        }
        else {
            templateValues["{OrigID}"] = '';
            templateValues["{OrigSymbol}"] = '';
        }
        if (originalValue != null)
            templateValues["{OrigValue}"] = Math.round(originalValue).toLocaleString().replace('.00', '');
        else
            templateValues["{OrigValue}"] = '';
        return template[templateid].replace(/{[^}]+}/g, function(str, offset, s) { var rep = templateValues[str]; return rep == null ? str : rep; });
    };
    this.write = function(templateid, usdValue, originalValue, originalID) {
        document.write(this.format(templateid, usdValue, originalValue, originalID));
    };
}
/*CurrencyUtils end*/
/*Moved from Search.js start*/
function ValidatePrice(form) {
    var isValid = false;
    var errorMsg = document.getElementById('priceError');
    if (form.MaxPrice.value == '' || form.MinPrice.value == '' || parseInt(form.MinPrice.value) < parseInt(form.MaxPrice.value)) {
        isValid = true;
        errorMsg.style.display = 'none';
    }
    else {
        errorMsg.style.display = 'inline';
    }
    return isValid;
}
function ValidateNeighborhood(form, currentState) {
    var isValid = false;
    var errorMsg = document.getElementById('hoodError');
    //if there is no currentNode or currentState, then this is a non columnview search
    if (typeof (currentNode) == 'undefined' || !currentNode || currentNode.selectable || currentState) {
        isValid = true;
        if (errorMsg) errorMsg.style.display = 'none';
    }
    else {
        if (errorMsg) errorMsg.style.display = 'inline';
    }
    return isValid;
}
function ValidateTypeId(form) {
    var isValid = false;
    var errorMsg = document.getElementById('typeIdError');
    if (form.TypeID) {
        for (i = 0; i < form.TypeID.length; i++) {
            if (form.TypeID[i].checked) {
                isValid = true;
                if (errorMsg) errorMsg.style.display = 'none';
                break;
            }
        }
    }
    else {
        isValid = true;
    }
    if (!isValid) {
        if (errorMsg) errorMsg.style.display = 'inline';
    }
    return isValid;
}
function ValidateStatus(form) {
    var isValid = false;
    var errorMsg = document.getElementById('statusError');
    for (i = 0; i < form.Status.length; i++) {
        if (form.Status[i].checked) {
            isValid = true;
            if (errorMsg) errorMsg.style.display = 'none';
            break;
        }
    }
    if (!isValid)
        if (errorMsg) errorMsg.style.display = 'inline';
    return isValid;
}
function ValidateSearchForm(form) {
    var isValid = (ValidatePrice(form) && ValidateNeighborhood(form) && ValidateTypeId(form) && ValidateStatus(form));
    if (!isValid) alert('Please complete missing or incorrect information before submitting your search');
    return isValid;
}
function Search(geoAreaId, xGeoAreaId, minPrice, maxPrice, beds, baths, typeID, status) {
    this.GeoAreaID = geoAreaId;
    this.XGeoAreaID = xGeoAreaId;
    this.MinPrice = minPrice;
    this.MaxPrice = maxPrice;
    this.MinBedroomCount = beds;
    this.MinBathroomCount = baths;
    this.TypeID = typeID;
    this.Status = status;
    this.ToString = function() {
        return 'g=' + this.GeoAreaID + '&xg=' + this.XGeoAreaID + '&minP=' + this.MinPrice + '&maxP=' + this.MaxPrice + '&bd=' + this.MinBedroomCount + '&bt=' + this.MinBathroomCount + '&t=' + this.TypeID + '&s=' + this.Status;
    };
}
/*Moved from Search.js end*/
/*OpenHouse start*/
var openHouses = new Array();
var showDate = new Date();
showDate.setDate(showDate.getDate() - 1);
function openHouse(id, start, end) {
    this.id = id;
    this.start = start;
    this.end = end;
}
function addOpenHouse(id, start, end) {
    o = new openHouse(id, start, end);
    openHouses.push(o);
}
function showOpenHouseDetails() {
    var valid = false;
    var str = "Open House:<ul>";
    for (var i = 0; i <= openHouses.length; i++) {
        if (i < openHouses.length) {
            if (openHouses[i].start > showDate) {
                valid = true;
                str += "<li class=\"OpenHouseTime\">";
                str += openHouses[i].start.format('DDDD, MMMM D, YYYY h:mm tt');
                str += " to ";
                if (openHouses[i].start.getDate() != openHouses[i].end.getDate())
                    str += openHouses[i].end.format('DDDD, MMMM D, YYYY h:mm tt');
                else
                    str += openHouses[i].end.format('h:mm tt');
                str += "</li>";
            }
        }
    }
    if (valid) {
        var node = document.getElementById('openHouses' + openHouses[0].id);
        str += "</li>";
        node.innerHTML = str;
        node.style.display = "block";
    }
}
function showOpenHouseLinks() {
    var firstInGroup = true;
    var valid = false;
    var curID = 0;
    var str = "";
    for (var i = 0; i <= openHouses.length; i++) {
        if ((i == openHouses.length || (curID != 0 && curID != openHouses[i].id)) && valid) {
            var node = document.getElementById('openHouses' + curID);
            node.title = str;
            node.style.display = "block";
            str = "";
            firstInGroup = true;
            valid = false;
        }
        if (i < openHouses.length && !(valid)) {
            curID = openHouses[i].id;
            if (openHouses[i].start > showDate) {
                valid = true;
                str += "Open House: "
                str += openHouses[i].start.format('DDDD, MMMM D, YYYY h:mm tt');
                str += " to ";
                if (openHouses[i].start.getDate() != openHouses[i].end.getDate())
                    str += openHouses[i].end.format('DDDD, MMMM D, YYYY h:mm tt');
                else
                    str += openHouses[i].end.format('h:mm tt');
            }
        }
    }
}
/*OpenHouse end*/
/*ListingSaver Start*/
function ListingSaver() {
    var SavedListings = new Array();
    this.Load = function(cookie) {
        var savedListings = cookie;
        if (!savedListings || savedListings == '')
            return;
        if (savedListings.indexOf('&n=') != -1) savedListings = this.reformat(savedListings);
        SavedListings = savedListings.split('|');
    };
    this.reformat = function(cookie) {
        var oldItems = cookie.split('|');
        var newItems = new Array();
        for (i = 0; i < oldItems.length; i++) {
            newItems[i] = oldItems[i].split('&')[0].split('=')[1];
        }
        return newItems.join('|');
    }
    this.Add = function(listingId) {
        for (var i = 0; i < SavedListings.length; i++) {
            if (SavedListings[i] == listingId) {
                return;
            }
        }
        SavedListings.push(listingId);
        this.Save();
    };
    this.Delete = function(listingId) {

        for (var i = 0; i < SavedListings.length; i++) {
            if (SavedListings[i] == listingId) {
                SavedListings.splice(i, 1);
                break;
            }
        }
        this.Save();
    };
    this.Save = function() {
        setCookie('SavedListings', SavedListings.join('|'), new Date(9999, 12, 31), '/');
    };
    this.ToQueryString = function() {
        var n = '';
        for (var i = 0; i < SavedListings.length; i++) {
            n += '&ListingID=' + SavedListings[i];
        }
        return n;
    }
}
/*ListingSaver End*/
