/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2446 $
 *
 * Version 2.1.1
 */

(function($){

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE6 
 * and adds a class to the iframe called 'bgiframe'. The iframe
 * is appeneded as the first child of the matched element(s) 
 * with a tabIndex and zIndex of -1.
 * 
 * By default the plugin will take borders, sized with pixel units,
 * into account. If a different unit is used for the border's width,
 * then you will need to use the top and left settings as explained below.
 *
 * NOTICE: This plugin has been reported to cause perfromance problems
 * when used on elements that change properties (like width, height and
 * opacity) a lot in IE6. Most of these problems have been caused by 
 * the expressions used to calculate the elements width, height and 
 * borders. Some have reported it is due to the opacity filter. All 
 * these settings can be changed if needed as explained below.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @param Map settings Optional settings to configure the iframe.
 * @option String|Number top The iframe must be offset to the top
 * 		by the width of the top border. This should be a negative 
 *      number representing the border-top-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-top-width if it is in pixels.
 * @option String|Number left The iframe must be offset to the left
 * 		by the width of the left border. This should be a negative 
 *      number representing the border-left-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-left-width if it is in pixels.
 * @option String|Number width This is the width of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetWidth.
 * @option String|Number height This is the height of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetHeight.
 * @option Boolean opacity This is a boolean representing whether or not
 * 		to use opacity. If set to true, the opacity of 0 is applied. If
 *		set to false, the opacity filter is not applied. Default: true.
 * @option String src This setting is provided so that one could change 
 *		the src of the iframe to whatever they need.
 *		Default: "javascript:false;"
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);





// Javascript Global Functions
function ShowDiv(idName) {
    var idObject = document.getElementById(idName);
    if (idObject) {
        idObject.style.display = "block";
    }
}
function HideDiv(idName) {
    var idObject = document.getElementById(idName);
    if (idObject) {
        idObject.style.display = "none";
    }
}
function ShowVisib(idName) {
    var obj = document.getElementById(idName);
    if (obj) {
        obj.style.visibility = "visible";
    }
}
function HideVisib(idName) {
    var obj = document.getElementById(idName);
    if (obj) {
        obj.style.visibility = "hidden";
    }
}
function ShowModal(idName) {
    ShowVisib("overlayBkgdDiv");
    ShowDiv(idName);
}
function HideModal(idName) {
    HideDiv(idName);
    HideVisib("overlayBkgdDiv");
}


/*------------------------------------------------------------------------------
Function: Open Window
Simple Popup Window

Parameters:
uri - string
width - number (of pixels)
height - number (of pixels)
options - string
name - string
------------------------------------------------------------------------------*/
var poppedWin = null;
function MM_openBrWindow(theURL, width, height, opt, name) {
    poppedWin = window.open(theURL, (name || "OutsideWindow"), "width=" + (width || 714) + ",height=" + (height || 536) + "," + (opt || "scrollbars=yes,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes"));
}
/*
Example of popup link. 
This way the popup window will not get blocked by popup-blockers:

<a href="http://URL-Path-File-Name-Here.aspx" onclick="MM_openBrWindow(this.href, 640, 450, 'ShareThisPageWin'); return false;">Share This Page</a>

*/



function CloseNow() {
    if (poppedWin.closed) {
        self.location.href = "/Client-Access/DMP/My-Documents/My-Documents/Check-User-Status.aspx";
    } else {
        CloseAndRedirect();
    }
}
function CloseAndRedirect() {
    setTimeout("CloseNow()", 1000);
}

function CloseNowDD() {
    if ((poppedWin == null) || poppedWin.closed) {
        self.location.href = "/Client-Access/DMP/Deposits/Sign-up-for-DepositDirect/Check-Sign-Status.aspx";
    } else {
        CloseAndRedirectDD();
    }
}

function CloseAndRedirectDD() {
    setTimeout("CloseNowDD()", 1000);
}

function OpenWindow(url, width, height, opt, name) {
    window.open(url, (name || "OutsideWindow"), "width=" + (width || 714) + ",height=" + (height || 536) + "," + (opt || "scrollbars=yes,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes")).focus();
}


// ---------------------------------------------------------------------------------------
// Predefined Popup Windows

function PopHowToPrint(url) {
    OpenWindow(url, 550, 230, "scrollbars=yes,menubar=no,toolbar=no,location=no");
}
function PopHowToPrintSave() {
    OpenWindow("/Templates/DMP/How-to-Print-and-Save.aspx", 550, 490, "scrollbars=yes,menubar=no,toolbar=no,location=no");
}
function PopCheck() {
    OpenWindow('/Templates/DMP/Check.aspx', 400, 400, 'scrollbars=no,menubar=no,toolbar=no,location=no');
}
function PopCoupon(url) {
    OpenWindow(url, 640, 480, 'scrollbars=no,menubar=no,toolbar=no,location=no');
}

// ---------------------------------------------------------------------------------------
// Get Query String
function getQuery() {
    return window.location.href.slice(window.location.href.indexOf('?') + 1);
}


// ---------------------------------------------------------------------------------------
// BEGIN: Show Specific Tab in a page using URL Query
function HideAllToggle() {
    $(".toggle_display").each(function() {
        if ($(this).html() == "Hide") {
            $(this).html("Show");
            $(this).parent().next().removeClass('showing');
        }
    });
}
function ShowMatchingQueryTab(QueryString) {
    if (QueryString) {
        $("#" + QueryString + " .toggle_display").html("Hide");
        $("#" + QueryString).next().addClass('showing');
        location.href = "#" + QueryString;
    }
}
// END: Show Specific Tab in a page using URL Query



// ---------------------------------------------------------------------------------------
// BEGIN: JW Player
function deletePlayer(theWrapper, thePlaceholder, thePlayerId) {
    swfobject.removeSWF(thePlayerId);
    var tmp = document.getElementById(theWrapper);
    if (tmp) { tmp.innerHTML = "<div id=" + thePlaceholder + "></div>"; }
}
function createPlayer(thePlaceholder, thePlayerId, theFile, width, height) {
    var flashvars = {
        file: theFile,
        autostart: "false"
        //type: "video" if type is set to video then youtube videos don't play.
    };
    var params = {
        allowfullscreen: "true",
        allowscriptaccess: "always",
        wmode: "transparent"
    };
    var attributes = {
        id: thePlayerId,
        name: thePlayerId
    };
    swfobject.embedSWF("/_JS/JWPlayer/player-licensed.swf", thePlaceholder, width, height, "9.0.115", false, flashvars, params, attributes);
}
function initPlayer(theFile, width, height) {
    deletePlayer('wrapper', 'placeholder1', 'player1');
    createPlayer('placeholder1', 'player1', theFile, width, height);
}
// END: JW Player

// ---------------------------------------------------------------------------------------
// BEGIN: Set unique radio button in repeater

function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}
// END: Set unique radio button in repeater

