function KeyPressed(e, sButtonID) {
    var evt = e || window.event,
        btn;
    if (evt.keyCode == 13) {
        evt.returnValue = false;
        evt.cancel = true;
        btn = document.getElementById(sButtonID);
        if (btn) {
            btn.click();
        }
    }
}

/*
Used by custom page links for campaigns, where an override URL has been specified
(see CampaignPageListControl.ascx).
Will open the specified URL, either in the current window, or a new window
(if a new window is opened it will be of the size specified)
*/
function OpenPage(sURL, sWinName, bNewWindow, iWidth, iHeight, sResizable, sScrollbars) {
    x = (screen.width) ? Math.floor((screen.width - iWidth) / 2) : 100;
    y = (screen.height) ? Math.floor((screen.height - iHeight) / 2) : 100;

    if (!sScrollbars) { sScrollbars = '1'; }
    var sWinStats = 'resizable=' + sResizable + ',location=no,directories=no,menubar=no,toolbar=no,scrollbars=' + sScrollbars + ',status=no,width=' + iWidth + ',height=' + iHeight + ',left=' + x + ',top=' + y;
    /*	alert(sWinStats);*/
    if (bNewWindow) {
        win = window.open(sURL, sWinName, sWinStats);
        if (win && !win.closed) win.focus();
    }
    else {
        document.location = sURL;
    }


}

function SubmitForm(sFormId, sAction, bNewWindow) {
    var oForm = document.getElementById(sFormId);

    if (oForm == null)
        return;

    var oViewState = oForm['__VIEWSTATE'];

    if (oViewState != null) {
        // Remove the viewstate node (must have a reference to its parent node to do this)
        var oParent = oViewState.parentNode;
        if (oParent != null) {
            oParent.removeChild(oViewState);
        }
    }

    if (sAction != null) {
        oForm.action = sAction;
    }

    if (bNewWindow) {
        oForm.target = "_blank";
    }

    oForm.submit();
}

function menuOn(sMenu) {
    document.getElementById(sMenu).className = 'menuitemon';
}

function menuOff(sMenu) {
    document.getElementById(sMenu).className = 'menuitem';
}

var iCurRewardsCategoryID = 0;
function showRewards2(iCategoryID) {
    if (document.getElementById('rwds_' + iCurRewardsCategoryID)) {
        document.getElementById('rwds_' + iCurRewardsCategoryID).style.display = 'none';
    }
    document.getElementById('rwds_' + iCategoryID).style.display = 'block';
    iCurRewardsCategoryID = iCategoryID;
}

function showRewards(iCategoryID) {
    if (document.getElementById('rwds_' + iCategoryID)) {
        document.getElementById('rewardslisting').innerHTML = document.getElementById('rwds_' + iCategoryID).innerHTML;
    }
}

function ValidateQuestions(oSender, oArgs) {


    var oList1 = document.getElementById('oForm_lstQ1');
    var oList2 = document.getElementById('oForm_lstQ2');

    var sQuestion1 = oList1.options[oList1.selectedIndex].text;
    var sQuestion2 = oList2.options[oList2.selectedIndex].text;

    if (sQuestion1 == sQuestion2) {
        oArgs.IsValid = false;
        document.getElementById('oForm_valCompareQuestions').style.display = '';
    }
    else {
        oArgs.IsValid = true;
        document.getElementById('oForm_valCompareQuestions').style.display = 'none';
    }
    return;
}

function showSampleColour(sID) {
    if (document.getElementById('samp' + sID)) {
        window.onerror = function () { return true; }
        document.getElementById('samp' + sID).style.backgroundColor = ((document.getElementById('txt' + sID).value.length > 2 && document.getElementById('txt' + sID).value.length < 5) || (document.getElementById('txt' + sID).value.length > 5 && document.getElementById('txt' + sID).value.length < 8)) ? document.getElementById('txt' + sID).value : '#FFFFFF';
    }
}

