//CONSTANTS
var MapAreaCookieName = 'VeMapArea'
var MeasurementCookieName = 'Measurement'
var BuildingStyleCookieName = 'BuildingStyle'
var MapSearchResultsCookieName = 'MapSearchResults'
var MoreCriteriaCookieName = 'MoreCriteria'
var PreviousPageCookieName = "PreviousPage"

var delimiter = ";";
var elementdelimiter = ":";


function AntiFrameCobrand(allowedURL)
{
    if (top.location != window.location)
    {
        var UrlString = top.location + " "
        if (UrlString.indexOf(allowedURL) != -1)
        { }
        else
        {
            window.location = 'errors/antiframeError.aspx'
        }
    }
}

function validateComp()
{ return true; }

function validateCommunity(obj, message)
{
    if (obj && (!obj.value || obj.value.length < 3))
    {
        alert(message);
        return false;
    }
    return true;
}

function StripForm(frm)
{
    var r = new Array();
    for (var i = 0; i < frm.elements.length; ++i)
    {
        var e = frm.elements[i];
        if (e.getAttribute("xname"))
        {
            e.name = e.getAttribute("xname");
        } else
        {
            r[r.length] = e;
        }
    }
    for (var i = 0; i < r.length; ++i)
    {
        r[i].name = '';
        r[i].value = '';
    }
}
function ClearMLS(txt)
{
    if (!txt) return;
    if (!txt.orgnl) txt.orgnl = txt.value;
    if (txt.value == txt.orgnl) txt.value = '';
}
function LaunchButton(x)
{
    if (x && ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)))
    {
        x.click();
        event.cancelBubble = true;
        return false;
    }
    return true;
}

