﻿//the map object
var map = null;
//map start parameters
var mapArgs = null;
//Search Cache object, Relates LocationID -> ShapeID
var searchCache = new Cache();
//Pin Display Cache object, Relates various location IDs to a display strin for the pin
var pinCache = new Cache();
//Display Cache object, Relates a page number to a set of search results that are displayed on the right
var displayCache = new Cache();
//max items to display in right
var itemsOnPage = 6;
//max number of pages for the results retrieved
var maxPages = 0;
//check browser
var brwsr = BrowserDetect.browser;
//search result display id
var ContID = "51902ea2-552b-4d10-858c-061e2a4a017c";

//load map
function Page_Load() {

    // Firefox support - see VE wiki.
    var ffv = 0;
    var ffn = "Firefox/"
    var ffp = navigator.userAgent.indexOf(ffn);
    if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
    // If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
    if (ffv >= 1.5) {
        Msn.Drawing.Graphic.CreateGraphic = function(f, b) { return new Msn.Drawing.SVGGraphic(f, b) }
    }

    var queryParams = window.location.search.substring(1);
    var pubKey = "rcpub";
    var PubPerm = getCookie(pubKey);

    //added to mange the first visit to site with a redirect if it doesn't get to server code
    if (PubPerm == null || typeof (PubPerm) == "undefined" || PubPerm == "") {
        window.location = "/index.aspx";
        return true;
    }
    else {
        var PubTemp;
        var PubSet = readValue("defpublication"); //getCookie(pubKey);
        if (PubSet == null || typeof (PubSet) == "undefined" || PubSet == "") {
            PubTemp = PubPerm;
        }
        else {
            PubTemp = PubSet.value;
        }
    }

    //set the pub
    var mapPub;
    switch (PubTemp.toLowerCase()) {
        case "cgy":
        case "c":
            //divID, center, zoomlevel, style, fixed, mode, scale, showSwitch, display 
            mapArgs = new Renters.MapArgs("myMap", new VELatLong(51.024848, -114.107312), 10, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDistanceUnit.Kilometers, false, "homepage", PubTemp);
            break;
        case "edm":
        case "e":
            mapArgs = new Renters.MapArgs("myMap", new VELatLong(53.546018, -113.495636), 10, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDistanceUnit.Kilometers, false, "homepage", PubTemp);
            break;
        default:
            mapArgs = new Renters.MapArgs("myMap", new VELatLong(43.664152, -79.561539), 9, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDistanceUnit.Kilometers, false, "homepage", PubTemp);
            break;
    }

    //load map parameters - divID, center, zoomlevel, style, fixed, mode, scale, showSwitch, display
    //mapArgs = new Renters.MapArgs("myMap", new VELatLong(43.764152, -79.421539), 9, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDistanceUnit.Kilometers, false, "homepage");
    map = new Renters.Map(Renters.MapService, mapArgs);

    //check if specifc parameters were passed and initiate search if they exist
    var nmVals = queryParams.split("&");
    var nmVal;
    var doSrch = false;
    for (x = 0; x < nmVals.length; x++) {
        if (nmVals[x] !== null && typeof(nmVals[x]) !== "undefined") {
            nmVal = nmVals[x].split("=");
            if (nmVal[0] !== null && typeof (nmVal[0]) !== "undefined" && nmVal[1] !== null && typeof (nmVal[1]) !== "undefined") {
                if (nmVal[0].toString().toLowerCase() == "kyw") {
                    map.varSearchTerm = nmVal[1];
                    doSrch = true;
                } else if (nmVal[0].toString().toLowerCase() == "ac") {
                    map.varAdCode = nmVal[1];
                    doSrch = true;
                } else if (nmVal[0].toString().toLowerCase() == "loc") {
                    map.varLocationCode = nmVal[1];
                    doSrch = true;
                } else if (nmVal[0].toString().toLowerCase() == "rad") {
                    map.varRadius = nmVal[1];
                    doSrch = true;
                }
            }
        }
    }
    if (doSrch) {
        map._GetFirstSearchData();
    }
}

//Clean up all objects
function Page_Unload() {
    if (map !== null) {
        map.Dispose();
        map = null;
    }
}

