
var REAchieveJsCheck = "";
function AddDays(dateStr, numDays) {
    var returnDate = new Date(dateStr);
    returnDate.setTime(returnDate.getTime() + 60000 * 60 * 24 * numDays);
    return returnDate;
}

function GetFourDigitYearDate(dateStr, format) {
    if (format == null) { format = Date.CultureInfo.dateElementOrder; }
    format = format.toUpperCase();
    if (format.length != 3) { format = Date.CultureInfo.dateElementOrder.toUpperCase(); }
    if ((format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1)) { format = Date.CultureInfo.dateElementOrder.toUpperCase(); }
    
    if (format.substring(0, 1) == "Y") { // If the year is first
        var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
        var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
    }
    else if (format.substring(1, 2) == "Y") { // If the year is second
        var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
        var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
    }
    else { // The year must be third
        var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
        var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
    }
    // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
    if ((reg1.test(dateStr) == false) && (reg2.test(dateStr) == false)) { return false; }

    var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
    // Check to see if the 3 parts end up making a valid date
    if (format.substring(0, 1) == "M") { var mm = parts[0]; }
    else if (format.substring(1, 2) == "M") { var mm = parts[1]; }
    else { var mm = parts[2]; }

    if (format.substring(0, 1) == "D") { var dd = parts[0]; }
    else if (format.substring(1, 2) == "D") { var dd = parts[1]; }
    else { var dd = parts[2]; }

    if (format.substring(0, 1) == "Y") { var yy = parts[0]; }
    else if (format.substring(1, 2) == "Y") { var yy = parts[1]; }
    else { var yy = parts[2]; }

    if (yy.length <= 2) {
        yy = (parseFloat(yy) + 2000).toString();
    }

    return Date.parseExact(mm + "/" + dd + "/" + yy, "M/d/yyyy").toString(Date.CultureInfo.formatPatterns.shortDate);
}

//IsValidDate is removed from here as this method is already present in utilities.js.

function stripCRFromString(myString) {
    var goodString = "";
    var nr = "\n\r";

    for (var i = 0; i < myString.length; i++) {
        if (nr.indexOf(myString.charAt(i)) == -1)
            goodString += myString.charAt(i);
        else
            goodString += "";
    }
    return goodString;
}

function FixDateYear(strDate, fieldToFix, isFixedWidth) {
    var month, dayOfMonth;
    date = new Date(strDate);
    if (date.getFullYear() < 2000) {
        date.setYear(date.getFullYear() + 100);
        month = date.getMonth() + 1;
        dayOfMonth = date.getDate();

        if (isFixedWidth) {
            month = (month < 10) ? "0" + month : "" + month;
            dayOfMonth = (dayOfMonth < 10) ? "0" + dayOfMonth : "" + dayOfMonth;
        }

        strDate = month + "/" + dayOfMonth + "/" + date.getFullYear();
        if (fieldToFix) {
            fieldToFix.value = strDate;
        }
    }
    return date;
}

function StartsWith(testOn, testWith) {
    var reFilter = new RegExp();
    reFilter.compile("^" + testWith);
    return (reFilter.test(testOn));
}