function mlsnmbrKeyDown(e, err)
{
    var evt = (navigator.appName == 'Netscape') ? e : event;
    if (evt.keyCode == 13)
    {
        if (evt.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
            e.preventBubble();
        } else
        {
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
        mlsnmbrLaunch(err);
    }
}
function mlsnmbrLaunch(err)
{
    var mlsinput = document.getElementById("mlsnmbr");
    if (mlsinput && mlsinput.value)
    {
        top.location = '/Disclaimer.aspx?Mode=5&id=' + mlsinput.value;
        var evt = (navigator.appName == 'Netscape') ? e : event;
        if (evt.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
            e.preventBubble();
        } else
        {
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
        return;
    }
    alert(err);

}



function MLSNumberSearch(event)
{
    var ReferenceNumber = document.getElementById("txtMlsNumber")



    if (event.keyCode == 13 || event.type == 'click')
    {
        if (ReferenceNumber.value != '')
        {
            event.cancelBubble = true;
            if (document.all) // if it is IE; Sasan
            {
                event.returnValue = false; // needed for IE to behave properly,  but it will change the event model if it executes in FireFox
            }
            else if (event && event.preventDefault)
            {
                event.preventDefault(); // DOM style, used for Fire fox

            }
            event.cancel = true;
            ReferenceNumber.click()
            window.location = 'Disclaimer.aspx?Mode=5&id=' + ReferenceNumber.value
            return false; // IE style

        }
    }

}


function SideNavIn(td)
{
    td.className = 'SideNavIn';
}
function SideNavOut(td)
{
    td.className = 'SideNav';
}
function MM_preloadImages()
{ //v3.0
    var d = document; if (d.images)
    {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}
function MM_swapImgRestore()
{ //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_findObj(n, d)
{ //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length)
    {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}
function MM_swapImage()
{ //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

function MM_showHideLayers()
{ //v6.0
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) if ((obj = MM_findObj(args[i])) != null)
    {
        v = args[i + 2];
        if (obj.style) { obj = obj.style; v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v; }
        obj.visibility = v;
    }
}

function MortgageCalculator(SalePrice, CultureCode)
{
    var Height = 600;
    var Width = 550;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=no,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    if (isNaN(SalePrice)) { SalePrice = "" }
    var wn = window.open('Calculators/' + CultureCode + '/calculator.aspx?Price=' + SalePrice, '', params);
    wn.focus();
}
function openSlide()
{
    var Height = 500;
    var Width = 500;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open(document.images.show.src.replace(/medres/ig, 'highres'), 'PhotoFull', params);
    wn.focus();
}
function CurrencyCalculator(SalePrice)
{
    var Height = 600;
    var Width = 600;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=no,scrollbars=no,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('Calculators/Converter.aspx?Price=' + SalePrice, '', params);
    wn.focus();
}


function OpenPrintWindow(PrintPage)
{
    var Height = 500;
    var Width = 795;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,location=no,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open(PrintPage, 'print', params);
    wn.focus();
}

function get_random()
{
    var ranNum = Math.round(Math.random() * 4);
    return ranNum;
}

function SwitchMeasurement(p)
{
    if (!p) p = document;
    for (var i = 0; i < p.childNodes.length; ++i)
    {
        var c = p.childNodes[i];
        if (c.childNodes && c.childNodes.length)
        {
            SwitchMeasurement(c);
        }
        if (c.title && c.getAttribute("isMeasurement"))
        {
            var t = c.title;
            var x = getText(c);
            if (x)
            {
                c.title = x;
                c.innerHTML = t;
            }
        }
    }
}
function getText(node)
{
    if (typeof node.innerText != "undefined")
    {
        return node.innerText;
    }
    return getNodeText(node);
}
function getNodeText(N)
{
    var s = '';
    for (var i = 0, c = N.childNodes; i < c.length; ++i)
    {
        if (c[i].nodeType == 3) s += c[i].nodeValue;
        else if (c[i].nodeType == 1) s += arguments.callee(c[i]);
    }
    return s
}

function LimitSize(textArea, MaxSize)
{
    if (!textArea || !MaxSize || MaxSize == -1) return;
    if (textArea.value.length >= MaxSize)
    {
        textArea.value = textArea.value.substring(0, MaxSize);
    }
}


function EmailToFriend(PropertyID, MLSNumber)
{
    createCookie(PreviousPageCookieName, window.location.href, 0)
    var Height = 500;
    var Width = 460;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=auto,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('EmailFriend.aspx?PropertyID=' + PropertyID + '&MLS=' + MLSNumber, '', params);
    wn.focus();
}

function EmailRealtor(ID, Key, ReferenceNumber, Mode, PropertyID, PropertyAddress)
{
    createCookie(PreviousPageCookieName, window.location.href, 0)
    var Height = 690;
    var Width = 500;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('EmailRealtor.aspx?ID=' + ID + '&Key=' + Key + '&RefererenceNumber=' + ReferenceNumber + '&PropertyID=' + PropertyID + '&Mode=' + Mode + '&Title=EmailRealtor&Type=1', 'EmailRealtor', params);
    wn.focus();
}

function EmailCompany(ID, Key, ReferenceNumber, Mode, PropertyID)
{
    createCookie(PreviousPageCookieName, window.location.href, 0)
    var Height = 690;
    var Width = 500;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('EmailRealtor.aspx?ID=' + ID + '&Key=' + Key + '&RefererenceNumber=' + ReferenceNumber + '&PropertyID=' + PropertyID + '&Mode=' + Mode + '&Title=EmailOffice&Type=3', 'EmailOffice', params);
    wn.focus();
}

function rbPreSelect(CSV, frmObj)
{

    var x = document.all[frmObj]
    if (x.defaultValue == CSV)
    {
        x.checked = true;
    }

}




function PreSelectSubtype(CSV, frmObj)
{
    var x = document.all[frmObj]
    var arr = new String(CSV)
    arr = arr.split(",")

    for (i = 0; i < x.length; i++)
    {
        for (var j = 0; j < arr.length; j++)
        {
            if (arr[j] == x.options[i].value)
            {

                x[i].selected = true

            }
        }
    }

}

function HideAllCategories(p)
{
    if (!p) p = document;
    for (var i = 0; i < p.childNodes.length; ++i)
    {
        var c = p.childNodes[i];
        if (c.childNodes && c.childNodes.length)
        {
            HideAllCategories(c);
        }
        if (c.title == "Category")
        {
            c.style.visibility = "hidden"
            c.style.position = "absolute"
        }
    }
}

function ShowAllCategories(p)
{
    if (!p) p = document;
    for (var i = 0; i < p.childNodes.length; ++i)
    {
        var c = p.childNodes[i];
        if (c.childNodes && c.childNodes.length)
        {
            ShowAllCategories(c);
        }
        if (c.title == "Category")
        {
            c.style.visibility = "visible"
            c.style.position = "static"
        }
    }
}


function ToggleButtons(pnlCategoryName, btnCategoryName)
{
    HideAllCategories()
    pnlCategoryName.style.visibility = "visible"
    pnlCategoryName.style.position = "static"
    ToggleBackgroundColor(btnCategoryName)
}


function ClearAllButtonsColors()
{
    for (var i = 0; i < document.forms[0].length; ++i)
    {
        if (document.forms[0].elements[i].type == "button")
        {
            document.forms[0].elements[i].removeAttribute('style');
            document.forms[0].elements[i].classname = "class='buttons1'"
        }
    }
}

function ToggleBackgroundColor(objElement)
{
    ClearAllButtonsColors();
    objElement.style.background = "#e0e0e0";
}

function removeDuplicateOptions(selectbox)
{

    var i, x, counter;
    for (i = 0; i <= selectbox.options.length - 1; i++)
    {

        counter = 0
        for (x = 0; x <= selectbox.options.length - 1; x++)
        {
            if (selectbox.options[i].text == selectbox.options[x].text)
            {
                counter = counter + 1
                if (counter > 1)
                { selectbox.remove(x) }
            }
        }
    }
}

function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
        while (1)
    {
        curleft += obj.offsetLeft;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}


function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
        while (1)
    {
        curtop += obj.offsetTop;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function rbLoadPage(obj, Url)
{
    window.location = Url + obj.defaultValue
}
function LoadPage(obj, Url)
{

    var myindex = obj.selectedIndex
    var SelValue = obj.options[myindex].value
    window.location = Url + obj.options[myindex].value
}


function XMLBuilder(strValue, xmlTag)
{
    if (strValue.trim() != '')
    {
        return xmlTag + strValue + xmlTag.replace("<", "</")
    }
    return ''
}


function DisplayLoadingIcon(show)
{
    if (show == true)
    {
        document.getElementById('spnLoading').style.visibility = "visible"
    }
    else
    {
        document.getElementById('spnLoading').style.visibility = "hidden"
    }
}


String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function()
{
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function()
{
    return this.replace(/\s+$/, "");
}

function htmlBuilder(html1, value, html2)
{
    if (value != '' && value != undefined)
    {
        return html1 + value + html2
    }
    else
    { return '' }

}


function htmlMultimediaBuilder(html1, value, imageName, html2)
{

    if (value != '' && value != undefined)
    {
        var url = 'redirect.aspx?t=multimedia&r=' + URLEncode(value)
        return html1 + '<a target="_new" href="' + url + '">' + imageName + '</a>' + html2
    }
    else
    { return '' }

}


function htmlBuilderCompound(html1, value1, value2, html2, seperator)
{
    if (value1 == undefined) { value1 = '' }
    if (value2 == undefined) { value2 = '' }

    if (value1 != '' && value2 != '')
    { return html1 + value1 + seperator + value2 + html2 }

    else if (value1 != '' && value2 == '')
    { return html1 + value1 + html2 }

    else if (value2 != '' && value1 == '')
    { return html1 + value2 + html2 }

    else
    { return '' }

}


function returnBool(value)
{
    if (value == 'false')
    {
        return false;
    }
    else if (value == 'true')
    {
        return true;
    }
    return false;
}

function DrivingDirections(PropertyID)
{
    var Height = 850;
    var Width = 775;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('DrivingDirections.aspx?PropertyID=' + PropertyID, '', params);
    wn.focus();
}

function pauseComp(millis)
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while (curDate - date < millis);
}


function GetDropdownValue(obj)
{
    var index = obj.selectedIndex
    return obj.options[index].value
}


function calcLeftPosition(obj)
{
    var curleft = obj.offsetLeft;

    while (obj.offsetParent)
    {
        curleft = curleft + (obj.offsetParent.offsetLeft);
        obj = obj.offsetParent;
    }

    return curleft;
}

function calcTopPosition(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (1)
        {
            curtop += obj.offsetTop;


            if (!obj.offsetParent)
            {
                break;
            }
            obj = obj.offsetParent;
        }

    }
    else if (obj.y)
    {
        curtop += obj.y;
    }
    return curtop;
}



function showPrices(objCheckbox, x)
{

    if (objCheckbox.checked == true)
    {
        x.style.visibility = "visible"
        x.style.position = "static"
    }

    else
    {
        x.style.visibility = "hidden"
        x.style.position = "absolute"

    }

}

function formatCurrency(num)
{
    var num2 = num;
    var num = num.toString().replace(/\$|\,/g, '');

    if (isNaN(num)) { return ('') }
    if (num == 0) { return ('') }

    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3));
    return ('$' + num2 + '.' + cents);
}


function CreatePricingLabel(Price, PerUnit, PerTime)
{
    var NewPrice = parseInt(Price.toString().replace(/\$|\,/g, ''))

    if (isNaN(NewPrice) == true) { return ('') }
    if (NewPrice == 0) { return ('') }
    if (NewPrice != '')
    {
        Price = Price.replace('.00', '')
        //Price = Price.replace(',00','')
        return Price + ' ' + PerUnit + ' ' + PerTime
    }
}


function CreateLabel(Value, Label)
{
    if (isNaN(Value) == true) { return ('') }
    if (Value == 0) { return ('') }
    if (Value != '') { return Value + ' ' + Label }
}

function OpenPropertyPhotos(PropertyId, PhotoNum)
{
    var Height;
    var Width;
    if (PhotoNum <= 2)
    {
        Width = 630;
        Height = 500;
    }
    else if (PhotoNum > 2)
    {
        if (BrowserDetect.browser == 'Explorer')
        {
            Width = 900;
        }
        else if (BrowserDetect.browser == 'Firefox')
        {
            Width = 965;
        }
        else if (BrowserDetect.browser == 'Safari')
        {
            Width = 960;
        }
        Height = 820;
    }

    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);


    var params = 'resizable=yes,location=no,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('PropertyPhotos.aspx?propertyID=' + PropertyId + '&PhotoNum=' + PhotoNum, 'PropertyPhotos', params);
    wn.focus();
}
function createCookie(name, value, days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name)
{
    createCookie(name, "", -1);
}


function SaveMeasurement(value)
{
    createCookie(MeasurementCookieName, value, 0)
}

function BuildStringFromArray(arr, delimiter)
{
    var newString = ''

    for (i = 0; i < arr.length; i++)
    {
        newString = newString + arr[i]
        if (i != arr.length - 1)
        {
            newString = newString + delimiter
        }
    }

    return newString

}


function CreateCSVFromDropdown(frmObj)
{
    var csv = ''

    for (i = 0; i < frmObj.length; i++)
    {
        if (frmObj.options[i].selected == true && frmObj.options[i].value != '')
        { csv = frmObj.options[i].value + ',' + csv }
    }

    if (csv.length != 0)
    { csv = csv.substring(0, csv.length - 1) }
    return csv
}


function ShowHideElement(objName, ToggleCookie)
{

    var x = document.getElementById(objName)

    var MoreCriteria = readCookie(MoreCriteriaCookieName)

    if (MoreCriteria == "visible")
    {
        x.style.visibility = "visible"
        x.style.position = "static"
        if (ToggleCookie == true)
        {
            createCookie(MoreCriteriaCookieName, "hidden", 0)
            x.style.visibility = "hidden"
            x.style.position = "absolute"
        }
    }
    else
    {
        x.style.visibility = "hidden"
        x.style.position = "absolute"
        if (ToggleCookie == true)
        {
            createCookie(MoreCriteriaCookieName, "visible", 0)
            x.style.visibility = "visible"
            x.style.position = "static"
        }
    }
}


function viewHelp(Content)
{
    var Height = 550;
    var Width = 995;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('Help.aspx?f=' + Content, 'OpenHelp', params);
    wn.focus();
}

function URLEncode(parameter)
{
    var encodedInputString = escape(parameter);
    encodedInputString = encodedInputString.replace("+", "%2B");
    encodedInputString = encodedInputString.replace("/", "%2F");
    return encodedInputString;
}

function URLDecode(parameter)
{
    var inputString = unescape(parameter);
    return inputString
}


function isIE()
{
    var browserName = navigator.appName;
    if (browserName == "Microsoft Internet Explorer")
    { return true }
    else
    { return false }
}

function sanitizeForJavascript(data)
{
    var iChars = "&\\\'|\"";
    var newString = ''
    for (var i = 0; i < data.length; i++)
    {
        if (iChars.indexOf(data.charAt(i)) == -1)
        { newString += data.charAt(i) }
        else
        {
            var string = ''
            if (data.charAt(i) == "'")
            {
                newString += string.replace(data.charAt(i), "\'")
            }
            else { newString += ' ' }

        }
    }

    return newString
}


function SetFormFields(qStr)
{
    var qStrSplitResult = qStr.split(delimiter);
    PopulateForm(qStrSplitResult);
}

function resizeMessage()
{
    var ni = document.getElementById('divCaution');
    var n2 = document.getElementById('divCaution2');

    if (BrowserDetect.browser != 'Explorer' && (GetCurrentView() == CurrentView.Thumbnail || GetCurrentView() == CurrentView.Gallery))
    {
        ni.style.width = 750
        n2.style.width = 750

    }
    else if (BrowserDetect.browser != 'Explorer')
    {
        ni.style.width = 305
        n2.style.width = 305
    }

}

function Loading(show)
{
    var obj = document.getElementById("imgLoading")
    var obj2 = document.getElementById("imgLoading2")

    if (GetCurrentView() == CurrentView.Map)
    {
        obj2.style.left = calcLeftPosition(document.getElementById("MAIN")) + 350
        if (show == true) { obj2.style.display = "block" }
        else
        {
            obj2.style.display = "none"
        }
    }
    else
    {
        obj.style.left = calcLeftPosition(document.getElementById("MAIN")) + 525
        if (show == true) { obj.style.display = "block"; }
        else { obj.style.display = "none"; }
    }
}


function ClearCalendar(calendarName, TextBoxName)
{
    document.getElementById(TextBoxName).value = '';
    calendarName.Clear()
}

function displayCalendar(calendarId, e)
{

    if (calendarId.Io == true)
    {
        calendarId.displayCalendar(e);
    }


    calendarId.displayCalendar(e);

}

function ClearMapWorkAround()
{
    map.DeleteAllShapes();
    map.DeleteRoute();
    map.DeleteAllShapeLayers();
}


function getBrowserWindowSize()
{
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    return { width: myWidth, height: myHeight };
}
var browserVersion;
var objIds = new Array();
var numberOfValues = 0;
var readyStateTest1;
var readyStateTest2;

function PrintPropertyCompare()
{
    var Height = 768;
    var Width = 1024;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('PropertyCompare.aspx?prn=yes', 'PropertyCompare', params);
    wn.focus();
    Print(wn);   
       
    
}


function PrintFavouriteViews()
{
    var Height = 768;
    var Width = 1024;
    var Top = (screen.height / 2) - (Height / 2);
    var Left = (screen.width / 2) - (Width / 2);
    var params = 'resizable=yes,scrollbars=yes,height=' + Height + ',width=' + Width + ',top=' + Top + ',left=' + Left;
    var wn = window.open('PropertyFavourites.aspx?prn=yes', 'PropertyFavourite', params);
    wn.focus();
    Print(wn);
    
}
function Print(win) {
    debugger;
    getBrowserVersion();
    if (browserVersion == "mozilla") {
        win.setTimeout('win.print();', 8000);   
    }
    else if (browserVersion == "safari") {
        self.print();
    }
    else {
        win.print();
    }   
}

// ****************** cookie operations functions and APIs



//------------ Cookie General APIs

function getBrowserVersion()
{
    var userAgent = navigator.userAgent;
    userAgent = userAgent.toLowerCase();

    if (document.all)
    {
        browserVersion = "ie";
        return;
    }
    if (userAgent.indexOf('safari') != -1)
    {
        browserVersion = 'safari';
        return;
    }
    else if (userAgent.indexOf('mozilla') != -1)
    {
        browserVersion = 'mozilla';
        return;
    }
}

//resetCookies();

var mapPageFlag = false;
var intervalID;

function cancelCookieOp() // being called on mouseout of the map
{
    mapPageFlag = false;
    startContinCookie();
       //window.status = "Setting flag to false";
}

function runCookieInterval() // this is called from  MouseShapeHandler(), which in turn is called from mouse over on the map
{

    intervalID = setInterval("startCookie()", 100)
}

function startContinCookie() // this is called on mouse move on the map, in the map page
{
    if (mapPageFlag)
    {
        //window.status = 'startContinCookie ' + '*** ' + mapPageFlag
        startCookie();
    }
    else
    {
        clearInterval(intervalID);
    }
    
}

// this function is used on the page load, to set the count and the state of checkboxes for favourite and compare
function startCookie()
{

    //window.status = " StartCookie ---> The flag value *** " + mapPageFlag  ;
    if (mapPageFlag == false)
    {
       //window.status = " Retruning from StartCookie";
        return;
    }

    setSpanCount();
    setCheckboxState();
}

// this function is called when a click event is taken place on the favourite or compare checkbox
function startCookieOperation(obj, name, id)
{
    var cookieName = name;
    var propertyId = id;

    // if no cookieName or Id is passed, get it from the Obj id
    if (!cookieName || cookieName == "")
    {
        cookieName = getStringValueLeft(obj.id, getDelimiter())
    }
    if (!propertyId || propertyId == "")
    {
        propertyId = getStringValueRight(obj.id, getDelimiter());
    }

    // if the checkbox is checked, add to cookie, otherwise remove from the cookie
    if (obj.checked)
    {
        if (maxCompareReached(cookieName, getCookieValueArray(cookieName)) == true)
        {
            obj.checked = false;
            return true;
        }

        buildCookie(cookieName, propertyId)
    }
    else
    {
        removeFromCookie(cookieName, propertyId)
    }
    if (cookieName == "PropertyCompare")
    {
        setIdCount(cookieName); // set the counts in the spans related to compare
    }
    setCheckboxState(cookieName) // set the state of all the check boxes related to the cookie


    //updateWindowStatus(cookieName);
}

function updateWindowStatus(cookieName)
{
    if (cookieName == "PropertyCompare")
    {
        window.status = "PropertyCompare Cookie Values ---> "
        + getCookieValueArray("PropertyCompare") + " ***  The Count ---> " + getCookieValueCount(cookieName);
    }
    else
    {
        window.status = "PropertyFavourite Cookie Values ---> "
        + getCookieValueArray("PropertyFavourite") + " ***  The Count ---> " + getCookieValueCount(cookieName);
    }
}

// these two functions are only kept for compatibility purposes
function compareOperation(propertyId, obj)
{
    var cookieName = "PropertyCompare";
    startCookieOperation(obj, cookieName, propertyId);
}

function favouriteOperation(propertyId, obj)
{
    var cookieName = "PropertyFavourite";
    startCookieOperation(obj, cookieName, propertyId);
}

function getCookieValueCount(cookieName)
{
    // get the cookie value string as an array
    var valueArray = getCookieValueArray(cookieName);
    numberOfValues = 0;

    if (!valueArray)
    {
        return 0;
    }

    for (var i = 0; i < valueArray.length; i++)
    {
        if (valueArray[i] != "")
        {
            ++numberOfValues;
        }
    }
    return numberOfValues;
}

function buildCookie(cookieName, value)
{
    // if the cookie doesn't exit, create it with the value passed
    if (checkCookie(cookieName, value) == null)
    {
        value += getDelimiter();
        createCookieValue(cookieName, value, 70);
    }
    else  //if the cookie exist, add the new value to the other values for the cookie, if not duplicate
    {
        addToCookie(cookieName, value);
    }
}

// Adds a value to the cookie
function addToCookie(cookieName, value)
{
    //if the value is not in the cookie
    if (checkCookie(cookieName, value) == false)
    {
        var cookieValueString = readTargetedCookie(cookieName)
        cookieValueString += value + getDelimiter();
        createCookieValue(cookieName, cookieValueString, 70);
    }
}

function removeFromCookie(cookieName, value)
{
    var newValueString = "";
    var cookieExists = checkCookie(cookieName, value);

    // if the cookie does not exit, or the value in the cookie does not exist
    if (!cookieExists || cookieExists == false)
    {
        return false;
    }
    else
    {
        // get the array of cookie values
        var cookieValueArray = getCookieValueArray(cookieName)

        // find the cookie value and remove it from the string of value
        for (var i = 0; i < cookieValueArray.length; i++)
        {
            if (cookieValueArray[i] == value)
            {
                cookieValueArray[i] = "";

                // if there are no more values left, erase the cookie
                if (i == 0)
                {
                    deleteCookie(cookieName);
                }
                break;
            }
        }
        for (var i = 0; i < cookieValueArray.length; i++)
        {
            // add only if it is not empty string
            if (cookieValueArray[i] != "")
            {
                newValueString += cookieValueArray[i] + getDelimiter();
            }
        }
        if (newValueString && newValueString != "")
        {
            createCookieValue(cookieName, newValueString, 70);
        }
    }
}

function createCookieValue(cookieName, value, days)
{
    var expires;
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else
    {
        expires = "";
    }
    document.cookie = cookieName + "=" + value + expires + "; path=/";
}


// returns the value string of a cookie
function readTargetedCookie(cookieName)
{
    var nameEQ = cookieName + "=";
    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];

        while (c.charAt(0) == ' ') c = c.substring(1, c.length);

        if (c.substring(0, c.indexOf("=")) == cookieName)
        {
            // if the cookie starts at position 0 of the string, then start the substring from that position
            // to the end of the string length
            if (c.indexOf(nameEQ) == 0)
            {
                return c.substring(nameEQ.length, c.length);
            }
        }
    }
    return null;
}