function processNumber(inputField) {
    var ok = true;
    try {
        var inpVal = parseInt(inputField.value, 10);
        if (isNaN(inpVal)) {
            ok = false;
        }
    } catch (e) {
        ok = false;
    }
    return ok;
}

function IsFloat(inputField) {
    var ok = true;
    try {
        var inpVal = parseFloat(inputField);
        if (isNaN(inpVal)) {
            ok = false;
        }
    } catch (e) {
        ok = false;
    }
    return ok;
}

function fnSetValues() {
    //Set values for popup window with results
    var height = "768px";  //screen.height;
    var width = "1050px";  //screen.width;
    var sFeatures = 'height=' + height + ',width=' + width + ',location=0,scrollbars=1,menubar=0,toolbar=0,status=0,screenX=0,screenY=0,left=0,top=0,fullscreen=0,resizable=yes';
    return sFeatures;
}

function fnOpen(locationid, adcode, locationcode, isad) {
    // important, only location id with either adcode or locationid will be passsed
    // locationid and adcode cannot be passed at same time...will skew results 
    var sFeatures = fnSetValues();
    var sURL = "LocationWindow.aspx?loc=" + locationcode.toString() + "&";
    if (isad === true && adcode != "" && adcode !== null && typeof (adcode) !== "undefined") {
        sURL = sURL + "ac=" + adcode.toString();
    } else {
        sURL = sURL + "lid=" + locationid.toString();
    }
    open_window = window.open(sURL, "LocationWindow", sFeatures);
    open_window.focus();
}

function parseHiddenInput(html) {
    var ShapeIDList = "";
    if (html !== null && typeof (html) !== "undefined" && html != "" && html.indexOf("input ") >= 0) {
        var root = document.createElement("div");
        root.innerHTML = html;
        var inpt = root.getElementsByTagName("input");
        if (inpt !== null && typeof (inpt) !== "undefined" && inpt != "") {
            ShapeIDList = inpt[0].value;
            inpt = null;
        }
        root = null;
    }
	return ShapeIDList;
	}

function parseImgLocID(html) {
    var LocID = "";
    if (html !== null && typeof (html) !== "undefined" && html != "" && html.indexOf("img ") >= 0) {
        var root = document.createElement("div");
        root.innerHTML = html;
        var img = root.getElementsByTagName("img");
        if (img !== null && typeof (img) !== "undefined" && img != "") {
            LocID = img[0].id;
            img = null;
        }
        root = null;
    }
    return LocID;
}

function Highlight(shapeID) {
    // originally had "map" reference but prototyping "overrides" the base methods for the map object
    // so reference map._map
    // ShapeTracker = e.srcElement.name;
    var shape;
    var icon;
    var found = false;
    var locations = "";
    var desc = "";

    if (shapeID != null) {
        shape = map._map.GetShapeByID(shapeID);
        var icon = shape.GetCustomIcon().CustomHTML;
        if (icon !== null && typeof (icon) !== "undefined" && icon != "") {
            icon = icon.replace(".png", "_on.png");
        } else {
            icon = shape.GetCustomIcon();
            if (icon !== null && typeof (icon) !== "undefined" && icon != "") {
                icon = icon.replace(".png", "_on.png");
            }
        }
        shape.SetCustomIcon(icon);
    } 
    return false;
}

function Lowlight(shapeID) {
    if (shapeID != null) {
        shape = map._map.GetShapeByID(shapeID);
        var icon = shape.GetCustomIcon().CustomHTML;
        if (icon !== null && typeof (icon) !== "undefined" && icon != "") {
            icon = icon.replace("_on.png", ".png");
        } else {
            icon = shape.GetCustomIcon();
            if (icon !== null && typeof (icon) !== "undefined" && icon != "") {
                icon = icon.replace("_on.png", ".png");
            }
        }
        shape.SetCustomIcon(icon);
    }
    return false;
}

function fnSearchResultPage(PageNumber) {
    map._SearchResultPage(PageNumber);
}

