﻿function OmedaNewsletter() {
}

OmedaNewsletter.prototype.Init = function () {
    var thisScope = this;

    this.NewsletterPromoFocusEvents(this);
    this.NewsletterRegistrationFocusEvents(this);

    $("div.newsletterSignup fieldset input[type=submit]").click(function () {
        var emailAddress = jQuery.trim(jQuery(this).parent().children("input[type=text]").attr("value"));
        var idExtension = jQuery(this).parent().parent().attr("id").replace("newsletterSignup", "");
        var brand = jQuery.trim(jQuery(this).parent().children("input[type=hidden]").attr("value"));

        if (thisScope.ValidateNewsletterPromoForm(thisScope, this, emailAddress)) {
            // Valid email address
            jQuery(this).parent().parent().children("div.error").css("display", "none");
            jQuery(this).parent().parent().children("div.error").html("");
            jQuery(this).parent().children("input[type=text]").removeClass("failed");
            thisScope.LookUp(emailAddress, idExtension, brand);
        } else {
            // Non valid email address
            jQuery(this).parent().parent().children("div.error").css("display", "block");
            jQuery(this).parent().children("input[type=text]").addClass("failed");
        }
        return false;
    });

    $("div.formBox fieldset input[type=submit]").click(function () {
        var emailAddress = jQuery.trim(jQuery(this).parent().children("input[type=text]").attr("value"));
        var idExtension = $("#newsLetterOverlayId").attr("value");
        var brand = jQuery.trim(jQuery(this).parent().children("input[type=hidden]").attr("value"));

        if (thisScope.ValidateNewsletterPromoForm(thisScope, this, emailAddress)) {
            // Valid email address
            $("#persistentToolbar .formError").css('display', 'none');
            jQuery(this).parent().parent().children("div.error").css("display", "none");
            jQuery(this).parent().parent().children("div.error").html("");
            jQuery(this).parent().children("input[type=text]").removeClass("failed");
            thisScope.LookUp(emailAddress, idExtension, brand);
        } else {
            // Non valid email address
            $("#persistentToolbar .formError").css('display', 'block');
            jQuery(this).parent().children("input[type=text]").addClass("failed");
        }
        return false;
    });

    $("div.newsletterRegistration input[type=submit]").click(function () {
        var idExtension = jQuery(this).attr("id").replace("newsletterSubscribe", "");
        var brand = jQuery.trim(jQuery(this).parent().parent().parent().children("input[id=brand2" + idExtension + "]").attr("value"));
        var displayErrorMessage = thisScope.ValidateNewsletterRegistrationForm(thisScope, this, idExtension);
        if (displayErrorMessage == false) {
            // valid
            jQuery(this).parent().children("div.failed").html("");
            jQuery(this).parent().children("div.failed").css("display", "none");
            $("div.newsletterRegistration" + idExtension + " input").removeClass("failed");
            $("div.newsletterRegistration" + idExtension + " select").removeClass("failed");
            thisScope.QueueData(idExtension, brand);
        } else {
            // not valid
            jQuery(this).parent().children("div.failed").html("Please correct the highlighted fields");
            jQuery(this).parent().children("div.failed").css("display", "block");
        }
        return false;
    });

    $("div.newsletterRegistration a.ssClose").closeDOMWindow({
        eventType: 'click'
    });
}

// validation in backend Code as well, updates here may need to be made there as well
OmedaNewsletter.prototype.ValidateNewsletterPromoForm = function (outerScope, innerScope, emailAddress) {
    if (outerScope.ValidateEmailAddress(emailAddress)) {
        return true;
    } else {
        jQuery(innerScope).parent().parent().children("div.error").html("Invalid e-mail address, please re-enter");
        return false;
    }
}

// validation in backend Code as well, updates here may need to be made there as well
OmedaNewsletter.prototype.TextInputValidationHandler = function (xpath, text, displayErrorMessage) {
    var inputTag = $(xpath);
    if (jQuery.trim(inputTag.attr("value")).length == 0 || inputTag.attr("value") == text) {
        inputTag.addClass("failed");
        displayErrorMessage = true;
    } else {
        inputTag.removeClass("failed");
    }
    return displayErrorMessage;
}