function deleteCookie(name)
{
    createCookieValue(name, "", -1);
}

function resetCookies()
{
    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ')
        {
            c = c.substring(1, c.length);
        }
        var equalLocation = c.indexOf("=");
        var name = c.slice(0, equalLocation);

        deleteCookie(name);
    }
}

function maxCompareReached(cookieName, valueArray, msg)
{
    if (cookieName == "PropertyCompare")
    {
        if (valueArray)
        {
            if (valueArray.length > 5)
            {
                if (!msg)
                {
                    if (ShowTooManyItemsInCompareMessage())
                        return true;
                    else
                        alert("You have reached the maximum allowable limit!")
                }
                else
                {
                    alert(msg);
                }
                return true;
            }
        }
    }
    if (cookieName == "PropertyFavourite")
    {
        if (valueArray)
        {
            if (valueArray.length > 100)
            {
                if (!msg)
                {
                    if (ShowTooManyItemsInFavouriteMessage())
                        return true;
                    else
                        alert("You have reached the maximum allowable limit!")
                }
                else
                {
                    alert(msg);
                }
                return true;
            }
        }
    }

    return false;
}

//-------- General Cookie Operations

function getDelimiter()
{
    return "~"; // started to change delimiter
}

function setIdCount(id)
{
    // get all the spans that share the id
    var spans = findHTMLObjsInArray(getSpanObjs(), id, getDelimiter(), "left");

    getCookieValueCount(id);

    for (var i = 0; i < spans.length; i++)
    {
        spans[i].innerHTML = '(' + numberOfValues + '/5)'
    }
}