function styleListControls() {
    var oElements = document.getElementsByTagName('input');
    for (var iLoop = 0; iLoop < oElements.length; ++iLoop) {
        if (oElements[iLoop].type == 'radio') { oElements[iLoop].className = 'rdo'; }
        if (oElements[iLoop].type == 'checkbox') { oElements[iLoop].className = 'check'; }
    }
}

function setDefaultColours() {
    for (var iLoop = 1; iLoop <= 7; ++iLoop) {
        window.opener.setColour('oColour' + iLoop + '_txtColour', document.getElementById('txtColour' + iLoop).value);
        window.opener.setColour('oAltColour' + iLoop + '_txtColour', document.getElementById('txtAltColour' + iLoop).value);
    }
}

function fnCompanySelect(oSelect, sTextBoxID) {
    var oTextBox = document.getElementById(sTextBoxID);

    if ((oTextBox != null) && (oSelect != null)) {
        var sText = oSelect.options[oSelect.selectedIndex].text;

        if (sText.length > 0)
            oTextBox.value = oSelect.options[oSelect.selectedIndex].text;
    }
}

function fnCompanySelectReset(oTextBox, sSelectID) {
    var oSelect = document.getElementById(sSelectID);

    if ((oTextBox != null) && (oSelect != null)) {
        //if (oTextBox.value.length == 0)
        oSelect.selectedIndex = 0;
    }
}

function fnIsInputNumeric(event, bAllowDecimal, bAllowMinus) {
    var keyCode = event.keyCode;
    if (keyCode == 0) keyCode = event.which;

    if (keyCode == 8 || keyCode == 9 || keyCode == 37 || keyCode == 39 || (keyCode >= 48 && keyCode <= 57)) {
        return true;
    }
    else if ((bAllowDecimal != undefined) && (bAllowDecimal) && (keyCode == 46)) {
        return true;
    }
    else if ((bAllowMinus != undefined) && (bAllowMinus) && (keyCode == 45)) {
        return true;
    }

    return false;
}

function fnSetChecked(aCheckboxes, check) {
    if (aCheckboxes == null)
        return;


    for (var i = 0; i < aCheckboxes.length; i++) {
        var oCheckbox = document.getElementById(aCheckboxes[i]);

        if (oCheckbox != null)
            oCheckbox.checked = check;
    }
}

function getHeight(oObj) {

    var iHeight;

    if (oObj.innerHeight) {
        iHeight = oObj.innerHeight;
    }
    else if (oObj.documentElement && oObj.documentElement.scrollHeight) {
        iHeight = oObj.documentElement.scrollHeight;
    }
    else if (oObj.body) {
        iHeight = oObj.body.scrollHeight;
    }

    return iHeight;
}


