var Merit_PopupBlockedMessage = "Your window has been blocked. \n\n Try pressing Ctrl while clicking the link. \n\nYou can check your browser information bar for more details.\nYou can also edit your popup-blocker settings to always allow popups for this site.";

function DoLogin(appName, user, pass, forceLogin, id, from, order, email)
{
	var url = appName + 'Login/DoLogin.aspx';
	var mainWin = Merit_OpenFullScreen(null);
	//var mainWin = window.open(null, '_blank', 'menubar=0,addressbar=0,toolbar=0,resizable=1,status=0,scrollbars=1')
	if (mainWin)
	{
		var doc = mainWin.document;
		doc.open();
		doc.write("<html><body><form name='frmLogin' action='" + url + "' method=post>");
		doc.write("<input type=hidden name=user value='" + user.value + "'>");
		doc.write("<input type=hidden name=pass value=''>");
		doc.write("<input type=hidden name=from value='" + from + "'>");
		var force = 0;
		if (forceLogin.checked) 
			force = 1;
		doc.write("<input type=hidden name=force value='" + force + "'>");
		if (order)
			doc.write("<input type=hidden name=po value='" + order + "'>");
		if (email)
			doc.write("<input type=hidden name=eml value='" + email + "'>");
		if (id)
			doc.write("<input type=hidden name=id value='" + id + "'>");
		doc.write("</form></body></html>");
		doc.close();
		
		doc.frmLogin.pass.value = pass.value;
		doc.frmLogin.submit();
	}
}

function CloseWin()
{
	//window.open('', '_parent', '');
	//window.close();
	var newwin = window.open(location.href,'_parent','');
	newwin.close();
}

function DoTransferToLC(appName)
{
	var url = appName + 'Login/LearningCenter.aspx?new=1';
	var mainWin = Merit_OpenFullScreen(url);
	if (mainWin)
	{
		window.opener = '';
		window.close();
	}
}

function Merit_PopupReportWindow(url)
{
	window.open(url, '_blank', 'location=0,menubar=1,toolbar=0,scrollbars,status=0,resizable');
}
function Merit_GetListSelectedValue(list)
{
	for(var i=0; i<list.options.length; i++)
	{
		if (list.options[i].selected)
			return list.options[i].value;
	}
	return null;
}

function Merit_OpenFullScreen(url)
{
	var width = screen.availWidth - 12;
	var height = screen.availHeight - 60;
	var mainWin = window.open(url, '_blank', 'left=0,top=0,width=' + width + ',height=' + height + ',menubar=0,toolbar=0,resizable=1,status=1,scrollbars=1')
	//var mainWin = window.open(url, '_blank', 'fullscreen,scrollbars,status=0')
	if (!mainWin)
	{
		alert(Merit_PopupBlockedMessage);
		return null;
	}
	return mainWin;
}

function Merit_PopupWithMenu(popURL, popWidth, popHeight, name)
{
	var popLeft = 0;
	var popTop = 0;
	if (screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
		popTop = (screen.height / 2) - (popHeight/2)
	}
	
	if (null == name)
		name = '';
		
	var winPopup = window.open(popURL, name, 'width='+ popWidth +',height='+ popHeight +',left='+ popLeft +',top='+ popTop + ',menubar=1,scrollbars=1,status=0,toolbars=0,resizable=1')
	if (!winPopup)
	{
		alert(Merit_PopupBlockedMessage);
		return null;
	}
	return winPopup;
}

function Merit_Popup(popURL, popWidth, popHeight, name)
{
	var popLeft = 0;
	var popTop = 0;
	if (screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
		popTop = (screen.height / 2) - (popHeight/2)
	}
	
	if (null == name)
		name = '';
		
	var winPopup = window.open(popURL, name, 'width='+ popWidth +',height='+ popHeight +',left='+ popLeft +',top='+ popTop + ',menubar=0,scrollbars=1,status=0,toolbars=0,resizable=1')
	if (!winPopup)
	{
		alert(Merit_PopupBlockedMessage);
		return null;
	}
	return winPopup;
}

function Merit_PopupAtTopZeroPosition(popURL, popWidth, popHeight, name)
{
	var popLeft = 0;
	var popTop = 0;
	if (screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
	}
	
	if (null == name)
		name = '';
		
	var winPopup = window.open(popURL, name, 'width='+ popWidth +',height='+ popHeight +',left='+ popLeft +',top='+ popTop + ',menubar=0,scrollbars=1,status=0,toolbars=0,resizable=1')
	if (!winPopup)
	{
		alert(Merit_PopupBlockedMessage);
		return null;
	}
	return winPopup;
}

//These global variables are used for client side validation
var VLD_Message="";
var VLD_IsValidated=0;
var VLD_FocusObject=null;