// ---------------------------------------------------------------------------------------
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
    $.fn.hoverIntent = function(f, g) {
        // default configuration options
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        // override configuration options with user supplied object
        cfg = $.extend(cfg, g ? { over: f, out: g} : f);

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval);
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } }
            if (p == this) { return false; }

            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = jQuery.extend({}, e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // else e.type == "onmouseover"
            if (e.type == "mouseover") {
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $(ob).bind("mousemove", track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); }

                // else e.type == "onmouseout"
            } else {
                // unbind expensive mousemove event
                $(ob).unbind("mousemove", track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function() { delay(ev, ob); }, cfg.timeout); }
            }
        };

        // bind the function to the two event listeners
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Jquery
$(document).ready(function() {

    /*
    //====== Start of job #22141 version 1.0 client approved this version but it's not completed work with every form in the site.
    //// Find ALL <form> tags on your page 
    //$('form').submit(function() {
    //    $('input:submit[id*=btnSubmit]', this).css("background-image", "url('/Images/CommonImages/loader.gif')");
    //    $('input:submit[id*=btnSubmit]', this).css("font-size", "1px");
    //    $('input:submit[id*=btnSubmit]', this).parent("div").css("background", "none");
    //    $('input:submit[id*=btnSubmit]', this).click(function() { return false; });
    //    $('input:submit[id*=btnCancel]', this).hide();
    //});
    //===== end of job ##22141 version 1.0 client approved this version but it's not completed work with every form in the site.

//@20100525 !!!! we decided to exlude this job from the deployment 
    //===== Start of job #22141 version 2.0 This code can prevent pressing multiple enter key to repeat submit form but still doesn't work for every single form.
    //    $(".j_loader").hide();
    //    var isSubmit = false;
    //    // Find ALL <form> tags on your page
    //    $('form').submit(function() {
    //        if (!isSubmit) {
    //            $(".j_loader").show();
    //            $('input:submit[id*=btnSubmit]', this).parents(".btn_round:first").hide();
    //            $('input:submit[id*=btnCancel]', this).parents(".btn_round:first").hide();
    //            $('input:submit[id*=btnReset]', this).parents(".btn_round:first").hide();
    //            isSubmit = true;
    //        }
    //        else {
    //            return false;
    //        }
    //    });
    ///==== end Start of job #22141 version 2.0 This code can prevent pressing multiple enter key to repeat submit form but still doesn't work for every single form.
    */



    /*
    0022141 Trail 3 - 2010, 11, 09 - dhagman
    BEGIN -->
    */

    //	$("form").each(function() { //go through each form on the page/site
    //		var thisForm = $(this); //for each for, create the current form variable
    //		$(this).submit(function() { // on this form submit
    //			var submitButton = $(thisForm).find("input[type='submit']"); // get the submit button (storing a variable is quicker)
    //			var btnWrapper = $(submitButton).parent(); // get the submit button parent object
    //			$(submitButton).attr("value", "Loading..."); // change value of submit button to indicate user the button has been clicked
    //			$(btnWrapper).css("position","relative").append("<div class='btn_overlay'/>"); // create an overlay ontop of the button to prevent any clicking
    //			$(".btn_overlay").fadeTo(0, .5); // fade the overlay immediately to 50%
    //		});
    //	});
    // NOTE: This snippet didn't work as the footer newsletter signup field would trigger a form-submit and cause the Contact Us/Register/Etc Submit button to go into 'loading' and never come out


    //	$('form').submit(function() {
    //		var thisBtn = $("input:submit[id*='btnSubmit']", this);
    //		var btnWrapper = $(thisBtn).parent();
    //		$(thisBtn).attr("value", "Loading..."); // change value of submit button to indicate user the button has been clicked
    //		$(btnWrapper).css("position","relative").append("<div class='btn_overlay'/>"); // create an overlay ontop of the button to prevent any clicking
    //		var btnOverlay = $(btnWrapper).children(".btn_overlay");
    //		$(btnOverlay).fadeTo(0, .5); // fade the overlay immediately to 50%
    //	});
    // NOTE: This snippet didn't work as the footer newsletter signup field would trigger a form-submit and cause the Contact Us/Register/Etc Submit button to go into 'loading' and never come out

    $("input[id*='btnSubmit']").after("<img src='/Images/CommonImages/ajax-loader2.gif' id='btnSpin' alt='loading...' class='spinwheel' />");
    var submitting = false; // if form is currently submitting
    $("input[id*='btnSubmit']").click(function() { // this snippet will only apply to buttons that contain anywhere in the id 'btnSubmit'
        var thisBtn = $(this); // create a variable of this button
        var btnWrapper = $(thisBtn).parent(); // create a variable of this button's parent object
        if (!submitting) {
            submitting = true; // set form to submitting state
            disableSubmitClick(thisBtn, btnWrapper); // disable button for click events
        }
    });

    // bind false return events to buttons from keypresses
    $("input:submit[id*='btnSubmit']").keypress(function(event) {
        if (submitting) { // if submitting...
            //spacebar key returns false (does not submit)
            if (event.keyCode == '13') { return false; }
            // enter key returns false (does not submit)
            if (event.keyCode == '32') { return false; }
        } else { /*console.log(event.keyCode);*/ }
    });
    $("input").keypress(function(event) {
        if (submitting) {
            // enter key
            if (event.keyCode == '13') { return false; }
        } else { /*console.log(event.keyCode);*/ }
    });

    function disableSubmitClick(btn, wrapper) {
        $(btn).hide();
        $(wrapper).css("background-image", "none");
        $("#btnSpin").remove();
        $(btn).after("<img src='/Images/CommonImages/ajax-loader2.gif' id='btnSpin' alt='loading...' style='margin:0 50px;'/>");
    }

    /*
    <--- END
    0022141 Trail 3 - 2010, 11, 09 - dhagman 
    */



    // ---------------------------------------------------------------------------------------
    // Browse Topic box HOVER
    $(".roundbox_active").hover(

	function() {
	    $(this).addClass("roundbox_type2");
	}, function() {
	    $(this).removeClass("roundbox_type2");
	});

    // ---------------------------------------------------------------------------------------
    // Browse Topic box HOVER
    $(".addhover").hover(
	function() {
	    $(this).addClass("over");
	}, function() {
	    $(this).removeClass("over");
	});

    // ---------------------------------------------------------------------------------------
    // Shows Calendar
    $(".datepicker").datepicker({ changeMonth: true, changeYear: true, yearRange: '-100:+10' });


    // ---------------------------------------------------------------------------------------
    // Open ups correct tab
    $(".tab_hd a").click(function() {
        if ($(this).attr('rel') != "") {
            $(this).parents(".tab_area").find(".tab_container").hide();
            $($(this).attr('rel')).show();
            $(this).parents(".tab_area").find(".tab_hd a.on").removeClass('on');
            $(this).addClass('on');
        }
    });


    // ---------------------------------------------------------------------------------------
    // BEGIN: Dropdown Menu
    function addHoverHide(linkClass, layerId, t) {
        $("." + linkClass).hover(function() {
            clearTimeout(t);
            $(".prinav_menu").each(function() {
                if ($(this) != $("." + layerId)) {
                    $(this).hide();
                }
            });
            $("." + layerId).show();
        }, function() {
            t = setTimeout(function() { $("." + layerId).hide(); }, 600);
        });

        $("." + layerId).hover(function() {
            clearTimeout(t);
            $("." + layerId).show();
        }, function() {
            t = setTimeout(function() { $("." + layerId).hide(); }, 200);
        });
    }

    function clearTimeoutAll() {
        clearTimeout(nav2timer);
        clearTimeout(nav3timer);
        clearTimeout(nav4timer);
        clearTimeout(nav5timer);
    }
    // END: Dropdown Menu

    // ---------------------------------------------------------------------------------------
    // BEGIN: Dropdown Menu Initialize
    var nav1timer; // Account Overview (no sub items)
    addHoverHide("nav1", "navmenu1", nav1timer);
    var nav2timer; // Creditor Accounts
    addHoverHide("nav2", "navmenu2", nav2timer);
    var nav3timer; // eStatements
    addHoverHide("nav3", "navmenu3", nav3timer);
    var nav4timer; // Deposits
    addHoverHide("nav4", "navmenu4", nav4timer);
    var nav5timer; // My Documents
    addHoverHide("nav5", "navmenu5", nav5timer);

    /* Utilities Menus */
    var utilnav1timer; // My Account
    addHoverHide("util1", "utilmenu1", utilnav1timer);
    var utilnav2timer; // My Account
    addHoverHide("util2", "utilmenu2", utilnav2timer);
    // END: Dropdown Menu Initialize



    // ---------------------------------------------------------------------------------------
    //form highlights
    $(".formcell").click(function() {
        $(".form_selected").removeClass('form_selected');
        $(this).addClass('form_selected');
    });



    // ---------------------------------------------------------------------------------------
    // BEGIN: add color to ODD rows in tables
    $(".tbl_data_rows").each(function() {
        $(this).find("tr:even").addClass('odd');
    });

    $(".tbl_alt_rows").each(function() {
        $(this).find("tr:even").addClass('odd');
    });
    // END: add color to ODD rows in tables


    // ---------------------------------------------------------------------------------------
    // BEGIN: toggle_display
    /* Clicks on link Hide/Show */
    $(".toggle_display").toggle(function() {
        if ($(this).html() == "Show") {
            $(this).html("Hide");
        } else {
            $(this).html("Show");
        }
        $(this).parent().next().slideToggle();
    }, function() {
        if ($(this).html() == "Show") {
            $(this).html("Hide");
        } else {
            $(this).html("Show");
        }
        $(this).parent().next().slideToggle();
    });

    /* Clicks on Header to Hide/Show */
    $(".toggle_display_hd").toggle(function() {
        if ($(this).parent().find(".toggle_display").html() == "Show") {
            $(this).parent().find(".toggle_display").html("Hide");
        } else {
            $(this).parent().find(".toggle_display").html("Show");
        }
        $(this).parent().next().slideToggle();
    }, function() {
        if ($(this).parent().find(".toggle_display").html() == "Show") {
            $(this).parent().find(".toggle_display").html("Hide");
        } else {
            $(this).parent().find(".toggle_display").html("Show");
        }
        $(this).parent().next().slideToggle();
    });

    /* Clicks on Header to Hide/Show */
    $(".expander_hd").click(function() {
        if ($(this).attr('class').split(' ').slice(-1) == "minus") {
            $(this).removeClass("minus");
        } else {
            $(this).addClass("minus");
        }
        $(this).next('.collapsable').slideToggle();
    });
    // END: toggle_display

    // ---------------------------------------------------------------------------------------
    // BEGIN: accordion
    /* Clicks on link Hide/Show */
    $(".accordion h3").click(function() {
        if ($(this).find(".hd_link").html() == "Show") {
            $(".accordion h3").find(".hd_link").html("Show");
            $(this).find(".hd_link").html("Hide");
            $(".accordion .collapsable").slideUp();
            $(this).next().slideDown();
        } else {
            $(this).find(".hd_link").html("Show");
            $(this).next().slideUp();
        }
    });
    // END: accordion

    // ---------------------------------------------------------------------------------------
    // BEGIN: Clear form input values
    $('.clear_button').click(function() {
        var $thisForm = $(this).parents('fieldset');
        $thisForm.find(':text').val('');
        $thisForm.find('textarea').val('');
        $thisForm.find('select').each(function() {
            $(this).find('option:first').attr('selected', 'selected').parent('select');
        });
        return false;
    });
    // END: Clear form input values

    // ---------------------------------------------------------------------------------------
    // BEGIN: Clear Header Search field's default text
    $(".headsearchtxt").focus(function() {
        //alert ($(this).val() == "Enter keywords");
        if (($(this).val() == $(this).attr("rel")) || ($(this).val() == $(this).attr("title"))) {
            $(this).val("");
            $(this).removeClass("off");
        }

    }).blur(function() {
        if ($(this).val() == "") {
            if ($(this).attr("rel")) {
                $(this).val($(this).attr("rel"));
            } else {
                $(this).val($(this).attr("title"));
            }
            $(this).addClass("off");
        }
    });

    //forum search
    $(".yafsearch_input").focus(function() {
        //alert ($(this).val() == "Enter keywords");
        if (($(this).val() == $(this).attr("rel")) || ($(this).val() == $(this).attr("title"))) {
            $(this).val("");
            $(this).removeClass("off");
        }

    }).blur(function() {
        if ($(this).val() == "") {
            if ($(this).attr("rel")) {
                $(this).val($(this).attr("rel"));
            } else {
                $(this).val($(this).attr("title"));
            }
            $(this).addClass("off");
        }
    });
    // END: Clearn Header Search field's default text


    // ---------------------------------------------------------------------------------------
    // BEGIN: modal window
    function getDimensions() {
        winWidth = $(window).width();
        winHeight = $(window).height();

        pageWidth = $(document).width();
        pageHeight = $(document).height();

        wrapperWidth = $(".wrapper").width();

        modalWidth = $(".modal").outerWidth();
        modalHeight = $(".modal").outerHeight();
    }
    function sizeOverlay() {
        if (winWidth <= wrapperWidth) {
            $(".overlayBkgd").width(wrapperWidth);
        } else {
            $(".overlayBkgd").width(winWidth);
        }
        $(".overlayBkgd").height(pageHeight);
    }
    function positionModal() {
        /* Top */
        modalTop = ((winHeight - (modalHeight + 100)) / 2) / 2;
        if (modalTop <= 0) {
            modalTop = $(window).scrollTop() + 10;
        } else {
            modalTop = $(window).scrollTop() + 100;
        }
        $(".modal").css("top", modalTop + "px");

        /* Left */
        modalMarginLeft = modalWidth / 2;
        if (winWidth <= wrapperWidth) {
            $(".modal").css("margin-left", "-" + modalMarginLeft + "px");
            $(".modal").css("left", (wrapperWidth / 2) + "px");
        } else {
            $(".modal").css("margin-left", "-" + modalMarginLeft + "px");
            $(".modal").css("left", "50%");
        }
    }
    function modalInit() {
        getDimensions();
        sizeOverlay();
        positionModal();
    }
    $(window).resize(function() {
        var Mask = document.getElementById("overlayBkgdDiv");
        if (Mask) {
            if (Mask.style.visibility == "visible") {
                modalInit();
            }
        }
    });

    //select all the a tag with name equal to modal
    $('.modal_link').click(function() {
        modalInit();
    });
    // END: modal window

    // ---------------------------------------------------------------------------------------
    // BEGIN: select_all / unselect_all
    $('.select_all').click(function() {
        var $thisForm = $(this).parents('fieldset');
        $thisForm.find(':checkbox').attr("checked", "checked");
        return false;
    });
    $('.unselect_all').click(function() {
        var $thisForm = $(this).parents('fieldset');
        $thisForm.find(':checkbox').removeAttr("checked");
        return false;
    });
    // END: select_all / unselect_all



    // ---------------------------------------------------------------------------------------
    // BEGIN: checkboxdisabled
    /*$('.checkboxdisabled').click(function() {
    if ($(this).is(':checked')) {
    $(this).parents('.checkboxdisabled_group').find('.checkboxdisabled_field').removeClass('disabled');
    } else {
    $(this).parents('.checkboxdisabled_group').find('.checkboxdisabled_field').addClass('disabled');
    }
    });
    */


    // ---------------------------------------------------------------------------------------
    // BEGIN: dropnav: onclick and mouseleave
    $(".arrow").click(function() {
        // on click of arrow add class to <li> that turns on the drop nav

        $(this).parents("li").toggleClass("dropon");
    });

    $(".mmi li").mouseleave(function() {
        // dropnav is inside the <li>
        // on mouseout of <li> remove the class
        $(this).removeClass("dropon");
    });



    // ---------------------------------------------------------------------------------------
    // BEGIN: Accordion
    /* Accordion */
    function initMenu() {
        $('.acc_menu ul').hide();

        /* Show Sub links for Selected Tab */
        $('.acc_menu span.sel').siblings().show();
        $('.acc_menu span.sel').find("b").addClass("minus");

        /*$('#menu ul:first').show();*/
        $('.acc_menu li span b.expand').click(function() {
            /* Clears any initial Sel tab */
            /*$('.acc_menu li span.sel').removeClass("sel");*/

            var checkElement = $(this).parent().next();
            if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                /* Clicking on selected tab - collapses tab */
                $('.acc_menu ul:visible').parent().find("b").removeClass("minus");
                $('.acc_menu ul:visible').slideUp('normal');


                /* Use this code if you do not want the accordion effect of hiding everything */
                /*$(this).parent().find("b").removeClass("minus");
                checkElement.slideUp('normal');
                */

                /*return false;*/
            }
            if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                /* Clicking on other tabs - expand and change icon to "-" */

                /* Add sel style */
                /*$(this).addClass("sel");*/

                /* Comment next 2 lines if you do not want accordion effect of hiding everything */
                $('.acc_menu ul:visible').parent().find("b").removeClass("minus");
                $('.acc_menu ul:visible').slideUp('normal');

                $(this).parent().find("b").addClass("minus");
                checkElement.slideDown('normal');
                /*return false;*/
            }
        });
    }
    initMenu();
    // END: Accordion




    // ---------------------------------------------------------------------------------------
    // BEGIN: toc
    /* Section Nav - toc - automatically collapse as default */

    $('.toc div.on').each(function() {
        $(this).next().next().show();
    });

    // END: toc


    // ---------------------------------------------------------------------------------------
    // BEGIN: Add_Ellipsis - use ellipsis max characters
    function Add_Ellipsis(classname, maxchars, removehtml) {
        var slicePoint = (maxchars || 50);
        $(classname).each(function() {
            var allText = $(this).html();
            var editText;

            if (removehtml) {
                // This removes all HTML Tags
                editText = allText.replace(/<\/?[^>]+>/gi, '');
            } else {
                editText = allText;
            }

            if (editText.length > slicePoint) {
                // This cuts off after 65 characters but up to the word
                var startText = editText.slice(0, slicePoint).replace(/\w+$/, '');

                // Add ellipsis
                startText = startText + "...";
                $(this).html(startText);
            }
        });
    }
    // Initialize Ellipsis Here
    // Example - 
    // Add_Ellipsis(jQuery_class_name, maxCharacters, removeHTML?);
    // Add_Ellipsis('.result_title a', 90, false);

    // Template... Search-Results.aspx
    Add_Ellipsis('.result_title a', 90, false);
    Add_Ellipsis('.result_teaser', 200, true);

    // Banner Bread Crumb MMI page
    Add_Ellipsis('.banner_bc a', 30, false);
    Add_Ellipsis('.banner_bc b', 50, false);
    Add_Ellipsis('.banner2 h1 span', 50, false);


    // END: Add_Ellipsis - use ellipsis max characters



    // ---------------------------------------------------------------------------------------
    // BEGIN: Slide Down to Error Message
    if ($('.formgroup.error').length > 0) {
        var targetOffset = $('.error_popup:visible').offset().top - 6;
        $('html,body').animate({ scrollTop: targetOffset }, 1000);
    }
    // END: Slide Down to Error Message


    // ---------------------------------------------------------------------------------------
    // BEGIN: image resizing
    $('.flickr_post .img_holder img').each(function() {
        var imgwidth = $(this).width();
        var imgheight = $(this).height();
        // 240/160 = 1.5
        if ((imgwidth / imgheight) > 1.5) {
            $(this).height('160px');
        } else {
            $(this).width('240px');
        }
    });
    $('.tbl_thumb_large .thumb img').each(function() {
        var imgwidth = $(this).width();
        var imgheight = $(this).height();
        // 138/125 = 1.5
        if ((imgwidth / imgheight) > 1.104) {
            $(this).height('125px');
        } else {
            $(this).width('138px');
        }
    });
    // END: image resizing


    // ---------------------------------------------------------------------------------------
    // BEGIN: forum_tbl - add style to first tbody row
    var ForumTable = $('.forum_tbl');
    if (ForumTable.length) {
        var ForumPreview = $('.fm_preview_hd');
        if (ForumPreview.length) {
            ForumPreview.next().addClass("nobg");
        }
        ForumTable.find("tr.tbody_info:first").addClass("nobg");
    }
    // END: forum_tbl - add style to first tbody row



    // ---------------------------------------------------------------------------------------
    // BEGIN: ReportProfile
    $("#ReportProfile").dialog({
        bgiframe: true,
        width: 400,
        modal: true,
        autoOpen: false,
        draggable: false,
        resizable: false,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        }
    });
    $("#ReportProfile").parent().appendTo("form");

    // Open Dialog
    window.OpenDialog = function(idName) { $("#" + idName).dialog("open"); };
    // Close Dialog
    window.CloseDialog = function(idName) { $("#" + idName).dialog("close"); };
    // END: ReportProfile



    // ---------------------------------------------------------------------------------------
    // BEGIN: InfoGraphic Area cursor style
    var thisImg = "";
    var thisMap = "";
    $("area").hover(function() {
        thisMap = $(this).parent("map").attr("name");
        $("img").each(function() {
            if ($(this).attr("usemap") == "#" + thisMap) {
                thisImg = $(this);
                $(this).css("cursor", "pointer");
            } else {
                //
            }
        });

    }, function() {
        thisImg.css("cursor", "default");
    });
    // END: InfoGraphic Area cursor style

    // ---------------------------------------------------------------------------------------
    // BEGIN: Video listing right-hand tabs/accordion

    $("a.tab_link").click(function() {
        $(this).parent(".video_listing_tab").siblings().children(".selected_tab").slideUp(350).removeClass("selected_tab");
        $(this).next(".video_listing_tab_content").toggleClass("selected_tab");
        $(this).next(".video_listing_tab_content").slideToggle(350);
    });


});

