/* --- Variables--- */
var browser=navigator.appName; /*GUI4*/

var isIE6 = false;
var isIE7 = false;
var opacityValue = "0.5";
var coIsAppend = false;
var isAssistantSubscrContLoaded = false;

$(document).ready(function(){
    if(jQuery.browser.msie) {
        if( jQuery.browser.version == "6.0" ) {
            isIE6 = true;
        }
        else if( jQuery.browser.version == "7.0" ) {
            isIE7 = true;
        }
    }

    /*Documentation located in navigation.js.doc in Dev Team Sharepoint */
    if (isAuthor() || (readCookie("MTIPCNTY") == getBrowsingCountry())){
        $('.estore').css("display","inline");
    }
    captureHttpReferrer();

    //send download clicks to eloqua
    if(typeof elqFCS == 'function'){
        $("a[onclick^='observeDownload']").click(function() {
            //alert("sending to eloqua: " + document.domain + $(this).attr("href"));
            elqFCS("http://" + document.domain + $(this).attr("href") + "?download=true");
        });
    }

	populateFooterSitemap();

	if(isIE6){
		$("input:radio").addClass("radio");
		$("input:checkbox").addClass("checkbox");
	}
});

//
// functions
//

function captureHttpReferrer() {
    var ckieReferrer = readCookie("MT_REFERRER");
    var referrer = document.referrer;
    if ((ckieReferrer == null || ckieReferrer != referrer)) {
        var idx = referrer.indexOf(".mt.com/");
        var qsidx = referrer.indexOf("?");
        if (idx < 0 || (idx > qsidx && qsidx > -1)) {
            createCookie("MT_REFERRER", document.referrer, null);
        }
    }
}

function getBrowsingCountry() {
    var split_url = document.URL.split('/');
    return isAuthor() ? split_url[4] : split_url[3];

}

function getBrowsingDomainCountryLanguage() {
    var split_url = document.URL.split('/');
    return isAuthor() ? split_url[0]+"//"+split_url[2]+"/"+split_url[3]+"/"+split_url[4]+"/"+split_url[5] : split_url[0]+"//"+split_url[2]+"/"+split_url[3]+"/"+split_url[4];
}

function isAuthor() {
    var split_url = document.URL.split('/');
    return split_url[3] == 'author';
}

//
// Cookie functions
//
function readCookie(name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';

    for (var i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == name )
        {
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                return unescape( decodeURI(a_temp_cookie[1]).replace(/^\s+|\s+$/g, '').replace(/\+/g,' ') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
        }
    }
    return null;
}

function readUTF8Cookie(name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';

    for (var i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == name )
        {
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                //console.log("1). ",a_temp_cookie[1]);
                //console.log("2). ",decodeURI(a_temp_cookie[1]));
                //console.log("3). ",decodeURI(a_temp_cookie[1]).replace(/^\s+|\s+$/g, '').replace(/\+/g,' '));
            	//console.log("4). ",decodeURI(a_temp_cookie[1]).replace(/^\s+|\s+$/g, '').replace(/\+/g,' ').replace(/%26/gi,"&").replace(/%3D/gi,"="));
            	//console.log("5). ",decodeURI(decodeURI(a_temp_cookie[1]).replace(/^\s+|\s+$/g, '').replace(/\+/g,' ').replace(/%26/gi,"&").replace(/%3D/gi,"=")));
            	var decodedString = decodeURI(a_temp_cookie[1]).replace(/^\s+|\s+$/g, '').replace(/\+/g,' ').replace(/%26/gi,"&").replace(/%3D/gi,"=");
            	return decodeURI(decodedString);
            }
            // note that in cases where cookie is initialized but no value, null is returned
        }
    }
    return null;
}

function createCookie(name, value, days) {
    var path = '/';

    createPathCookie(path, name, value, days);
}

function createPathCookie(path, name, value, days) {
    // set time, it's in milliseconds
    var today = new Date();
    // if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    var expires;
    if (days)
    {
        expires = days * 1000 * 60 * 60 * 24;
    }
    //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
    var expires_date = new Date( today.getTime() + (expires) );
    //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

    document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
        ( ( path ) ? ";path=" + path : "" );
}