// validation in backend Code as well, updates here may need to be made there as well
OmedaNewsletter.prototype.ValidateNewsletterRegistrationForm = function (outerScope, innerScope, idExtension) {
    var brand = $("div.newsletterRegistration" + idExtension + " input[id=brand2" + idExtension + "]").attr("value");

    var displayErrorMessage = false;
    var baseXPath = "div.newsletterRegistration" + idExtension + " .rightColumn ";
    var baseInputXPath = baseXPath + "input[name=";
    var baseSelectXPath = baseXPath + "select[name=";

    // email address validation
    var emailAddress = $(baseInputXPath + "EMAIL_ADDRESS]");
    if (!outerScope.ValidateEmailAddress(emailAddress.attr("value"))) {
        emailAddress.addClass("failed");
        displayErrorMessage = true;
    } else {
        emailAddress.removeClass("failed");
    }

    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "FNAME]", "First Name", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "LNAME]", "Last Name", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "COMPANY]", "Company Name", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "ADDRESS2]", "Street Address", displayErrorMessage);
    displayErrorMessage = outerScope.TextInputValidationHandler(baseInputXPath + "CITY]", "City", displayErrorMessage);

    // state/providence validation
    var stateProvidence = $(baseSelectXPath + "STATE]");
    var zipPostalCode = $(baseInputXPath + "ZIPCODE]");
    var country = $(baseSelectXPath + "COUNTRY]");
    var chosenStateProvidence = null;
    if (stateProvidence.find(":selected").index() == 0) {
        stateProvidence.addClass("failed");
        zipPostalCode.addClass("failed");
        country.addClass("failed");
        displayErrorMessage = true;
    } else {
        stateProvidence.removeClass("failed");
        chosenStateProvidence = stateProvidence.find(":selected").val();
    }

    // zip/postal code validation
    var isUSPostalCode = false;
    var isCanadianPostalCode = false;
    if (chosenStateProvidence != null && isNaN(chosenStateProvidence)) {
        // is a US territory
        if (!outerScope.ValidateUSZipCode(zipPostalCode.attr("value"))) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            isUSPostalCode = true;
            zipPostalCode.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence != 53) {
        // is a Canadian territory
        if (!outerScope.ValidateCanadianZipCode(zipPostalCode.attr("value"))) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            isCanadianPostalCode = true;
            zipPostalCode.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence == 53) {
        // is not a US or Canadian territory
        if (jQuery.trim(zipPostalCode.attr("value")).length == 0 || zipPostalCode.attr("value") == "ZIP/Postal Code") {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            zipPostalCode.removeClass("failed");
        }
    } else {
        stateProvidence.addClass("failed");
        zipPostalCode.addClass("failed");
        country.addClass("failed");
        displayErrorMessage = true;
    }

    // country validation
    var chosenCountry = null;
    chosenCountry = jQuery.trim(country.find(":selected").text());
    if (chosenStateProvidence != null && isNaN(chosenStateProvidence)) {
        // is a US territory
        if (chosenCountry != "United States" || !isUSPostalCode) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            country.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence != 53) {
        // is a Canadian territory
        if (chosenCountry != "Canada" || !isCanadianPostalCode) {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            country.removeClass("failed");
        }
    } else if (chosenStateProvidence != null && !isNaN(chosenStateProvidence) && chosenStateProvidence == 53) {
        // is not a US or Canadian territory
        if (country.find(":selected").index() == 0 || chosenCountry == "United States" || chosenCountry == "Canada") {
            stateProvidence.addClass("failed");
            zipPostalCode.addClass("failed");
            country.addClass("failed");
            displayErrorMessage = true;
        } else {
            country.removeClass("failed");
        }
    } else {
        stateProvidence.addClass("failed");
        zipPostalCode.addClass("failed");
        country.addClass("failed");
        displayErrorMessage = true;
    }

    // validate other field for Primary Business
    var primaryBusiness = $(baseSelectXPath + "PRIMARY_BUSINESS]");
    var primaryBusinessDesc = $(baseInputXPath + "PRIMARY_BUSINESS_DESC]");
    var checkPrimaryBusinessOtherField = false;
    if (primaryBusiness.val() == 99 ||
        ((brand == "res" || brand == "rm") && primaryBusiness.val() == 9)) {
        checkPrimaryBusinessOtherField = true;
    }
    if (checkPrimaryBusinessOtherField && (jQuery.trim(primaryBusinessDesc.attr("value")).length == 0 ||
            primaryBusinessDesc.attr("value") == "If \"Other\" please specify")) {
        primaryBusinessDesc.addClass("failed");
        displayErrorMessage = true;
    } else {
        primaryBusinessDesc.removeClass("failed");
    }

    // validate other field for Job Title
    var jobTitle = $(baseSelectXPath + "JOB_TITLE]");
    var jobTitleDesc = $(baseInputXPath + "JOB_TITLE_DESC]");
    var checkJobTitleOtherField = false;
    if (jobTitle.val() == 99 || (brand == "rm" && jobTitle.val() == 9)) {
        checkJobTitleOtherField = true;
    }
    if (checkJobTitleOtherField && (jQuery.trim(jobTitleDesc.attr("value")).length == 0 ||
            jobTitleDesc.attr("value") == "If \"Other\" please specify")) {
        jobTitleDesc.addClass("failed");
        displayErrorMessage = true;
    } else {
        jobTitleDesc.removeClass("failed");
    }

    return displayErrorMessage;
}

