/****************************************************************************
 * BEGIN handlers for Forgot User ID popup
 * Required:
 * - /js/shade.js
 ***************************************************************************/
var forgotUserID = {
    show: function() {
        if($('#lostidDiv').length == 0){
            forgotUserID.createLayer();
        }
        var $modal = $('#lostidDiv');
        $modal.css({
            'top' : $(window).scrollTop() + 200 + 'px',
            'left' : (($(window).width() / 2) - 141) + 'px'
        });
        shade.show();
        $modal.fadeIn(1000);
    },

    /* creates the login layer if it doesn't exist */
    createLayer: function() {
        var $layertext = '<div id="lostidDiv">' +
                '<div style="text-align: center; margin-bottom: 10px;">' +
                '<img src="images/refresh09/title_forgotuserid.gif" width="162" height="20" alt="Forgot Your User ID?"/>' +
                '</div>' +

                '<p><strong>Not a Problem!</strong> Your Plum Benefits user ID is your email address.</p>' +

                '<p>Typically, your work email addresss (jdoe@acmecorp.com) has been used to set up your account although' +
                'in some instances your personal email address has been used.' +
                'If you have any problems accessing your Plum Benefits account using one of these two user ID options,' +
                'please contact our Customer Support Team at 212.660.1888.' +
                '</p>' +

                '<div style="margin-top: 10px; text-align: center"><a href="javascript:forgotUserID.hide()"><img src="images/refresh09/BTN_Close.gif" width="75" height="24" alt="Close"/></a></div>' +
                '</div>';

        $(document.body).append($layertext);
    },

    hide: function() {
        shade.hide();
        $('#lostidDiv').fadeOut(1000);
    }
};
/****************************************************************************
 * END handlers for Forgot User ID popup
 ***************************************************************************/

function checkLogin() {
    var passwordInput = document.getElementById('password');
    if (passwordInput.value.length > 0) {
        showRealPassword();
    }
}

function clearUsername(usernameId, state) {
    var txt = 'Enter e-mail address';
    //var usernameObj = document.getElementById('username');
	if(!usernameId){
		usernameId = 'username';
	}
    var usernameObj = document.getElementById(usernameId);
    if (usernameObj.value == txt) {
        usernameObj.value = '';
    }
}

function checkUsername(usernameId, state) {
    var txt = 'Enter e-mail address';
    //var usernameObj = document.getElementById('username');
	if(!usernameId){
		usernameId = 'username';
	}
    var usernameObj = document.getElementById(usernameId);
    //var passwordInput = document.getElementById('password');
    //var passwordMaskDiv = document.getElementById('passwordMask');

    if (usernameObj.value != txt) {
        showRealPassword();
    }
}

function inputMaskFocus() {
    var txt = 'Enter password';
    var passwordMaskInput = document.getElementById('passwordMaskInput');

    if (passwordMaskInput.value == txt) {
        passwordMaskInput.value = '';
        showRealPassword();
    }
}

function showRealPassword() {
    var passwordMaskDiv = document.getElementById('passwordMask');
    var passwordInput = document.getElementById('password');
    passwordMaskDiv.style.display = 'none';
    passwordInput.style.display = 'block';
    passwordInput.focus();
}

//sniffer
var agt = navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();
var is_mac = (agt.indexOf("mac") != -1);
var is_minor = parseFloat(appVer);
var is_major = parseInt(is_minor);
var is_opera = (agt.indexOf("opera") != -1);
var iePos = appVer.indexOf('msie');
var is_mac_ie = false;
if (iePos != -1) {
    is_minor = parseFloat(appVer.substring(iePos + 5, appVer.indexOf(';', iePos)));
    is_major = parseInt(is_minor);
}
var is_ie = ((iePos != -1) && (!is_opera));
if (is_mac && is_ie) {
    is_mac_ie = true;
}
var is_ie5up = (is_ie && is_minor >= 5);
var is_ie5_5up = (is_ie && is_minor >= 5.5);
var is_safari = ((agt.indexOf('safari') != -1) && (agt.indexOf('mac') != -1)) ? true : false;
var nn4 = false;
if (document.layers) {
    nn4 = true;
}
//end sniffer