// ---------------------------------------------------------------------------------------
// BEGIN: manipulate 3rd party captcha css styles
$(function() {
    $(".Captcha div").css({ marginLeft: "0px", textAlign: "left" });
    $(".Captcha div input").css({ borderColor: "#39658D" });

    $(".Captcha_Err div").css({ marginLeft: "0px", textAlign: "left" });
    $(".Captcha_Err div input").css({ borderColor: "#D60000" });
});


//BEGIN: hide or disable submit buttons on click event





//END

// Author: Brian Thopsey http://topcweb.com    - thanks to Rudi Shumpert
// Code for tracking of video player, Longtail - JWplayer on Omniture SC
// variables to help populate player
var currentBuffer = 0;
var currentPosition = 0;
var currentState = "NONE";
var defaultState = "NONE";
var currentLoad = 0;
var clipDuration = 0;
var player;
var playerLocation = "/_JS/JWPlayer/player-licensed.swf"; //--- Location of the JWplayer file
var videoFileName;

/* additional vars that are not neccessary */
var autoPlay;
var viralShare;
var captions;
var captionFile;

// Function for instatiating player
function playerReady(obj) {
    //alert('the videoplayer '+obj['id']+' has been instantiated');
    player = document.getElementById(obj['id']);
    addListeners();
};