function eraseCookie(name) {
    var path = '/';
    if (readCookie(name)) {
        document.cookie = name + "=" +
            ( ( path ) ? ";path=" + path : "") +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function createOmnitureCookie(cookieName, fieldNames){
	var dataString = "";
	for (var i = 0; i < fieldNames.length; i++ ){
		dataString = dataString + "&" + fieldNames[i] + "=" + $("[name=" + fieldNames[i] + "]").val();
	}
	if(dataString.length > 0){
		var encodedData = encodeURI(dataString);
		//create a session cookie (since no expiration length is provided, the code assumes session)
		createCookie(cookieName, encodedData);
	}
}

function createNonRegUserPrepopulateCookie(name){
	var dataString = "";
	$("#sharedQuestions input:text:visible").add("#sharedQuestions textarea:visible").each(function(index, element){
		if(element.value.length > 0 && !$(element).hasClass("suggestiveText")){
			dataString = dataString + "&" + element.name + "=" + element.value;
		}
	});
	$("#sharedQuestions input:radio:checked:visible").each(function(index, element){
		if(element.value.length > 0 && !$(element).hasClass("suggestiveText")){
			dataString = dataString + "&" + element.name + "=" + element.value;
		}
	});
	$("#sharedQuestions select:visible").each(function(index, element){
		if(element.selectedIndex != "undefined" && element.options[element.selectedIndex].value.length > 0){
			dataString = dataString + "&" + element.name + "=" + element.options[element.selectedIndex].value;
		}
	});
	if(dataString.length > 0){
		var encodedData = encodeURI(dataString);
		createCookie("NON_REG_USER_INFO",encodedData,90);
	}
}

function nonRegUserCookiePrepopulate(){
	var userInfoCookie = readUTF8Cookie("NON_REG_USER_INFO");
	if(userInfoCookie != null){
		var userData = userInfoCookie.substr(1);
		var userDataPairs = userData.split("&");
		for(k in userDataPairs){
			var nameValue = userDataPairs[k].split("=");
			//console.log("name:",nameValue[0]," value:",nameValue[1]);
			if(nameValue[0].length > 0 && nameValue[1].length > 0){
				var currentElement = $("[name="+nameValue[0]+"]");
				if(currentElement.is(":radio")){
					currentElement.find("[value="+nameValue[1]+"]").attr("checked","checked");
				}
				else{
					if(currentElement.not("[type=hidden]")){
						currentElement.val(nameValue[1]);
						if(nameValue[0] == "country"){
							updateOptInByCountry();
						}
					}
				}
			}
		}
	}
}


//
// Login functions
//
var cookieLOGGEDIN = readCookie('MT_LOGGEDIN');

function isLoggedIn() {
    cookieLOGGEDIN = readCookie('MT_LOGGEDIN');

    var loggedIn;

    if (cookieLOGGEDIN == 'true') {
        loggedIn = true;
    } else {
        loggedIn = false;
    }

    return loggedIn;
}

// checkLoggedInState() is called from footer.jsp
function checkLoggedInState() {
    if (isLoggedIn()) {
        showLoggedIn();
        setWelcomeMessage(decodeURI(readCookie('MT_LOGGEDIN_MSG')));
        $('img.secured').attr("src", function() {
            return this.src.replace(/images\/.*\.gif/, '/images/unlocked.gif');
        });
    } else {
        showLoggedOut();
        setWelcomeMessage("");
        $('img.secured').attr("src", function() {
            return this.src.replace(/images\/.*\.gif/, '/images/locked.gif');
        });
    }
}


function logout() {
    //alert('in logout()');
    eraseCookie('MT_LOGGEDIN');
    eraseCookie('MT_LOGGEDIN_MSG');
    checkLoggedInState();
    document.getElementById('logoutLink').submit();
}

var cookieVIPACCESS = readCookie("MT_LOGGEDIN_ACCESS");

/**BEGIN: VIP lock/unlock**/
$(document).ready(function(){
    var cookieVIPACCESS = readCookie("MT_LOGGEDIN_ACCESS");
    if(cookieVIPACCESS != null && cookieVIPACCESS.length > 0){
        $("span[class$=.securecontenticon.locked]").each(function (index) {
            var accessGroupLabel = $(this).attr("class").substr(0, $(this).attr("class").indexOf(".securecontenticon.locked"));
            if(cookieVIPACCESS.indexOf(accessGroupLabel) > -1){
                $("span[class=" + accessGroupLabel + ".securecontenticon.locked]").hide();
                $("span[class=" + accessGroupLabel + ".securecontenticon.unlocked]").show();
            }
        });
    }
});
/**END: VIP lock/unlock**/


function setWelcomeMessage(msg) {
    var msgWidth = $("#welcomeMsg").html(decodeURI(msg)).width();
    var loginWidth = $("#logoutLink").width();
    var wrapWidth = 289;
    if(isIE6 || isIE7){
        wrapWidth = 279;
    }
    //console.log("1). #loginLink width: ",loginWidth);
    //console.log("2). welcomeMsg width: ",msgWidth);
    //console.log("3). total width of status text: ",(msgWidth + loginWidth + 8),"\n\nwrapWidth: ",wrapWidth);
    //alert("total width of status text: "+(msgWidth + loginWidth + 8)+"\n\nwrapWidth: "+wrapWidth);
    if(msg != null && msg.length > 0 && (msgWidth + loginWidth + 8) > wrapWidth){
        $("#welcomeMsg").html("").hide();
        $("#loginLink").after("<div class='longWelcomeMessage'>" + decodeURI(msg) + "</div>");
        $("#logoutLink a:first").css("padding-left","0px");
    }
    else{
        $("div.longWelcomeMessage").html("").hide();
        $("logoutLink a").css("padding-left","8px");
    }
}

function showLoggedIn() {
    // hide
    $('#loginLink').hide();
    $('#countrySelect-container').hide();
    $('#newsMB').hide();
    // show
    $('#logoutLink').css("display","inline");
    $('#userProfile').slideDown();
}

function showLoggedOut() {
    // hide
    $('#logoutLink').hide();
    $('#userProfile').hide();
    // show
    $('#loginLink').css("display","inline");
    $('#countrySelect-container').show();
    $('#newsMB').show();
}

function observeDownloadParams(url, href, name, pageTitle, owner, secure) {
    $.ajax({
        type: "GET",
        url: url,
        data: ({
            useParams : true,
            href : href,
            name : name,
            pageTitle : pageTitle,
            owner : owner,
            secure : secure
        }),
        cache: false
    });
}

function observeDownload(url) {
    $.get(url);
}

function doSecureDownload(link, loginLink, observation) {
	if (cookieLOGGEDIN == 'true') {
		observeDownload(observation);
		window.open(link);
	} else {
		location.href = loginLink + '?quick';
	}
}

function doSecureDownloadParams(link, loginLink, url, href, name, pageTitle, owner) {
	if (cookieLOGGEDIN == 'true') {
		observeDownloadParams(url, href, name, pageTitle, owner, 'true');

		window.open(link);
	} else {
		location.href = loginLink + '?quick';
	}
}

function doAccessDownload(url, contentLink, loginLink, accessHandle, observation) {
	if (cookieLOGGEDIN == 'true') {
		//if(cookieVIPACCESS != null && cookieVIPACCESS.length > 0){
			//if(cookieVIPACCESS.indexOf(accessHandle) > -1){
				observeDownload(observation);
				window.open(url);
			//}
		//}
	} else {
		location.href = loginLink + '?quick';
	}
}

function doAccessDownloadParams(link, loginLink, url, href, name, pageTitle, owner) {
	if (cookieLOGGEDIN == 'true') {
		observeDownloadParams(url, href, name, pageTitle, owner, 'true');

		window.open(link);
	} else {
		location.href = loginLink + '?quick';
	}
}

function doSubscriptionsLogin(link, loginLink) {
	if (cookieLOGGEDIN == 'true') {
		window.open(link);
	} else {
		location.href = loginLink;
	}
}


//
// Menu functions
//

function openMenu(menuID,linkObj){
	if(um.ready){
		var coords = {'x' : um.getRealPosition(linkObj,'x'), 'y' : um.getRealPosition(linkObj,'y')};
		coords.y += (linkObj.offsetHeight + 0);
		coords.x += 1;
		um.activateMenu(menuID, coords.x + 'px', coords.y + 'px');
	}
}

function closeMenu(menuID){
	if(um.ready) {
		um.deactivateMenu(menuID);
	}
}

function observeBannerClick(banner) {
	$.get(banner);
}

//omniture ajax tracking
function omnitureAjaxTracking(propertyMap, url){
	for (var key in propertyMap) {
	    s[key] = propertyMap[key];
	}
	s.server = document.domain;
	s.eVar11 = s.prop2;
	s.eVar19 = propertyMap.prop13; // Site Section: 1
	s.eVar20 = propertyMap.prop14; // Site Section: 2
	s.prop17 = s.prop2 + " : " + propertyMap.prop5;
	s.hier1 = s.channel;
	void(s.t());
}

//omniture video tracking

/*Call on video load*/
function omniInitMediaTracking(mediaName,mediaLength,mediaPlayerName) {
	s.Media.open(mediaName,mediaLength,mediaPlayerName);
}

/*Call on video resume from pause and slider release*/
function omniMediaTrackingResume(mediaName,mediaOffset){
	s.Media.play(mediaName,mediaOffset);
}

/*Call on video pause and slider grab*/
function omniMediaTrackingStop(mediaName,mediaOffset){
	s.Media.stop(mediaName,mediaOffset);
}

/*Call on video end*/
function omniMediaTrackingDone(mediaName){
	s.Media.close(mediaName);
}

/*Begin: Video Settings*/
//http://www.rudishumpert.com/2009/08/19/one-player-to-rule-them-all/
var currentPosition = 0;
var currentVolume = 0;
var currentMute = false;
var currentState = "NONE";
var defaultState = "NONE";
var clipduration = 0;

var player = null;

function playerReady() {
	player = document.getElementById('jwplayer');
	addListeners();
}

function addListeners() {
	if (player) {
        addAllModelListeners();
    } else {
    	player = document.getElementById('jwplayer');
    	setTimeout("addListeners()",100);
    }
}

function addAllModelListeners() {
	 if (typeof player.addModelListener == "function") {
         player.addModelListener("BUFFER", "doNothing"); //{percentage,id,client,version}.
         player.addModelListener("ERROR", "doNothing"); //{message,id,client,version}.
         player.addModelListener("LOADED", "doNothing"); //{loaded,total,offset,id,client,version}.
         player.addModelListener("META", "doNothing"); //{variable1,variable2,variable3,...,id,client,version}.
         player.addModelListener("STATE", "stateListener");//{newstate,oldstate,id,client,version}.
         player.addModelListener("TIME", "positionListener"); //{position,duration,id,client,version}.
	}
}

function doNothing(obj) { //nothing
}

function positionListener(obj) {
	currentPosition = obj.position;
	clipduration = obj.duration;
	$("#vidposValue").html(currentPosition);
  	$("#vidtimevalue").html(clipduration);
}

function stateListener(obj) {
	oldState = obj.oldstate;

    if (defaultState == "NONE") {
    	//alert("started");
    	defaultState = "started";
    	getTimeValue();
    }
    currentState = obj.newstate;
    currentTime = getPosValue();
    if (currentState == "COMPLETED") {
  		omniMediaTrackingDone($("#videoFilePath").val());
  	  }
    if (currentState == "PLAYING") {
  		omniMediaTrackingResume($("#videoFilePath").val(),currentTime);
  	  }
    if (currentState == "PAUSED") {
  		omniMediaTrackingStop($("#videoFilePath").val(),currentTime);
  	  }
}

// you can not combine the listener events, so the functions below are a workaround to get the length/pos of the video file
function getTimeValue(){
	var tv = $("#vidtimevalue").html();
	if (tv == "0") {
		setTimeout("getTimeValue()",100);
		}
	else {
		omniInitMediaTracking($("#videoFilePath").val(),tv,'JW Player');
	}
}

function getPosValue() {
	var pv = $("#vidposValue").html();
	return pv;
}
/*End: Video Settings*/


// document.URL.split will enable the capture of either http or https prefixes.
// split_url[0] will equal either http or https.
var split_url = document.URL.split(':');
// document domain can get the domain for the server dynamically. EG. localhost or mt.com
var baseUrl = split_url[0] + '://' + document.domain;
var ie4 = false; if(document.all) { ie4 = true; }
var openImg = baseUrl + '/images_nav/open.gif';
var closeImg = baseUrl + '/images_nav/close.gif';

function getMBObject(id) {/* if (ie4) { return document.all[id]; } else { */ return document.getElementById(id); /*}*/}

function toggle(link, divId, state) {
    var obj1 = getMBObject(divId + "_open");
    var obj2 = getMBObject(divId + "_close");
    var d = getMBObject(divId);
    if (obj1 != null) {
        if (obj1.style.display=='') {
            obj1.style.display='none';
            obj2.style.display='';
            d.style.display = 'block';
        }
        else {
            if (state != 'open') {
                obj1.style.display='';
                obj2.style.display='none';
                d.style.display = 'none';
            }
        }
    }
}

function getObject(id) {
	return ie4 ? document.all[id] : document.getElementById(id);
}

function popup(url, height, width){
  window.open(url, "", "height=" + height + ",width=" + width + ",scrollbars=yes,menubar=no,resizable=yes,titlebar=no,status=no,toolbar=no,menubar=no,location=no");
}

// Email validator expression from
// http://www.breakingpar.com/bkp/home.nsf/Doc!OpenNavigator&U=87256B280015193F87256C40004CC8C6
function isEmailFieldInvalid(pTextObj) {
    var emailAddress = pTextObj.value;
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return !re.test(emailAddress);
}

/* used by checkTree */
function setChecked(bChecked,pChkID) {
  var formObj = document.profile_update;
  if (formObj != null) {
    var iElementLen = formObj.elements.length;
    var iLoop = 0;
    for( iLoop=0 ; iLoop < iElementLen; iLoop++) {
        if (formObj.elements[iLoop].id == pChkID) {
            formObj.elements[iLoop].checked = bChecked;
        }
    }
  }
}

/* used by checkTree */
function checkChildren(bChecked,pParentID) {
    var formObj = document.profile_update;
    if (formObj != null) {
        var iCheckboxLen = formObj.elements.length;
        var iLoop = 0;
        var iParentLen = pParentID.length;
        var sElementID = "";
        for( iLoop=0 ; iLoop < iCheckboxLen; iLoop++) {
            sElementID = formObj.elements[iLoop].id;
            if (sElementID.length > iParentLen) {
                if (sElementID.substring(0, iParentLen) == pParentID) {
                    if (! formObj.elements[iLoop].disabled ) {
                        formObj.elements[iLoop].checked = bChecked;
                    }
                }
            }
        }
    }
}

function checkTree(pCheckBox, checkParent) {
    if (window.navigator.appName=="Microsoft Internet Explorer" && parseInt(window.navigator.appVersion) >= 4 ){
        var sCurrentID = pCheckBox.id;
        var sSplit = "/"
        var iLastSplit = 0;
        var sParent = "";
        var sCurrentNode = pCheckBox.id;
        if (pCheckBox.checked) {
            if (checkParent) {
                iLastSplit = sCurrentNode.lastIndexOf(sSplit);
                while (iLastSplit > 0) {
                    sParent = sCurrentNode.substring(0,iLastSplit);
                    setChecked(true, sParent);
                    sCurrentNode = sParent;
                    iLastSplit = sCurrentNode.lastIndexOf(sSplit);
                }
            }
            checkChildren(true, sCurrentID + sSplit);
        } else {
            if (!checkParent) {
                //need to uncheck the parent
                iLastSplit = sCurrentNode.lastIndexOf(sSplit);
                while (iLastSplit > 0) {
                    sParent = sCurrentNode.substring(0,iLastSplit);
                    setChecked(false, sParent);
                    sCurrentNode = sParent;
                    iLastSplit = sCurrentNode.lastIndexOf(sSplit);
                }
            }
            checkChildren(false, sCurrentID + sSplit);
        }
    }
}

function isTxtFieldEmpty(pTextObj) {
    var fieldText = pTextObj.value.replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') ;
    return fieldText.length <= 0;
}

function limitChars(ta, n){
  return (ta.value.length < n);
}

/***
 * http://blog.firetree.net/2005/07/04/javascript-find-position/
 * */
function findPosX(obj)  {
    var curleft = 0;
    if(obj.offsetParent) {
        while(1) {
          curleft += obj.offsetLeft;
			if (!obj.offsetParent) {break;}
          obj = obj.offsetParent;
        }
    }
	else if (obj.x) {curleft += obj.x;}
    return curleft;
  }


function findPosY(obj)  {
    var curtop = 0;
	if (obj.offsetParent) {
        while(1)
        {
          curtop += obj.offsetTop;
			if (!obj.offsetParent) {break;}
          obj = obj.offsetParent;
        }
	}
	else {
		if (obj.y) {curtop += obj.y;}
	}
    return curtop;
}

function displayPopUpLayer (reference, elementId, center) {
    var xpos = findPosX(reference);
    var ypos = findPosY(reference);
    var box = document.getElementById(elementId);
    if (box != null) {
        box.style.display='block';
        box.style.position='absolute';
        box.style.top=ypos-20+'px';
        if (center) {
        	box.style.left=xpos-(box.offsetWidth/2)+20+'px';
        } else {
        	box.style.left=xpos+20+'px';
        }
    }
}

// Function : Script to close the pop-up layer
function closeMe (elementId) {
    var box = document.getElementById(elementId);
    if (box != null) {
        box.style.display='none';
    }
}

function showElement(elementName) {
	var element = getObject(elementName);

	if (element != null) {
		element.style.visibility='visible'
	}
}

function hideElement(elementName) {
	var element = getObject(elementName);

	if (element != null) {
		element.style.visibility='hidden'
	}
}

function display(elementName, displayType) { //display type is "block" or "inline",  by default "block"
    var element = getObject(elementName);
    if (element != null) {
        if (displayType != null) {
            element.style.display=displayType;
        } else {
            element.style.display='block';
        }
    }
}

function hide (elementName) {
    var element = getObject(elementName);
    if (element != null) {
        element.style.display='none';
    }
}

/* Function to allow the easy change of an elements class */
// not used
function changeClassOfId(id, newClass) {
	identity=document.getElementById(id);
	identity.className=newClass;
}

/**
The Ultimate getElementsByClassName
Written by Jonathan Snook, http://www.snook.ca/jonathan
**/
// ---
// Revised version May 11th 2007
//DEPRECATED use jquery library
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/-/g, "\-");
	var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

// ---
// Array support for the push method in IE 5
if(typeof Array.prototype.push != "function"){
	Array.prototype.push = ArrayPush;
	function ArrayPush(value){
		this[this.length] = value;
	}
}

function rotateBanners(mb) {
	var elements = jQuery("#bannerBlock-" + mb + " .rotate-banner");
	var ran_number= Math.floor(Math.random()*elements.size());
	var currentTeaserImage = 0;
	elements.each(function(index, domElement){
		if ( index == ran_number ) {
			jQuery(this).show();
        	if(elements.size() > 1){
        		mt_ShowNextItem("bannerBlock", "rotate-banner", mb, index);
        	}
        }
    });
}

function mt_ShowNextItem(wrapper, itemClass, id, startIndex) {
	/*Wait 10 seconds then run*/
	window.setTimeout(function () {
		jQuery("#" + wrapper + "-" + id + " ." + itemClass).hide();
		var nextIndex = startIndex + 1;
		var setSize = jQuery("#" + wrapper + "-" + id + " ." + itemClass).size();
		if(setSize > nextIndex){
			jQuery("#" + wrapper + "-" + id + " ." + itemClass).eq(nextIndex).fadeIn(2500);
			mt_ShowNextItem(wrapper, itemClass, id, nextIndex);
		}
		else{
			jQuery("#" + wrapper + "-" + id + " ." + itemClass).eq(0).fadeIn(2500);
			mt_ShowNextItem(wrapper, itemClass, id, 0);
		}
	},10000);
}

function rotateMSTeasers(num) {
	var elements = jQuery("#rotateMSTeasers-" + num + " .rotateMSTeaser");
	var ran_number= Math.floor(Math.random()*elements.size());
	var currentTeaserImage = 0;
	if(elements.size() > 1){
		elements.each(function(index, domElement){
			if ( index == ran_number ) {
				jQuery(this).show();
	        	if(elements.size() > 1){
	        		mt_ShowNextItem("rotateMSTeasers", "rotateMSTeaser", num, index);
	        	}
	        }
	    });
	}
	else{
		elements.show();
	}
}

function toggleField(id) {
	var field = document.getElementById(id);
	if (field.value == "true") {
		field.value="false";
	} else {
		field.value="true";
	}
}

function formatTime (time) {
	try  {
		var firstColon = time.indexOf(":");
		if (firstColon > -1 && time.length>firstColon+1) {
			var secondColon = time.indexOf(":", firstColon+1);
			if (secondColon > -1 && time.length > secondColon+1) {
				var space = time.indexOf(" ", secondColon+1);
				if (space > secondColon) {
					return time.substr(0, secondColon) + time.substr(space);
				} else {
					return time.substr(0, secondColon);
				}
			}
		}
	  }
	catch(err) {}
	return time;
}

/**
 * Begin: Country and Language Select Component (GUI4)
 */
$(document).ready(function(){

	// Open/Close Country Dropdown
    jQuery(".select_country").click(function(){
        jQuery("#dropdown_country").toggle();
        jQuery(this).addClass("active");
        jQuery(this).unbind("mouseleave");
        listenToKey();

        // Scrollbars vor Meta-Dropdown
        jQuery('#dropdown_country .scroll_area').jScrollPane({'scrollbarWidth' : '10'});

        jQuery("#dropdown_language").hide();
        jQuery(".select_language").removeClass("active");

        jQuery(".meta_table").mouseleave(function() {
            jQuery("#dropdown_country").hide();
            jQuery(".select_country").removeClass("active");
            jQuery(window).unbind("keydown");
            jQuery(window).unbind("scroll");
            jQuery(this).find("a").removeClass("scrolled_to");
        });

        jQuery("#dropdown_country a").click(function(){
            jQuery("#dropdown_country").hide();
            jQuery(".select_country").removeClass("active");
            var sContent = jQuery(this).clone();
            jQuery(".select_country .wrapper").html(sContent);
        });
    });
    function listenToKey() {

    	jQuery(document).keydown(function(event){
    		var keyMatchCounter = 0;
            if(keyMatchCounter == 0){
	    		var key = String.fromCharCode(event.which);
	            jQuery(".scroll_area a").removeClass("scrolled_to");
	            jQuery(".scroll_area a").each(function() {

	                var foundElement = jQuery(this);
	                var name = foundElement.find("span").html();//attr("rel");

                    if (name.indexOf(key) === 0) {
                        var offsetTop = foundElement.position().top;
                        jQuery("#dropdown_country .scroll_area")[0].scrollTo(offsetTop);
                        foundElement.addClass("scrolled_to");
                        jQuery(window).scroll(function(){
                            foundElement.removeClass("scrolled_to");
                        });
                        foundElement.mouseover(function(){
                            foundElement.removeClass("scrolled_to");
                        });
                        keyMatchCounter++;
                        return false;
                    }
                });
            }
        });
    }
    // Open/Close Language Dropdown
    jQuery(".select_language").click(function(){
        jQuery("#dropdown_language").toggle();
        jQuery(this).addClass("active");
        jQuery(this).unbind("mouseleave");
        jQuery("#dropdown_country").hide();
        jQuery(".select_country").removeClass("active");

        jQuery(".meta_table").mouseleave(function() {
            jQuery("#dropdown_language").hide();
            jQuery(".select_language").removeClass("active");
        });
        jQuery("#dropdown_language a").click(function(){
            jQuery("#dropdown_language").hide();
            jQuery(".select_language").removeClass("active");

             var sContent = jQuery(this).html();
            jQuery(".select_language .wrapper").html(sContent);
        });
    });

    if (browser == "Microsoft Internet Explorer") {

        jQuery(".select_language").mouseover(function(){
            jQuery(this).addClass("active");
        }).mouseleave(function(){
            jQuery(this).removeClass("active");
        });

        jQuery(".select_country").mouseover(function(){
            jQuery(this).addClass("active");
        }).mouseleave(function(){
            jQuery(this).removeClass("active");
        });
    }
});
/**
 * End: Country and Language Select Component (GUI4)
 */

/*Begin: Homepage Scripts*/
function esbuBoxHoverLink(){
$(document).ready(function(){
    // ESBU Box Mouseover and Links
    jQuery(".esbu_table tr.esbu_header td, .esbu_table tr.esbu_footer td").mouseenter(function(){
        if (!jQuery(this).hasClass("spacing")) {
            jQuery(this).find(".content").addClass("hover");
        }
    }).mouseleave(function(){
        if (!jQuery(this).hasClass("spacing")) {
            jQuery(this).find(".content.hover").removeClass("hover");
        }
    }).click(function(){
    	if (!jQuery(this).hasClass("spacing")) {
	    	var address = jQuery(this).find(".more_link a").attr("href");
	        window.open(address, '_self');
    	}
    });

});
}
/*End: Homepage Scripts*/

/**
 * Begin: Main Nav
 */
$(document).ready(function(){
    // Main Navigation - Open Dropdowns
    jQuery("#main_navi_layer li").mouseover( function() {
        jQuery(this).find(".dropdown").show();
        jQuery(this).find("a").addClass("active");
	}).mouseleave( function() {
		jQuery(this).find(".dropdown").hide();
		jQuery(this).find("a").removeClass("active");
	});
});
/**
 * End: Main Nav
 */

/**
 * Begin: Tabs
 */
$(document).ready(function(){
	prepareTabs();
});

function prepareTabs() {
	jQuery(".tab_navigation li a").mouseover(function(){
	    jQuery(this).parent().addClass("hover");

	    var id = jQuery(this).parents(".tab_navigation").attr("id");
	    var index = jQuery("#"+id+" a").index(this);

	    if (index > 0) {
	        var prev = index -1;
	        jQuery(this).parent().prev().addClass("no_border_hover");
	    }

	}).mouseleave(function(){

	    var id = jQuery(this).parents(".tab_navigation").attr("id");
	     var index = jQuery("#"+id+" a").index(this);
	    jQuery(this).parent().removeClass("hover");
	    if (index > 0) {
	        var prev = index -1;
	        jQuery(this).parent().prev().removeClass("no_border_hover");
	    }
	});

	jQuery(".newList").mouseleave(function(){
	    jQuery(this).hide();
	});

	// Tab-Navigation for Main-Content and Right-Content
	jQuery(".tab_navigation li a").click(function(){

	    var id = jQuery(this).parents(".tab_navigation").attr("id");
	    var index = jQuery("#"+id+" a").index(this);

	    jQuery("#"+id+" li").removeClass("no_border");
	    if (index > 0) {
	        var prev = index -1;
	        jQuery(this).parent().prev().addClass("no_border");
	    }
	});

	jQuery(".tab_navigation li.last").each( function() {
	    var iWidth = jQuery(this).width();
	    iWidth = iWidth -10;
	    jQuery(this).css("width", iWidth);
	});

}

$(document).ready(function() {
	// Opens the Product Family Popup-Info-Boxes by clicking on the "Plus"-Icon
    jQuery(".plus_table .plus_tab img.plus").click(function() {

        jQuery(".plus_table .plus_tab img.plus").attr("src", (isAuthor() ? "/author" : "") + "/images/button_plus.gif");

        if (jQuery(this).parent().parent().parent().parent().parent().parent().find(".popup_info").css("display") == "block") {

            // if Box is open, hide it and put it in the background
            jQuery(this).attr("src", (isAuthor() ? "/author" : "") + "/images/button_plus.gif");
            jQuery(this).css("z-index", "102");
            jQuery(this).parent().parent().parent().parent().parent().css("z-index", "101");
            jQuery(this).parent().parent().parent().parent().parent().parent().css("z-index", "100");
            jQuery(this).parent().parent().parent().parent().parent().parent().find(".popup_info").hide();
            jQuery(".thin_line_bottom").css("z-index", "1");
            jQuery(".anythingSlider").css("z-index", "1");

        } else {
            // Hide all other Info-Boxes
            hideAllOtherInfoBoxes();

            //if current selected element has no content, go fetch it
            //Note: I removed the .trim() method from the condition below because it was causing IE6 to break [Ben Zemmer 02-26-2010]
            if (jQuery(this).parents("td.info").find(".popup_info").html().indexOf("/images/ajax_loader.gif") > -1) {
            		var url = jQuery(this).parent().parent().parent().parent().parent().find("a").attr("href");
            		//todo: need regular expression to only replace the last .html
            		url = url.replace(".html", ".previewchildren.html");
            		isSortEnabled = false;
            		try{
            			jQuery(this).parents("td.info").find(".popup_info").load(url);
            		}
            		catch(err){
            			alert("there was an error loading the product content");
            		}
            }

            // Open Box of current selected Element
            jQuery(this).parent().parent().parent().parent().parent().parent().find(".popup_info").addClass("open")
            jQuery(this).attr("src", (isAuthor() ? "/author" : "") + "/images/button_minus.gif");

            // Set z-index to display current Box on Top
            jQuery(this).parent().parent().parent().parent().parent().parent().css("z-index", "190");
            jQuery(this).parent().parent().parent().parent().parent().css("z-index", "200");
            jQuery(this).css("z-index", "210");

            // Display current Box
            jQuery(this).parent().parent().parent().parent().parent().parent().find(".popup_info").show();
        }
    });


});

function hideAllOtherInfoBoxes(){
	jQuery(".popup_info.open").hide();

    // Set z-index to put other Boxes in the background
    jQuery(".popup_info").css("z-index", "76");
    jQuery(".popup_info").parent().css("z-index", "75");
    jQuery(".popup_info").parent().parent().css("z-index", "10");
    jQuery(".matching_box").css("z-index", "-1");
    jQuery(".thin_line_bottom").css("z-index", "-1");
    jQuery(".anythingSlider").css("z-index", "-1");

    jQuery(".popup_info.open").removeClass("open");
}

function preselectMainTab(paramTab){
	var activeTabId = "";
	var activeTabIndex = 0;
	if(paramTab != null && paramTab.length > 0){
		activeTabId = paramTab;
		if(activeTabId.length > 0){
			$("#main_tabs li").each(function(index, element){
				if((activeTabId+"_li") == element.id){
					activeTabIndex = index;
				}
			});
		}
	}
	// Set Up: Implementation and config options for the idTabs jQuery library
	$("#main_tabs").idTabs({ start:activeTabIndex, change:false },false);
	if(activeTabId.length > 0){
		window.setTimeout(function () {
			// Default scroll position to top
			windowScrollTop();
		},500);
	}
}


/**
 * Main Tabs:
 * @name: preselectMainTabViaURL
 * This function looks for the tab id as a string value set off by a hash in the url.
 * If none is present, default the active state to the first visible tab.
 **/
function preselectMainTabViaURL(){
	var activeTabId = "";
	if(window.location.hash != null && window.location.hash.length > 0){
		activeTabId = window.location.hash.replace("#","");
		if(activeTabId.indexOf("?") > -1){
			activeTabId = activeTabId.substr(0,activeTabId.indexOf("?"));
		}
	}
	preselectMainTab(activeTabId);
}



/**
 * Main Tabs:
 * @name: noContentPresentHideTab
 * This function is called in two cases (both are necessary).
 * 1). At the begining of the ptabs component (/components/ptabs/start.jsp) to check if any of the tabs were not loaded
 * 2). Inside individual tabs to check if given containers inside the tab do not have any content
 **/
function noContentPresentHideTab(tabId, selectorString) {
	if(isHideTabsEnabled() && selectorString != null && selectorString.length > 0 && tabId != null && tabId.length > 0){
		// Strip out all HTML content, line breaks, and spaces
		var strippedTabContent = $(selectorString).html().replace(/<\/?[^>]+(>|$)/g, "");
		strippedTabContent = strippedTabContent.replace(/\s/g, "");
		// If there is no text, Hide the Tab and its Content
		if(strippedTabContent == ""){
			// Hide the Tab Item
			$(tabId).hide();
			// Hide the Content Container
			var currentTabContainer = tabId.replace("_li","");
			$(currentTabContainer).hide();
			// If the current tab being hidden was set to selected, default the selected style to the first available tab
			if($(tabId).hasClass("selected")){
				$(tabId).removeClass("selected");
				showNextAvailableMainTab();
			}
		}
	}
}
function isHideTabsEnabled(){
	var isHideTabsEnabled = true;
	if(isAuthor()){
		var authorViewingMode = readCookie("Show");
		(authorViewingMode != null && authorViewingMode == "ShowMode") ? isHideTabsEnabled = true : isHideTabsEnabled = false;
	}
	return isHideTabsEnabled;
}
function showNextAvailableMainTab(){
	var newTabContainerId = $("#main_tabs li:visible").eq(0).addClass("selected").attr("id").replace("_li","");
	$("#"+newTabContainerId).show();
}

/**
 * Main Tabs:
 * @Name: noTagPresentHideTab
 * 1). this function checks inside a given container inside specified tabs to see if there is no match for the specified html tag
 * 2). this function cannot be merged with the "noContentPresentHideTab" function because there are certain cases where
 *     there will be text within specified container (ie. <h2> tags), but the Tab still needs to be hidden.
 **/
function noTagPresentHideTab(tabId, selectorString, htmlTag){
	if(isHideTabsEnabled() && tabId != null && tabId.length > 0 && selectorString != null && selectorString.length > 0 && htmlTag != null && htmlTag.length > 0){
		var numberOfSelectorsWithContent = 0;
		$(selectorString).each( function(index, element) {
			if($(element).find(htmlTag).size() > 0){
				numberOfSelectorsWithContent = numberOfSelectorsWithContent + 1;
			}
			else{
				/*There may be other selectors with content on this tab. But, since this selector does not have any content, it must be hidden*/
				$(element).hide();
			}
		});
		if(numberOfSelectorsWithContent == 0){
			/* Hide the current tab if the content returned by the selector string (or both selector strings if applicable) does not contain the specified html element*/
			$("#"+tabId+"_li").hide();
			$("#"+tabId).hide();

			// If the current tab being hidden was set to selected, default the selected style to the first available tab
			if($("#"+tabId+"_li").hasClass("selected")){
				$("#"+tabId+"_li").removeClass("selected");
				$("#main_tabs li:visible").eq(0).addClass("selected");
				var firstAvailableTabContentContainer = $("#main_tabs li:visible").eq(0).attr("id").replace("_li","");
				$("#"+firstAvailableTabContentContainer).show();
			}
		}
	}
}

/**
 * Matching Block Tabs:
 * @name: testForEmptyMBTabs
 * This function checks for a lack of <li> elements inside tabbed matching block content.
 **/
function testForEmptyMBTabs() {
	if(isHideTabsEnabled()){
		$("div[id^=mbtab_]").each(function (index, element) {
			var numberOfListItems = $(element).find("div.center div.inner_content ul li").size();
			// If the Content of a Tab is Empty Hide the Tab and its Content
			if(numberOfListItems == 0){
				// Hide the Tab Item
				$("#right_tabs li").eq(index).hide();

				// Hide the Tab Content Container
				$(element).hide();

				// If the first tab (which is selected by default) has blank content display the very next tab
				if(index == 0){
					$("#right_tabs li").eq(1).addClass("selected");
					$($("#right_tabs li a").eq(1).attr("href")).show();
				}

				// If all the tabs have been hidden, hide the containing <ul> container as well.
				// Note: Expect <li class="hidden"></li> at the end of every list. That is why the <ul> is hidden if there are 1 or less <li> tags.
				if($("#right_tabs li:visible").size() <= 1){
					$("#right_tabs").hide();
				}
			}
		});
		// If there are no tab <li> tags, hide the containing <ul> tag
		// Note: Expect <li class="hidden"></li> at the end of every list. That is why the <ul> is hidden if there are 1 or less <li> tags.
		if($("#right_tabs li").size() <= 1){
			$("#right_tabs").hide();
		}
	}
}
/**
 * End: Tabs
 */

/**
 * Begin: Assistant Box
 */
$(document).ready(function() {

    // Varibales for Assistant Box Functionality
    var lastClickedLink;
    var width = $(".expandable_link_list li a.exp_link:first").width();
    var contentWidth;

    // Assistant Box
    $(".expandable_link_list li a.exp_link").click(function() {

        var element = $(this);

        contentWidth = $(this).parent().find(".assistant_content").width();

        closeOtherInfos($(this));
        openAssitantInfo($(this));

        $(this).unbind("click");

        $(this).click(function(){
            closeThisBox($(this));
        });

    });

    // Assistant Box - Close Other Infoboxes and List Elements
    function closeOtherInfos(clickedElement) {

		/* start - update - 2010-04 08 - fz */
		if(coIsAppend) {
			setDefaultValues();
		}
		/* end - update - 2010-04 08 - fz */

        $(document).unbind("click");

        var oPanel = clickedElement.parent().parent();

        oPanel.find("a.exp_link.open").css("width", width);

        oPanel.find("a.exp_link.open").click(function() {

        	closeOtherInfos($(this));
            openAssitantInfo($(this));

            $(this).unbind("click");

            $(this).click(function(){
                closeThisBox($(this));
            });

        });


        oPanel.find("a.exp_link").removeClass("open");
        oPanel.find("li").removeClass("open");
        oPanel.find(".assistant_content").css("display", "none");
        oPanel.find("a").stop();
        oPanel.find(".assistant_content").stop().hide();

    }

    function showOverlay() {
        // Dark Background
        jQuery("#popup_overlay").css("display", "block");
		/* start - update - 2010-04 08 - fz */
        jQuery("#popup_overlay").css("opacity", opacityValue);
        /* end - update - 2010-04 08 - fz */
        _centerOverlay();
        _resizeOverlay($(window).width());
        jQuery(window).scroll(function(){ $scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay($(window).width()); });
		jQuery(window).resize(function(){ _centerOverlay(); _resizeOverlay($(window).width()); });
    }


    //Assistant Box - Open Infobox for Clicked Element
    function openAssitantInfo(clickedElement) {
		/* start - update - 2010-04 08 - fz */
		jQuery("#mood_layer.blue").css("border-rightt", "1px solid #7F7F7F");
		jQuery("#mood_layer").css("border-right", "1px solid #7F7F7F");
		jQuery("#popup_overlay").css("z-index","19");
		jQuery("#main_layer").css("z-index","22");
		jQuery("#mood_navigation").css("z-index","19");
		jQuery("#header_layer").css("z-index","18");
		hideAllOtherInfoBoxes();
		if(!coIsAppend) {
			if( ! (isIE6 || isIE7) ) {
				jQuery("#main_layer").append("<div class=\"contentOverlay\"></div>");
			}
			coIsAppend = true;
        }
		if( isIE6 ) {
			jQuery("#main_layer").css("padding-bottom","0");

			jQuery("#top_meta_layer").css("z-index","15");

			jQuery("#popup_overlay").css("z-index","-1");

			jQuery("#header_layer").append("<div class=\"contentOverlay\"></div>");
			jQuery("#header_layer .contentOverlay").css("height", "400px");

			jQuery("#main_navi_layer").append("<div class=\"contentOverlay\"></div>");
			jQuery("#main_navi_layer .contentOverlay").css("height", "36px");

			jQuery("#frame_layer").append("<div class=\"contentOverlay\"></div>");
			jQuery("#frame_layer").css("background", "#fff");
			jQuery("#frame_layer .contentOverlay").css("height", "25000");
			jQuery("#frame_layer .contentOverlay").css("width", "1009");
			jQuery("#frame_layer .contentOverlay").css("top", "-5");
			jQuery("#frame_layer .contentOverlay").css("left", "-32");

			jQuery("#stage").css("overflow-y","hidden");

			jQuery(".contentOverlayML").css("display", "block");
			jQuery(".contentOverlayML").css("opacity", opacityValue);
		}
		if( isIE7 ) {
			jQuery("#header_layer").append("<div class=\"contentOverlay\"></div>");

			jQuery("#top_meta_layer").css("z-index","15");

			jQuery("#main_navi_layer").append("<div class=\"contentOverlay\"></div>");
			jQuery("#main_navi_layer .contentOverlay").css("height", "36px");

			jQuery("#frame_layer").append("<div class=\"contentOverlay\"></div>");
			jQuery("#frame_layer").css("background", "#fff");
			jQuery("#frame_layer .contentOverlay").css("height", "25000");
			jQuery("#frame_layer .contentOverlay").css("width", "1009");
			jQuery("#frame_layer .contentOverlay").css("top", "-5");
			jQuery("#frame_layer .contentOverlay").css("left", "-32");

			jQuery("#stage").css("overflow-y","hidden");

			jQuery("#popup_overlay").css("z-index","-1");
		}
		jQuery(".contentOverlay").css("display", "block");
        jQuery(".contentOverlay").css("opacity", opacityValue);
        showOverlay();
		/* end - update - 2010-04 08 - fz */

        contentWidth = clickedElement.parent().find(".assistant_content").width();

        clickedElement.addClass("open");
        clickedElement.parent("li").addClass("open");
        clickedElement.css("width", "193px");

        clickedElement.animate({ width: contentWidth+width-6 }, 500, null, function(){

        	clickedElement.next(".assistant_content").slideDown("normal", function() {

        		/**
        		 * eNewsletter Slideout
        		 * Handle IE bug where the onSubscriptionLoad() function call is not made the first time the slideout is clicked
        		 **/
				var clickedElementParent = clickedElement.parent();
        		if(clickedElementParent.attr("id").length > 0 && clickedElementParent.attr("id").indexOf("_SubscribeTo") > -1){
        			window.setTimeout(function () {
        				$("#assistant_SubscribeTo_content").append("<input type='hidden' id='Assistant_eNewsletter_Debug02_animationSuccess' value='INFO: @navigation.js.  The subscription (enewsletter) slideout animation has completed.  The following logic will now check to see if the onSubscriptionLoad() function has already been called'/>");
        				$("#assistant_SubscribeTo_content").append("<input type='hidden' id='Assistant_eNewsletter_Debug02b_onsubscription_called_"+isAssistantSubscrContLoaded+"' value='INFO: @navigation.js.  Has the onSubscriptionLoad() function already been called'/>");
        				// Check to see if the Subscription specific logic has been executed already
            			if(!isAssistantSubscrContLoaded){
            	    		// Since the logic has not been executed, run the call again.
            				onSubscriptionLoad();
            				$("#assistant_SubscribeTo_content").append("<input type='hidden' id='Assistant_eNewsletter_Debug03_firstcallFailure' value='INFO: @navigation.js. The onSubscriptionLoad() function was just called a second time because the function call on enewsletter/start.jsp did not run.'/>");
            	    	}
        			},200);
        		}
        		
        		// Close Open Panel by clicking outside the box
                $(document).click(function(event) {

                	var cTgr = $(event.target);

                	// Check if Element is inside Current Assistant-Content
                    if (cTgr.parents(".expandable_link_list").length) {

                    }
                    else {
                        closeOtherInfos(clickedElement);
                    }

                });

            });

        });

    }

    function closeThisBox(clickedElement) {

    	clickedElement.next(".assistant_content").slideUp("fast", function() {

    		clickedElement.removeClass("open");
    		clickedElement.parent().removeClass("open");
    		clickedElement.animate({width: width}, 500, null, function() {

               clickedElement.click(function() {
            	   closeOtherInfos($(this));
            	   openAssitantInfo($(this));

                   $(this).unbind("click");

                   $(this).click(function() {
                       closeThisBox($(this));
                   });

               });

           });

        });
		/* start - update - 2010-04 08 - fz */
		setDefaultValues();
		/* end - update - 2010-04 08 - fz */
   }

	/* start - update - 2010-04 08 - fz */
	function setDefaultValues() {
		jQuery("#popup_overlay").hide();
		jQuery("#popup_overlay").css("z-index","9500");
		jQuery("#main_layer").css("z-index","10");
        jQuery(".contentOverlay").css("display", "none");
		jQuery(".contentOverlay").remove();
		jQuery("#main_layer").css("padding-bottom","5px");
		jQuery("#mood_layer.blue").css("border-right", "1px solid #fff");
		jQuery("#mood_layer").css("border-right", "1px solid #fff");
		jQuery(".plus_tab").css("z-index","100");
		jQuery("#mood_navigation").css("z-index","60");
		jQuery("#header_layer").css("z-index","20");
		jQuery("#top_meta_layer").css("z-index","500");
		if( isIE6 ) {
			jQuery("#main_layer .contentOverlayML").remove();
			//jQuery("#footer_layer").css("overflow","auto");
		}
		if( isIE7 ) {
			jQuery("#main_layer .contentOverlayML").remove();
		}
		coIsAppend = false;
	}
	/* end - update - 2010-04 08 - fz */

});

function makeEsbuBoxClickable(){
    // ESBU Box Mouseover and Link (old version)
    jQuery(".esbu_box").mouseover(function(){
        jQuery(this).addClass("hover");
    }).mouseleave(function(){
        jQuery(this).removeClass("hover");
    }).click(function(){
		/* start - update - 2010-04 08 - fz */
        var address = "";
		if(jQuery(this).find(".more_link a").attr("href")) {
			address = jQuery(this).find(".more_link a").attr("href");
		}
		else {
			address = jQuery(this).find(".esbu_link a").attr("href");
		}
        window.open(address, '_self');
		/* end - update - 2010-04 08 - fz */
    });
}
/**
 * End: Assistant Box
 */

/** Feedback Button Overlay **/
jQuery(document).ready(function() {
	transformFeedbackLinksToPopupLinks("a.fb-button-gui4");
	transformFeedbackLinksToPopupLinks("a.fb-button");
	transformFeedbackLinksToPopupLinks("a.action_button2");
});
function transformFeedbackLinksToPopupLinks(selector){
	if(selector == "a.fb-button-gui4"){	
		preventContentBoxFbButtonWraping();
	}
	
	$(selector).each(function(index, element){
		var href = element.href;
		element.href = "javascript:void(0);";

		//console.log("href: ",href);

		$(element).click(function(){
			windowScrollTop();
			showPopup(buildPopupFeedbackHTML(href));
		});
	});
}

function preventContentBoxFbButtonWraping(){
	/*Note: the logic below is used to gracefully handle label values that cause the buttons to exceed the width of their containers*/
	var totalWidth = 0;
	var newHtml = "";
	$(".cont_box_right .cont_box_btn_wrpr").each(function(index){
		var currentElement = $(this);
		totalWidth = totalWidth + $(this).width();
		newHtml = newHtml + "<tr><td class='cont_box_btn_wrpr' valign='top'>" + $(this).html() + "</td></tr>";
	});
	if(totalWidth > 282){
		$(".cont_box_right .cont_box_btns_wrpr").html("<tbody>"+newHtml+"</tbody>");
	    if(isIE7){
	        $(".cont_box_right .fb-button-wrapper").each(function(index, element){
	            var thisElement = $(element);
	            thisElement.css("width",(thisElement.width()+20)+"px");
	        });
	    }
	}
}

function buildPopupFeedbackHTML(url){
	var modifiedUrl = url.replace(".html",".excludeWrappers");
	return "<div class='popup_top'><div class='top_right popup_close'></div><div class='top_left'></div><div class='top_middle'></div></div><div class='overlay_center'><div class='iframe_contents_wrapper'><div class='align_center' id='feedback_popup_loading'><img src='"+(isAuthor() ? "/author" : "")+"/images/ajax_loader.gif'></div><iframe frameborder='0' scrolling='no' hspace='0' src='"+modifiedUrl+"' id='feedback_popup_frame' name='feedback_popup_frame'> </iframe></div></div><div class='popup_bottom'><div class='bottom_left'></div><div class='bottom_right'></div><div class='bottom_middle'></div></div>";
}

/*Feedback Form Error Message Bubble*/
function showErrorMsgBbl(element){
	if(!$("[name="+element.name+"]").hasClass("valid")){
		var position = $(element).position();
		var msg = $(element).siblings("label.error").text();
		if(msg.length == 0){
			window.setTimeout(function () {
				msg = $(element).siblings("label.error").text();
				positionErrorMsgBbl(element, position, msg);
			},100);
		}
		else{
			positionErrorMsgBbl(element, position, msg);
		}
	}
}
function positionErrorMsgBbl(element, position, msg){
	$("#errorMsgBbl").css({'top':position.top,'left':position.left}).show().find("#errorMsgTxt").text(msg);
	var errorMsgBbl_padding_top = parseInt($("#errorMsgBbl").css("padding-top").replace("px",""));
	var errorMsgBbl_padding_bottom = parseInt($("#errorMsgBbl").css("padding-bottom").replace("px",""));
	var label_height = 14;
	if(isIE7){label_height = 10;}
	if(isIE6){label_height = 8;}
	var errorMsgBbl_height = $("#errorMsgBbl").height() + errorMsgBbl_padding_top + errorMsgBbl_padding_bottom;
	var errorMsgBbl_offset = errorMsgBbl_height + label_height;
	var errorMsgBbl_top_offset = position.top-(errorMsgBbl_offset);
	$("#errorMsgBbl").css({'top':errorMsgBbl_top_offset,'left':position.left});
	if(isIE6){
		// IE6 work around for selectboxes showing through the bubble
		$("#errorMsgBbl").bgiframe();
	}
}
/*Feedback Form Validation Callbacks*/
function feedbackFormFocusInCallback(element){
	// signal this element as the current element
	$(element).addClass("element_in_focus");

	// create and position error message bubble
	if($(element).hasClass("error")) {
		showErrorMsgBbl(element);
	}
}
function feedbackFormFocusOutCallback(element){
	// hide error message bubble
	$("#errorMsgBbl").hide();
}
function feedbackFormHighlightCallback(element){
	if(element.name.length > 0){
		// store label element
		var field_label;
		// add error styling to the field label
		if($(element).siblings("label.field_label").size() > 0){
			field_label = $(element).siblings("label.field_label").addClass("field_error");
			$("[name="+element.name+"]").siblings(".field_inline_label").addClass("field_error");
		}
		else{
			if(!$(element).parent().hasClass("nosee_secure")) {
				field_label = $(element).parent().siblings("label.field_label").addClass("field_error");
				$("[name="+element.name+"]").siblings(".field_inline_label").addClass("field_error");
			}
		}
		// Show error message when user hovers over the label/input field pair
		var hoverTarget = $(element).parents("div.field_pair:eq(0)");
		$(hoverTarget).hover(
			function(){
				showErrorMsgBbl(element);
				$(element).addClass("element_in_focus");
			},
			function(){
				$("#errorMsgBbl").hide();
				$(element).removeClass("element_in_focus");
			}
		);
		if($(element).hasClass("element_in_focus")){
			showErrorMsgBbl(element);
		}
	}
}
function feedbackFormUnhighlightCallback(element){
	// remove error styling from the field label
	if($(element).siblings("label.field_label").size() > 0){
		$(element).siblings("label.field_label").removeClass("field_error");
		$("[name="+element.name+"]").siblings(".field_inline_label").removeClass("field_error");
		if($("[name="+element.name+"]").hasClass("element_in_focus")){
			$("#errorMsgBbl").hide();
		}
	}
	else{
		if(!$(element).parent().hasClass("nosee_secure")) {
			$(element).parent().siblings("label.field_label").removeClass("field_error");
			$("[name="+element.name+"]").siblings(".field_inline_label").removeClass("field_error");
		}
	}
}
function feedbackFormShowLabelCallback(element){
	// apply error styling to the field label
	$(element).siblings("label.field_label").addClass("field_error");
	$("[name="+element.name+"]").siblings(".field_inline_label").addClass("field_error");
}
function validateAllPreceedingFields(currentElement) {
	var jqCurrentElem = $(currentElement);
	jqCurrentElem.addClass("active");
	var isCurrentElemRequired = true;
	if(!jqCurrentElem.hasClass("required")){
		// since the current form element is not a required field, find the next closest required field
		if(jqCurrentElem.parent().siblings().find(".required").size() > 0){
			closestSibling = (jqCurrentElem.parent().siblings().find(".required").size() - 1);
			currentElement = jqCurrentElem.parent().siblings().find(".required").get(closestSibling);
		}
		else if(jqCurrentElem.parent().parent().siblings().find(".required").size() > 0){
			closestSibling = (jqCurrentElem.parent().parent().siblings().find(".required").size() - 1);
			currentElement = jqCurrentElem.parent().parent().siblings().find(".required").get(closestSibling);
		}
		isCurrentElemRequired = false;
	}
	var requiredElemNameValuePairs = {};
	$("#feedbackForm .required").each(function(index, element){
		var iterElem = $(element);
		if(isCurrentElemRequired){
			// validate all fields to the left or above the active field
			if(element.name == currentElement.name){
				return false;
			}
			if(element.name.length > 0 && requiredElemNameValuePairs[element.name] == null){
				requiredElemNameValuePairs[element.name] = element.value
			}
		}
		else{
			// if the active field is not required, then validate all fields to the left or above this field (including the closest required field)
			if(element.name.length > 0 && requiredElemNameValuePairs[element.name] == null){
				requiredElemNameValuePairs[element.name] = element.value
			}
			if(element.name == currentElement.name){
				return false;
			}
		}
	});
	for(nameKey in requiredElemNameValuePairs){
		$("#feedbackForm").validate().element($("[name="+nameKey+"]"));
	}
}
function clearFeedbackSuggestiveText(){
	$(".suggestiveText").val("").removeClass("suggestiveText");
}
function popuplateSuggestiveFeedbackText(name,value){
	$("[name="+name+"]").val(value).addClass("suggestiveText").focus(function(){
        var element = $(this);
		if(element.hasClass("suggestiveText")){
			element.val("").removeClass("suggestiveText");
		}
    }).blur(function(){
        if(this.value.length == 0){
            $(this).val(value).addClass("suggestiveText");
        }
    });
}
function popuplateFeedbackText(name,value){
	$("[name="+name+"]").val(value).blur(function(){
        if(this.value.length == 0){
            $(this).val(value);
        }
    });
}
function fixFaultyFeedbackTitleWrapInIE(){
    if(isIE6 || isIE7){
    	$(".feedbackTitle .title_part").each(function(){
    		if($(this).width() > 685){
    			$(this).css("white-space","normal");
			}
        });
	}
}


/**
 * Begin: Mood Area
 */

/**
 * function getMood()
 * param - id
 * templates/mood.jsp sets up the mood array
 * components/moodimage/start.jsp populates the array with each mood
 * This function returns the array object representing the mood that matches the given id.
 */
function getMood(id) {
	for (i=0; i < moods.length; i++) {
		var mood = moods[i];
		if (mood.id == id) {
			return mood;
		}
	}
	return null;
}

/**
 * function selectMood()
 * returns a randomly selected mood object from the moods array
 */
function selectMood() {

	if (moods != null) {
		var numMoods = moods.length;
		if (numMoods > 0) {
			var randomNum = Math.floor(Math.random() * numMoods);
	        var moodEl = moods[randomNum];
	        return moodEl;
		}
		else {
			return null;
		}
	}
}

/**
 * function showMood()
 * displays the mood with the given id
 * @param id
 * @return
 */
function showMood(id) {
	var mood = getMood(id);

	//hide other moods
	$('.mood').hide();

	//set up src attribute of mood image
	$('#mood-'+mood.id+'-image').attr('src', mood.img);


	if (isAuthor()) {
		//configure mood links for authoring
		$('#mood_links').children().css('text-decoration', 'underline');
		$('#mood_links').children().css('font-weight', 'normal');
		$('#mood_' + mood.id + '_link').css('text-decoration', 'none');
		$('#mood_' + mood.id + '_link').css('font-weight', 'bold');

	}


	//set title style
	$('#mood_navigation').removeClass();
	$('#mood_navigation').addClass(mood.titlestyle);

	//show mood
	$('#mood-'+mood.id).show();
}

/**
 * function initializeMood()
 * Called on document.read in the mood template to select and display a mood.
 * @return
 */
function initializeMood() {
	var mood;
	var cookieVal = readCookie('mood');
	if (cookieVal == null) {
        mood = selectMood();
        if (mood != null) {
	        var url = document.location.href;
	        var uri = url.substr(url.indexOf('/', 7), url.length);
            createPathCookie(uri, 'mood', mood.id + ';' + mood.titlestyle, null);
        }
	}
	else {
		//get mood from cookie
		var moodOptions = cookieVal.split(';');
		var cookieMoodId = moodOptions[0];

		mood = getMood(cookieMoodId);
		//if mood in cookie does not exist, select a new one randomly
		if (mood == null) {
		    mood = selectMood();
		    if (mood != null) {
		    	var url = document.location.href;
		        var uri = url.substr(url.indexOf('/', 7), url.length);
		        createPathCookie(uri, 'mood', mood.id + ';' + mood.titlestyle, null);
		    }
		}
	}

	if (mood != null) {
		showMood(mood.id);
	}
}



/**
 * Begin: Popup (Mood - Flash/Video Popup)
 */
/* --- Functions and Variables for the Popup and Overlay --- */
var doresize = false;

//Set overlay dimensions
function _resizeOverlay(browserWidth) {

	if(popupContentWidth < browserWidth){
		$("#popup_overlay").css({
			'height':$(document).height(),
			'width':$(window).width()
		});
	}
	else{
		$("#popup_overlay").css("height",$(document).height()+"px");
	}

}

//keep Overlay centered (ie. while scrolling )
function _centerOverlay() {

	if(jQuery.browser.opera) {
		windowHeight = window.innerHeight;
		windowWidth = window.innerWidth;
	}
	else{
		windowHeight = $(window).height();
		windowWidth = $(window).width();
	};

	if(doresize) {

		$pHeight = $("#popup").height();
		$pWidth = $("#popup").width();
		$tHeight = $("#popup_overlay").height();

		projectedTop = (windowHeight/2) + $scrollPos['scrollTop'] - ($pHeight/2);

		if(projectedTop < 0) projectedTop = 0 + $tHeight;

		$("#popup_overlay").css({
			'top' : projectedTop - $tHeight/2}
		);

	};

}

var cqEditBarHeight = 0;
$(document).ready(function(){
	if ($("#CFCToolBarDiv a[href=http://www.day.com]").size() > 0 && location.href.indexOf("/global/") > -1){
		cqEditBarHeight = 53;
	}
});

//Opens the Popup-Layer with dark Background-Overlay

var popupContentWidth = 0;

function showPopup(feedbackForm) {

	$("#popup_overlay").fadeIn("fast", function() {

		if(feedbackForm != null && feedbackForm.length > 0){
			$("#popup").html(feedbackForm);
			$("#popup").css("width","750px");

			$('#feedback_popup_frame').load(function()
				{
					try {
						// Set inline style to equal the body height of the iframed content.
						$(this).height((this.contentWindow.document.body.offsetHeight + cqEditBarHeight) + 'px');
						$("#feedback_popup_loading").hide();
					} catch(err) {
						var bh = $(document).height();
						$(this).height(bh + 'px');
						$("#feedback_popup_loading").hide();
					}
				}
			);
		}

        var browserHeight = $(document).height();
        var browserWidth = $(window).width();
        var contentWidth = $("#popup").width();
        var contentHeight = $("#popup").height();

        var posLeft = (browserWidth - contentWidth)/2;
        var posTop = (browserHeight - contentHeight)/2;

        $("#popup").css("left", posLeft );
        $("#popup").fadeIn("fast");

        centerOverlayWidth(browserWidth);

        jQuery("#popup_overlay").fadeTo("fast", opacityValue);

        _centerOverlay();
        _resizeOverlay(browserWidth);

        setOverlayWidthForIE();

        $(window).scroll(function(){$scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay($(window).width());});
		$(window).resize(function(){_centerOverlay(); _resizeOverlay($(window).width());});

        $(document).keydown(function(event) {

            if (event.which == 27) {
                $("#popup_overlay").hide();
                $("#popup").hide();
                $(document).unbind("keydown");
            }

        });

        //Close Popup by Clicking the Close-Button
        $(".popup_close").click(function() {
        	close_popup_overlay();
            $(document).unbind("keydown");
        });

        // Close Popup by Clicking on the Overlay
        $("#popup_overlay").click(function() {
            $(this).hide();
            $("#popup").hide().css("width","auto");
            $("#popup .overlay_center").css("width","auto");
            $(document).unbind("keydown");
        });

    });
}

function close_popup_overlay(){
	$("#popup_overlay").hide();
    $("#popup").hide().css("width","auto");
    $("#popup .overlay_center").css("width","auto");
}

function setOverlayWidthForIE() {
    if(isIE6 || isIE7){
    	/**
		 * Note:
		 * The overlay popup needs to have a specified width in order to render properly in IE6 and IE7.
		 * The code below sets the width given the different types of content to be placed inside the overlay
		 **/
    	var totalPopupWidth = 500;
    	var overlayTable = $("#popup .overlay_table");
    	var overlayImage = $("#popup .largeImagePopup");
    	if(overlayTable.is(":visible")){
    		totalPopupWidth = overlayTable.width() + 50;
    		$("#popup .overlay_contents").css("width", overlayTable.width());
    	}
    	else if(overlayImage.is(":visible")) {
    		totalPopupWidth = overlayImage.width() + 50;
    	}
    	else{
    		totalPopupWidth = $("#popup").width();
    	}
    	$("#popup .popup_top").css("width",totalPopupWidth + "px");
    	$("#popup .popup_bottom").css("width",totalPopupWidth + "px");
    }
}
function centerOverlayWidth(browserWidth) {
	var overlayImage = $("#popup .largeImagePopup");
	if(isIE6 && overlayImage.is(":visible")){
		$("#popup .overlay_center").css("width", (overlayImage.width()+10));
	}
	if($("#popup .overlay_table").is(":visible")){
		popupContentWidth = ($("#popup .overlay_table").width() + 20);
	}
	else{
		popupContentWidth = ($("#popup .overlay_center").width() + 20);
	}
	//alert("popupContentWidth: "+popupContentWidth+" browserWidth: "+browserWidth);
	if(popupContentWidth < browserWidth){
    	var posLeft = (browserWidth - popupContentWidth)/2;
	    $("#popup").css("left", posLeft );
    }
    else{
    	//alert("browser width ("+browserWidth+") is less than content width ("+popupContentWidth+")");
    	var posLeft = 0;
    	$("#popup_overlay").css('width',(popupContentWidth+40)+"px");
    	$("#popup").css("left", posLeft );
    	if(isIE6 || isIE7){
	    	$("#popup").css("width",(popupContentWidth+30)+"px");
	    }
    }
}
function resizeOverlayByContentWidth(selector1, selector2, extraWidth) {
	if(selector2 != null && selector2.length > 0){
		$("#popup").css("width",($(selector1).width() + $(selector2).width() + extraWidth)+"px");
	}
	else{
		$("#popup").css("width",($(selector1).width() + extraWidth)+"px");
	}
}
function adjustIframeHeight(specificHeight){
	if(specificHeight != null){
		window.setTimeout(function () {
		$("#feedback_popup_frame").height(specificHeight + cqEditBarHeight);
		},100);
	}
	else{
		alert("Window frame cannot resize without a specific height");
	}
}
function measureIframeBodyHeight(){
	window.setTimeout(function () {
		parent.adjustIframeHeight($('body').height());
	},100);
}
function windowScrollTop(){
	var bodyelem = "";
	//Safari appies scrolling to the body tag not the html tag
	if($.browser.safari){
		bodyelem = $("body");
	}
	else{
		bodyelem = $("html");
	}
	bodyelem.scrollTop(0);
}

function showLoadingPopup() {
	$('#popup').html('<div class="popup_top"><div class="top_right popup_close"></div><div class="top_left"></div><div class="top_middle"></div></div><div class="overlay_center"><div class="overlay_contents"><div class="align_center" ><img src="'+(isAuthor() ? '/author' : '') + '/images/ajax_loader.gif"></div></div></div><div class="popup_bottom"><div class="bottom_left"></div><div class="bottom_right"></div><div class="bottom_middle"></div></div>');
    showPopup();
}

/**
 * End: Popup (Mood - Flash/Video Popup)
 */

/**
 * Begin: Footer Sitemap (affects/involves the following files: footer.jsp, navigationmenu/generateJS.jsp)
 */

 function populateFooterSitemap(){

		$("#sitemap_layer_col1 ul").append($("#navibar_01_col_A ul").html());
		$("#sitemap_layer_col2 ul").append($("#navibar_01_col_B ul").html());
		$("#sitemap_layer_col3 ul").append($("#navibar_02_col_A ul").html());
		$("#sitemap_layer_col4 ul").append($("#navibar_02_col_B ul").html());
		$("#sitemap_layer_col5 ul").append($("#navibar_03_col_A ul").html());
		$("#sitemap_layer_col6 ul").append($("#navibar_04_col_A ul").html());

 		$("#footer_sitemap_servicesandsupport_label").html($("#navmenu_servicesandsupport_label").text());
 		$("#footer_sitemap_aboutus_label").html($("#navmenu_aboutus_label").text());

 }
/**
 * End: Footer Sitemap (affects/involves the following files: footer.jsp, navigationmenu/generateJS.jsp)
 */

//Get Scrolling Position
function _getScroll() {

	if (self.pageYOffset) {

 		scrollTop = self.pageYOffset;
 		scrollLeft = self.pageXOffset;

 	}
	else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict

 		scrollTop = document.documentElement.scrollTop;
 		scrollLeft = document.documentElement.scrollLeft;

 	}
	else if (document.body) { // all other Explorers

 		scrollTop = document.body.scrollTop;
 		scrollLeft = document.body.scrollLeft;

 	}

 	return {scrollTop:scrollTop, scrollLeft:scrollLeft};

};