function IsValidURL(strURL) {
    var reFilter = new RegExp();
    reFilter.compile("^http://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
    return (reFilter.test(strURL));
}

function IsValidEmailAddress(strAddress) {
    strAddress = strAddress.replace(/^\s+/, '').replace(/\s+$/, '');
    return (MLX_ValidEmailRegExp.test(strAddress));
}

function isInteger(s) {
    var i;
    for (i = 0; i < s.length; i++) {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function openSvcCity(svcType) {
    var url = "/ManageSvcCities.aspx?svcType=" + svcType;
    window.open(url, 'wSelect', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=550,height=550');
}

function DeleteArrayElement(array, index) {
    var arr = array;

    if (index >= 0 && index < array.length)
        arr = array.slice(0, index).concat(array.slice(index + 1, array.length));

    return arr;
}

function SwapArrayElements(array, indexA, indexB) {
    var tempValue = array[indexA];
    array[indexA] = array[indexB];
    array[indexB] = tempValue;

    return array;
}

function ValidateRecipients(obj) {
    //Author: Dave Duran (dave.duran@soniceagle.com)
    //Date: 12/5/2002
    //Parameters: object obj (a page object)
    //Required functions: IsValidEmailAddress(string strEmail)
    //
    //Checks the page object's value for a comma seperated list of email addresses
    //presents a dialog to the user allowing the user to remove any bad addrresses
    //with a single click.
    //
    //Returns: true if no bad email addresses remain, false otherwise.
    var blnClean = true;
    //remove whitespace
    obj.value = obj.value.replace(/\s/g, "");
    //remove double commas
    obj.value = obj.value.replace(/,,/g, ",");
    //add leading and trailing commas (needed to replace bad addresses)
    if (obj.value.substr(0, 1) != ",") {
        obj.value = "," + obj.value;
    }
    if (obj.value.substr(obj.value.length - 1, 1) != ",") {
        obj.value += ",";
    }
    var arS = obj.value.split(",");
    var arBadAddress = new Array();
    for (var i in arS) {
        if ((arS[i].length > 0) && (!IsValidEmailAddress(arS[i]))) {
            arBadAddress[arBadAddress.length] = arS[i];
        }
    }
    //check with user to remove any bad email addresses
    if (arBadAddress.length > 0) {
        blnClean = false;
        var strMessage;
        if (arBadAddress.length > 10) {
            strMessage = "There were " + arBadAddress.length + " bad addresses.\n\nClick OK to remove these and send the message, or Cancel to exit without sending the message."
        }
        else {
            strMessage = "The following email addresses are not valid:\n\n" + arBadAddress.toString() + "\n\nClick OK to remove these and send the message, or Cancel to exit without sending the message."
        }
        if (confirm(strMessage)) {
            for (i in arBadAddress) {
                obj.value = obj.value.replace(new RegExp("," + arBadAddress[i] + ","), ",");
            }
            blnClean = true;
        }
    }
    //clean up extra commas
    if (obj.value == ",") obj.value = "";
    obj.value = obj.value.substr(1, obj.value.length - 2);
    return blnClean;
}

function ShowCalendar(eP, eD) {
    var dF = document.getElementById("CalFrame");
    
    var eL = 0;
    var eT = 0;

    dF.contentWindow.document.getElementById("Popup").formname.value = eD;

    for (var p = eP; p && p.tagName != 'BODY'; p = p.offsetParent) {
        eL += p.offsetLeft;
        eT += p.offsetTop;
    }

    var eH = eP.offsetHeight;
    var dH = dF.style.pixelHeight;
    var sT = document.body.scrollTop;
    dF.style.left = eL + "px";

    if (eT - dH >= sT && eT + eH + dH > document.body.clientHeight + sT)
        dF.style.top = (eT - dH) + "px";
    else
        dF.style.top = (eT + eH) + "px";

    if ("none" == dF.style.display)
        dF.style.display = "block";
}

function ShowColorSelector(eP, eD) {
    var dF = document.getElementById("ColFrame");
    var wF = document.getElementById("ColFrame");

    var eL = 0;
    var eT = 0;

    wF.contentDocument.getElementById("Popup").formname.value = eD;

    for (var p = eP; p && p.tagName != 'BODY'; p = p.offsetParent) {
        eL += p.offsetLeft;
        eT += p.offsetTop;
    }

    var eH = eP.offsetHeight;
    var dH = dF.style.pixelHeight;
    var sT = document.body.scrollTop;
    dF.style.left = eL;

    if (eT - dH >= sT && eT + eH + dH > document.body.clientHeight + sT)
        dF.style.top = eT - dH;
    else
        dF.style.top = eT + eH;
    if ("none" == dF.style.display)
        dF.style.display = "block";
}

function HelpMe(page) {
    var help_url = '/Help/Default.aspx?path=' + URLEncode(page);

    if (getCookie('HelpWinExists') == 'yes')
        CloseHelp();
    else {
        if (document.getElementById("tdAAHelp") != null && document.getElementById("frmAAHelp") != null) {
            $("#tdAAHelp").css("display", "table-cell");
            $("#tdAAHelp").width(230);
            document.getElementById("frmAAHelp").src = help_url;
            setCookie('HelpWinExists', 'yes');
        }
    }

    if (typeof (AAPage_Resize) == 'function')
        AAPage_Resize($("#tdAAHelp").width());
}

function CloseHelp() {
    setCookie('HelpWinExists', 'no');

    if (document.getElementById("tdAAHelp") != null && document.getElementById("frmAAHelp") != null)
        document.getElementById("tdAAHelp").style.display = "none";
}

function setCookie(name, value, expires) {
    document.cookie = name + "=" + escape(value) + "; path=/" +
	((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

function getCookie(name) {
    var cookieName = name + "=";
    var objCookie = document.cookie;
    var cookieStart;
    var cookieEnd;
    if (objCookie.length > 0) {
        cookieStart = objCookie.indexOf(cookieName);
        if (cookieStart != -1) {
            cookieStart += cookieName.length;
            cookieEnd = objCookie.indexOf(";", cookieStart);
            if (cookieEnd == -1) {
                cookieEnd = objCookie.length;
            }
            return unescape(objCookie.substring(cookieStart, cookieEnd));
        }
    }
    return null;
}

function copyCookies(source, target) {
    var sourceCookie = null;
    try {
        sourceCookie = source.cookie;
    }
    catch (e)
	{ }

    if (sourceCookie) {
        if (target.cookie != source.cookie) {
            var ca = source.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                target.cookie = ca[i];
            }
        }
    }
}

function AA_PrintListing(listingID) {
    SE_AP_ModalDialog.callbackFunction = AA_PrintListingCallback;
    SE_AP_ModalDialog.listingID = listingID;
    SE_AP_ModalDialog.show('/PropertyDetail/PrintDialog.aspx?', 350, 325, 'SelectFormat');
}
function AA_PrintListingCallback() {
    if (SE_AP_ModalDialog.returnValue) {
        var split = SE_AP_ModalDialog.returnValue.indexOf("&");
        var qs1 = SE_AP_ModalDialog.returnValue.substr(0, split);
        var qs2 = SE_AP_ModalDialog.returnValue.substr(split);

        var format = qs1 += "Email" + qs2;
        SE_AP_ModalDialog.returnValue = "";
        SE_LN_OpenWin('/PropertyDetail/PropertyDetailData.aspx?listingID=' + SE_AP_ModalDialog.listingID + '&print=true&format=' + format, 700, 600);
    }
}

function AA_EmailListings(strContactQS, strListingsQS) {
    SE_AP_ModalDialog.callbackFunction = AA_EmailListingsCallback;
    SE_AP_ModalDialog.strListingsQS = strListingsQS;
    SE_AP_ModalDialog.strContactQS = strContactQS;
    SE_AP_ModalDialog.show('/PropertyDetail/PrintDialog.aspx?nofooteroptions=', 350, 325, 'SelectFormat');
}
function AA_EmailListingsCallback() {
    if (SE_AP_ModalDialog.returnValue) {
        var formatQS = SE_AP_ModalDialog.returnValue;
        if (formatQS != null) {
            var agent = navigator.userAgent.toLowerCase();
            var windowHeight = (screen.height <= 600 && agent.indexOf("mac") == -1) ? 500 : 657;
            SE_AP_ModalDialog.returnValue = "";
            ComposeEmail(SE_AP_ModalDialog.strContactQS + "&" + SE_AP_ModalDialog.strListingsQS + "&format=" + formatQS);
        }
    }
}

function ComposeEmail(strArguments) {
    var strComposeURL = '/Email/ComposePopUp.aspx';
    var agent = navigator.userAgent.toLowerCase();
    var windowHeight = (screen.height <= 600 && agent.indexOf("mac") == -1) ? 500 : 660;

    if (strArguments && strArguments.length > 0)
        strComposeURL += "?" + strArguments;

    SE_OpenWin2('http://' + window.location.hostname + strComposeURL, 750, windowHeight, '');
}

function ComposeEmailWithBody(strArguments, contentDoc) {
    
    var fNoDiv = true;
    if ((typeof (contentDoc) == 'undefined') || !contentDoc)
        contentDoc = document;

    contentDiv = contentDoc.getElementById("divPageContent");
    if (!contentDiv) {
        alert("This page cannot be emailed.");
        return;
    }

    var $cloneDiv = $(contentDoc).find("#divPageContent").clone().css("display", "none");
    $cloneDiv.find("#divMessage").remove();
    $cloneDiv.find(".notforemail").remove();

    content = MLX_PrepListingEmail($cloneDiv.html()); 

    args = GetArgs(contentDoc.location.search);
    if (args["src"] && args["src"] != "") {
        argsSrc = GetArgs(args["src"]);
        if (argsSrc["format"] && argsSrc["format"].length > 0) {
            re10 = new RegExp(/<SHOWEMAILHEADER><\/SHOWEMAILHEADER>/gi);
            content = content.replace(re10, "<SHOWEMAILHEADER>yes<\/SHOWEMAILHEADER>");
        }
    }

    var strComposeURL = '/Email/ComposePopUp.aspx';
    var agent = navigator.userAgent.toLowerCase();
    var windowHeight = (screen.height <= 600 && agent.indexOf("mac") == -1) ? 500 : 620;

    if (strArguments && strArguments.length > 0)
        strComposeURL += "?" + strArguments;

    var win = window.open("", 'newMessage', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=750,height=' + windowHeight + ',top=50,left=50');

    var f = document.createElement('form');
    f.setAttribute('name', 'frmNewMessage');
    f.setAttribute('action', window.location.protocol + '//' + window.location.hostname + strComposeURL);
    f.setAttribute('target', 'newMessage');
    f.setAttribute('method', 'post');
    f.setAttribute('style', 'display:none;');

    var b = document.createElement('input');
    b.setAttribute('type', 'hidden');
    b.setAttribute('name', 'hdnMessageBody');
    b.setAttribute('id', 'hdnMessageBody');
    b.setAttribute('value', content);
    f.appendChild(b);

    document.body.appendChild(f);
    f.submit();
}

//These functions handle printing of the different report views on the Property Detail page pop-up
function HideListAgentInfo() {
    document.getElementById("listAgentInfo").style.display = "none";
    document.getElementById("showInfo").style.visibility = "visible";
}

function ShowListAgentInfo() {
    document.getElementById("listAgentInfo").style.display = "block";
    document.getElementById("showInfo").style.visibility = "hidden";
}

var visibleDivs = new Array()

function PrintMe() {

    //Get any DIVs that may exist on page
    var arrDivs = document.getElementsByTagName("div");

    //if the page to be printed has DIVs, the following code will hide them.
    if (arrDivs.length > 0) {
        var j = 0
        for (i = 0; i < arrDivs.length; i++) {
            var div = arrDivs[i];
            if ((div.style.visibility == "visible") && (div.id.indexOf("pnl") < 0)) {
                visibleDivs[j] = div;
                visibleDivs[j].style.visibility = "hidden";
                j++;
            }
        }
    }

    //Prints the contents of the frmData window.
    window.parent.frames.frmData.focus();
    window.parent.frames.frmData.print();

    //If there were DIVs that were hidden, they will now be restored.
    if (arrDivs.length > 0) {
        setTimeout('RestoreDivs()', 6000);
    }
}

function RestoreDivs() {
    for (k = 0; k < visibleDivs.length; k++) {
        visibleDivs[k].style.visibility = "visible";
    }
}

function URLEncode(plaintext) {
    return encodeURIComponent(plaintext);
}

// ZoomIn (takes an image and Zooms In)
function ZoomIn(img) {
    var src = img.src;
    if (src.indexOf("map.aspx") == -1) return;
    var loc = src.substring(0, src.indexOf("?"));
    var qs = src.substring(src.indexOf("?") + 1);
    var args = GetArgs(qs);
    var zoom = 0.5;
    if (args.zoom) zoom = parseFloat(args.zoom);

    if (zoom <= 0.25) return;

    zoom = zoom / 2;

    var newSrc = loc + "?zoom=" + zoom;
    if (args.mlsid) newSrc += "&mlsID=" + args.mlsid;
    if (args.classid) newSrc += "&classID=" + args.classid;
    if (args.listingid) newSrc += "&listingID=" + args.listingid;
    if (args.width) newSrc += "&width=" + args.width;
    if (args.height) newSrc += "&height=" + args.height;
    if (args.startpin) newSrc += "&startPin=" + args.startpin;
    if (args.x) newSrc += "&x=" + URLEncode(args.x);

    img.src = newSrc;
}
// ZoomOut (takes an img object and alters the url by increasing the zoom property)
function ZoomOut(img) {
    var src = img.src;
    if (src.indexOf("map.aspx") == -1) return;
    var loc = src.substring(0, src.indexOf("?"));
    var qs = src.substring(src.indexOf("?") + 1);
    var args = GetArgs(qs);

    var zoom = 0.5;
    if (args.zoom) zoom = parseFloat(args.zoom);

    if (zoom > 10) return;

    zoom = zoom * 2;

    var newSrc = loc + "?zoom=" + zoom;
    if (args.mlsid) newSrc += "&mlsID=" + args.mlsid;
    if (args.classid) newSrc += "&classID=" + args.classid;
    if (args.listingid) newSrc += "&listingID=" + args.listingid;
    if (args.width) newSrc += "&width=" + args.width;
    if (args.height) newSrc += "&height=" + args.height;
    if (args.startpin) newSrc += "&startPin=" + args.startpin;
    if (args.x) newSrc += "&x=" + URLEncode(args.x);

    img.src = newSrc;
}

function GetArgs(s) {
    //returns name/value objects from a querystring
    var args = new Object()
    if (s.indexOf("?") == -1)
        var query = s;
    else
        var query = s.substring(s.indexOf("?") + 1);
    var pairs = query.split("&");

    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf("=");
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos).toLowerCase();
        var value = pairs[i].substring(pos + 1);
        args[argname] = unescape(value);
    }
    args.count = pairs.length;
    return args;
}

var SE_HV_ModalDialog = null;
function HelpVideo(page) {
    SE_HV_ModalDialog = new SE_ModalDialog('SE_HV_ModalDialog', null);
    SE_HV_ModalDialog.show('/Help/VideoHelp.aspx?moviePath=' + page, 812, 640, 'HelpVideo', 'dependent=yes,fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,directories=no,location=no,');
}

function HowDoesThisWork(Item) {
    window.open(window.location.protocol + '//' + window.location.hostname + '/Help/HowDoesThisWork.aspx?item=' + Item, 'HowDoesThisWork', 'toolbar=0,status=0,menubar=0,width=350,height=400,resizable=0,scrollbars=yes');
}

function trim(str) {
    return str.replace(/^\s*|\s*$/g, "");
}

// for asp.net custom validation controls
function possiblePhone(sender, args) {
    if (args) {
        var reg = /[\D]+/i;
        var str = args.Value;
        str = str.replace(reg, "");
        args.IsValid = str.length > 6;
    } else
        args.IsValid = true;
}

function formatPhone(field) {
    field.value = trim(field.value);

    var ov = field.value;
    var v = "";
    var x = -1;

    // is this phone number 'escaped' by a leading plus?
    if (0 < ov.length && '+' != ov.charAt(0)) { // format it
        // count number of digits
        var n = 0;

        for (i = 0; i < ov.length; i++) {
            var ch = ov.charAt(i);

            // build up formatted number
            if (ch >= '0' && ch <= '9') {
                if (n == 0)
                    v += "(";
                else if (n == 3)
                    v += ") ";
                else if (n == 6)
                    v += "-";

                v += ch;
                n++;
            }

            // check for extension type section;
            // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
            if (!(ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
                x = i;
                break;
            }
        }

        // add the extension
        if (x >= 0)
            v += " " + ov.substring(x, ov.length);

        // if we recognize the number, then format it
        if (n == 10 && v.length <= 40)
            field.value = v;
    }

    return true;
}

function MLX_FormatNumber(nStr) {
    nStr = nStr.replace(',', '');
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function IsValidHexidecimalColorCode(objValue) {
    objValue = objValue.replace(/^\s+/, '').replace(/\s+$/, '');
    var reFilter = /^#[a-fA-F0-9]{6}/;
    return (reFilter.test(objValue));
}

function EditTask(taskID) {
    EditTask(taskID, '');
}

function EditTask(taskID, qs) {
    var url = window.location.protocol + '//' + window.location.hostname + '/Calendar/TaskPopUp.aspx?taskID=' + taskID;
    if (qs)
        url += '&' + qs;

    window.open(url, 'EditTask', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=800,height=700,top=200,left=200');
}

var SE_taskWin = null;

function NewTask(userID, contactID) {
    var strURL = '/Calendar/TaskPopUp.aspx';
    var delim = '?';
    if (userID > 0) {
        strURL += '?CalendarUser=' + userID;
        delim = '&';
    }
    if (contactID > 0) {
        strURL += delim + 'ContactID=' + contactID;
    }

    if (SE_taskWin && !SE_taskWin.closed)
        SE_taskWin.focus();
    else
        SE_taskWin = window.open(window.location.protocol + '//' + window.location.hostname + strURL, 'CreateTask', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=800,height=600,top=200,left=200');
}

var SE_apptWin = null;

function NewAppointment(queryString) {
    var strURL = '/Calendar/EditAppointmentPopUp.aspx';
    var hours = 0;
    if (queryString != null && queryString.length > 0) {
        strURL += '?' + queryString;
    }
    else {
        currentTime = new Date();
        currentYear = currentTime.getYear();

        if (currentYear < 1900)
            currentYear += 1900;

        queryString1 = (currentTime.getMonth() + 1) + "/" + currentTime.getDate() + "/" + currentYear + " ";

        if (currentTime.getHours() > 12)
            hours = (currentTime.getHours() - 12);
        else
            hours = currentTime.getHours();

        if (currentTime.getMinutes() > 30)
            hours = hours + 1;

        queryString1 += hours;

        if (currentTime.getMinutes() > 30)
            queryString1 += ":00 ";
        else
            queryString1 += ":30 ";

        if (currentTime.getHours() > 11)
            queryString1 += "PM";
        else
            queryString1 += "AM";

        strURL += "?Date=" + queryString1;
    }

    if (SE_apptWin && !SE_apptWin.closed)
        SE_apptWin.focus();
    else
        SE_apptWin = window.open(window.location.protocol + '//' + window.location.hostname + strURL, 'CreateAppointment', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=800,height=600,top=200,left=200');
}

function ReloadCalendarWindow() {
    var calendarWindow = SE_FindChildNodeByClass(window.top.document.documentElement, 'contentIFrame', false);
    
    if (calendarWindow && calendarWindow.contentWindow && calendarWindow.contentWindow.location) {
        try {
            calendarWindow.contentWindow.location.reload();
        }
        catch (e) {
            window.top.location.href = window.top.location.href;
        }
    }
    else
        window.top.location.href = window.top.location.href;
}

function notePop(strNoteURL) {
    window.open(strNoteURL, 'Note', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=yes,directories=no,location=no,width=250,height=200,top=200,left=200');
}

function getFunky() {
    alert("You are so funky!");
}

// checks to see if any of the text, select or radio elements have data
function HasData(strControlBaseId) {
    var elem;
    var field = '';
    for (var j = 0; j < document.forms[0].elements.length; j++) {
        elem = document.forms[0].elements[j];
        if (elem.id.indexOf(strControlBaseId) != -1) {
            switch (elem.type) {
                case "text":
                    if (elem.value != '') field = elem.id;
                    break;
                case "select-one":
                    if (elem.selectedIndex != 0) field = elem.id;
                    break;
                case "select-multiple":
                    for (var i = 1; i < elem.options.length; i++) {
                        if (elem.options[i].selected) field = elem.id;
                    }
                    break;
                case "radio":
                    if (elem.checked) {
                        if (elem.id.indexOf("_0") == -1) field = elem.id;
                    }
                    break;
            }
            if (field.length > 0) {
                return true;
            }
        }
    }
    alert("Please enter some criteria on which to search.");
    return false;
}


// returns number of checkboxes (with the name strIdFieldName) that are checked
function GetMarkedIDCount(strIdFieldName) {
    var count = 0;
    var ck = document.getElementsByName(strIdFieldName);

    if (ck[0] == undefined) {
        if (ck.checked)
            count = 1;
        else
            count = 0;
    }
    else {
        for (var i = 0; i < ck.length; i++) {
            if (ck[i].checked)
                count++;
        }
    }
    return count;
}

// returns comma separated list of the values of the checkboxes (with the name strIdFieldName) that are checked
function GetMarkedIDList(strIdFieldName) {
    var count = 0;
    var ids = '';
    var ck = document.getElementsByName(strIdFieldName);

    if (ck[0] == undefined) {
        if (ck.checked)
            ids += ck.value;
    }
    else {
        for (var i = 0; i < ck.length; i++) {
            if (ck[i].checked) {
                if (i > 0) ids += ', ';
                ids += ck[i].value;
            }
        }
    }
    return ids;
}

// returns comma separated list of the values of the listboxes (with the name strIdFieldName) that are checked
function GetSelectListboxItemText(listBoxName) {
    var count = 0;
    var selValues = '';
    var lb = document.getElementById(listBoxName);

    for (var i = 0; i < lb.options.length; i++) {
        if (lb.options[i].selected) {
            if (selValues.length > 0) selValues += ', ';
            selValues += lb.options[i].text;
        }
    }
    return selValues;
}

// ------------------ BEGIN POPUP CODE --------------------

// popup window object, set properties (e.g. url, width, height) and then open it
// it will cascade closing of children popups when you leave the current screen
function noError() {
    // ignore this error - use to avoid permission denied errors when crossing http/https windows
    // may leave some windows open in this circumstance
    return true;
}

var oldErrorHandler = window.onerror;
window.onerror = noError;

// keep and array of windows on the original opener 
// we use this only to count the total windows to give them a unique windowname
// without the unique name we will end up closing the wrong windows
var popups = new Array();
try {
    if (window.opener && window.opener.getPopups)
        popups = window.opener.getPopups();
}
catch (e) { 
}

window.onerror = oldErrorHandler;
if (!popups) var popups = new Array();
// myChildren holds the windows that this window (may be a second or third level popup) has opened
myChildren = new Array();

function getPopups() {
    // function called by child popup to get back to opener's list of popups
    return popups;
}

function popupWindow() {
    this.fullscreen = "no";
    this.toolbar = "no";
    this.status = "no";
    this.menubar = "no";
    this.scrollbars = "yes";
    this.resizable = "yes";
    this.directories = "no";
    this.location = "no";
    this.width = "300";
    this.height = "400";
    this.top = "100";
    this.left = "100";
    this.url = "";
    this.open = function(fNew) {
        // remove any closed child windows from the array
        count = myChildren.length;
        for (var i = 0; i < count; i++) {
            if (myChildren[myChildren.length - 1].closed)
                myChildren.slice(myChildren.length - 1, 1);
        }

        var fNeeded = true;
        if ((myChildren.length > 0) && !fNew) {
            // resuse an existing popup (the last one created)
            if (!myChildren[myChildren.length - 1].closed) {
                try {
                    myChildren[myChildren.length - 1].location = this.url;
                    myChildren[myChildren.length - 1].resizeTo(this.width, this.height);
                }
                catch (e) {
                    // permission denied (e.g. https page called from http page)
                }
                myChildren[myChildren.length - 1].focus();
                fNeeded = false;
            }
        }

        // need to create (not reuse) a new popup
        if (fNeeded) {
            // MUST have a unique name
            this.windowname = "wPopup" + popups.length;
            if ((this.height > 500) && (screen.height <= 600)) {
                var agent = navigator.userAgent.toLowerCase();
                if (agent.indexOf("mac") == -1) this.height = 500;
            }
            // create the window and add it to the myChildren array
            if (this.url.indexOf('http') == -1)
                this.url = location.protocol + '//' + window.location.hostname + this.url;
            myChildren[myChildren.length] = window.open(this.url, this.windowname,
					'fullscreen=' + this.fullscreen +
					',toolbar=' + this.toolbar +
					',status=' + this.status +
					',menubar=' + this.menubar +
					',scrollbars=' + this.scrollbars +
					',resizable=' + this.resizable +
					',directories=' + this.directories +
					',location=' + this.location +
					',width=' + this.width +
					',top=' + this.top +
					',left=' + this.left +
					',height=' + this.height);
            // also add it to the opener array so we have an accurate count
            popups[popups.length] = myChildren[myChildren.length - 1];
            // every window will take care of closing its children
            window.onunload = this.close;
            myChildren[myChildren.length - 1].focus();
        }
    }
    this.close = function() {
        // go through the children - newest to oldest and close
        var count = myChildren.length;
        for (var i = 0; i < count; i++) {
            try {
                if (!myChildren[myChildren.length - 1].closed)
                    myChildren[myChildren.length - 1].close();
            }
            catch (e)
				{ }
            if (myChildren.length > 0)
                myChildren = myChildren.slice(0, myChildren.length - 1);
        }
    }
}
var winPopup = new popupWindow();

// ------------------ END POPUP CODE --------------------



function checkMonth(fldDayField, fldMonthField) {
    var intDaysInMonth = 31;
    var intMonth = fldMonthField.selectedIndex;
    if (intMonth == 2) intDaysInMonth = 29;
    if (intMonth == 4) intDaysInMonth = 30;
    if (intMonth == 6) intDaysInMonth = 30;
    if (intMonth == 9) intDaysInMonth = 30;
    if (intMonth == 11) intDaysInMonth = 30;
    var intDays = fldDayField.selectedIndex;
    if (intDays > intDaysInMonth) {
        alert("The selected month doesn't have " + intDays + " days.");
        fldDayField.selectedIndex = intDaysInMonth;
    }
}

function Reply(objectType, objectID, response, fromWhere) {
    var url = '/Email/AppointmentReplyPopup.aspx?objectType=' + objectType + '&objectID=' + objectID + '&reply=' + response;

    if (fromWhere == 'email')
        url += '&calledFromEmail=1';
    else if (fromWhere == 'editappt')
        url += '&calledFromEditAppointment=1';

    window.open(window.location.protocol + '//' + window.location.hostname + url, '', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=375,height=275');
}

function ProposeNewTime(objectType, objectID, fromWhere) {
    var url = '/Email/ProposeNewTimePopup.aspx?objectType=' + objectType + '&objectID=' + objectID;

    if (fromWhere == 'email')
        url += '&calledFromEmail=1';
    else if (fromWhere == 'editappt')
        url += '&calledFromEditAppointment=1';

    window.open(window.location.protocol + '//' + window.location.hostname + url, '', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=555,height=300');
}

function ExportReport(contentElement, fileName) {
    var form = document.createElement("FORM");
    form.action = "/ExportToExcel.aspx";
    form.method = "post";

    var fn = document.createElement("INPUT");
    fn.setAttribute('type', 'hidden');
    fn.name = "fileName";
    fn.value = fileName;
    form.appendChild(fn);

    var excelData = document.createElement("INPUT");
    excelData.setAttribute('type', 'hidden');
    excelData.name = "excelData";
    excelData.value = contentElement.innerHTML;
    form.appendChild(excelData);

    document.appendChild(form);
    form.submit();
}

// for driving directions and routes
var visibleSpans = new Array();
var visibleShowDivs = new Array();

function HideAllListAgentInfo() {
    //Get and hide Span tags that may exist on page
    var arrSpans = document.getElementsByTagName("span");

    if (arrSpans.length > 0) {
        var j = 0;
        for (i = 0; i < arrSpans.length; i++) {
            var span = arrSpans[i];
            if (span.id == 'listAgentInfo') {
                if (span.style.display == "block") {
                    visibleSpans[j] = span;
                    visibleSpans[j].style.display = "none";
                    j++;
                }
            }
        }
    }

    //Get and show any Div tags that may exist on page
    var arrShowDivs = document.getElementsByTagName("div");

    if (arrShowDivs.length > 0) {
        for (i = 0; i < arrShowDivs.length; i++) {
            if (arrShowDivs[i].id == 'showInfo')
                arrShowDivs[i].style.visibility = "visible";
        }
    }
}

function ShowAllListAgentInfo() {
    //Get and show Span tags that may exist on page
    var arrSpans = document.getElementsByTagName("span");

    if (arrSpans.length > 0) {
        var j = 0;
        for (i = 0; i < arrSpans.length; i++) {
            var span = arrSpans[i];
            if (span.id == 'listAgentInfo') {
                if (span.style.display == "none") {
                    visibleSpans[j] = span;
                    visibleSpans[j].style.display = "block";
                    j++;
                }
            }
        }
    }

    //Get and hide any Div tags that may exist on page
    var arrShowDivs = document.getElementsByTagName("div");
    if (arrShowDivs.length > 0) {
        var j = 0;
        for (i = 0; i < arrShowDivs.length; i++) {
            if (arrShowDivs[i].id == "showInfo")
                arrShowDivs[i].style.visibility = "hidden";
        }
    }
}

function RemoveCurrencyFormatting(str) {
    if (str.length == 0)
        return 0;
    else {
        str = str.replace(/\$|\,/g, '');

        if (isNaN(str))
            return 0;
        else
            if (str.indexOf(".") == 0)
            return parseInt("0" + str);
        else
            return parseInt(str);
    }
}

function RemovePercentFormatting(str) {
    str = str.replace(/%/g, '');

    if (!isNaN(str) && str.length > 0) {
        var per = parseFloat(str) / 100;

        if (per < 0)
            per = -per;

        if (per > 0.9999)
            per = 0;

        return per;
    }
    else
        return 0;
}

function formatPercent(strValue) {
    if (isNaN(strValue))
        strValue = "0";

    strValue = strValue.toString().replace(/%/g, '');
    var flt = parseFloat(strValue);

    return Math.floor(flt * 100 + 0.0000000001).toString() + '.' + Math.floor(((flt * 100) - Math.floor(flt * 100 + 0.0000000001)) * 100 + 0.0000000001).toString();
}

function formatCurrency(strValue) {
    if (isNaN(strValue))
        strValue = "0";
    strValue = strValue.toString().replace(/\$|\,/g, '');
    dblValue = parseFloat(strValue);

    blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    dblValue = Math.floor(dblValue * 100 + 0.50000000001);
    dblValue = Math.floor(dblValue / 100).toString();

    for (var i = 0; i < Math.floor((dblValue.length - (1 + i)) / 3); i++)
        dblValue = dblValue.substring(0, dblValue.length - (4 * i + 3)) + ',' + dblValue.substring(dblValue.length - (4 * i + 3));

    return (((blnSign) ? '' : '-') + '$' + dblValue);
}

// ----------------------------------------------
// code for scrollage tables with fixed headers
// ----------------------------------------------

// build an array of the controls so we can handle multiple scrollable tables on a page
var tablesWithHeaders = new Array();
var divHeaders = new Array();
var divReports = new Array();


// call this function in the web page and pass in the DIV and TABLE controls
// assumes structure as follows
// <div id=divHeadername><table id=tablenameHeader1></table></div>
// <div id=divReportname><table id=tablename></table></div>
// page will fill main table (e.g. "tablename") with header row and rows of data
// both divs should have overflow-y:scroll to provide scroll bars on the right
function addScrollableTable(tableReport, divHeader, divReport) {
    // we build a list of tables to format
    tablesWithHeaders[tablesWithHeaders.length] = tableReport;
    divHeaders[divHeaders.length] = divHeader;
    divReports[divReports.length] = divReport;

    // we will actually format the tables in the onload event 			
    if (!window.onload)
        window.onload = loadMe;
    else if (window.onload.toString().indexOf('loadMe') == -1) {
        var prev_onload = window.onload;
        window.onload = function() { prev_onload(); loadMe(); }
    }

    // we will also need to reformat when the page is resized
    if (!window.onresize)
        window.onresize = resizeMe;
}

// main function to cut and paste header from main table into header table
// and set the widths of all cells in both the header and main tables
// called from both onload and onresize events
function resizeHeader(dataTable, divHeader, divReport) {
    if (dataTable == null) {
        canResize = false
        return canResize;
    }

    var headerTable = document.getElementById(dataTable.id + "Header");
    // we only need to move the title rows once (not on every resize)
    isTitleSet = (headerTable.rows.length > 0);

    // quit is we don't have any records except the header in the data table
    if (!isTitleSet && (dataTable.rows.length == 1))
        return;

    // if the title has been set then only change if the page has a size 
    // and/or the size has changed significantly
    canResize = ((dataTable.offsetWidth > 0)
		&& (document.body.clientWidth > 0)
		&& (document.body.clientWidth > 0));

    if (canResize) {
        doResize = true;

        // make the divs the width of the body so we have scroll bars	
        if (divHeader.parentNode.offsetWidth < document.body.clientWidth)
            width = divHeader.parentNode.offsetWidth;
        else
            width = document.body.clientWidth;

        if (width < 0)
            width = 0;

        divHeader.width = "";
        divReport.width = "";
        divHeader.style.width = width + "px";
        divReport.style.width = width + "px";

        // save the width - e will set it after we have set the cell widths

        var tableWidth = "";
        // if the calling page has not set a width with % then the table size must be set
        if ((dataTable.width.indexOf("%") == -1) && (dataTable.style.width.indexOf("%") == -1)) {
            // make them wide so cell resizing happens quickly
            if (!isTitleSet) {
                headerTable.width = "";
                headerTable.style.width = "";
                dataTable.width = "";
                dataTable.style.width = "";
            }
            // we don't need to resize everytime with a fixed width table - so quit here
            doResize = (!isTitleSet);
            tableWidth = divHeader.clientWidth;
        }

        if (!isTitleSet && doResize) {
            // copy the header row of the data table into the header table
            headerTable.cellSpacing = dataTable.cellSpacing;
            headerTable.border = dataTable.border;
            headerTable.cellPadding = dataTable.cellPadding;

            var tr = headerTable.insertRow(headerTable.rows.length);
            tr.className = dataTable.rows[0].className;

            for (var i = 0; i < dataTable.rows[0].cells.length; i++) {
                var headerCell = tr.insertCell(tr.cells.length);
                var dataCell = dataTable.rows[0].cells[i];
                headerCell.align = dataCell.align;
                headerCell.vAlign = dataCell.vAlign;
                headerCell.className = dataCell.className;
                headerCell.noWrap = "nowrap";
                headerCell.innerHTML = dataCell.innerHTML;
                headerCell.colSpan = dataCell.colSpan;
            }
        }

        if (doResize) {
            hasMulticolumns = false
            offset_width_delta = (2 * dataTable.cellPadding) + (2 * dataTable.border);

            for (var i = 0; i < dataTable.rows[0].cells.length; i++) {
                var headerCell = headerTable.rows[0].cells[i];
                var dataCell = dataTable.rows[0].cells[i];
                headerCell.style.width = "";
                dataCell.style.width = "";
            }

            for (var i = 0; i < dataTable.rows[0].cells.length; i++) {
                var headerCell = headerTable.rows[0].cells[i];
                var dataCell = isTitleSet && dataTable.rows.length > 1 ? dataTable.rows[1].cells[i] : dataTable.rows[0].cells[i];

                if (headerCell.colSpan)
                    hasMulticolumns = true;

                // the header is still in the main table so the cell widths are the maximum of the header or data
                // set both the header and data cell widths to the current width 
                if (((dataCell.width) || (dataCell.style.width))
					&& (headerCell.offsetWidth < dataCell.offsetWidth)) {
                    // use a hard coded width as first choice
                    width = dataCell.width;
                    if (!width) width = dataCell.style.width;
                    if (dataCell.offsetWidth - offset_width_delta > width)
                        width = dataCell.offsetWidth - offset_width_delta;

                    if (dataCell && dataCell.style)
                        dataCell.style.width = width + (!isTitleSet ? "px" : "");

                    headerCell.style.width = width + (!isTitleSet ? "px" : "");
                }
                else {
                    // set the header cell width
                    var width = Math.max(dataCell.offsetWidth - offset_width_delta, 1);
                    headerCell.style.width = width + "px";

                    if (dataCell && dataCell.style)
                        dataCell.style.width = width + "px";
                }
            }

            if (dataTable.rows.length > 1) {
                for (var j = 0; j < dataTable.rows[1].cells.length; j++)
                    dataTable.rows[1].cells[j].style.width = (dataTable.rows[1].cells[j].offsetWidth - offset_width_delta) + "px";
            }

            // set widths to the real widths (but DO NOT CHANGE THE WIDTH OF % width tables)
            tableWidth = headerTable.offsetWidth;
            if ((tableWidth != "") && (dataTable.width.indexOf("%") == -1)) {
                dataTable.style.width = tableWidth + "px";
                headerTable.style.width = tableWidth + "px";
            }

            dataTable.rows[0].style.display = "none";
        }

        // set height after the header table has been filled
        if (divHeader.parentNode.clientHeight > 0) {
            if (divHeader.parentNode.tagName == "FORM")
                height = document.body.offsetHeight - divHeader.offsetHeight;
            else
                height = divHeader.parentNode.clientHeight - divHeader.offsetHeight;
        }
        else
            height = document.body.clientHeight - divHeader.offsetHeight;

        if (height < 0)
            height = 0;

        if (divReport.maxHeight && divReport.maxHeight < height)
            height = divReport.maxHeight;

        if (divReport.dontFillClient && divReport.offsetHeight < divReport.maxHeight)
            divReport.style.height = "";
        else
            divReport.style.height = height + "px";
    }

    return canResize;
}



// flag to prevent simultaneous resize sections before or during loading
var isLoaded = false;
function loadMe() {
    resizeHeaders(true);
    isLoaded = true;
}
function resizeMe() {
    resizeHeaders();
}

function resizeHeaders(force) {
    if (!isLoaded && !force) return;
    {
        var fContinue = true;
        if (isLoaded) {
            if (pageTimer.tStart) {
                if (pageTimer.elapsedTime() < pageTimer.delay)
                    fContinue = false;
            }
            else {
                // prevent constant resizes 
                pageTimer.delay = 100;
                pageTimer.functionToCall = "resizeHeaders()";
                // if a table has more than 100 rows then wait 200 milliseconds between calls
                maxrows = 0;
                for (j = 0; j < tablesWithHeaders.length; j++) {
                    if (tablesWithHeaders[j].length > maxrows)
                        maxrows = tablesWithHeaders[j].length;
                }
                if (maxrows > 400) pageTimer.delay = maxrows / 4;
                pageTimer.start();
                fContinue = false;
            }
        }

        if (fContinue) {
            // loop through all of the tables and resize each
            for (var j = 0; j < tablesWithHeaders.length; j++)
                resizeHeader(tablesWithHeaders[j], divHeaders[j], divReports[j]);

            if (isLoaded) pageTimer.stop();
        }
    }
}

function scrolldiv(myDiv, headerDiv) {
    // scroll the header table in synch with the datatable
    headerDiv.scrollLeft = myDiv.scrollLeft;
}

function timer() {
    this.tStart = null
    this.timeoutID = null;
    this.delay = 1000;
    this.functionToCall = "";
    this.start = function() {
        this.tStart = new Date();
        this.timeoutID = setTimeout(this.functionToCall, this.delay);

    }
    this.elapsedTime = function() {
        var tDate = new Date();
        return tDate.getTime() - this.tStart.getTime();
    }
    this.stop = function() {
        this.tStart = null;
        if (this.timeoutID) {
            clearTimeout(this.timeoutID);
            timerID = null;
        }
    }
}

pageTimer = new timer();

// ----------------------------------------------
// end code for tables with fixed headers
// ----------------------------------------------

// ----------------------------------------------
// listing checkbox management 
// ----------------------------------------------
var MAXMARKED_LISTINGS = 100;
function getCheckBoxes(chkID) {
    var chks = new Array();
    var frm = document.forms[0];
    for (var ax = 0; ax < frm.elements.length; ax++) {
        var elem = frm.elements[ax];
        if (elem.type == 'checkbox' && ((elem.id.match(chkID) != null) || (elem.name.match(chkID) != null))) {
            chks.push(elem);
        }
    }
    return chks;
}

function CheckAll(strIdFieldName, strMasterCheckName) {
    var masterCheck = "chkMaster";
    if (arguments.length == 2) {
        masterCheck = strMasterCheckName;
        chkBoxName = strIdFieldName;
    }

    var bool = document.getElementById(masterCheck).checked;
    var ck = getCheckBoxes(chkBoxName);

    for (var i = 0; i < ck.length; i++) {
        if (!ck[i].disabled)
            ck[i].checked = bool;
    }
}

function CheckBoxSelected(strIdFieldName) {
    return isCheckBoxSelected(strIdFieldName, true);
}

function isCheckBoxSelected(strIdFieldName, showAlert) {
    var intChecked = 0;

    for (var j = 0; j < document.forms[0].elements.length; j++) {
        if (document.forms[0].elements[j].id.indexOf(strIdFieldName) != -1)
            if (document.forms[0].elements[j].checked)
            intChecked = 1;
    }
    if (intChecked == 0) {
        if (showAlert == true) alert("Please select at least one item on which to perform this action.");
        return false;
    }
    else {
        return true;
    }
}



function MarkListing(listingID, bool) {
    var ck = getCheckBoxes(chkBoxName);
    for (var i = 0; i < ck.length; i++) {
        var cb = ck[i];
        if (cb.value == listingID) {
            cb.checked = bool;
            break;
        }
    }
}

function SetMarkedFromList(list) {
    if (list == undefined) return;

    var aMarked = list.split(",");
    for (var i = 0; i < aMarked.length; i++)
        MarkListing(aMarked[i], true);
}

function IsMarked(listingID) {
    ck = getCheckBoxes(chkBoxName);
    for (var i = 0; i < ck.length; i++) {
        if (ck[i].value == listingID) {
            return ck[i].checked;
            break;
        }
    }
}

function GetFirstMarkedListing() {
    var ck = getCheckBoxes(chkBoxName);

    for (var i = 0; i < ck.length; i++) {
        if (ck[i].checked)
            return ck[i].value;
    }
}

function GetMarkedListingCount() {
    var count = 0;
    var ck = getCheckBoxes(chkBoxName);

    for (var i = 0; i < ck.length; i++) {
        if (ck[i].checked)
            count++;
    }
    return count;
}

function GetUnmarkedListingCount() {
    var count = 0;
    var ck = getCheckBoxes(chkBoxName);

    for (var i = 0; i < ck.length; i++) {
        if (!ck[i].checked)
            count++;
    }
    return count;
}

function GetMarkedListings() {
    var s = "";
    var ck = getCheckBoxes(chkBoxName);

    var k = 0;
    for (var i = 0; i < ck.length; i++) {
        if (ck[i].checked) {
            if (s == "")
                s += ck[i].value;
            else
                s += "," + ck[i].value;
            k++;
        }
        if (k > MAXMARKED_LISTINGS - 1)
            break;
    }

    return s;
}

function GetMarkedListingsWithoutLimit() {
    var s = "";
    var ck = getCheckBoxes(chkBoxName);

    var k = 0;
    for (var i = 0; i < ck.length; i++) {
        if (ck[i].checked) {
            if (s == "")
                s += ck[i].value;
            else
                s += "," + ck[i].value;
            k++;
        }
    }

    return s;
}

function GetUnmarkedListings() {
    var s = "";
    var ck = getCheckBoxes(chkBoxName);

    for (var i = 0; i < ck.length; i++) {
        if (!ck[i].checked) {
            if (s == "")
                s += ck[i].value;
            else
                s += "," + ck[i].value;
        }
    }

    return s;
}

function GetAllListings() {
    var s = "";
    var ck = getCheckBoxes(chkBoxName);

    for (var i = 0; i < ck.length; i++) {
        if (s == "")
            s += ck[i].value;
        else
            s += "," + ck[i].value;
    }

    return s;
}


// ----------------------------------------------
// end listing checkbox management 
// ----------------------------------------------
function createXMLDocument(rootNodeName) {
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML("<" + rootNodeName + "></" + rootNodeName + ">");
    return xmlDoc;
}

function AppendXmlNode(xmlDoc, appendToNode, nodeName, nodeText) {
    n1 = xmlDoc.createNode(1, nodeName, "");
    n2 = xmlDoc.createNode(3, "", "");
    n2.text = nodeText;
    n1.appendChild(n2);
    appendToNode.appendChild(n1);
}

function showPhotoTour(mlsID, classID, listingID) {
    if (document.getElementById("propPhoto").src.indexOf("map.aspx") == -1)
        isMap = "no";
    else
        isMap = "yes";

    window.open('/MLSSearch/PhotoTour.aspx?mlsID=' + mlsID + '&classID=' + classID + '&listingID=' + listingID + '&isMap=' + isMap, 'PhotoTour', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=800,height=600');
}

function SE_UserAgent(userAgentText) {
    var _userAgent = navigator.userAgent.toLowerCase();
    if (userAgentText == "msie")
        return (_userAgent.indexOf(userAgentText) != -1) && (_userAgent.indexOf('opera') == -1);
    else
        return _userAgent.indexOf(userAgentText) != -1;
}

function SE_AppendEvent(origEvent, newMethod) {
    // we will actually format the tables in the onload event 			
    if (!origEvent)
        origEvent = newMethod;
    else {
        re = /function (\w*)/gi
        origname = re.exec(origEvent.toString())
        if (origname[1] && newMethod.toString().indexOf(origname[1]) == -1) {
            var prev_onload = origEvent;
            origEvent = function() { prev_onload(); newMethod(); }
        }
    }
    return origEvent;
}

function SE_AA_GoCMA(cmaID, markedListings) {
    if (!cmaID)
        window.top.location.href = "/Tools/ReportBuilder/Default.aspx" + window.location.search + "&addListingIDs=" + markedListings;
    else {
        if (addListingIDs.length > 0)
            window.top.location.href = "/Tools/ReportBuilder/Comparables.aspx" + window.location.search + "&addListingIDs=" + markedListings;
        else
            window.top.location.href = "/Tools/ReportBuilder/Comparables.aspx?cmaID=" + cmaID;
    }
}

//Indicates if any relevant form field data has been changed
var isDirty = false;

//False = user wants to leave page w/o saving
//True  = user wants to save or not leave page
function SE_SaveBeforeExit(customMessage, callback) {
    var message = (customMessage) ? customMessage : "Do you want to save your changes\nbefore you leave this section?\n\nClick \"OK\" to save. If you click \"Cancel\"\nyour unsaved content will be lost.";
    var doSave;
    if (isDirty) {
        doSave = window.confirm(message);
        if (doSave) {
            var el = document.getElementById("txtDirtySaveRequired");
            if (el)
                el.value = "true";

            //Do some work
            if (callback)
                return callback(null);
            else
                return true;
        }
        else {
            //Data may be lost, but proceed anyways
            return false;
        }
    }
    else {
        //Data has not been touched, no confirmation required
        return false;
    }
}

function SE_SetDirty(flag) {
    isDirty = flag;
    var el = document.getElementById("txtIsDirty");
    if (el)
        el.value = flag;
}

function SE_CMA_AddEditCalendarItem(cmaID, cmaCalendarItemID, actionSuccessCallback, defaultDate, showDate) {
    winPopup.url = "/tools/ReportBuilder/CalendarItemPopUp.aspx?cmaID=" + cmaID + "&cmaCalendarItemID=" + cmaCalendarItemID + "&date=" + URLEncode(defaultDate) + "&show=" + showDate;
    winPopup.scrollbars = 0;
    winPopup.height = 315;
    winPopup.open();

    if (actionSuccessCallback) {
        // This is meant to be invoked by the child (popup) window
        window.actionSuccessCallback = actionSuccessCallback;
    }
}

function SE_OnLoadHandler(delegates) {
    this.delegates = delegates; // For convenience only - the array of delegates still must have a global scope, sadly

    // This must be invoked after all possible direct assignments to window.onload
    this.attach = function() {
        // Add the existing onload handler
        if (typeof (window.onload) == 'function') {
            this.addDelegate(window.onload);
        }

        window.onload = function() {
            if (typeof (myOnLoadDelegates) == 'object') {
                var i;
                for (i = 0; i < myOnLoadDelegates.length; i++)
                    myOnLoadDelegates[i]();
            }
        }
    }

    this.addDelegate = function(delegate) {
        if (typeof (delegate) == 'function')
            this.delegates.push(delegate);
    }
}
var myOnLoadDelegates = new Array();
var myOnLoadHandler = new SE_OnLoadHandler(myOnLoadDelegates);


function SE_ParseFloat(str) {
    var retVal = str;

    retVal = retVal.replace(/\$/, "");
    retVal = retVal.replace(/,/, "");

    return parseFloat(retVal);
}

function SE_GetAllRadioButtons() {
    var elForm;
    var arRadio = new Array();
    var idx = 0;

    for (var j = 0; j < document.forms.length; j++) {
        elForm = document.forms[j];
        for (var i = 0; i < elForm.elements.length; i++) {
            if (elForm.elements[i].type == "radio")
                arRadio[idx++] = elForm.elements[i];
        }
    }

    return arRadio;
}

function SE_EscapeForXml(text) {
    if (text && typeof (text) == "string") {
        text = text.replace("&", "&amp;");
        text = text.replace("<", "&lt;");
        text = text.replace(">", "&gt;");
        text = text.replace("\"", "&quot;");
    }

    return text;
}

function MoreInformation(addinItemID) {
    var url = "/moreAddInInfo.aspx?addInItemID=" + addinItemID;
    SE_OpenWin(url, 900, 680, "moreInfo")
}

function CLX_VL(concatListingID) {
    var url = "/PropertyDetail/PropertyDetail.aspx?listingID=" + concatListingID;
    SE_OpenWin(url, 750, 657, 'detail');
}

function CMAReport(cmaID, myID) {
    this.myID = myID;
    this.pdfProcessingStatus = "Creating PDF";
    this.pdfSuccessStatus = "PDF Created";
    this.startPDFProcessing = null;
    this.maxSecondsToProcess = 60;
    this.updateInterval = 0;
    this.cmaID = cmaID
    this.statusUrl = "/tools/reportbuilder/createreport.aspx?action=status&cmaid=" + this.cmaID;
    this.createUrl = "/tools/reportbuilder/createreport.aspx?action=generate&cmaid=" + this.cmaID;
    this.viewUrl = "/tools/reportbuilder/viewreport.aspx?cmaid=" + this.cmaID;
    this.onSuccess = null;

    this.close =
        function () {        
            this.stopUpdatingDialog();
            setTimeout(function(){$("#divCreateStatusDialog").dialog("destroy")},50) ;
        };
    this.stopUpdatingDialog =
        function () {
            clearInterval(this.updateInterval);
            this.updateInterval = 0;          
        };

        this.openDialog =
        function () {
            if ($("#divCreateStatusDialog").length == 0) {
                $("<div id=\"divCreateStatusDialog\" style=\"display:none\"></div>").appendTo("body");
            }
            
            $("#divCreateStatusDialog").html("<div id=\"divReportStatus\" style=\"font-weight:bold;padding:12px;text-align:center;\"> </div>"
                + "<div id=\"divReportLink\" style=\"text-align:center;\"></div>");
           
            var myReport = this;
            var closeMe = function () { myReport.stopUpdatingDialog(); }
            $("#divCreateStatusDialog").dialog({
                title: "Report Generation Status",
                height: 100,
                close: closeMe
            });
        }

        this.updateStatus =
        function (thisStatus) {
            if ($("#divReportStatus").is(":visible")) {
                if (thisStatus)
                    $("#divReportStatus").html(thisStatus);
                else {
                    var myReport = this;
                    $.get(myReport.statusUrl + "&" + MLX_UniqueString(),
                    function (pdfStatus) {

                        if ($("#divReportStatus").html().indexOf(pdfStatus) != 0)
                            $("#divReportStatus").html(pdfStatus);
                        else
                            $("#divReportStatus").html($("#divReportStatus").html() + ".");

                        if (pdfStatus == myReport.pdfProcessingStatus) {
                            if (myReport.startPDFProcessing == null)
                                myReport.startPDFProcessing = new Date();
                            var now = new Date();

                            if ((now.getTime() - myReport.startPDFProcessing.getTime()) / 1000 > myReport.maxSecondsToProcess) {
                                clearInterval(myReport.updateInterval);
                                myReport.updateStatus("This report is taking a while to generate. Please check back later.");
                                setTimeout(function () { myReport.stopUpdatingDialog(); }, 0);
                            }
                        }
                        else if (pdfStatus == myReport.pdfSuccessStatus) {
                            clearInterval(myReport.updateInterval);
                            $("#divReportLink").html("<a href='" + myReport.viewUrl + "&" + MLX_UniqueString() + " '><span onmouseup='" + myReport.myID + ".close()' >View report</span></a>");
                            
                            if (myReport.onSuccess)
                                myReport.onSuccess();
                        }
                        else if (pdfStatus.length > 100) {
                            clearInterval(myReport.updateInterval);
                            myReport.updateStatus("We had a problem creating your report");
                        }
                    });
                }
            }
            else {
                this.stopUpdatingDialog();
            }
        }

   this.GenerateReport =
        function () {
            // generate aar and set cma status
            this.openDialog();
            this.updateStatus("Preparing Report Content");
            
            var myReport = this;
            $.get(this.createUrl + "&" + MLX_UniqueString(),
                function (aarData) {
                    if (aarData == "complete")
                        myReport.StartUpdatingPDFStatus();
                    else
                        myReport.updateStatus("We had a problem creating the xml file for this CMA.");
                });
        }

    this.StartUpdatingPDFStatus =
        function () {
            this.openDialog();
            this.updateStatus();
            var myReport = this;
            this.updateInterval = setInterval(function () { myReport.updateStatus(); }, 1000);
        }
}
CMAReport.ShowDetail = function (cmaID) {
    $("#status" + cmaID).dialog({ title: "Report Status" });
}