OmedaNewsletter.prototype.NewsletterPromoFocusEvents = function (thisScope) {
    thisScope.TextInputFocusEventHandler("E-mail address", "div.newsletterSignup fieldset input[type=text]");
    thisScope.TextInputFocusEventHandler("E-mail address", "div.signUpBox fieldset input[type=text]");
}

OmedaNewsletter.prototype.TextInputFocusEventHandler = function (defaultText, xpath) {
    $(xpath).focus(function () {
        if (jQuery.trim(jQuery(this).attr("value")).toLowerCase() == defaultText.toLowerCase() ||
            jQuery.trim(jQuery(this).attr("value")).toLowerCase().length == 0) {
            jQuery(this).attr("value", "");
        }
    }).blur(function () {
        if (jQuery.trim(jQuery(this).attr("value")).toLowerCase().length == 0) {
            jQuery(this).attr("value", defaultText);
        }
    });
}

OmedaNewsletter.prototype.NewsletterRegistrationFocusEvents = function (thisScope) {
    var basePath = "div.newsletterRegistration .rightColumn fieldset input[name=";
    thisScope.TextInputFocusEventHandler("E-mail address", basePath + "EMAIL_ADDRESS]");
    thisScope.TextInputFocusEventHandler("First Name", basePath + "FNAME]");
    thisScope.TextInputFocusEventHandler("Last Name", basePath + "LNAME]");
    thisScope.TextInputFocusEventHandler("Title (optional)", basePath + "TITLE]");
    thisScope.TextInputFocusEventHandler("Company Name", basePath + "COMPANY]");
    thisScope.TextInputFocusEventHandler("Street Address", basePath + "ADDRESS2]");
    thisScope.TextInputFocusEventHandler("City", basePath + "CITY]");
    thisScope.TextInputFocusEventHandler("ZIP/Postal Code", basePath + "ZIPCODE]");
    thisScope.TextInputFocusEventHandler("Business Phone (optional)", basePath + "PHONE]");
    thisScope.TextInputFocusEventHandler("If \"Other\" please specify", basePath + "PRIMARY_BUSINESS_DESC]");
    thisScope.TextInputFocusEventHandler("If \"Other\" please specify", basePath + "JOB_TITLE_DESC]");
}

// validation in backend Code as well, updates here may need to be made there as well
OmedaNewsletter.prototype.ValidateEmailAddress = function (emailStringToValidate) {
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!filter.test(emailStringToValidate)) {
        return false;
    }
    return true;
}

// validation in backend Code as well, updates here may need to be made there as well
OmedaNewsletter.prototype.ValidateUSZipCode = function (zipCodeStringToValidate) {
    var re = /^\d{5}([\-]\d{4})?$/;
    return (re.test(zipCodeStringToValidate));
}

// validation in backend Code as well, updates here may need to be made there as well
OmedaNewsletter.prototype.ValidateCanadianZipCode = function (zipCodeStringToValidate) {
    var re = /^([ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9])*$/;
    return (re.test(zipCodeStringToValidate));
}