function addListeners() {
    //load the JWplayer event listners
    if (player) {
        addAllModelListeners();
    }
}

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", "loadedListener"); //{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 loadedListener(obj) {
    var playlist = player.getPlaylist();
    var playerConfig = player.getConfig();
    if (playlist[playerConfig.item].title)
        videoFileName = playlist[playerConfig.item].title;
}

function positionListener(obj) {
    //let's us know where we are in the video
    currentPosition = obj.position;
    clipDuration = obj.duration;
}

function stateListener(obj) {
    oldState = obj.oldstate;
    if (defaultState == "NONE") {
        defaultState = "started";
        getTimeValue();
    }

    currentState = obj.newstate;
    //currentTime = obj.position;

    //pass the event to Omniture
    if (currentState == "COMPLETED") {
        //alert('Video Tracking Test\n completed');    //testing
        omniMediaTrackingDone(videoFileName, currentPosition);
        //alert('Hello');
    }
    if (currentState == "PLAYING") {
        //alert('Video Tracking Test\n play');    //testing
        if (currentPosition != "0") {
            omniMediaTrackingResume(videoFileName, currentPosition);
        }
    }
    if (currentState == "PAUSED") {
        //alert('Video Tracking Test\n paused');      //testing
        //alert(videoFileName);      //testing
        //alert(currentPosition);      //testing
        omniMediaTrackingStop(videoFileName, currentPosition);
        //alert('Hello');
    }
}

// according to Rudi 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() {
    if (currentPosition == "0") {
        //needed to allow the video to load in in order to capture the parameters
        setTimeout("getTimeValue()", 100);
    } else {
        omniInitMediaTracking(videoFileName, clipDuration, 'JWplayer');
    }
}