function centerPopup() {

	var browserHeight = jQuery(document).height();
	var browserWidth = jQuery(window).width();

	var contentWidth = jQuery("#popup").width();
	var contentHeight = jQuery("#popup").height();

	var posLeft = (browserWidth - contentWidth)/2;
	var posTop = (browserHeight - contentHeight)/2;

	jQuery("#popup").css("left", posLeft);

}

function loadFlash(element, file, version, width, height, configParam, configFile) {

	var s1 = new SWFObject(file, element, width, height, version);

	s1.addVariable(configParam, configFile);

	s1.write(element);
}

function loadVideo(element, file, version, width, height, image, autostart, controlbar) {

	var s1 = new SWFObject((isAuthor() ? '/author' : '') + '/mediaplayers/player.swf', 'jwplayer', width, height, version);

	s1.addParam('allowfullscreen', 'true');

	s1.addVariable('file', file);

	if(image !=null && image.length > 0){
		s1.addVariable('image',image);
	}
	s1.addVariable('autostart', autostart);

	if (controlbar == false) {
		s1.addVariable('controlbar', 'none');
	}

	s1.write(element);

	playerReady();
}

function loadPopupFlash(file, title, version, width, height, configParam, configFile) {

	loadFlash('popup_video', file, version, width, height, configParam, configFile)

	$("#popup .currentVideoLabel").html(title);
}