/* IFrame Handling Functions */
function resizeIFrame(sFrame, bFlag) {
    var oFrame = document.getElementById(sFrame);

    if (oFrame) {
        var oDoc = (oFrame.contentWindow || oFrame.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;

        oFrame.style.height = getHeight(oDoc).toString() + 'px';
        oDoc.body.style.margin = '0';
        oDoc.body.style.padding = '0';
        oDoc.body.style.overflow = 'hidden';
        oFrame.style.overflowY = 'hidden';

        //DN removed - causes problem with resizing IFrame.
        //window.location.href = '#';

        if (!bFlag) {
            oLastFrame = oFrame;
            window.setTimeout('resizeIFrame("' + sFrame + '", true);', 0);
        }
    }
}

// Dynamically set a CSS attribute on the fly
function setCssAttribute(sSelector, sAttribute, sValue) {

    var sRules = (document.all) ? 'rules' : 'cssRules';

    for (var iLoop = 0; iLoop < document.styleSheets.length; iLoop++) {
        var oRules = document.styleSheets[iLoop][sRules];
        for (var iRule = 0; iRule < oRules.length; iRule++) {
            if (oRules[iRule].selectorText == sSelector) {
                oRules[iRule].style[sAttribute] = sValue;
            }
        }
    }
}

// Retrieve a CSS attribute
function getCssAttribute(sSelector, sAttribute) {

    var sRules = (document.all) ? 'rules' : 'cssRules';

    for (var iLoop = 0; iLoop < document.styleSheets.length; iLoop++) {
        var oRules = document.styleSheets[iLoop][sRules];
        for (var iRule = 0; iRule < oRules.length; iRule++) {
            if (oRules[iRule].selectorText == sSelector) {
                return oRules[iRule].style[sAttribute];
            }
        }
    }
}

function toggleClass(oItem, sSelector) {
    if (oItem.checked) {
        setCssAttribute(sSelector, "display", "block");
    } else {
        setCssAttribute(sSelector, "display", "none");
    }
}


function UrlEncode(sInput) {
    // This function required because escape() doesn't do the job!
    var SAFECHARS = "0123456789" + 				// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()"; 				// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
    var sEncoded = "";
    for (var iLoop = 0; iLoop < sInput.length; iLoop++) {
        var sChar = sInput.charAt(iLoop);
        if (sChar == " ") {
            sEncoded += "+"; 			// x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(sChar) != -1) {
            sEncoded += sChar;
        } else {
            var sCharCode = sChar.charCodeAt(0);
            if (sCharCode > 255) {
                alert("Unicode Character '"
							+ sChar
							+ "' cannot be encoded using standard URL encoding.\n" +
							"(URL encoding only supports 8-bit characters.)\n" +
							"A space (+) will be substituted.");
                sEncoded += "+";
            } else {
                sEncoded += "%";
                sEncoded += HEX.charAt((sCharCode >> 4) & 0xF);
                sEncoded += HEX.charAt(sCharCode & 0xF);
            }
        }
    }
    return sEncoded;
};

function swapThankYouCard(img) {

    var allImages = document.getElementsByTagName('img');
    for (var i = 0; i < allImages.length; i++) {
        if (allImages[i].className == 'thankYouImage thankYouImageSelected') {
            allImages[i].className = 'thankYouImage';
        }
    }

    document.getElementById('Image1').src = img.src;
    document.getElementById('txtImageURL').value = img.src;

    var imageProperties = img.src.split('~');
    document.getElementById('divMessage').style.fontFamily = imageProperties[1].replace('%20', ' ').replace('%20', ' ');
    document.getElementById('divMessage').style.fontSize = (imageProperties[2].replace('%20', ' ').replace('%20', ' ') * 1.5) + 'px';
    document.getElementById('divMessage').style.color = '#' + imageProperties[3].replace('.jpg', '');
    img.className = 'thankYouImage thankYouImageSelected';

}

$(document).ready(function () {
    $('div.divCategoryContainer span.nomCategory').hover(function () {
        $('.nomCatDesc').each(function () {
            $(this).css({ 'display': 'none' });
        });
        $('div.nomCatLevelDesc').each(function () {

            $(this).css({ 'display': 'none' });
        });
        var descID = $(this).attr('id').split('_')[1];
        $('div#nomCatDesc_' + descID).css({ 'display': 'block' });
        $('img#nomCatImage_' + descID).css({ 'display': 'block' });
    }
    );

    $('div.divCategoryContainer span.nomCategoryLevel').hover(function () {
        $('div.nomCatLevelDesc').each(function () {

            $(this).css({ 'display': 'none' });
        });
        $('div.nomCatDesc').each(function () {

            $(this).css({ 'display': 'none' });
        });
        var descID = $(this).attr('id').split('_')[1];
        $('div#nomCatLevelDesc_' + descID).css({ 'display': 'block' });
    }
    );

    if ($("#tabbedMenuContainer").length > 0) {
        if (!documentLoaded) {
            InitTabbedMenu();
            documentLoaded = true;
        }
    }

});

var openSubMenuID = null;
var openMenuItemID = null;
var menuTimeout;

function InitTabbedMenu() {
    var mm = $('#mm-body').length > 0;
    var contentBoxMarginLeft = $("div#contentbox").css("margin-left");
    var offSet = (mm) ? 340 : 200;
    if (contentBoxMarginLeft == "225px") {
        offSet = 225;
    }
    $(".tabbedmenuitem").hover(function () {
        if (openMenuItemID != null) {
            $("td#" + openMenuItemID).removeClass("hover");
            openMenuItemID = null;
            clearTimeout(menuTimeout);
        }
        if (openSubMenuID != null) {
            $("div#" + openSubMenuID).css({ "display": "none" });
            openSubMenuID = null;
            clearTimeout(menuTimeout);
        }

        var submenuid = $(this).attr("id").split('_')[1];
        var menuWidth = Math.max($(this).width() - 10, 220);
        $(this).addClass("hover");
        $("div#tabbedsubmenu_" + submenuid).stop(true, true);

        if (mm) {
            var left = $.browser.msie ? '0px' : 'auto';
            $(this).append($("div#tabbedsubmenu_" + submenuid).css({ display: 'block', position: 'absolute', width: menuWidth + 'px', left: left }));
        } else {
            var coordinates = $(this).offset();
            var leftOffset = coordinates.left - offSet;
            $("div#tabbedsubmenu_" + submenuid).css({ "display": "block", 'left': leftOffset + 'px', 'width': menuWidth + 'px' });
        }

        openSubMenuID = "tabbedsubmenu_" + submenuid;
        openMenuItemID = $(this).attr("id");
        //console.log("menu item: openSubMenuID = " + openSubMenuID);
        //console.log("menu item: openMenuItemID = " + openMenuItemID);
    },
    function () {
        var menuItemID = $(this).attr("id");
        var submenuid = $(this).attr("id").split('_')[1];

        menuTimeout = setTimeout(function () { $("#" + menuItemID).removeClass("hover"); $("div#tabbedsubmenu_" + submenuid).css({ "display": "none" }); openSubMenuID = null; openMenuItemID = null; }, 250);
        //$("div#tabbedsubmenu_" + submenuid).css({ "display": "none" });
    });

    $("div.tabbedsubmenu").hover(function () {
        clearTimeout(menuTimeout);
        var submenuitemid = $(this).attr("id").split('_')[1];
        $(this).stop(true, true);
        $("td#tabbeditem_" + submenuitemid).addClass("hover");
        $(this).css({ "display": "block" });
        openSubMenuID = $(this).attr("id");
        openMenuItemID = "tabbeditem_" + submenuitemid;
        //console.log("sub menu item: openSubMenuID = " + openSubMenuID);
        //console.log("sub menu item: openMenuItemID = " + openMenuItemID);
    },
        function () {
            var menuItemID = $(this).attr("id");
            var submenuitemid = $(this).attr("id").split('_')[1];
            menuTimeout = setTimeout(function () { $("#" + menuItemID).css({ "display": "none" }); $("td#tabbeditem_" + submenuitemid).removeClass("hover"); openSubMenuID = null; openMenuItemID = null; }, 250);
            // $(this).css({ "display": "none" });

            //  $("td#tabbeditem_" + submenuitemid).removeClass("hover");
        }
        );

        $("span.tabbedmenuitem-switch").click(function () {
            if ($(this).hasClass("on")) {
                $(this).html("+");
                $(this).removeClass("on");
            }
            else {
                $(this).html("-");
                $(this).addClass("on");
            }

            $(this).parent().find("ul").toggle();
        });
}

/*function InitCategorySideMenu() {
$("li.category").click(function() {
if ($(this).find("ul.hidden").length > 0) {
if ($("ul.categoryMenu li ul:not(.hidden)").length > 0) {
var link = $(this);
$("ul.categoryMenu li ul:not(.hidden)").hide("slow", function() {
$(this).addClass("hidden");
$("ul.categoryMenu li.selected").removeClass("selected");
if (link.find("ul li").length > 0) {
link.addClass("selected");
link.find("ul").show("slow", function() { $(this).removeClass("hidden"); });
}
else {
link.addClass("selected");
}

});
}
else {
$("ul.categoryMenu li.selected").removeClass("selected");
if ($(this).find("ul li").length > 0) {
var link = $(this);
$(this).find("ul").show("slow", function() { $(this).removeClass("hidden"); link.addClass("selected"); });
}
else {
$(this).addClass("selected");
}
}
}
});
}*/

function toggleOtherReason(obj) {
    if (obj.options[obj.selectedIndex].text == 'other') {
        document.getElementById('txtNomApproveDeclineOther').style.display = 'inline';
    }
    else {
        document.getElementById('txtNomApproveDeclineOther').style.display = 'none';
    }
}

$(document).ready(function () {
    $('a.modalPopup').click(function (e) {
        var campaignID = $(this).attr('class').split(' ')[1];
        $('#hidSelectedSubCampaign').val(campaignID);
        $('#basic-modal-content-' + campaignID).modal();
    });

    $('input.Submit').click(function () {
        $('#chkTermsAgreed_checked').val($(this).parent().find('input[type="checkbox"]:checked').length > 0);
        document.forms[0].submit();
    });

    ResizeMyMoneyPanels();   
});

function ResizeMyMoneyPanels() {
    var maxHeight = 0;

    var panels = $('div#mm-home-panels').find('div.mm-panel-inner');

    // Resize the My-Money panels height to the height of the tallest panel.
    panels.each(function (index) {
        var curHeight = $(this).height();
       
        if (curHeight > maxHeight) {
            maxHeight = curHeight;
        }
    });    

    if (maxHeight > 0) {
       panels.each(function (index) {            
            $(this).height(maxHeight);
        });
    }
}

function LimitMultiLineLength(obj) {
    x = obj.value.length;
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxLength")) : ""
    if (navigator.appName == 'Microsoft Internet Explorer') {
        if (x >= mlength) {
            window.event.returnValue = false;
        }
    }
    else {
        return (x < mlength);
    }
}

// This really convoluted approach is thanks to IE glitches!
var showForgottenPasswordPrompt = function () {
    $('#fp-modal-container').addClass('shadow');

    var closeDialog = function (dialog) {
        if ($.browser.msie) {
            if ($.browser.version == 6) {
                window.location.href = window.location.href;
            }
            showForgottenPasswordPrompt.curDialog = dialog;
            dialog.container.hide();
            dialog.overlay.hide();
        } else {
            $.modal.close();
        }
    };

    // This is included here because the one already in this script doesn't work properly but changing it may break other parts of the system
    var getCssAttribute = function (sSelector, sAttribute) {

        var sRules = (document.all) ? 'rules' : 'cssRules';

        for (var iLoop = document.styleSheets.length - 1; iLoop >= 0; iLoop--) {
            var oRules = document.styleSheets[iLoop][sRules];
            for (var iRule = oRules.length - 1; iRule >= 0; iRule--) {
                if (oRules[iRule].selectorText == sSelector) {
                    return oRules[iRule].style[sAttribute];
                }
            }
        }
    };

    var bgColor = showForgottenPasswordPrompt._bgColor;
    if (bgColor == undefined) {
        bgColor = showForgottenPasswordPrompt._bgColor = getCssAttribute('.btn', 'backgroundColor');
    }

    var curDialog = showForgottenPasswordPrompt.curDialog;
    if (curDialog) {
        curDialog.container.show();
        curDialog.overlay.show();
        curDialog.container.find('.simplemodal-close').bind('click.simplemodal', function (e) { e.preventDefault(); closeDialog(curDialog); });
    } else {
        $('#forgotten-password').modal({
            appendTo: 'form',
            overlayId: 'fp-modal-overlay',
            containerId: 'fp-modal-container',
            dataId: 'fp-modal-data',
            persist: true,
            onOpen: function (dialog) {
                if ($.browser.msie) {
                    dialog.container.css('position', 'absolute');
                    DD_roundies.addRule('#fp-modal-container', '10px 10px 10px 10px', true);
                    dialog.data.find('.btn').css('background-color', bgColor);
                }
                dialog.overlay.show();
                dialog.container.show();
                dialog.data.show();
                dialog.data.find('input:eq(0)').focus();
            },
            onClose: closeDialog
        });
    }
}