function doSearch(buttonName, e) {
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

    if (window.event) {
        //IE
        key = window.event.keyCode;
    }
    else {
        //firefox
        key = e.which;
    }

    if (key == 13) {
        //Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn !== null) {
            //If we find the button click it
            btn.click();
            event.keyCode = 0;
        }
    }
}

function fnReset(doLoc) {
    //SearchTerm, LocationCode, PropertyType, Amenities, CloseBy, Region, Bedrooms, Bathrooms, MaxPrice, MinPrice, Utilities, Features
    var docSearchTerm = document.getElementById("location");
    var docLocationCode = document.getElementById("locationcode");
    var docPropertyType = document.getElementById("propertytype");
    var docAmenities = document.getElementsByName("amenities");
    var docCloseBy = document.getElementsByName("closeby");
    //var docRegion = document.getElementById("region");
    var docRegion = readValue("ctlDDLRegion");
    var docBedrooms = document.getElementById("bedroom");
    var docBathrooms = document.getElementById("baths");
    var docMaxPrice = document.getElementById("pricemax");
    var docMinPrice = document.getElementById("pricemin");
    var docUtilities = document.getElementsByName("utilities");
    var docFeatures = document.getElementsByName("features");
    //var docProduct = document.getElementsByName("product");
    //var docPublication = document.getElementsByName("publication");

    docSearchTerm.value = introText;
    if (doLoc) { docLocationCode.value = "" };
    docPropertyType.selectedIndex = 0;
    for (var i = 0; i < docAmenities.length; i++) {
        if (docAmenities[i].checked) {
            docAmenities[i].checked = false;
        }
    }
    for (var j = 0; j < docCloseBy.length; j++) {
        if (docCloseBy[j].checked) {
            docCloseBy[j].checked = false;
        }
    }
    docRegion.selectedIndex = 0;
    docBedrooms.selectedIndex = 0;
    docBathrooms.selectedIndex = 0;
    docMaxPrice.value = "";
    docMinPrice.value = "";
    for (var k = 0; k < docUtilities.length; k++) {
        if (docUtilities[k].checked) {
            docUtilities[k].checked = false;
        }
    }
    for (var l = 0; l < docFeatures.length; l++) {
        if (docFeatures[l].checked) {
            docFeatures[l].checked = false;
        }
    }
}

//function fnZoomOutSearch() {
//    map._map.LoadMap(mapArgs.Center, mapArgs.Zoomlevel, mapArgs.Style, mapArgs.Fixed, mapArgs.Mode, mapArgs.ShowSwitch);
//    fnSearch(true);
//}

//function fnLocCodeSearch() {
//    //LocationCode
//    var docLocationCode = document.getElementById("locationcode");

//    //clear map search variables for map prototype function variables
//    map._ClearSearchVars();

//    //set variables from page settings
//    if (docLocationCode.value != "") {
//        map.varLocationCode = docLocationCode.value;
//        map._GetFirstSearchData();
//    }
//}