function loadPopupVideo(file, title, version, width, height, image, autostart, controlbar) {

	loadVideo('popup_video', file, version, width, height, image, autostart, controlbar);

	$("#popup .currentVideoLabel").html(title);
}

function showPopupVideoLoader(id) {
	$(id).html('<div class="align_center"><img src="'+(isAuthor() ? "/author" : "")+'/images/ajax_loader.gif"></div>');
}




/**
* Below are several deprecated functions.
* Because they are still called in some hardcoded feedback button markup created by authors, they must not be deleted.
**/
function sfMouseout(){ return false;}
function sfMouseover(){ return false;}
/**
* End: deprecated functions
**/

/**
 * Begin: Sortable Table
 */
function removeDuplicateArrayValues(array) {
 var a = [];
 var l = array.length;
 for(var i=0; i<l; i++) {
   for(var j=i+1; j<l; j++) {
     // If array[i] is found later in the array
     if (array[i] === array[j]){
       j = ++i;
     }
   }
   a.push(array[i]);
 }
 //Return new array with duplicate values removed
 return a;
};
var isSortEnabled = true;
function initializeSortableTable(tableID, isShowIcon, isShowPrice){
	if(isSortEnabled){
		var oTable;
	 	var asInitVals = new Array();
	 	var totalColumns = $("#"+tableID+" tr:eq(1) td").size();
	 	var noSortColumns = 1;
	 	//console.log("totalColumns: ",totalColumns);

	 	if(isShowIcon){
	 		noSortColumns = noSortColumns + 1;
	 	}

	 	// Since the first column should not be sortable, add sorting only when ther is more than one column
	 	if(totalColumns > noSortColumns){
	 		// Create a property array that will tell jQuery not to sort the first column but allow default sorting for all other columns
	 		var columnArray = new Array();
	 		columnArray[0] = { "bSortable":false };
	 		if(isShowIcon){
	 			columnArray[1] = { "bSortable":false };
	 		}
	 		for(var j=noSortColumns; j < totalColumns ; j++){
	 			columnArray[j] = null;
	 		}
	 		//console.log("aoColumns: ",columnArray.length);
	 		oTable = $('#'+tableID).dataTable( {
	 			"oLanguage": {
	 				"sSearch": "Search all columns:"
	 			},
	 			"bPaginate": false,
	 			"bInfo": false,
	 			"aoColumns": columnArray
	 		} );

	 		// Create Filter Row
	 		var filterRowHTML = "<tr id='filterRow'>"
	 		$("#"+tableID+" thead th").each(function(index, element){
	 			var count = index + 1;
	 			// No filtering for the first column (if icons are displayed, no sorting on the first two columns...)
	 			if(count <= noSortColumns){
	 				filterRowHTML = filterRowHTML + "<td>&nbsp;</td>";
	 			}
	 			else{
	 				var a = new Array();
	 				$("#"+tableID+" tr td:nth-child("+count+")").each(function(index, element){
	 					a[index] = $(element).text();
	 				});
	 				//console.log("(",count,"). Regular array results: ",a.sort());
	 				//console.log("(",count,"). Unique array results: ",removeDuplicateArrayValues(a).sort());
	 				a = removeDuplicateArrayValues(a).sort();

	 				filterRowHTML = filterRowHTML + "<td><select style='width:100px'><option value=''>Filter...</option>";
	 				for(i=0;i<a.length;i++){
	 					filterRowHTML = filterRowHTML + "<option value='" + a[i] + "'>" + a[i] + "</option>";
	 				}
	 				filterRowHTML = filterRowHTML + "</select></td>";
	 			}
	 		});
	 		filterRowHTML = filterRowHTML + "</tr>"

	 		$("#"+tableID+" thead").append(filterRowHTML);
	 		jQuery("#filterRow select").sSelect();

	 		$("#filterRow select").change( function () {
	 			/* Filter on the column (the index) of this element */
	 			$("#hiddenFilterInput").val(this.value)
	 			oTable.fnFilter( this.value, ($("#filterRow select").index(this) + noSortColumns));
	 		} );
	 	}
	}
}
/**
 * End: Sortable Table
 */