OmedaNewsletter.prototype.DisplayHandler = function (xpath, displayChoice) {
    var loadingDisplay = "none";
    var errorDisplay = "none";
    var loadedDisplay = "none";
    var successDisplay = "none";
    switch (displayChoice) {
        case "loading":
            loadingDisplay = "block";
            break;
        case "error":
            errorDisplay = "block";
            break;
        case "loaded":
            loadedDisplay = "block";
            break;
        case "success":
            successDisplay = "block";
            break;
    }
    $(xpath + "Loading").attr("style", "display:" + loadingDisplay);
    $(xpath + "Error").attr("style", "display:" + errorDisplay);
    $(xpath + "Loaded").attr("style", "display:" + loadedDisplay);
    $(xpath + "Success").attr("style", "display:" + successDisplay);
}

OmedaNewsletter.prototype.IE6Fixes = function (hideLoadedScreenDropDowns, loadedScreenXpathBase) {
    // currently applying this fix to all browsers (may change that in the future; works either way)
    //if (jQuery.browser.msie && jQuery.browser.version.indexOf("6.") >= 0) {
    if (hideLoadedScreenDropDowns) {
        // hide the drop downs
        $(loadedScreenXpathBase + " select").css("display", "none");
    } else {
        // display the drop downs
        $(loadedScreenXpathBase + " select").css("display", "inline");
    }
    //}
}

OmedaNewsletter.prototype.LookUp = function (emailAddress, windowSourceIdExtension, brand) {

    var baseDisplayXPath = "div.newsletterRegistration" + windowSourceIdExtension + " .newsletter";
    var baseLoadedDisplayXPath = baseDisplayXPath + "Loaded";

    try {

        // scope of OmedaNewsletter instance
        var thisScope = this;

        // initialize to loading screen
        this.DisplayHandler(baseDisplayXPath, "loading");
        this.IE6Fixes(true, baseLoadedDisplayXPath);

        // open window
        $.openDOMWindow({
            windowSourceID: '#newsletterRegistration' + windowSourceIdExtension
        });

        thisScope.SetOverlayWindowHeight();
        thisScope.CSSFixes();

        var standardErrorMessage = "Newsletter service unavailable at this time.";
        $.ajax({
            url: "/development/omedanewsletterservice.svc/lookup/" + brand,
            dataType: 'json',
            type: 'POST',
            data: '{ "EmailAddress": "' + emailAddress + '" }',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                var d = eval(data);
                if (d.Succeeded == true) {
                    // operation succeeded
                    thisScope.RemoveErrorMessage(windowSourceIdExtension);
                    thisScope.DisplayHandler(baseDisplayXPath, "loaded");
                    thisScope.IE6Fixes(false, baseLoadedDisplayXPath);
                    thisScope.PopulateOverlay(d, windowSourceIdExtension, thisScope);
                    thisScope.SetOverlayWindowHeight();
                } else {
                    // operation failed
                    thisScope.DisplayHandler(baseDisplayXPath, "error");
                    thisScope.IE6Fixes(true, baseLoadedDisplayXPath);
                    thisScope.InsertErrorMessage(standardErrorMessage, windowSourceIdExtension);
                    thisScope.SetOverlayWindowHeight();
                }
            },
            error: function (a, b, c, d) {
                // operation failed
                thisScope.DisplayHandler(baseDisplayXPath, "error");
                thisScope.IE6Fixes(true, baseLoadedDisplayXPath);
                thisScope.InsertErrorMessage(standardErrorMessage, windowSourceIdExtension);
                thisScope.SetOverlayWindowHeight();
            }
        });

    } catch (err) {
        // operation failed
        this.DisplayHandler(baseDisplayXPath, "error");
        this.IE6Fixes(true, baseLoadedDisplayXPath);
        this.InsertErrorMessage(standardErrorMessage, windowSourceIdExtension);
        this.SetOverlayWindowHeight();
    }
}