// generic function to set the count for compare and favourite counts
//debugger
function setSpanCount()
{
    //if it is on mappage, execute the function continously for flyovers to work.
    setIdCount("PropertyCompare");   
}

// generic function to set the state of the check box for both compare and favourite
function setCheckboxState(id)
{
    // making sure all the objects on the page are loaded, so we can grab and access check boxes
    if (!id)
    {
        //window.status = " SetchecBoxState AFTER the ID check";
        if (mapPageFlag)
        {

            //window.status = " SetchecBoxState AFTER the FLAG check";
            setCheckBoxes("PropertyCompare");
            setCheckBoxes("PropertyFavourite");
        }
        else // if not from mappage
        {
            setCheckBoxes("PropertyCompare");
            setCheckBoxes("PropertyFavourite");

        }
    }
    else // if id is being passed it is from a click event, which means all the objects are on the page and only set certain boxes
    {
        setCheckBoxes(id); //problem with Safari
    }
}

function setCheckBoxes(id)
{
    // find all the check boxes with the id to the left of the delimiter
    var checkBoxes = findHTMLObjsInArray(getCheckBoxObjs(), id, getDelimiter(), "left");

    for (var i = 0; i < checkBoxes.length; i++)
    {
        // check all the objects to see if the HTML object id to the right of delimiter (i.e. cookie value) is in the cookie
        if (checkCookie(id, getStringValueRight(checkBoxes[i].id, getDelimiter())))
        {
            checkBoxes[i].checked = true;
            
        }
        else
        {
            checkBoxes[i].checked = false;
        }
    }
}