/*--- Begin: Product Registration ---*/
function registerProductDay(page2Url, productPath) {
	var promoCode = document.getElementById("idPromotionCode");
	var promoInput = document.getElementById("idPromotionInput");
	var prodRegForm = document.getElementById("prodRegForm");
	if(promoInput) {
		promoCode.value = promoInput.value;
	}
	var productNameField = document.getElementById("idProductPath");
	if (productPath) {
		productNameField.value = productPath;
	}

	prodRegForm.action=page2Url;

	prodRegForm.submit();
}
/*--- End: Product Registration ---*/


/*--- Begin: Subscriptions ---*/

/* Expand or contract a subscription type*/
function toggleSubType(/*int*/catNum) {
	if ( "none" == document.getElementById("Category" + catNum).style.display ) {
	    document.getElementById("Category" + catNum).style.display = "block";
	    document.getElementById("Plus" + catNum).style.display = "none";
	    document.getElementById("Minus" + catNum).style.display = "block";
	} else {
	    document.getElementById("Category" + catNum).style.display = "none";
	    document.getElementById("Plus" + catNum).style.display = "block";
	    document.getElementById("Minus" + catNum).style.display = "none";
	}
}

/* Mark or unmark all checkboxes for the given subscription number (number is generated by the order of the categories)*/
function markAllFromSubType(/*Object*/o, /*int*/catNum, /*int*/numSubs) {
	var checked = o.checked;
	if(checked){
		document.getElementById("SubscriptionsSubmit").disabled=false;
	}else{
		document.getElementById("SubscriptionsSubmit").disabled=true;
	}
	for (var i = 0; i < numSubs; i++) {
	    if ( !document.getElementById("Category" + catNum + i).disabled ) {
	    	document.getElementById("Category" + catNum + i).checked = checked;
	    }
	}
}