//code for redirecting to www.plumbenefits.com
//Updated for jboss switchover:
//  Since we're clustering the apps, we have hostname aliases that fall prey to
//  getting www prepended to the name. So this if check it to make sure that this
//  doesn't happen.
if(window.location.href.search(/plumweb.*/i) == -1 &&
	window.location.href.search(/plumapp.*/i) == -1 &&
	window.location.href.search(/doma\.plumbenefits\.com.*/i) == -1){

	if (window.location.href.indexOf("plumbenefits") != -1 && window.location.href.indexOf("www") == -1) {
		var b = window.location.href.split("//");
		if (b[1].indexOf("www") == -1 && b[1].indexOf("elqLForm") == -1) {
			var newURL = b[0] + "//www." + b[1];
			window.location = newURL;
		}
	}
}
//MENU GLOBALS AND FUNCTIONS
var currMenu = -1;
var id = 0;
var mytimeout;
var clearDelayDuration = 100;
var selectBoxHack = 0;
var mask;
var maskOffsetTop = 23;
var maskOffsetHeight = -45;
var maskOffsetLeft = 0;
var maskOffsetWidth = 0;

// Turn iFrame mask on for IE 5.5+ / PC only
if (is_ie && !is_mac_ie) {
    if (is_ie5_5up) {
        selectBoxHack = 2;
    } else {
        selectBoxHack = 1;
    }
}

function showme(id) {
    clearTimeout(mytimeout);
    if (currMenu != id) {
        //show menu
        try {
            var o = getObj("menu" + id);
            var os = getStyleObj(o);
            os.visibility = "visible";
            currMenu = id;

            if (selectBoxHack && (o.offsetHeight + maskOffsetHeight) > 0) {
                if (selectBoxHack > 1) {
                    mask = getObj("mask");
                    mask.style.left = offsetLeft(o) + maskOffsetLeft;
                    mask.style.top = offsetTop(o) + maskOffsetTop;
                    mask.style.width = o.offsetWidth + maskOffsetWidth;
                    mask.style.height = o.offsetHeight + maskOffsetHeight;
                } else {
                    toggleSelect("hide");
                }
            }
        } catch (e) {
        }
    }
}

function clearme() {
    if (currMenu != -1) {
        //hide menu
        clearTimeout(mytimeout);
        var o = getObj("menu" + currMenu);
        var os = getStyleObj(o);
        os.visibility = "hidden";
        currMenu = -1;

        if (selectBoxHack) {
            if (mask) {
                mask.style.left = -500;
                mask.style.top = -500;
            }
            toggleSelect("show");
        }
    }
}

function clearmenus() {
    clearTimeout(mytimeout);
    mytimeout = setTimeout("clearme()", clearDelayDuration);
}

function getObj(theId) {
    if (document.getElementById) {
        theObj = document.getElementById(theId);
    } else if (document.all) {
        theObj = document.all[theId];
    } else {
        theObj = document.layers[theId];
    }
    return theObj;
}

function getStyleObj(o) {
    if (document.getElementById || document.all) {
        return o.style;
    } else {
        return o;
    }
}

//Mac IE offset fix
function offsetLeft(o) {
    var i = 0;
    var hack = 0;
    while (o.offsetParent != null) {
        i += o.offsetLeft;
        hack = o.offsetLeft;
        o = o.offsetParent;
    }
    return i + o.offsetLeft - hack;
}
function offsetTop(o) {
    var i = 0;
    while (o.offsetParent != null) {
        i += o.offsetTop;
        o = o.offsetParent;
    }
    return i + o.offsetTop;
}

function toggleSelect(v) {
    var f = document.forms;
    for (var i = 0; i < f.length; i++) {
        for (var j = 0; j < f[i].elements.length; j++) {
            if (f[i].elements[j].type == 'select-one') {
                if (v == 'show') {
                    f[i].elements[j].style.visibility = 'visible';
                } else {
                    f[i].elements[j].style.visibility = 'hidden';
                }
            }
        }
    }
}
//END MENU

function swapImg(target, value) {
    document.getElementById(target).src = document.getElementById(value).src
}

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;
        if ('1' == ov.charAt(0)) {  // skip it
            ov = ov.substring(1, ov.length);
        }

        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 ltrim(s) {
    return s.replace(/^\s*/, "");
}

function rtrim(s) {
    return s.replace(/\s*$/, "");
}

function trim(s) {
    return rtrim(ltrim(s));
}

function clearForm(obj) {
    var f = document.getElementById(obj);
    try {
        for (x = 0; x < f.elements.length; x++) {
            if (f.elements[x].type == "checkbox") {
                f.elements[x].checked = 0;
            }
            if (f.elements[x].type == "text") {
                f.elements[x].value = "";
            }
        }
    } catch (e) {
        alert(e.description);

    }
}