//This function sets the focus on the control
function SetFocusOnControl(ctlFocus)
{
	if (ctlFocus != null && ctlFocus.focus && !ctlFocus.disabled)
		ctlFocus.focus();
}

function ValidateForEquality(ctToValidate1, ctToValidate2 , ErrorMessages)
{
	var ValidationControl1 = document.getElementById(ctToValidate1);
	var ValidationControl2 = document.getElementById(ctToValidate2);
	
	if(ValidationControl1 != null  && ValidationControl2 != null )
	{
		if(ValidationControl1.value != ValidationControl2.value)
		{
			VLD_IsValidated = 1;
			if(VLD_FocusObject==null)
				VLD_FocusObject = ValidationControl1;		
			if(VLD_Message =='')
				VLD_Message = '- '+ErrorMessages;
			else
				VLD_Message  = VLD_Message + '\n- ' + ErrorMessages;
			return false;
		}
		else
		{
			return true;
		}	
	}
	else
	{
		return false;
	}
}

function isInteger(s)
{   var i;
	if(s.length==null)
	return false;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

//This function validate the control and accordingly set the values of above global variables.
function ValidateField(ctToValidate,ValidationType,ErrorMessages, ctl2Validate)
{
	var ValidationControl = document.getElementById(ctToValidate);
	if(ValidationType=='R')
	{
		if(Trim(ValidationControl.value)=='')
		{
			VLD_IsValidated = 1;
			if(VLD_FocusObject==null)
				VLD_FocusObject = ValidationControl;		
			if(VLD_Message =='')
				VLD_Message = '- '+ErrorMessages;
			else
				VLD_Message  = VLD_Message + '\n- ' + ErrorMessages;
				
			return false;
		}
		else
			return true;
	}
	else if (ValidationType=='C' && ctl2Validate)
	{
		var ctl2 = document.getElementById(ctl2Validate);
		if (Trim(ctl2.value) != Trim(ValidationControl.value))
		{
			VLD_IsValidated = 1;
			if (!VLD_FocusObject)
				VLD_FocusObject = ctl2;		
			if (VLD_Message == '')
				VLD_Message = '- ' + ErrorMessages;
			else
				VLD_Message = VLD_Message + '\n- ' + ErrorMessages;
			return false;
		}
		else return true;
	}
}

function ShowValidationMessage(ErrorMessage)
{
	alert(ErrorMessage);
}

function SetAllCheckBoxes(ctl, ctlChild, handlePrint)
{
	var chkBox = document.getElementById(ctl);
	var chkChild = document.forms[0].elements[ctlChild];
	
	if (chkChild) 
	{
		if (chkChild.length)
		{
			for (var i=0; i < chkChild.length; i++) 
			{
				if (!chkChild[i].disabled)
				{
					chkChild[i].checked = chkBox.checked;
					if (handlePrint)
						SetCheckBoxRowStateForPrint(chkChild[i]);
				}
			}
		}
		else
		{
			if (!chkChild.disabled)
			{
				chkChild.checked = chkBox.checked;
				if (handlePrint)
					SetCheckBoxRowStateForPrint(chkChild);
			}
		}
	}
}

function SetHeaderCheckBox(headerCheck, commonCheck, handlePrint)
{
	var headerChkBox = document.getElementById(headerCheck);
	var commonChkBox = document.getElementById(commonCheck);
	
	if (commonChkBox.checked==false)
	{
		headerChkBox.checked=false;
	}

	if (handlePrint)
		SetCheckBoxRowStateForPrint(commonChkBox);
}
function SetCheckBoxRowStateForPrint(commonChkBox)
{
	if ((commonChkBox.parentElement && commonChkBox.parentElement.parentElement) || 
		(commonChkBox.parentNode && commonChkBox.parentNode.parentNode))
	{
		var tr;
		if (commonChkBox.parentElement)
			tr = commonChkBox.parentElement.parentElement;
		else 
			tr = commonChkBox.parentNode.parentNode;
			
		var css = tr.className;
		var uncheckClass = "rptUnChkRow";
		var pos = css.indexOf(uncheckClass);
		if (commonChkBox.checked == true)
		{
			if (pos >= 0)
			{
				css = css.substring(0, pos-1);
			}
		}
		else
		{
			if (pos < 0)
			{
				css = css + " " + uncheckClass;
			}
		}
		tr.className = css;
	}
}
function PrintPage()
{
	if(navigator.userAgent.indexOf('Safari')!=-1)
	{
		alert("Use cmd key + p to print the page.\nOr you can also use control + mouse click and then choose Print Page option for printing the page.");
	}
	else
	{
		window.print();
	}
}
//	Function used to show print options.
function ShowPopup(url, framename)
{
	var frame=document.getElementById(framename);
	frame.style.display = 'block';
	frame.src = url;
}

// This file shall contain all the general javascript functionalities for OLMS application
function PopupWindow(popURL, popWidth, popHeight)
{
	popLeft = 0;
	popTop = 0;
	if(screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
		popTop = (screen.height / 2) - (popHeight/2)
	}

	showPopup = window.open(popURL, 'Popup','width='+ popWidth +', height='+ popHeight +', left='+ popLeft +',top='+ popTop + ',scrollbars=1,status=0');
}

function PopupWindowWithPrint(popURL, popWidth, popHeight, name)
{
	popLeft = 0;
	popTop = 0;
	if(screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
		popTop = (screen.height / 2) - (popHeight/2)
	}
	
	if (null == name)
		name = 'PrintPopup';
		
	// 'Popup'
	showPopup = window.open(popURL, name, 'width='+ popWidth +',height='+ popHeight +',left='+ popLeft +',top='+ popTop + ',menubar=1,scrollbars=1,status=0,toolbars=0,resizable=1')
}

// This function displays all properties of the passed object. It can be used for debugging/testing.
function dispProp(obj)
{
	var properties = "";
	var ct=0;
	for (var prop in obj)
	{
		if (ct >= 30)
		{
			alert(properties);
			properties = "";
			ct = 0;
		}
		eval ("properties += prop + \" = \" + obj.getAttribute(\"" + prop + "\") + \"\\r\\n\";");
		ct++; 
	}
	alert(properties);
}

function ToggleLayerDisplay(div)
{
	var obj = document.getElementById(div);
	if (obj.style.display == 'block')
	{
		obj.style.display = 'none';
	}
	else
	{
		obj.style.display = 'block';
	}
}

// This function displays the Forms collection in javascript. It can be used for debugging/testing.
function ShowFormValues(form)
{
	var obj;
	var msg;
	for(var idx=0; idx<form.elements.length; idx++)
	{
		obj = form.elements[idx];
		msg += "ID: " + obj.id + " | NAME: " + obj.name + " | VALUE: " + obj.value + "\r\n";
	}
	alert(msg);
}
function f_scrollTop() 
{
		return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function ShowLayerOverPage(divLayer, centered, showBigger, createLayer)
{
	if (divLayer)
	{
		// Show the div
		divLayer.style.display = 'block';
		divLayer.style.zIndex = 4;

		// Position the div in the center of the page, if specified		
		if (null == centered)
			centered = true;
			
		if (centered)
		{
			if (showBigger)
			{
				if (showBigger==1)
					divLayer.style.width=600;
				else
					divLayer.style.width=280;
			}
			var scrollheight= f_scrollTop();

			divLayer.style.left = (document.body.clientWidth - divLayer.clientWidth)/2;
			divLayer.style.top = (document.body.clientHeight - divLayer.clientHeight)/2 + scrollheight;
		}
		
		// For IE, create an ifram and position it to hide selects 
		if (createLayer)
		{
			// the frame layering is not used in workbook js for now, as we need the left and right curve images
			// of controls like tip, etc to be transparent. when shown on a frame, they appear to have a white background
			// this creates problems because since the control can be shown above any other area of the page, we cant even apply a bgcolor
			if (navigator.appName.toLowerCase() != 'netscape')
			{
				// Create an iframe, if div is being shown for the first time 
				var underlyingFrameId = divLayer.id + '_frame';
				var frameExists = false;
				eval("frameExists = ('undefined' == typeof(" + underlyingFrameId + ")) ? false : true");
				if (!frameExists)
				{
					document.body.insertAdjacentHTML("beforeEnd", "<iframe id='" + underlyingFrameId + "' src='javascript:false;' frameBorder=0 style='position:absolute; display:none' allowTransparency='true'></iframe>");
				}
				
				// Position the iframe beneath the div
				var underlyingFrame = document.getElementById(underlyingFrameId);
				underlyingFrame.style.display = 'block';
				underlyingFrame.style.zIndex = 3;
				underlyingFrame.style.top = divLayer.style.top;
				underlyingFrame.style.left = divLayer.style.left;
				underlyingFrame.style.height = divLayer.clientHeight;
				underlyingFrame.style.width = divLayer.clientWidth;
			}
		}
	}
}

function HideLayerOverPage(divLayer)
{
	if (divLayer)
	{
		divLayer.style.display = 'none';
		var underlyingFrame = document.getElementById(divLayer.id + '_frame');
		if (underlyingFrame)
		{
			underlyingFrame.style.display = 'none';
		}
	}
}

function ShowInfoBox(infoLayerId, headerText, messageText)
{
	var infoLayer = document.getElementById(infoLayerId + "_Info");
	ShowLayerOverPage(infoLayer);
	if (infoLayer)
	{
		var span;
		if (null != headerText)
		{
			span = document.getElementById(infoLayerId + '_hdr');
			span.innerText = headerText;
		}
		if (null != messageText)
		{
			span = document.getElementById(infoLayerId + '_msg');
			span.innerText = messageText;
		}
	}
}

function HideInfoBox(infoLayerId)
{
	var infoLayer = document.getElementById(infoLayerId + "_Info");
	HideLayerOverPage(infoLayer);
}

function HideShowMessage(controlID)
{
	var showMessageLayer = document.getElementById(controlID + "_msgDv");
	HideLayerOverPage(showMessageLayer);
}

function ShowOutLineNotepad(outlinenotpadId,headerText,messageText)
{
	var OutlineLayer = document.getElementById(outlinenotpadId+ "_OutLine");
	ShowLayerOverPage(OutlineLayer);
	if (OutlineLayer)
	{
		
		if (null != headerText)
		{
			span = document.getElementById(infoLayerId + '_hdr');
			span.innerText = headerText;
		}
		if (null != messageText)
		{
			span = document.getElementById(infoLayerId + '_msg');
			span.innerText = messageText;
		}
	}
}

function HideOutLineBox(infoLayerId)
{
	var infoLayer = document.getElementById(infoLayerId + "_OutLine");
	HideLayerOverPage(infoLayer);
}
//Removes Space from both sides of String supplied.
function Trim(TRIM_VALUE)
{
	if(TRIM_VALUE.length < 1)
	{
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE=="")
	{
		return "";
	}
	else
	{
		return TRIM_VALUE;
	}
} //End Function

function TrimNewLines(text)
{
	var length = text.length;
	if (length <= 0)
		return text;
	var r = "";
	for (i=0; i < text.length; i++)
		{
		if (text.charAt(i) != '\n' && text.charAt(i) != '\r' &&  text.charAt(i) != '\t') 
		   {
			r += text.charAt(i);
		   }
		}
	return r;
}

//Truncates Space on Right of String
function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0)
	{
		return"";
	}
	var iTemp = v_length -1;

	while(iTemp > -1)
	{
		if(VALUE.charAt(iTemp) == w_space)
		{
		}
		else
		{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
	iTemp = iTemp-1;

	} //End While
	return strTemp;
} //End Function

//Truncates String From Left of String.
function LTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	if(v_length < 1)
	{
		return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = 0;
	while(iTemp < v_length)
	{
		if(VALUE.charAt(iTemp) == w_space)
		{
		}
		else
		{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	} //End While
	return strTemp;
} //End Function

function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) 
{
	var nameq = name + "=";
	var c_ar = document.cookie.split(';');
	for (var i=0; i<c_ar.length; i++) 
	{
		var c = c_ar[i];
		while (c.charAt(0) == ' ') 
			c = c.substring(1,c.length);
		if (c.indexOf(nameq) == 0) 
			return unescape(c.substring(nameq.length, c.length));
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
	alert('Erasing the cookie');
}

function LoadDemoWB(url)
{
	var width = screen.availWidth - 12;
	var height = screen.availHeight - 60;
	var mainWin = window.open('', '_blank', 'left=0,top=0,width=' + width + ',height=' + height + ',menubar=0,toolbar=0,resizable=1,status=1,scrollbars=1')
	LoadWaitMessage(mainWin,url);
}

function OpenWorkbook(url)
{
	var win = Merit_OpenFullScreen('');
	LoadWaitMessage(win,url);
}

function LoadWaitMessage(win, url)
{
	if (win)
	{
		WriteDocument(win);
		win.location.href = url;
		window.opener = win;
		window.close();
	}
}

//Get the previous page number in history
function GotoPrevPageNumInHist(postbackCount,divId)
{
	if(window.history.length >0 && window.history.length >= -postbackCount)
	{
		window.history.go(postbackCount);
	}
	else
	{
		var divId = document.getElementById(divId);
		if(divId && divId.style)
		{
			divId.style.display = "none";
		}
	}
}

function disableCtrlKeyCombination(e)
{
        //list all CTRL + key combinations you want to disable
        var forbiddenKeys = new Array('n');
        var key;
        var isCtrl;
	    if(window.event)
        {
                key = window.event.keyCode;     //IE
                if(window.event.ctrlKey)
                        isCtrl = true;
                else
                        isCtrl = false;
        }
        else
        {
                key = e.which;     //firefox
                if(e.ctrlKey)
                        isCtrl = true;
                else
                        isCtrl = false;
        }
		//if ctrl is pressed check if other key is in forbidenKeys array
        if(isCtrl)
        {
				for(i=0; i<forbiddenKeys.length; i++)
                {
                        //case-insensitive comparation
                        if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
                        {
                                //alert('Key combination CTRL + '+String.fromCharCode(key)+'has been disabled.');
                                return false;
                        }
                }
        }
        return true;
}