/* Mark or unmark the "All" checkbox if all checkboxes under that category have become checked or unchecked*/
function allBoxesCheck(/*int*/catNum, /*int*/numSubs) {
	var numChecked = 0;
	for (var i = 0; i < numSubs; i++) {
	    if ( document.getElementById("Category" + catNum + i).checked ) {
	    	numChecked++;
	    }
	}
	if( numChecked == 0 ) {
		document.getElementById("SubscriptionsSubmit").disabled=true;
	}else{
		document.getElementById("SubscriptionsSubmit").disabled=false;
	}
	if ( numChecked == 0 ) {
	    document.getElementById("CheckboxHeader" + catNum).checked = false;
	} else if ( numChecked == numSubs ) {
	    document.getElementById("CheckboxHeader" + catNum).checked = true;
	}
}

function displayTipBox (checkBox) {
	var xpos = findPosX(checkBox);
	var ypos = findPosY(checkBox);
	var box = document.getElementById("howToUnsubscribe");
	if (box != null) {
		    box.style.display='block';
		    box.style.position='absolute';
		    box.style.top=ypos+10+'px';
		    box.style.left=xpos+20+'px';
		    checkBox.checked='true';
	}
}

function closeUnsubscribeTip () {
	var box = document.getElementById("howToUnsubscribe");
	if (box != null) {
		    box.style.display='none';
	}
}
/*--- End: Subscriptions ---*/
function ajaxPrepopulate(url){

	var xmlDoc;
	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlDoc=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		// code for IE6, IE5
		xmlDoc=new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		//alert("Your browser does not support XMLHTTP.  In order to have prepopulated forms, you will need to upgrade to a newer browser.");
	}

	xmlDoc.open("GET",url,false);
    xmlDoc.send("");

    if(xmlDoc.responseXML != null){
	    if(xmlDoc.responseXML.getElementsByTagName("title")[0].childNodes.length > 0){
			if($(":radio[value*=" + xmlDoc.responseXML.getElementsByTagName("title")[0].childNodes[0].nodeValue + "]").size() > 0){
	    		$(":radio[value*=" + xmlDoc.responseXML.getElementsByTagName("title")[0].childNodes[0].nodeValue + "]").get(0).click();
			}
		}
		if(xmlDoc.responseXML.getElementsByTagName("firstName")[0].childNodes.length > 0){
			$(":input[name=firstName]").val(xmlDoc.responseXML.getElementsByTagName("firstName")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("lastName")[0].childNodes.length > 0){
			$(":input[name=lastName]").val(xmlDoc.responseXML.getElementsByTagName("lastName")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("email")[0].childNodes.length > 0){
			$(":input[name=email]").val(xmlDoc.responseXML.getElementsByTagName("email")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("company")[0].childNodes.length > 0){
			$(":input[name=company]").val(xmlDoc.responseXML.getElementsByTagName("company")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("department")[0].childNodes.length > 0){
			$(":input[name=department]").val(xmlDoc.responseXML.getElementsByTagName("department")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("position")[0].childNodes.length > 0){
			$(":input[name=position]").val(xmlDoc.responseXML.getElementsByTagName("position")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("address1")[0].childNodes.length > 0){
			$(":input[name=address1]").val(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("address1")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("address2")[0].childNodes.length > 0){
			$(":input[name=address2]").val(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("address2")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("city")[0].childNodes.length > 0){
			$(":input[name=city]").val(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("city")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("state")[0].childNodes.length > 0){
			$(":input[name=state]").val(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("state")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("postalCode")[0].childNodes.length > 0){
			$(":input[name=postalCode]").val(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("postalCode")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("country")[0].childNodes.length > 0){
			$(":input[name=country] [value^="+xmlDoc.responseXML.getElementsByTagName("address")[0].getElementsByTagName("country")[0].childNodes[0].nodeValue+"]").attr("selected", "selected");
		}
		if(xmlDoc.responseXML.getElementsByTagName("phoneNumber")[0].childNodes.length > 0){
			$(":input[name=phoneNumber]").val(xmlDoc.responseXML.getElementsByTagName("phoneNumber")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("faxNumber")[0].childNodes.length > 0){
			$(":input[name=faxNumber]").val(xmlDoc.responseXML.getElementsByTagName("faxNumber")[0].childNodes[0].nodeValue);
		}
		if(xmlDoc.responseXML.getElementsByTagName("optIn")[0].childNodes.length > 0){
			if(xmlDoc.responseXML.getElementsByTagName("optIn")[0].childNodes[0].nodeValue == "true"){
				$("input[name=optIn]").get(0).click();
			}
			else{
				$("input[name=optIn]").get(1).click();
			}
		}
    }
}

function processQueryParams() {
    var q = $.parseQuery();
    var params = ['email','firstName','lastName','instructionToRecipient', 'message'];

    for (var i in params) {
        var param = params[i];
        var value = q[param];

        if (value) {
            $(':input[name=' + param + ']').val(value);
        }
    }
}

/*Multimedia for Product Model Overview Tab*/
function MultipleMediaPopup(a, title, id) {
	windowScrollTop();
	showLoadingPopup();
	if (id) {
		$('#popup').html($('#MultipleMediaComponentContainer-'+id).html());
	} else {
		$('#popup').html($("#MultipleMediaComponentContainer").html());
	}

    $.ajaxSetup({cache: true});
    
    showPopupVideoLoader('#popup .multiplemedia_popup_video');
    //$('#popup .multiplemedia_popup_video').html('<div class="align_center"><img src="'+(isAuthor()?"/author":"")+'/images/ajax_loader.gif"></div>');

    $("#popup .multiplemedia_popup_video").attr("id","multiplemedia_popup_video").load(a.href, function(){
        $("#popup .currentVideoLabel").html(title);
        showPopup();
        windowScrollTop();
    });
}
function MultipleMediaLoad(href, title) {
	showPopupVideoLoader('#popup .multiplemedia_popup_video');
	//$('#popup .multiplemedia_popup_video').html('<div class="align_center"><img src="'+(isAuthor()?"/author":"")+'/images/ajax_loader.gif"></div>');
    $("#multiplemedia_popup_video").load(href, function(){
        $("#popup .currentVideoLabel").html(title);
        setOverlayWidthForIE();
        centerOverlayWidth($(window).width());
    });
}

/**
 * Wimpy function to do fake html character escaping for values that show up in selectors.
 * (Can't have a semi-colon in the selector or the filename will be incomplete when cached on the web server.)
 *
 * @param v
 * @return
 */
function escapeHtml(v) {
    v = v.replace(/\</g, "-lt-");
    v = v.replace(/\>/g, "-gt-");
    return v;
}

/**
 * eNewsletter 
 * Begin
 */
function onSubscriptionLoad() {
	isAssistantSubscrContLoaded = true;
	var href = $('#href').text();

    $('#loading_GIF').show();

    errorClear();

    $('#subscribeForm').validate({
        rules: {
            email: {email:true}
        },
        onfocusin: function(element) {
            this.lastActive = element;
            feedbackFormFocusInCallback(element);
            if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
                this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
                this.errorsFor(element).hide();
            }
        },
        onfocusout: function(element) {
            $(element).removeClass("element_in_focus");
            feedbackFormFocusOutCallback(element);
            if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
                this.element(element);
            }
        },
        highlight: function( element, errorClass, validClass ) {
            $(element).addClass(errorClass).removeClass(validClass);
            feedbackFormHighlightCallback(element);
        },
        unhighlight: function( element, errorClass, validClass ) {
            $(element).removeClass(errorClass).addClass(validClass);
            feedbackFormUnhighlightCallback(element);
        }
    });

    var omnitureSent = false;

    $.ajax({
        url: $('#href').text(),
        cache: false,
        dataType: 'json',
        data: { mode: 'load' },
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        success: function(data) {
            if (data.omniture.assistBox == true) {
                omnitureEvent(data.omniture, 'event21');
            } else {
                if (omnitureSent == false) {
                    $('[name="title"],[name="firstName"],[name="lastName"],[name="email"]').click(function(event) {
                        omnitureLoad(data.omniture, event);
                    });

                    $('#submit-subscribe').click(function(event) {
                        omnitureLoad(data.omniture, event);
                        submitSubscribe(event);
                    });
                }
            }

            if (data.user.title) {
                $('[name="title"]').filter('[value="' + data.user.title + '"]').attr('checked', true);
            }

            if (data.user.firstName) {
                $('[name="firstName"]').val(data.user.firstName);
            }

            if (data.user.lastName) {
                $('[name="lastName"]').val(data.user.lastName);
            }

            if (data.user.emailAddress) {
                $('[name="email"]').val(data.user.emailAddress);
            }

            $('#subscribe').show();
            $('#loading_GIF').hide();
        },
        error: function(request, status, errorThrown) {
            errorLoad(request, status, errorThrown);

            $('#subscribe').show();
            $('#loading_GIF').hide();
        }
    });

    function omnitureLoad(omniture, event) {
        omnitureEvent(omniture, 'event21');
        omnitureSent = true;

        $('[name="title"],[name="firstName"],[name="lastName"],[name="email"],#submit-subscribe').unbind('click');
        $('#submit-subscribe').click(function(event) {
            submitSubscribe(event);
        });
    }

    $('#submit-subscribe').click(function(event) {
        submitSubscribe(event);
    });

    $('#submit-interests').click(function(event) {
        event.preventDefault();

        $('#serverError').removeClass('error');
        $('#serverError').addClass('hide');

        if ($("#interestsForm").valid() == true) {
            $('#loading_GIF').show();
            $('#interests').hide();
            $('#submit-interests').attr('disabled', 'disabled');

            errorClear();

            $.ajax({
                url: $('#href').text(),
                cache: false,
                dataType: 'json',
                contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                data: {
                    mode: 'interests',
                    title: $('[name="title"]:checked').val(),
                    firstName: $('[name="firstName"]').val(),
                    lastName: $('[name="lastName"]').val(),
                    email: $('[name="email"]').val(),
                    industry: $('[name="industry"]:checked').val(),
                    products: getSelectedProducts()
                },
                success: function(data) {
                    $('#loading_GIF').hide();
                    $('#submit-interests').removeAttr('disabled');

                    if (data.success == true) {
                        omnitureEvent(data.omniture, 'event22');

                        $('#selectedInterests').text(data.interestsText);
                        $('#thank-you-change').html($('#thank-you-change').html().replace(/{mt:email\/}/g, $('[name="email"]').val()));
                        $('#change').show();
                    } else {
                        $('#serverError').removeClass('hide');
                        $('#serverError').addClass('error');
                        $('#interests').show();
                    }
                },
                error: function(request, status, errorThrown) {
                    errorLoad(request, status, errorThrown);

                    $('#loading_GIF').hide();
                    $('#submit-interests').removeAttr('disabled');
                    $('#interests').show();
                }
            });
        }
    });

    $('#submit-change').click(function(event) {
        event.preventDefault();

        $('#loading_GIF').show();
        $('#change').hide();
        $('#submit-change').attr('disabled', 'disabled');

        errorClear();

        $.ajax({
            url: $('#href').text(),
            cache: false,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: {
                mode: 'change',
                title: $('[name="title"]:checked').val(),
                firstName: $('[name="firstName"]').val(),
                lastName: $('[name="lastName"]').val(),
                email: $('[name="email"]').val()
            },
            success: function(data) {
                $('#loading_GIF').hide();
                $('#submit-change').removeAttr('disabled');

                if (data.success == true) {
                    show(data);

                    $('#interests').show();
                } else {
                    $('#serverError').removeClass('hide');
                    $('#serverError').addClass('error');
                    $('#change').show();
                }
            },
            error: function(request, status, errorThrown) {
                errorLoad(request, status, errorThrown);

                $('#loading_GIF').hide();
                $('#submit-change').removeAttr('disabled');
                $('#change').show();
            }
        });
    });
}

function submitSubscribe(event) {
    event.preventDefault();

    $('#serverError').removeClass('error');
    $('#serverError').addClass('hide');

    if ($("#subscribeForm").valid() == true) {
        $('#loading_GIF').show();
        $('#subscribe').hide();
        $('#submit-subscribe').attr('disabled', 'disabled');

        errorClear();

        // attach query params from existing request
        var q = $.parseQuery();

        $.ajax({
        	type: 'POST',
            url: $('#href').text(),
            cache: false,
            dataType: 'json',
            data: ({
                mode: 'subscribe',
                title: $('[name="title"]:checked').val(),
                firstName: $('[name="firstName"]').val(),
                lastName: $('[name="lastName"]').val(),
                email: $('[name="email"]').val(),
                interestType: q.interestType,
                id: q.id
            }),
            success: function(data) {
                $('#loading_GIF').hide();
                $('#submit-subscribe').removeAttr('disabled');

                if (data.success == true) {
                    omnitureEvent(data.omniture, 'event8');

                    $('#thank-you-interests').html($('#thank-you-interests').html().replace(/{mt:email\/}/g, $('[name="email"]').val()));

                    show(data);

                    $('#interests').show();
                } else {
                    $('#serverError').removeClass('hide');
                    $('#serverError').addClass('error');
                    $('#subscribe').show();
                }
            },
            error: function(request, status, errorThrown) {
                errorLoad(request, status, errorThrown);

                $('#loading_GIF').hide();
                $('#submit-subscribe').removeAttr('disabled');
                $('#subscribe').show();
            }
        });
    }
}

function reloadInterests() {
    $('#interests').hide();
    $('#loading_GIF').show();
    $('[name="industry"],[name="products"],[name="products-all"]').attr('disabled', 'disabled');

    errorClear();

    $.ajax({
        url: $('#href').text(),
        cache: false,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: {
            mode: 'reload',
            title: $('[name="title"]:checked').val(),
            firstName: $('[name="firstName"]').val(),
            lastName: $('[name="lastName"]').val(),
            email: $('[name="email"]').val(),
            industry: getSelectedIndustry(),
            products: getSelectedProducts()
        },
        success: function(data) {
            $('[name="industry"],[name="products"],[name="products-all"]').removeAttr('disabled');

            if (data.success == true) {
                show(data);

                $('#interests').show();
            } else {
                $('#serverError').removeClass('hide');
                $('#serverError').addClass('error');
            }

            $('#loading_GIF').hide();
        },
        error: function(request, status, errorThrown) {
            errorLoad(request, status, errorThrown);

            $('[name="industry"],[name="products"],[name="products-all"]').removeAttr('disabled');
            $('#loading_GIF').hide();
        }
    });
}

function show(data) {
    $('#cell-products').hide();

    showIndustries(data.industries);
    showProducts(data.products);

    if ($('[name="industry"]').is(':checked') ) {
        $('#submit-interests').removeAttr('disabled');
        $('#cell-products').show();
    } else {
        $('#submit-interests').attr('disabled', true);
    }

    if (data.displayProducts == true) {
        $('#cell-products').show();
    }

    if ($('[name="products"]').length == $('[name="products"]:checked').length) {
        $('[name="products-all"]').attr('checked', 'checked');
    }
}

function showIndustries(industries) {
    $('#container-industries div').remove();
    $('#container-products div').remove();

    $.each(industries, function(i) {
        var industryDiv;

        if (this.selected == true) {
            industryDiv = '<div><input id=\"industry-' + i + '\" class=\"required\" type=\"radio\" name=\"industry\" value=\"'
                + this.id + '\" checked /><span class=\"subscriptions_label\">'
                + this.title + '</span></div>';
        } else {
            industryDiv = '<div><input id=\"industry-' + i + '\" class=\"required\" type=\"radio\" name=\"industry\" value=\"'
                + this.id + '\"/><span class=\"subscriptions_label\">'
                + this.title + '</span></div>';
        }

        $('#container-industries').append($(industryDiv));
    });

    if ($.browser.msie) {
        $('[name="industry"]').click(function() {
            this.blur();
            this.focus();
        });
    }

    $('[name="industry"]').change(function() {
        reloadInterests();
    });
}

function showProducts(products) {
    $('#container-products div').remove();

    var count = 0;

    $.each(products, function() {
        var productDiv;

        if (this.selected == true) {
            productDiv = '<div><input type=\"checkbox\" name=\"products\" value=\"'
                + this.id + '\" checked /><span class=\"subscriptions_label\">'
                + this.title + '</span></div>';
        } else {
            productDiv = '<div><input type=\"checkbox\" name=\"products\" value=\"'
                + this.id + '\"/><span class=\"subscriptions_label\">'
                + this.title + '</span></div>';
        }

        count++;

        $('#container-products').append($(productDiv));
    });

    if (count > 1) {
        var all = $('#all').text();

        $('#container-products').append($('<div><input type=\"checkbox\" name=\"products-all\" /><span class=\"subscriptions_label\">' + all + '</span></div>'));
        $('[name="products-all"]').click(function() {
            var status = this.checked;

            $('[name="products"]').each(function() {
                this.checked = status;
            });

            reloadInterests();
        });
    }

    if ($.browser.msie) {
        $('[name="products"]').click(function() {
            this.blur();
            this.focus();
        });
    }

    $('[name="products"]').change(function() {
        reloadInterests();
    });
}

function getSelectedIndustry() {
    if ($('[name="industry"]').is(':checked') ) {
        return $('[name="industry"]:checked').val();
    } else {
        return '';
    }
}

function getSelectedProducts() {
    var selectedProducts = [];

    $('[name="products"]:checked').each(function() {
        selectedProducts.push($(this).val());
    });

    return selectedProducts;
}

$("#subcribeForm input").focus(function(){
    $(this).addClass("active");
});

$("#subcribeForm input").blur(function(){
    $(this).removeClass("active");
});

$('#subscribeForm').submit(function(event){
    event.preventDefault();

    $('#submit-subscribe').click();
});

$('#interestsForm').submit(function(event){
    event.preventDefault();

    $('#submit-interests').click();
});

var firstPageName;

function omnitureEvent(vars, event) {
    var omnitureVariables = {};

    if (vars.assistBox == true) {
        omnitureVariables.linkTrackVars = "channel,server,prop1,prop2,prop3,prop4,prop5,prop6,prop13,prop14,prop15,prop16,prop17,prop18,hier1,hier2,eVar4,eVar5,eVar6,eVar11,eVar19,eVar20,eVar23,eVar24,events";
    } else {
        omnitureVariables.linkTrackVars = "channel,server,prop1,prop2,prop3,prop4,prop5,prop6,prop13,prop14,prop15,prop16,prop17,prop18,hier1,hier2,eVar4,eVar5,eVar6,eVar11,eVar19,eVar20,eVar24,events";
    }

    omnitureVariables.linkTrackEvents = "None";
    omnitureVariables.pageName = vars.pageName;
    omnitureVariables.channel = vars.channel;
    omnitureVariables.prop5 = vars.prop5;
    omnitureVariables.prop13 = vars.prop13;
    omnitureVariables.prop14 = vars.prop14;
    omnitureVariables.hier2 = vars.hier2;
    omnitureVariables.eVar24 = vars.source;

    if (vars.assistBox == true) {
        if (event == 'event21') {
            omnitureVariables.eVar23 = s.pageName;
            firstPageName = s.pageName;
        } else {
            omnitureVariables.eVar23 = firstPageName;
        }
    }

    omnitureVariables.events = event;

    omnitureAjaxTracking(omnitureVariables, '');
}

function errorLoad(request, status, errorThrown) {
    $('#ajaxErrorText').text(request.responseText);
    $('#ajaxErrorStatus').text(status);
    $('#ajaxErrorThrown').text(errorThrown);
    $('#serverError').removeClass('hide');
    $('#serverError').addClass('error');
}

function errorClear() {
    $('#ajaxErrorText,#ajaxErrorStatus,#ajaxErrorThrown').text('');
    $('#serverError').removeClass('error');
    $('#serverError').addClass('hide');
}
/**
 * eNewsletter
 * End
 */