function addToCompArray(obj)
{
    favArray[favArray.length] = obj;
}

function removeFromCompArray(obj)
{
    for (var i = 0; i < favArray.length; i++)
    {
        if (obj == favArray[i])
        {
            favArray[i] = null;
        }
    }
}

// Retrieve a given cookie and check for the value in the cookie
function checkCookie(cookieName, value)
{
    //if the cookie exists, then get all the values from the string
    var valueArray = getCookieValueArray(cookieName);

    if (valueArray)
    {
        for (var i = 0; i < valueArray.length; i++)
        {
            var c = valueArray[i];

            if (c.substring(0, c.length) == value)
            {
                return true;
            }
        }

        // the value in the cookie is not found
        return false;
    }
    else
    {
        // the cookie does not exit
        return null;
    }
}

// returns the cookie value string as an array
function getCookieValueArray(cookieName)
{
    var cookieValueString = readTargetedCookie(cookieName);

    // if the cookie is found, create an array from the values
    if (cookieValueString)
    {
        var ca = cookieValueString.split(getDelimiter());

        if (ca)
        {
            for (var i = 0; i < ca.length; i++)
            {
                var c = ca[i];
                while (c.charAt(0) == ' ')
                {
                    c = c.substring(1, c.length);
                }
                ca[i] = c;
            }
        }
        return ca;
    }
    else
    {
        return null;
    }
}