OmedaNewsletter.prototype.QueueData = function (windowSourceIdExtension, brand) {

    var baseDisplayXPath = "div.newsletterRegistration" + windowSourceIdExtension + " .newsletter";
    var baseLoadedDisplayXPath = baseDisplayXPath + "Loaded";

    try {
        var standardErrorMessage = "Newsletter service unavailable at this time.";
        var thisScope = this;
        var jsonData = this.GetNewsletterFormData(windowSourceIdExtension, brand, thisScope);

        // display loading screen
        this.DisplayHandler(baseDisplayXPath, "loading");
        this.IE6Fixes(true, baseLoadedDisplayXPath);
        this.SetOverlayWindowHeight();
        $.ajax({
            url: "/development/omedanewsletterservice.svc/QueueData/" + brand,
            dataType: 'json',
            type: 'POST',
            data: thisScope.Stringify(jsonData),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                var d = eval(data);
                if (d.Succeeded == true) {
                    // operation succeeded
                    thisScope.DisplayHandler(baseDisplayXPath, "success");
                    thisScope.IE6Fixes(true, baseLoadedDisplayXPath);
                    thisScope.SetOverlayWindowHeight();
                    s = s_gi(s_account);
                    s.events = 'event16';
                    s.tl(this, 'o', 'Newsletter Submit');

                } else {
                    // operation failed
                    thisScope.DisplayHandler(baseDisplayXPath, "error");
                    thisScope.IE6Fixes(true, baseLoadedDisplayXPath);
                    thisScope.InsertErrorMessage(standardErrorMessage, windowSourceIdExtension);
                    thisScope.SetOverlayWindowHeight();
                }
            },
            error: function () {
                // operation failed
                thisScope.DisplayHandler(baseDisplayXPath, "error");
                thisScope.IE6Fixes(true, baseLoadedDisplayXPath);
                thisScope.InsertErrorMessage(standardErrorMessage, windowSourceIdExtension);
                thisScope.SetOverlayWindowHeight();
            }
        });
    } catch (err) {
        // operation failed
        this.DisplayHandler(baseDisplayXPath, "error");
        this.IE6Fixes(true, baseLoadedDisplayXPath);
        this.InsertErrorMessage(standardErrorMessage, windowSourceIdExtension);
        this.SetOverlayWindowHeight();
    }
}

OmedaNewsletter.prototype.Stringify = function (jsonData) {
    var strJsonData = '{';
    var itemCount = 0;
    for (var item in jsonData) {
        if (itemCount > 0) {
            strJsonData += ', ';
        }
        var value = "";
        for (var i = 0; i < jsonData[item].length; i++) {
            if (jsonData[item].substr(i, 1) == "\\") {
                value += "\\" + "\\"; // escape slashes
            } else if (jsonData[item].substr(i, 1) == "\"") {
                value += "\\" + "\""; // escape quotes
            } else {
                value += jsonData[item].substr(i, 1);
            }
        }
        strJsonData += '"' + item + '":"' + value + '"';
        itemCount++;
    }
    strJsonData += '}';
    return strJsonData;
}