function fnSearch(LocCodeSearch) {
    //SearchTerm, LocationCode, PropertyType, Amenities, CloseBy, Region, Bedrooms, Bathrooms, MaxPrice, MinPrice, Utilities, Features
    var docSearchTerm = document.getElementById("location");
    var docLocationCode = document.getElementById("locationcode");
    var docPropertyType = document.getElementById("propertytype");
    var docAmenities = document.getElementsByName("amenities");
    var docCloseBy = document.getElementsByName("closeby");
    //var docRegion = document.getElementById("ctlDDLRegion");
    var docRegion = readValue("ctlDDLRegion");
    var docBedrooms = document.getElementById("bedroom");
    var docBathrooms = document.getElementById("baths");
    var docMaxPrice = document.getElementById("pricemax");
    var docMinPrice = document.getElementById("pricemin");
    var docUtilities = document.getElementsByName("utilities");
    var docFeatures = document.getElementsByName("features");
    var docProduct = document.getElementById("defproduct");
    //var docPublication = document.getElementById("defpublication");
    var docPublication = readValue("defpublication");

    var _searchTerm = "";

    //clear map search variables for map prototype function variables
    map._ClearSearchVars();
    
    //set variables from page settings
    if (LocCodeSearch && docLocationCode.value != "") {
        map.varLocationCode = docLocationCode.value;
    } else {
        if (docSearchTerm.value != introText) {
            _searchTerm = docSearchTerm.value;
            map.varSearchTerm = docSearchTerm.value;
        }
//        map.varLocationCode = docLocationCode.value;
        if (docPropertyType.selectedIndex >= 0) { map.varPropertyType = docPropertyType.options[docPropertyType.selectedIndex].value; }

        var _amenities = "";
        for (var i = 0; i < docAmenities.length; i++) {
            if (docAmenities[i].checked) {
                _amenities += docAmenities[i].value + ",";
            }
        }
        if (_amenities.length > 0) { map.varAmenities = _amenities.substr(0, _amenities.length - 1); }

        var _closeBy = "";
        for (var j = 0; j < docCloseBy.length; j++) {
            if (docCloseBy[j].checked) {
                _closeBy += docCloseBy[j].value + ",";
            }
        }
        if (_closeBy.length > 0) { map.varCloseBy = _closeBy.substr(0, _closeBy.length - 1); }

        if (docRegion.selectedIndex >= 0) { map.varRegion = docRegion.options[docRegion.selectedIndex].value; }
        if (docBedrooms.selectedIndex >= 0) { map.varBedrooms = docBedrooms.options[docBedrooms.selectedIndex].value; }
        if (docBathrooms.selectedIndex >= 0) { map.varBathrooms = docBathrooms.options[docBathrooms.selectedIndex].value; }
        var _maxprice = -1;
        if (processNumber(docMaxPrice) && docMaxPrice.value != "") {
            _maxprice = docMaxPrice.value;
            map.varMaxPrice = docMaxPrice.value;
        }
        var _minprice = -1;
        if (processNumber(docMinPrice) && docMinPrice.value != "") {
            _minprice = docMinPrice.value;
            map.varMinPrice = docMinPrice.value;
        }

        var _utilities = "";
        for (var k = 0; k < docUtilities.length; k++) {
            if (docUtilities[k].checked) {
                _utilities += docUtilities[k].value + ",";
            }
        }
        if (_utilities.length > 0) { map.varUtilities = _utilities.substr(0, _utilities.length - 1); }

        var _features = "";
        for (var l = 0; l < docFeatures.length; l++) {
            if (docFeatures[l].checked) {
                _features += docFeatures[l].value + ",";
            }
        }
        if (_features.length > 0) { map.varFeatures = _features.substr(0, _features.length - 1); }
        if (docProduct.value != "") { map.varProduct = docProduct.value; }
        if (docPublication.value != "") {
            var _pub;
            switch (docPublication.value.toLowerCase()) {
                case "c":
                case "cgy":
                    _pub = "calgary";
                    break;
                case "E":
                case "edm":
                    _pub = "edmonton";
                    break;
                default:
                    _pub = "toronto";
                    break;
            }
            map.varPublication = _pub; 
        }
    }

    if (docRegion.selectedIndex >= 0 || (LocCodeSearch && docLocationCode.value != "")) {
        map._GetFirstSearchData();
    } else {
        map._GetSearchData();
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

//returns the container prefix as all controls have that on their ids
function getCrtlPrefix()
{
   var prefix;
   var objCrtlPrefix = document.getElementById("ctrlPrefix");

   if (objCrtlPrefix)
       prefix = objCrtlPrefix.value;

   return prefix;
}
//returns the control with the prefix appended to the original control name
function readValue(ctrlName)
{
    var prefix = getCrtlPrefix();
    var objCrtl = document.getElementById(prefix + ctrlName);

    if (objCrtl) {
        //alert("Prefix: " + prefix + " - value: " + objCrtl.value);
        return objCrtl;
    } else {
        //alert("not found!");
        return null;
    }}

//set page event handlers
if (window.attachEvent) {
    window.attachEvent("onload", Page_Load);
    window.attachEvent("onunload", Page_Unload);
} else {
    window.addEventListener("DOMContentLoaded", Page_Load, false);
    window.addEventListener("unload", Page_Unload, false);
}

if (typeof (Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }

