/* common.js */

/* Detect browser name and version */
var agt=navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();
var is_minor = parseFloat(appVer);
var is_major = parseInt(is_minor);
var iePos = appVer.indexOf('msie');
if (iePos !=-1) {
    is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
    is_major = parseInt(is_minor);
}
var is_ie = ((iePos!=-1));
var is_ie6down = (is_ie && is_minor <= 6);


// allows multiple functions attached to the window.onload event
if ( typeof( addLoadEvent ) == "undefined" ) {
	function addLoadEvent(f) { var old = window.onload; if (typeof window.onload != 'function') { window.onload = f; } else { window.onload = function onloadHandler() { old(); f();} } }
}

// runs scripting when the DOM is ready, instead of when the page is ready
function init() {
	// quit if this function has already been called
	if (arguments.callee.done) return;

	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;
	oGod.mInit();
};

// for Mozilla (IE's eventlistener is set through the htc)
if (document.addEventListener) { document.addEventListener("DOMContentLoaded", init, null); }
// for other browsers
addLoadEvent( init );


// main object for controlling behaviour
var oGod = new cGod();
function cGod(){
	var self = this;
	var DUMMY_LINK = "javascript:void(false);";
	var oWaitMessage;
	this.oWaitMessage = oWaitMessage;
	
	
	var scrollElement = "";
	this.scrollElement = scrollElement;
	
	// init is run as soon as the DOM is ready
	this.mInit = function mInit(){
		mShowWaitMessage();
		mKillFrames();
		mSetHeight();
		window.onresize = mSetHeight;
	};

	// load is run as soon as the entire document is ready, including images
	this.mLoad = function mLoad(){
		//mFixLinks();
		// attach the new link resolver, replacing mFixLinks, which is slow when there's lot's of links
		Event.observe( document.body, "click", mLinkResolver );
		fAssignCapsCheck();
		mCreateDraggables();
		
		// mScrollIntoView must appear last, or at least very late
		mScrollIntoView();
		
		// Added by RP / Morgan to fix popperIframe problem in the Safari browser on Mac
		var oPopperIframe = $( "popperIframe" );
		if (oPopperIframe)  {
		    oPopperIframe.style.position = "absolute";
		}
	};
	
	function mScrollIntoView(){
		if ( self.scrollElement && self.scrollElement != "" ){
			var oItem = $( self.scrollElement );
			if ( oItem && oItem.scrollIntoView ) {
				var oActiveElement;
				if ( document.activeElement ) { oActiveElement = document.activeElement; }
				oItem.scrollIntoView();
				// return focus to the element that had focus before we started our scrolling adventure
				if ( oActiveElement ) { oActiveElement.focus(); }
			}
		}
	}
	
	function mCreateDraggables(){
	    // set a timeout to avoid slowdowns due to calling getStyle before page has finished rendering
	    window.setTimeout( function() {
	        if ( typeof( Draggable ) != "undefined" ) {
	            var popperIframe = $( "popperIframe" );
	            if ( popperIframe ) { 
	                new Draggable( popperIframe, {revert:false, starteffect:null, endeffect:null } );
                }
                var helperIframe = $( "helperIframe" );
	            if ( helperIframe ) {
	                new Draggable( helperIframe, {revert:false, starteffect:null, endeffect:null } );
	            }
            }
	    }, 50);
	}

	function mShowWaitMessage(){
		// make sure this only get's activated once
		if ( !self.oWaitMessage ) {
			self.oWaitMessage = new Object();
			self.oWaitMessage.div = $( "waitMsg" );
			self.oWaitMessage.span = $( "waitMsgIndicator" );
			if ( !self.oWaitMessage.div || !self.oWaitMessage.span ) {
				self.oWaitMessage = null;
				return;
			}
			
			// create iframe that prevents IE's bleeding bug
			// TODO: find a more elegant way of finding out if the browser is less than IE7
			 /*@cc_on @*/
            /*@if (@_win32)
                var agt=navigator.userAgent.toLowerCase();
                var appVer = navigator.appVersion.toLowerCase();
                var is_minor = parseFloat(appVer);
                var is_major = parseInt(is_minor);
                var iePos = appVer.indexOf('msie');
                if (iePos !=-1) {
                    is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
                    is_major = parseInt(is_minor);
                }
                var is_ie = ((iePos!=-1));
                var is_ie6down = (is_ie && is_minor <= 6);
            
			    if ( is_ie6down && !self.oWaitMessage.div.getElementsByTagName( "iframe" )[0] ){
				    self.oWaitMessage.div.innerHTML = '<iframe class="bleedMat" src="about:blank" scrolling="no" frameborder="0"></iframe>' + self.oWaitMessage.div.innerHTML;
				    var ieMat = self.oWaitMessage.div.firstChild;
				    ieMat.style.width = self.oWaitMessage.div.offsetWidth + "px";
				    ieMat.style.height = self.oWaitMessage.div.offsetHeight + "px";			
			    }
            /*@end @*/
			
			self.oWaitMessage.count = 2;
		
			self.oWaitMessage.tick = function waitTimer_Handler() {
				if ( oGod.oWaitMessage && oGod.oWaitMessage.count > 0  ) {
					oGod.oWaitMessage.count--;
					//oGod.oWaitMessage.span.innerHTML = oGod.oWaitMessage.count;
				} else { 
					oGod.mHideWaitMessage();
				}
			};
			oGod.oWaitMessage.id = window.setInterval( oGod.oWaitMessage.tick, 1000 );			
			self.oWaitMessage.div.style.display = "block";
		}
		
	}
	this.mShowWaitMessage = mShowWaitMessage;
	
	function mHideWaitMessage(){
		if ( self.oWaitMessage ) {
			window.clearInterval( self.oWaitMessage.id );
			self.oWaitMessage.div.style.display = "none";
			self.oWaitMessage = null;
		}
	}
	this.mHideWaitMessage = mHideWaitMessage;
	

	// Sets the height of the main content area
	function mSetHeight() {
		var oMenuBar = $( "menubar" );
		var oContentWrapper = $( "content_wrapper" );
		var oContent = $( "content" );
		var oBottomWrapper = $( "bottomBanner_wrapper" );
		
		if ( oMenuBar && oContentWrapper ) {
		
			// Set height
			var iTopAndBottomHeight = 89 + 34; // Set this to the total height of the topbar(s) and bottombar(s)
			var x,y;
			if (window.innerHeight) { // all except Explorer
				x = window.innerWidth;
				y = window.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				x = document.documentElement.clientWidth;
				y = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				x = document.body.clientWidth;
				y = document.body.clientHeight;
			}
			var newHeight = y - iTopAndBottomHeight;
			if (newHeight < 0)
				newHeight = 0;
			oMenuBar.style.height = newHeight + "px";
			if (oBottomWrapper)
				iTopAndBottomHeight += 60;
			iTopAndBottomHeight += 48; // Padding
			newHeight = y - iTopAndBottomHeight;
			if (newHeight < 0)
				newHeight = 0;
			oContent.style.height = newHeight + "px";
			
//			var newWidth = x - 165;
//			if (newWidth < 20)
//				newWidth = 0;								
//			else if (newWidth > 450)
//				newWidth = 450;
//			else
//				newWidth = newWidth - 20;
//			oContentWrapper.style.width = newWidth + "px";
		}
	}
	
	// Gets how many pixels the window has been scrolled down
	this.get_ScrollYPosition = function get_ScrollYPosition()
	{
	    return ie? ietruebody().scrollTop : window.pageYOffset;
	}
	
	// Gets the height of the main content area
	this.get_WindowHeight = function get_WindowHeight()
	{
	    if (window.innerHeight)
	        // all except Explorer
	        return window.innerHeight;
	    else if (document.documentElement && document.documentElement.clientHeight)
	        // Explorer 6 Strict Mode
	        return document.documentElement.clientHeight;   
	    else if (document.body)
	        // other Explorers
	        return document.body.clientHeight
	    else
	        return -1;
	}
	
	// Gets the width of the main content area
	this.get_WindowWidth = function get_WindowWidth()
	{
	    if (window.innerWidth)
	        // all except Explorer
	        return window.innerWidth;
	    else if (document.documentElement && document.documentElement.clientWidth)
	        // Explorer 6 Strict Mode
	        return document.documentElement.clientWidth;   
	    else if (document.body)
	        // other Explorers
	        return document.body.clientWidth
	    else
	        return -1;
	}	
	
    this.mOpenPopperIframe = function mOpenPopperIframe( href )
    {
        //document.body.scrollIntoView();
        var top = this.get_ScrollYPosition();        
	
        var oContainer = $( "popperIframe" );
        oContainer.style.top = top + 100 + "px"
        oContainer.style.display = "block";
        var oClose = $( "btnClose" );
        oClose.onclick = function CloseOnClick() {
	        oContainer.style.display = "none";
	        return true;
        }
        var oPopperFrame = $( "popperFrame" );
        var oPopperFrameScrolling = $( "popperFrameScrolling" );
        if ( false ) // this.rel == "popperIframeWithScrolling" ) {
        {
			if (oPopperFrameScrolling.contentDocument)
			{
				// open followed by close clears existing content.
				oPopperFrameScrolling.contentDocument.open();
				oPopperFrameScrolling.contentDocument.close();
			}
	        oPopperFrame.style.display = "none";
	        oPopperFrameScrolling.style.display = "block";
	        oPopperFrameScrolling.src = href;
        } else {            
			if (oPopperFrame.contentDocument)
			{
				// open followed by close clears existing content.
				oPopperFrame.contentDocument.open();
				oPopperFrame.contentDocument.close();
			}			
	        oPopperFrame.src = href;
	        oPopperFrame.style.display = "block";
	        oPopperFrameScrolling.style.display = "none";
        } 
        oGod.mCloseHelperIframe();
    }
    
	// by declaring the function on this, it becomes public
	this.mClosePopperIframe = function mClosePopperIframe( doPostBack, reloadPage ) {
		mCloseAnyIframe( "popperIframe", "popperFrame", doPostBack, reloadPage, null, null );
	}

	// by declaring the function on this, it becomes public
	this.mClosePopperIframeWithArguments = function mClosePopperIframeWithArguments( eventTarget, eventArgument ) {
		mCloseAnyIframe( "popperIframe", "popperFrame", true, false, eventTarget, eventArgument );
	}

	// by declaring the function on this, it becomes public
	this.mCloseHelperIframe = function mCloseHelperIframe( doPostBack, reloadPage ) {
		mCloseAnyIframe( "helperIframe", "helperFrame", doPostBack, reloadPage, null, null );
	}

	// by declaring the function on this, it becomes public
	function mCloseAnyIframe( sContainerId, sFrameId, doPostBack, reloadPage, postbackEventTarget, postbackEventArgument ) {
		var oContainer = $( sContainerId );
		var oFrame = $( sFrameId );
		if ( oContainer && oFrame ) {
			oContainer.style.display = "none";
			
			if (oFrame.contentDocument)
			{
				// Open opens a stream for writing new content. 
				// Close forces the document to render. This effectively
				// clears the iFrame before showing (otherwise old
				// content may appear if another iFrame has been opened)
				oFrame.contentDocument.open();
				oFrame.contentDocument.close();
	        }
			
			oFrame.src = "";
		}
	    if ( doPostBack ) {
		    __doPostBack(postbackEventTarget, postbackEventArgument);
	    } else if ( reloadPage ) {
		    window.location.reload( true );
	    }
        return false;
	}

    // Refresh this page, either by postback, which maintains viewstate, or a reload, which starts everything over
    this.mRefresh = function mRefresh( doPostBack, reloadPage, bCascade ) {
	    if ( doPostBack ) {
		    __doPostBack(null, null);
	    } else if ( reloadPage ) {
	        window.location.reload( true );
	    }
	    if ( window.opener && bCascade ) {
		    window.opener.oGod.mRefresh( doPostBack, reloadPage, bCascade );
	    }
    }
	
	this.mFixIframeScrolling = function mFixIframeScrolling() {
		// only fix this for IE
		if ( !window.innerHeight ) {
			var iFrame = $("popperIframe");
			if ( iFrame ) {
				iFrame.scrolling = "yes";
			}
		}
	}

	function mKillFrames() {
	    // close frame if opened in frame by another site
	    // only exeception is our own ExternalProfileFrame.aspx (an iframe which we offer other sites use on their sites)
		var ExternalProfileFrame = $("ExternalProfileFrame");
		if ( !ExternalProfileFrame ) {

            try {
		        if (window.self.location.href != window.top.location.href) {
			        if ( window.top.location.replace ) {
				        window.top.location.replace(window.self.location.href);
			        } else {
				        window.top.location = window.self.location.href;
			        }
		        }
            } catch ( ex ) {
                try {
                    window.top.location = window.self.location.href;
                } catch ( ex2 ) {
                    window.open( window.self.location.href );
                    window.close();
                }
            }			
		}

	}	
	
	
	// Attached to document.body, examines the rel attribute of clicked links, and acts accordingly
	// Replaces mFixLinks
	function mLinkResolver( e ){
        var origin = Event.element( e );
        if ( origin.tagName.toLowerCase() == "img" ) { 
            origin = origin.up( "a" );
        }
        
        // ps: fix - clicking on any image that was not supposed 
        // to be a link resulted in an js-error
        if (typeof(origin) == "undefined")
            return;
        
        if ( origin.tagName.toLowerCase() == "a" && origin.rel && origin.rel != "" ){
            var rel = String( origin.rel );
            
            switch( rel ) {
                case "popup":
				    window.open ( origin.href, "", "width=450,height=540,scrollbars=yes,resizable=yes" );
				    return false;
                    break;
                case "adminpopup":
       				window.open ( origin.href, "", "width=600,height=540,scrollbars=yes,resizable=yes,top=50,left=50" );
				    return false;
				    break;
				case "adminPopup":
				    window.open ( origin.href, "", "width=1024,height=768,scrollbars=yes,resizable=yes,top=50,left=50" );
				    return false;
				    break;
				case "external":
		            window.open( origin.href );
		            return false;
				    break;
				case "print":
			        origin.href = DUMMY_LINK;
                    window.print();
                    return false;
				    break;
				case "close":
			        origin.href = DUMMY_LINK;
			        window.close(); 
			        return false;
			        break;
			    case "popperIframe":
			    case "popperIframeWithScrolling":
			        // dual iframe thingy, because of scrollbars "feature" in IE
    			    
		            // Since popperIframes position is fixed, this makes sure that it is visible after being triggered by a link
		            // document.body.scrollIntoView();
                    var top = ie? ietruebody().scrollTop : window.pageYOffset        
		                			
			        var oContainer = $( "popperIframe" );
			        oContainer.style.top = top + 100 + "px";
			        oContainer.style.display = "block";
			        var oClose = $( "btnClose" );
			        oClose.onclick = function CloseOnClick() {
				        oContainer.style.display = "none";
				        return true;
			        }
			        var oPopperFrame = $( "popperFrame" );
			        var oPopperFrameScrolling = $( "popperFrameScrolling" );
			        if ( this.rel == "popperIframeWithScrolling" ) {
						if (oPopperFrame.contentDocument)
						{
							// open followed by close clears existing content.
							oPopperFrame.contentDocument.open();
							oPopperFrame.contentDocument.close();
						}						
				        oPopperFrame.style.display = "none";
				        oPopperFrameScrolling.style.display = "block";
				        oPopperFrameScrolling.src = origin.href;
			        } else {
						if (oPopperFrame.contentDocument)
						{
							// open followed by close clears existing content.
							oPopperFrame.contentDocument.open();
							oPopperFrame.contentDocument.close();
						}
				        oPopperFrame.src = origin.href;
				        oPopperFrame.style.display = "block";
				        oPopperFrameScrolling.style.display = "none";
			        } 
			        oGod.mCloseHelperIframe();
			        return false;
			        break;
                case "helper":
	                var oContainer = $( "helperIframe" );
	                if ( oContainer ) {
	                    oContainer.style.display = "block";
	                }
	                var oClose = $( "btnHelperClose" );
	                oClose.onclick = function HelperCloseOnClick() {
	                    oContainer.style.display = "none";
	                    return true;
	                }
	                var oHelperFrame = $( "helperFrame" );
	                if ( oHelperFrame ) {
	                    oGod.mClosePopperIframe();
	                    oHelperFrame.style.display = "block";
	                    oHelperFrame.src = origin.href;
	                }
	                return false;
                    break;		        
				case "impersonate": 
			        // Impersonate links must open in the same window
			        if (origin.impersonate) {
			            origin.impersonate.close()
			        }
			        origin.impersonate = window.open ( origin.href, "impersonate", "width=1024,height=768,toolbar=1,resizable=1,directories=0,status=1,menubar=1,scrollbars=1,location=1, top=20, left=20", true );	
			        origin.impersonate.focus();
			        return false;
				    break;
            }
        }
	}
	
	/* REFINE: - Calculate position of windows */
	function mFixLinks() {
		var oLinks = document.getElementsByTagName("a");
		var oLink, i = 0;
		
		// iterate throug all links, and assign behaviour based on values in rel attributes
		while ( oLink = oLinks[i++] ) {
		    var rel = String(oLink.rel);
			if ( rel == "popup" ) {
				oLink.onclick = function PopupOnCLick() {
					window.open ( this.href, "", "width=450,height=540,scrollbars=yes,resizable=yes" );
					return false;
				};
			} else if ( rel == "adminpopup" ) {
				oLink.onclick = function PopupOnCLick() {
					window.open ( this.href, "", "width=600,height=540,scrollbars=yes,resizable=yes" );
					return false;
				};
			} else if ( rel == "external" ) {
				oLink.target = "_blank";
			} else if ( rel == "adminPopup" ) {
				oLink.onclick = function AdminPopupOnClick() {
					window.open ( this.href, "", "width=1024,height=768,scrollbars=yes,resizable=yes" );
					return false;
				};
			} else if ( rel == "print" ) {
				oLink.href = DUMMY_LINK;
				oLink.onclick = function PrintOnClick() {
					window.print();
					return false;
				}
			} else if ( rel == "close" ) {
				oLink.href = DUMMY_LINK;
				oLink.onclick = function CloseOnClick() { 
					window.close(); 
					return false;
				};
			} else if ( rel == "popperIframe" || rel == "popperIframeWithScrolling" ) {
				// dual iframe thingy, because of scrollbars "feature" in IE
				oLink.onclick = function PopperIframeOnClick() {
				
				    // Since popperIframes position is fixed, this makes sure that it is visible after being triggered by a link
				    document.body.scrollIntoView();
				
					var oContainer = $( "popperIframe" );
					oContainer.style.display = "block";
					var oClose = $( "btnClose" );
					oClose.onclick = function CloseOnClick() {
						oContainer.style.display = "none";
						return true;
					}
					var oPopperFrame = $( "popperFrame" );
					var oPopperFrameScrolling = $( "popperFrameScrolling" );
					if ( this.rel == "popperIframeWithScrolling" ) {
						oPopperFrame.style.display = "none";
						oPopperFrameScrolling.style.display = "block";
						oPopperFrameScrolling.src = this.href;
					} else {
						oPopperFrame.src = this.href;
						oPopperFrame.style.display = "block";
						oPopperFrameScrolling.style.display = "none";
					} 
					oGod.mCloseHelperIframe();
					return false;
				};
			} else if ( rel == "helper" ) {
			    oLink.onclick = function helperIFrameOnClick() {
			        var oContainer = $( "helperIframe" );
			        if ( oContainer ) {
			            oContainer.style.display = "block";
			        }
			        var oClose = $( "btnHelperClose" );
			        oClose.onclick = function HelperCloseOnClick() {
			            oContainer.style.display = "none";
			            return true;
			        }
			        var oHelperFrame = $( "helperFrame" );
			        if ( oHelperFrame ) {
			            oGod.mClosePopperIframe();
			            oHelperFrame.style.display = "block";
			            oHelperFrame.src = this.href;
			        }
			        return false;
			    };
			} else if ( rel == "impersonate" ) {
				// Impersonate links must open in the same window
				oLink.onclick = function ImpersonateOnClick() {
					if (this.impersonate) {
					    this.impersonate.close()
					}
					this.impersonate = window.open ( this.href, "impersonate", "width=1024,height=768,toolbar=1,resizable=1,directories=0,status=1,menubar=1,scrollbars=1,location=1, top=20, left=20", true );	
					this.impersonate.focus();
					return false;
				};
			}
		}
	}
	
	/**
	    Validates multiple emails, separated by ";"
	*/
	function mValidateMultipleEmail( oInput, xEmail, xWhiteSpace ){	 
	    if ( !oInput || !xEmail || !xWhiteSpace ) { return null; }
	    oInput.value = oInput.value.replace( xWhiteSpace, ";" );
	    oInput.value = oInput.value.replace( /\,/g, ";" );
	    oInput.value = oInput.value.replace( /\;{2,}/g, ";" );
	    var aValues = oInput.value.split( ";" );
	    var aValue, i = 0;
	    var bIsValid = true;
	    while ( aValue = aValues[i++] ) {
		    if ( aValue != ";" ){
			    bIsValid = bIsValid && aValue.match( xEmail );	
		    } 
	    }
	    return bIsValid;
	}
	this.mValidateMultipleEmail = mValidateMultipleEmail;
	
	
	this.mPopulateSkillNames = function mPopulateSkillNames( sName, sAbbriviation, sControlID ) {
	    if ( typeof( PopulateSkillNames ) == "function" ) {
	        return ( PopulateSkillNames( sName, sAbbriviation, sControlID ) );
	    }
	    return false;
	}
	
	function fAssignCapsCheck() {
		var oInputs = document.getElementsByTagName("input");
		var oInput, i = 0;
		while ( oInput = oInputs[i++] ) {
			if ( oInput.className.indexOf( "capsLockOff" ) != -1 ) {
				oInput.onkeypress = function OnKeyPressHandler( e ) {
					if (!e) var e = window.event;
					var myKeyCode=0;
					var myShiftKey=false;

					// Internet Explorer 4+
					if ( document.all ) {
						myKeyCode = e.keyCode;
						myShiftKey = e.shiftKey;
					// Netscape 4
					} else if ( document.layers ) {
						myKeyCode = e.which;
						myShiftKey = ( myKeyCode == 16 ) ? true : false;
					// Netscape 6
					} else if ( document.getElementById ) {
						myKeyCode = e.which;
						myShiftKey = ( myKeyCode == 16 ) ? true : false;
					}
					// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
					if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
						this.className = "capsLockOn"
					} else {
						this.className = "capsLockOff"
					}
				}
			}
		}
	}
}

addLoadEvent( oGod.mLoad );

/** sets checked to true for a list of checkboxes */
function checkRest(){
	//get a list of all the input fields to check.
	var checkList = this.checkList.split(",");

	//if we are unchecking then don't check the rest in the list.
	if(this.checked == true){
		for(i = 0; checkList[i] != null; ++i ){
			var oCheckBox = $(checkList[i]);
			if ( oCheckBox ) {
				oCheckBox.checked = true;
			}
		}
	}
}


addLoadEvent( fIsFormDirty );
function fIsFormDirty(){
	oHidden = $("ctl00_FormDirty");
	if ( oHidden && ( oHidden.value == "true" || oHidden.value == "True" ) ){ 
		window.isDirty = true;
	}
}