function clearAccountForm(obj) {
    var f = document.getElementById(obj);
    try {
        for (x = 0; x < f.elements.length; x++) {
            if (f.elements[x].type == "checkbox") {
                f.elements[x].checked = 0;
            }
            if (f.elements[x].type == "text") {
                f.elements[x].value = "";
            }
        }
    } catch (e) {
        alert(e.description);

    }
}

function makeRequest(url, method, qs, handler) {
    var request = false;

    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
        if (request.overrideMimeType) {
            request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            }
        }
    }

    if (!request) { //error
        return false;
    }
    request.onreadystatechange = function() {
        eval(handler + "(request)");
    };
    request.open(method, url, true);
    request.send(qs);

}

function displayRecommendedOffers(request) {
    if (request.readyState != 4 || request.status != 200) {
        return false;
    }
    var outputA = "";
    var outputB = "<div class='home-content-tr'><table cellspacing='1' cellpadding='1' border='0'>";
    outputB += "<tr><td><img height='10' src='images/spacer.gif' width='1' border='0' /></td></tr>";
    outputB += "<tr><td><img height='32' alt='Based on your profile, we recommend the following events:' src='media/images/home_emp_Recommend.gif' width='227' border='0' /></td></tr>";
    outputB += "<tr><td><img height='10' src='images/spacer.gif' width='1' border='0' /></td></tr>";
    var alt_bgcolor = "#b2c396";
    var counter = 1;
    var offers = request.responseXML.getElementsByTagName('recommendedoffers').item(0).getElementsByTagName('offer');
    for (var i = 0; i < offers.length; i++) {
        var id = offers.item(i).getElementsByTagName('id')[0].firstChild.nodeValue;
        var name = offers.item(i).getElementsByTagName('name')[0].firstChild.nodeValue;
        outputA += "<div class='nav_over_content'><a href='/offers/detail?id=" + id + "&name=" + name + "'>" + name + "</a></div>";
        outputB += "<tr><td bgcolor=" + alt_bgcolor + ">&nbsp;<font color='#56653e'>" + counter + "&nbsp; <a style='TEXT-DECORATION: none' href='/offers/detail?id=" + id + "&name=" + name + "'><font color='#425721'><strong>" + name + "</strong></font></a></font></td></tr>";
        if (counter++ % 2) {
            alt_bgcolor = "";
        } else {
            alt_bgcolor = "#b2c396";
        }
    }
    if (offers.length < 1) {
        outputA = "<div class='nav_over_content'>No offers found</div>";
        outputB = "";
    } else {
        outputB += "<tr><td></td></tr>";
        outputB += "<tr><td>&nbsp;&nbsp; <img height='9' src='media/images/green_arrow_tran.gif' width='5' border='0' />&nbsp;<a href='/account/manage'><font color='#5f7846'>Manage Your Profile</font></a> </td></tr>";
        outputB += "</table></div>";

    }
    var divSearch = document.getElementsByTagName("div");
    for (var i = 0; i < divSearch.length; i++) {
        if (divSearch[i].className.toLowerCase() == "offer_wrapper1") {
            divSearch[i].innerHTML = outputA;
        }
        if (divSearch[i].className.toLowerCase() == "offer_wrapper2") {
            divSearch[i].innerHTML = outputB;
        }
    }
}

function togglePreferencesCheckBox(ckbox, size) {
    if (ckbox.checked) {
        //check all subcategories
        if (size > 0) {
            for (var i = 0; i < size; i++) {
                var subCatid = ckbox.id + i;
                var subCheckBox = document.getElementById(subCatid);
                subCheckBox.checked = true;
            }
        }
    } else {
        //uncheck all subcategories
        if (size > 0) {
            for (var i = 0; i < size; i++) {
                var subCatid = ckbox.id + i;
                var subCheckBox = document.getElementById(subCatid);
                subCheckBox.checked = false;
            }
        }
    }

}

function toggleTopCat(catid) {
    var topCatCkBox = document.getElementById(catid);
    topCatCkBox.checked = false;
}

//call AJAX onload
//var existingOnLoad = this.onload;
//this.onload = function() {
//	try {
//		existingOnLoad();
//	} catch(e) {}
//	makeRequest('/offers/myoffers?maxoffers=4', 'GET', null, 'displayRecommendedOffers')
//}