OmedaNewsletter.prototype.GetNewsletterFormData = function (windowSourceIdExtension, brand, scope) {
    var baseXPath = "div.newsletterRegistration" + windowSourceIdExtension;
    var baseInputXPath = baseXPath + " input[";
    var baseInputNameXPath = baseInputXPath + "name=";
    var baseSelectXPath = baseXPath + " select[name=";

    var jsonData = {};

    // get client customer id
    var id = $(baseInputXPath + "id=id" + windowSourceIdExtension + "]").attr("value");
    if (jQuery.trim(id).length > 0) {
        jsonData.Id = id;
    }

    // get newsletters signed up for
    var newslettersChecked = false;
    var newsletters = $(baseInputXPath + "type=checkbox]");
    for (var i = 0; i < newsletters.length; i++) {
        if (jQuery(newsletters[i]).attr("checked")) {
            if (!newslettersChecked) {
                jsonData.Newsletters = jQuery(newsletters[i]).attr("value");
                newslettersChecked = true;
            } else {
                jsonData.Newsletters += "," + jQuery(newsletters[i]).attr("value");
            }
        }
    }

    // get email address, first name, and last name (all are required fields)
    jsonData.EmailAddress = $(baseInputNameXPath + "EMAIL_ADDRESS]").attr("value");
    jsonData.FirstName = $(baseInputNameXPath + "FNAME]").attr("value");
    jsonData.LastName = $(baseInputNameXPath + "LNAME]").attr("value");

    // get the title (optional field)
    var title = $(baseInputNameXPath + "TITLE]").attr("value");
    if (jQuery.trim(title).length > 0 && jQuery.trim(title) != "Title (optional)") {
        jsonData.Title = title;
    }

    // get company, address, and city (all are required fields)
    jsonData.Company = $(baseInputNameXPath + "COMPANY]").attr("value");
    jsonData.Street = $(baseInputNameXPath + "ADDRESS2]").attr("value");
    jsonData.City = $(baseInputNameXPath + "CITY]").attr("value");

    // get the state (required field)
    var states = $(baseSelectXPath + "STATE]").children();
    for (var i = 1; i < states.length; i++) {
        if (jQuery(states[i]).attr("selected")) {
            jsonData.RegionCode = jQuery(states[i]).attr("value");
        }
    }

    // get the zip/postal code (required field)
    jsonData.PostalCode = $(baseInputNameXPath + "ZIPCODE]").attr("value");

    // get the country (required field)
    var countries = $(baseSelectXPath + "COUNTRY]").children();
    for (var i = 1; i < countries.length; i++) {
        if (jQuery(countries[i]).attr("selected")) {
            jsonData.CountryCode = jQuery(countries[i]).attr("value");
        }
    }

    // get the business phone number (optional field)
    var businessPhone = $(baseInputNameXPath + "PHONE]").attr("value");
    if (jQuery.trim(businessPhone).length > 0 && jQuery.trim(businessPhone) != "Business Phone (optional)") {
        jsonData.BusinessPhone = businessPhone;
    }

    // get the primary business or firm along with the other field
    var primaryBusinesses = $(baseSelectXPath + "PRIMARY_BUSINESS]").children();
    if (!jQuery(primaryBusinesses[0]).attr("selected")) {
        for (var i = 1; i < primaryBusinesses.length; i++) {
            if (jQuery(primaryBusinesses[i]).attr("selected")) {
                jsonData.PrimaryBusiness = jQuery(primaryBusinesses[i]).attr("value");
            }
        }
    }
    var primaryBusinessOther = $(baseInputNameXPath + "PRIMARY_BUSINESS_DESC]").attr("value");
    if (jQuery.trim(primaryBusinessOther).length > 0 && jQuery.trim(primaryBusinessOther) != "If \"Other\" please specify") {
        jsonData.PrimaryBusinessDesc = primaryBusinessOther;
    }

    // get job title along with the other field
    var jobTitles = $(baseSelectXPath + "JOB_TITLE]").children();
    if (!jQuery(jobTitles[0]).attr("selected")) {
        for (var i = 1; i < jobTitles.length; i++) {
            if (jQuery(jobTitles[i]).attr("selected")) {
                jsonData.JobTitle = jQuery(jobTitles[i]).attr("value");
            }
        }
    }
    var jobTitleOther = $(baseInputNameXPath + "JOB_TITLE_DESC]").attr("value");
    if (jQuery.trim(jobTitleOther).length > 0 && jQuery.trim(jobTitleOther) != "If \"Other\" please specify") {
        jsonData.JobTitleDesc = jobTitleOther;
    }

    return jsonData;
}

OmedaNewsletter.prototype.SetOverlayWindowHeight = function () {
    // fix the height of the overlay window
    var baseXPath = "#DOMWindow .newsletterRegistration";
    var baseLoadingXPath = baseXPath + " .newsletterLoading";
    var baseErrorXPath = baseXPath + " .newsletterError";
    var baseLoadedXPath = baseXPath + " .newsletterLoaded";
    var baseLoadedLeftColumnXPath = baseLoadedXPath + " .leftColumn";
    var baseLoadedRightColumnXPath = baseLoadedXPath + " .rightColumn";
    var baseSuccessXPath = baseXPath + " .newsletterSuccess";
    var extrapadding = 50;
    var logoHeight = $(baseXPath + " .logo").outerHeight();
    var newsletterHeight = null;
    if ($(baseErrorXPath).css("display").toLowerCase() == "block") {
        newsletterHeight = $(baseErrorXPath).outerHeight();
    } else if ($(baseLoadingXPath).css("display").toLowerCase() == "block") {
        newsletterHeight = $(baseLoadingXPath).outerHeight();
    } else if ($(baseLoadedXPath).css("display").toLowerCase() == "block") {
        if ($(baseLoadedLeftColumnXPath).outerHeight() >
                            $(baseLoadedRightColumnXPath).outerHeight()) {
            newsletterHeight = $(baseLoadedLeftColumnXPath).outerHeight();
        } else {
            newsletterHeight = $(baseLoadedRightColumnXPath).outerHeight();
        }
    } else if ($(baseSuccessXPath).css("display").toLowerCase() == "block") {
        newsletterHeight = $(baseSuccessXPath).outerHeight();
    }
    $(baseXPath).height(logoHeight + newsletterHeight + extrapadding);
    $("#DOMWindow").height($(baseXPath).outerHeight());
}