//----------------- General Utility Functions

// gets all the span tags on the page
function getSpanObjs()
{
    var spanObjs = new Array();
    return spanObjs = document.getElementsByTagName("span");
}

// gets all the check boxes on the page
function getCheckBoxObjs()
{
    var inputObjs = new Array();
    inputObjs = document.getElementsByTagName("input");

    var checkObjs = new Array();

    for (var i = 0; i < inputObjs.length; i++)
    {
        if (inputObjs[i].type == "checkbox")
        {
            checkObjs[checkObjs.length] = inputObjs[i];
        }
    }
    return checkObjs;
}

var anotherCounter = 0;

// creates an array of all the found objects (HTML objects) in the objArray that match the searchID that is being searched
// when they are delimited by a delimiter
function findHTMLObjsInArray(objArray, searchId, delimiter, direction)
{
    var foundHTMLObjs = new Array();
    var objId;
    objIds = []; // resetting the array

    for (var i = 0; i < objArray.length; i++)
    {
        if (direction == "left" && objArray[i].id)
        {
            // if the delimiter exits in the id of the object
            if (objArray[i].id.indexOf(delimiter) != -1)
                objId = getStringValueLeft(objArray[i].id, delimiter);
        }
        else if (direction == "right" && objArray[i].id)
        {
            if (objArray[i].id.indexOf(delimiter) != -1)
                objId = getStringValueRight(objArray[i].id, delimiter);
        }

        if (objId == searchId)
        {
            foundHTMLObjs[foundHTMLObjs.length] = objArray[i]; // collect all the HTML objects that meet the search ID
            collectObjsIdsArray(objArray[i].id, delimiter); // collect all the ids for the html objects, to the right of delimiter
        }

        objId = "";
    }

    //alert('1');
    
    anotherCounter++;
    //window.status = "Here is the count from foundHTMLObjs function ---> " + anotherCounter

    //if (testingFlag == true)
     //   alert("from foundHTML");
    
    return foundHTMLObjs;
}



// gets string value to the right of the delimiter
function getStringValueRight(stringValue, delimiter)
{
    var stringRight;

    if (delimiter)
    {
        stringRight = stringValue.slice(stringValue.indexOf(delimiter) + 1, stringValue.length);
    }
    return stringRight;
}

// sets string value to the left of the delimiter
function getStringValueLeft(stringValue, delimiter)
{
    var stringLeft;

    if (delimiter)
    {
        stringLeft = stringValue.slice(0, stringValue.indexOf(delimiter));
    }
    return stringLeft;
}

function collectObjsIdsArray(objId, delimiter)
{
    objIds[objIds.length] = getStringValueRight(objId, delimiter);
}

//*******************************************

function SetComparePropertyLabel()
{
    var i = 0
    var count = numberOfValues;
    var SpanTags = document.getElementsByTagName("span");
    for (i = 0; i <= SpanTags.length - 1; i++)
    {
        if (SpanTags[i].getAttribute("id") == "spnComparePropertiesCount")
        {
            SpanTags[i].innerHTML = '(' + count + '/5)'
        }
    }
}

function MoveModal()
{

    if (document.all['spnBackground'].style)
        document.all['spnBackground'].style.top = document.body.scrollTop;
}