OmedaNewsletter.prototype.CSSFixes = function () {
    // make css adjustments to correct display
    $("#DOMWindowOverlay").css("z-index", $("#DOMWindowOverlay").css("z-index") * 100);
    $("#DOMWindow").css("z-index", $("#DOMWindow").css("z-index") * 100);
    $("#DOMWindow").css("overflow", "hidden");
}

OmedaNewsletter.prototype.InsertErrorMessage = function (message, windowSourceIdExtension) {
    var brand = $("div.newsletterRegistration" + windowSourceIdExtension + " input[id=brand2" + windowSourceIdExtension + "]").attr("value");
    if (brand != null && jQuery.trim(brand).length > 0) {
        if (brand == "arch") {
            message += "  <a href=\"http://www.omeda.com/cgi-win/arch.cgi?mode=newsletter&t=nletal\" target=\"_blank\">Please try this alternative page to register.</a>";
        } else if (brand == "bldr") {
            message += "  <a href=\"http://www.omeda.com/cgi-win/bldr.cgi?mode-newsletter\" target=\"_blank\">Please try this alternative page to register for BUILDER Business Update.</a>  " +
                "<a href=\"http://www.omeda.com/cgi-win/nwbd.cgi?mode=elogin\" target=\"_blank\">Please try this alternative page to register for BUILDER Pulse.</a>";
        } else if (brand == "mfe") {
            message += "  <a href=\"http://www.omeda.com/cgi-win/mfe.cgi?mode=newsletter\" target=\"_blank\">Please try this alternative page to register.</a>";
        } else if (brand == "res") {
            message += "  <a href=\"http://www.omeda.com/cgi-win/res.cgi?mode=newsletter\" target=\"_blank\">Please try this alternative page to register.</a>";
        } else if (brand == "rm") {
            message += "  <a href=\"http://www.omeda.com/cgi-win/rm.cgi?mode=newsletter&p=testpromo\" target=\"_blank\">Please try this alternative page to register.</a>";
        }
    }
    $("div.newsletterRegistration" + windowSourceIdExtension + " .newsletterError").html("<p>" + message + "</p>");
}

OmedaNewsletter.prototype.RemoveErrorMessage = function (windowSourceIdExtension) {
    $("div.newsletterRegistration" + windowSourceIdExtension + " .newsletterError").html("");
}

OmedaNewsletter.prototype.PopulateInput = function (value, xpath, text) {
    if (value != null) {
        $(xpath).attr("value", value);
    } else {
        $(xpath).attr("value", text);
    }
    $(xpath).removeClass("failed");
}

OmedaNewsletter.prototype.PopulateOverlay = function (d, windowSourceIdExtension, thisScope) {

    var baseXPath = "div.newsletterRegistration" + windowSourceIdExtension;
    var baseIdXPath = baseXPath + " input[id=id" + windowSourceIdExtension + "]";
    var baseNewsletterSignupCheckboxesXPath = baseXPath + " .leftColumn input[type=checkbox]";
    var baseRightColumnXPath = baseXPath + " .rightColumn";
    var baseInputXPath = baseRightColumnXPath + " input[name=";
    var baseSelectXPath = baseRightColumnXPath + " select[name=";

    // populate hidden id
    if (d.Id != null) {
        $(baseIdXPath).attr("value", d.Id);
    } else {
        $(baseIdXPath).attr("value", "");
    }

    // check newsletter signup checkboxes
    var leftColChBxs = $(baseNewsletterSignupCheckboxesXPath);
    for (var i = 0; i < leftColChBxs.length; i++) {
        jQuery(leftColChBxs[i]).attr("checked", true);
    }

    this.PopulateInput(d.EmailAddress, baseInputXPath + "EMAIL_ADDRESS]", "E-mail address");
    this.PopulateInput(d.FirstName, baseInputXPath + "FNAME]", "First Name");
    this.PopulateInput(d.LastName, baseInputXPath + "LNAME]", "Last Name");
    this.PopulateInput(d.Title, baseInputXPath + "TITLE]", "Title (optional)");
    this.PopulateInput(d.Company, baseInputXPath + "COMPANY]", "Company Name");
    this.PopulateInput(d.Street, baseInputXPath + "ADDRESS2]", "Street Address");
    this.PopulateInput(d.City, baseInputXPath + "CITY]", "City");

    // populate state/providence
    var isStateOrProvidence = false;
    var baseSelectStateXPath = baseSelectXPath + "STATE]";
    if (d.RegionCode != null) {
        /*var options = $(baseSelectStateXPath).children();
        for (var i = 0; i < options.length; i++) {
        if (jQuery(options[i]).attr("value") == d.RegionCode) {
        jQuery(options[i]).attr("selected", "selected");
        jQuery(options[0]).removeAttr("selected");
        if (d.RegionCode != 53) {
        isStateOrProvidence = true;
        }
        } else {
        if (i != 0) {
        jQuery(options[i]).removeAttr("selected");
        }
        }
        }*/
        $(baseSelectStateXPath).val(d.RegionCode);
        if (d.RegionCode != 53) {
            isStateOrProvidence = true;
        }
    } else {
        jQuery($(baseSelectStateXPath).children()[0]).attr("selected", "selected");
    }
    $(baseSelectStateXPath).removeClass("failed");

    // populate postal code
    this.PopulateInput(d.PostalCode, baseInputXPath + "ZIPCODE]", "ZIP/Postal Code");

    // populate the country
    var baseSelectCountryXPath = baseSelectXPath + "COUNTRY]";
    if (isStateOrProvidence && isNaN(d.RegionCode)) {
        // USA
        /*
        var countries = $(baseSelectCountryXPath).children();
        for (var i = 0; i < countries.length; i++) {

        if (jQuery.trim(jQuery(countries[i]).text()) == "United States") {
        jQuery(countries[i]).attr("selected", "selected");
        jQuery(countries[0]).removeAttr("selected");
        }
        }
        */
        $(baseSelectCountryXPath).val("USA");
    } else if (isStateOrProvidence && !isNaN(d.RegionCode)) {
        // Canada
        /*
        var countries = $(baseSelectCountryXPath).children();
        for (var i = 0; i < countries.length; i++) {
        if (jQuery.trim(jQuery(countries[i]).text()) == "Canada") {
        jQuery(countries[i]).attr("selected", "selected");
        jQuery(countries[0]).removeAttr("selected");
        }
        }
        */
        $(baseSelectCountryXPath).val("CANADA");
    } else if (d.RegionCode != null && d.RegionCode == "53" && d.CountryCode != null && d.CountryCode.length > 0) {
        // not USA or Canada
        /*
        var countries = $(baseSelectCountryXPath).children();
        for (var i = 0; i < countries.length; i++) {
        if (jQuery.trim(jQuery(countries[i]).attr("value")) == d.CountryCode) {
        jQuery(countries[i]).attr("selected", "selected");
        jQuery(countries[0]).removeAttr("selected");
        }
        }
        */
        $(baseSelectCountryXPath).val(d.CountryCode);
    } else {
        jQuery($(baseSelectCountryXPath).children()[0]).attr("selected", "selected");
    }
    $(baseSelectCountryXPath).removeClass("failed");

    // populate the business phone number
    this.PopulateInput(d.BusinessPhone, baseInputXPath + "PHONE]", "Business Phone (optional)");

    // initialize primary business or firm to defaults
    jQuery($(baseSelectXPath + "PRIMARY_BUSINESS]").children()[0]).attr("selected", "selected");
    $(baseInputXPath + "PRIMARY_BUSINESS_DESC]").attr("value", "If \"Other\" please specify");
    $(baseSelectXPath + "PRIMARY_BUSINESS]").removeClass("failed");
    $(baseInputXPath + "PRIMARY_BUSINESS_DESC]").removeClass("failed");

    // intialize job title to defaults
    jQuery($(baseSelectXPath + "JOB_TITLE]").children()[0]).attr("selected", "selected");
    $(baseInputXPath + "JOB_TITLE_DESC]").attr("value", "If \"Other\" please specify");
    $(baseSelectXPath + "JOB_TITLE]").removeClass("failed");
    $(baseInputXPath + "JOB_TITLE_DESC]").removeClass("failed");

    // remove failed message
    jQuery($(baseXPath + " input[type=submit]").parent().children("div.failed")).html("");
    jQuery($(baseXPath + " input[type=submit]").parent().children("div.failed")).css("display", "none");
}

