/*
* $Id: standard.js 18591 2010-02-03 13:47:48Z 122999 $
*/

function isEven(x)
{
	return (x % 2) ? false : true;
}

function getYear(d)
{
  return (d < 1000) ? d + 1900 : d;
}

function checkDateFormat(fld)
{
	year = fld.value.substring(0, 4);
	month = fld.value.substring(5, 7);
	month = (month * 1) - 1;
	day = fld.value.substring(8, 10);

	var tempDate = new Date(year, month, day);
	if ((getYear(tempDate.getYear()) == year) && (month == tempDate.getMonth()) &&(day == tempDate.getDate()) )
	{
		return true;
	}
	else if (fld.value != '')
	{
		alert("The date must be entered in 'yyyy-mm-dd' format.")
		fld.value="";
	}
}

/*
* compare field1 to field2 to make sure filed2 comes after field1
*/

function checkDates(form,fld1,fld2,msg)
{
	var pass = true;

	var date1 = fld1.value.replace('-', '');
	var date2 = fld2.value.replace('-', '');

	if (date1 > date2)
	{
		pass = false;
	}

	if (!pass)
	{
		if (!msg)
		{
			alert("Please make sure you entered the dates properly.");
		}
		else
		{
			alert(msg);
		}
		return false;
	}
	else
	{
		return true;
	}
}

function isDate(elem,msg)
{
	var str = elem.value;
    var re = /^\d\d\d\d-\d\d-\d\d$/;
    var re2 = /^0000-00-00$/;
    str = str.toString();
    if (!str.match(re) || str.match(re2)) {
		if (msg)
		{
			alert(msg);
		}
		else
		{
	        alert("Enter only numbers into this field.");
		}
        setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
        return false;
    } else {
		elem.style.backgroundColor = "";
	}
    return true;
}

/*
* validates that the form element is not blank
*/

function isNotEmpty(elem) {
	var str = elem.value;
    var re = /.+/;
    if(!str.match(re)) {
        alert("Please fill in the required field.");
        setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
        return false;
    } else {
		elem.style.backgroundColor = "";
        return true;
    }
}

/*
* validates that the entry is a positive or negative number
*/

function isNumber(elem) {
	var str = elem.value;
    var re = /^[-]?\d*\.?\d*$/;
    str = str.toString();
    if (!str.match(re)) {
        alert("Enter only numbers into this field.");
        setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
        return false;
    } else {
		elem.style.backgroundColor = "";
	}
    return true;
}

function forceNumber(elem) {
	var str = elem.value;
    var re = /^[-]?\d*\.?\d*$/;
    str = str.toString();
    if (!str.match(re)) {
        elem.value = 0.00;
	}
}

function formatCurrency(strValue, noCents, prefix, emptyAllowed)
{
	strValue = strValue.toString().replace(/ /g,'');

	if (emptyAllowed==1 && strValue=='')
	{
		return '';
	}

	strValue = strValue.toString().replace(/\$|\,|&pound;|\u00A3|\�/g, '');

	if (isNaN(strValue) || strValue=='')
		strValue = "0";

	if (prefix)
	{
		prefix = prefix.toString().replace(/&pound;/g, '\u00A3');
	}
	else
	{
		prefix = '';
	}

	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));

	if (noCents=='' || !noCents) {
		return (prefix + ((blnSign)?'':'-') + dblValue + '.' + strCents);
	} else {
		return (prefix + ((blnSign)?'':'-') + dblValue);
	}
}

function currencyField(fld, noCents, prefix, emptyAllowed)
{
	fld.value = formatCurrency(fld.value, noCents, prefix, emptyAllowed);
}

/*
*   modified to remove pound signs by GSB 2006-08-03
*/

function cleanNumber(num)
{
	if (num == '') num = "0";
	num = num.toString().replace(/\$|\,|&pound;|\u00A3|\�/g, '');	
	return parseFloat(num);
}

/*
* validates that the entry is 16 characters long
*/

function isLen16(elem) {
	var str = elem.value;
    var re = /\b.{16}\b/;
    if (!str.match(re)) {
        alert("Entry does not contain the required 16 characters.");
        setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
        return false;
    } else {
		elem.style.backgroundColor = "";
        return true;
    }
}

/*
* validates that the entry is formatted as an e-mail address
* called from text field: onchange="if (isNotEmpty(this)) {isEMailAddr(this)}"
*/

function isEMailAddr(elem) {
	if (isNotEmpty(elem)) {
		var str = elem.value;
		var re = /^([a-zA-Z0-9_\.\-\'])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!str.match(re)) {
			alert("Verify the e-mail address format.");
			setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
			return false;
		} else {
			elem.style.backgroundColor = "";
			return true;
		}
	} else {
		return false;
	}
}

/*
* validate that the user made a selection other than default
*/

function isChosen(select) {
    if (select.selectedIndex == 0) {
        alert("Please make a choice from the list.");
        return false;
    } else {
        return true;
    }
}

/*
* validate that the user has checked one of the radio buttons
*/

function isValidRadio(radio) {
    var valid = false;
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            return true;
        }
    }
    alert("Make a choice from the radio buttons.");
    return false;
}

/*
* sets focus to a specified form element
*/

function focusElement(formName, elemName) {
    var elem = document.forms[formName].elements[elemName];
	var e = document.getElementById(elemName);

	e.style.borderColor = "crimson";
	e.style.borderWidth = 2;
	e.focus();
}

/*
* batch validation router
* called from form tag: onsubmit="return validateForm(this)"
*/

function validateFormExample(form) {
    if (isNotEmpty(form.name1)) {
        if (isNotEmpty(form.name2)) {
            if (isNotEmpty(form.eMail)) {
                if (isEMailAddr(form.eMail)) {
                    if (isChosen(form.continent)) {
                        if (isValidRadio(form.accept)) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}

function setDefaultFocus(fld)
{
	fld.focus()
}

/*
* launch new popup window
*/

var newWindow;
function launchStandardWindow(url,w,h,windowName)
{
	if (!newWindow || newWindow.closed) {
		newWindow = window.open(url, windowName, "toolbar=yes,status=no,resizable=yes,scrollbars=yes,location=yes,menubar=no,directories=no,width="+w+",height="+h);
	} else {
		newWindow.location.href = url;
		newWindow.resizeTo(w,h);
		newWindow.focus();
	}
}

function launchWindow(url,w,h,windowName)
{
	//	return newWindow;
	launchWindowBox(url,w,h,windowName);
}

function launchWindowBox(url, w, h, windowName, center)
{
	var pos;

	if (center == 1) {
		var int_left = (screen.width - w) / 2;
		var int_top = (screen.height - h) / 2;
		pos = ",top=" + int_top + ",left=" + int_left;
	}
	else
	{
		pos = '';
	}

	if (!newWindow || newWindow.closed) {
		newWindow = window.open(url, windowName, "toolbar=no,status=no,resizable=yes,scrollbars=yes,location=no,menubar=no,directories=no,width="+w+",height="+h+pos);
	} else {
		newWindow.location.href = url;
		newWindow.resizeTo(w, h);
		newWindow.focus();
	}

	/* return newWindow; */
}

function launchWindowBoxClean(url, w, h, windowName)
{
	var pos;

	if (w > 1000 || h > 750) {
		pos = ",top=0,left=0";
	}

	if (!newWindow || newWindow.closed) {
		newWindow = window.open(url, windowName, "location=0,toolbar=0,status=0,resizable=0,scrollbars=0,menubar=0,directories=0,width="+w+",height="+h+pos);
	} else {
		newWindow.location.href = url;
		newWindow.resizeTo(w,h);
		newWindow.focus();
	}
}

function getIndex(fld) {
	for (var i = 0; i < document.forms[0].elements.length; i++)
		if (fld == document.forms[0].elements[i])
			return i;
		return -1;
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*
* trims leading and trailing spaces
*
* use it like so:
* var_name.trim();
*/
String.prototype.trim = function () {
	return this.replace(/^\s*|\s*$/,"");
}

function fillSelect(selectCtrl, itemArray, defaultValue)
{
	var i, j, defaultSelected;

	if (selectCtrl.options)
	{
		j = 0;

		// empty existing items
		for (i = selectCtrl.options.length; i >= 0; i--)
		{
			selectCtrl.options[i] = null;
		}

		if (itemArray != null)
		{
			// add new items
			for (i = 0; i < itemArray.length; i++)
			{
				selectCtrl.options[j] = new Option(itemArray[i][0]);
				if (itemArray[i][1] != null)
				{
					selectCtrl.options[j].value = itemArray[i][1];
				}

				if (selectCtrl.options[j].value == defaultValue)
				{
					selectCtrl.options[j].selected = true;
					defaultSelected = 1;
				}

				j++;
			}

			// select first item (prompt) for sub list
			if (defaultSelected == null)
			{
				selectCtrl.options[0].selected = true;
			}
		}
	}
}

function selectEmployee(fld1,fld2,action,defaultLocation,clearFields,locations,include_all,run_js)
{
	var url = "/utils/selectEmployee.php?field_id="+fld1;

	if (fld2) {
		url += "&field_text="+fld2;
	}

	if (action)	{
		url += "&action="+action;
	}

	if (defaultLocation)	{
		url += "&selectLocation="+defaultLocation;
	}

	// comma separated list of fields to clear on parent form
	if (clearFields)	{
		url += "&clearFields="+clearFields;
	}

	// comma separated list of business units to limit drop down to
	if (locations)	{
		url += "&locations="+locations;
	}

	// whether or not to include inactive employees
	if (include_all)	{
		url += "&include_all=1";
	}

	// whether or not to include inactive employees
	if (run_js)	{
		url += "&run_js="+run_js;
	}

	launchWindowBox(url,375,170, 'selectEmployee');

	//return false;
}

function confirmDialog(msg)
{
	if (confirm(msg)) {
		return true;
	}
	else {
		return false;
	}
}

function goToStart(x) {
    history.go(x-history.length);
}

//Add addition options to your select box.
function addSelectOption(s,msg)
{
	if (!msg)
	{
		msg = 'Enter new value:';
	}

	var usr = 'option';
	if (s.value == 'other')
	{
		var o_new, o_old;
		while (usr == '' || usr == 'option')
			usr = prompt(msg, '');
		if (null != usr)
		{
			var pos = s.selectedIndex;
			o_old = s.options[s.options.length - 2];
			o_new = document.createElement('option');
			o_new.setAttribute('value', usr);
			o_new.appendChild(document.createTextNode(usr)); //remove red to maintain case
			s.insertBefore(o_new, o_old);
			s.selectedIndex = --pos;
			return true;
		}
	}
	if (!usr || s.value == 'spacer')
	{
		s.selectedIndex = 0;
		return false;
	}
}

function showHide(opt,icon)
{
	var x = document.getElementById(opt);

	var icon_show = new Image();
	var icon_hide = new Image();

	icon_show.src = "/img/button_add.gif";
	icon_hide.src = "/img/button_remove.gif";

	if (x.style.display == "none")
	{
		showElement(opt);
		if (icon) {
			document[icon].src = icon_hide.src;
		}
	}
	else
	{
		hideElement(opt);
		if (icon) {
			document[icon].src = icon_show.src;
		}
	}
}

function showElement(opt)
{
	var x = document.getElementById(opt);
	x.style.display = "block";
}

function hideElement(opt)
{
	var x = document.getElementById(opt);
	x.style.display = "none";
}

function reloadParent(form)
{
	var f;

	if (!form)
	{
		f = opener.document.forms[0];
	}
	else
	{
		f = eval("opener.document."+form);
	}

	if (f.refresh)
	{
		f.refresh.value = 1;
		f.submit();
	}

	parent.close();
}

/*
	Created for portal.  Reload parent was getting a permission denied error.
*/
function refreshParent()
{
	self.opener.location.reload();
	parent.close();
}

function tabNext(obj)
{
	var theform = obj.form;
	var i = getElementIndex(obj);
	var j=i+1;
	if (j >= theform.elements.length) { j=0; }
	if (i == -1) { return; }
	while (j != i)
	{
		borderLess = theform.elements[j].className.toUpperCase().indexOf('CURRENCYBORDERLESS');

		if (
			(theform.elements[j].type!="hidden") &&
	    	(theform.elements[j].name != theform.elements[i].name) &&
			(!theform.elements[j].disabled)
			)
		{
			if(borderLess==-1)
			{
				theform.elements[j].focus();
				theform.elements[j].select();
				break;
			}
		}
		j++;
		if (j >= theform.elements.length)
		{
			j=0;
		}
	}
}

function getElementIndex(obj)
{
	var theform = obj.form;
	for (var i=0; i<theform.elements.length; i++)
	{
		if (obj.name == theform.elements[i].name)
		{
			return i;
		}
	}
	return -1;
}

function showTab(opt)
{
	/*
	* changes the tab that the user sees on the request form
	*/

	var f = document.forms[0];

	var s;
	var panel = document.getElementById("panel_" + opt);
	var tab = document.getElementById("tab_" + opt);

	var tabs = new Array('details','reminder','repeat');

	for (i=0; i < tabs.length; i++)
	{
		s = tabs[i];
		document.getElementById("panel_" + s).style.display = "none";
		document.getElementById("tab_" + s).className = "inactive";
	}

	panel.style.display = "block";
	tab.className = "active";
}

function showRepeat(opt)
{
	/*
	* changes the form options for a repeating event
	*/
	if(opt)
	{
		var value = opt.value;

		hideElement('repeat_standard');
		hideElement('repeat_weekdays');

		if (value > 0)
		{
			showElement('repeat_standard');
		}

		if (value == 2)
		{
			showElement('repeat_weekdays');
		}
	}
}

function portalRedirect(url,template,environment)
{
	createCookie('portal_url',url);

	if (environment=='Development')
	{
		baseUrl = '/psp/dvp9/';
	}
	else
	{
		baseUrl = '/psp/prpr/';
	}

	if (template=='papp_no_nav_frame')
	{
		location.href = baseUrl + 'EMPLOYEE/EMPL/s/WEBLIB_EWS.ISCRIPT1.FieldFormula.IScript_external_url_target?url=pageletredirect.php';
	}
}

function link(url, target)
{
	if (target == 'no_nav_frame')
	{
		createCookie('portal_url', url);
		url = '/scrippsnet/redirect';
	}

	if (target == 'new')
	{
		newWindow = window.open(url, 'newWindow', 'toolbar=yes,status=yes,resizable=yes,scrollbars=yes,location=yes,menubar=yes,directories=no');
	}
	else
	{
		document.location.href = url;
	}
}

function jsgoto(url, type, key, target)
{
	url = '/goto?url='+escape(trim(url));

	if (type)
	{
		url += '&type='+escape(type);
	}

	if (key)
	{
		url += '&key='+escape(key);
	}

	link(url,target);
}

function trim(text)
{
	text = text.replace( /^\s+/g, "" ); // strip leading
	return text.replace( /\s+$/g, "" ); // strip trailing
}

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 var expires = "";
	document.cookie = name+"="+value+expires+"; path=/; domain=scrippsnet.com";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}

	return null;
}

function eraseCookie(name)
{
	createCookie(name, '', -1);
}

function clearPortalCookies()
{
	eraseCookie('PS_TOKEN');
	eraseCookie('fullname');
	eraseCookie('location');
	eraseCookie('PHPSESSID');
	eraseCookie('mylighthouse_user');
	eraseCookie('division_name');
	eraseCookie('location_name');
	eraseCookie('office');
}

function addRowClone(tblId, index)
{
	if (!index) index = 0;
	var tblBody = document.getElementById(tblId).tBodies[0];
	var newNode = tblBody.rows[index].cloneNode(true);
	tblBody.appendChild(newNode);
}

function showPopup (targetObjectId, e, sourceObjectId)
{
	if (e)
	{
		if (window.currentlyVisiblePopup == targetObjectId)
		{
			// hide any currently-visible popups
			hideCurrentPopup();
			// stop event from bubbling up any further
			e.cancelBubble = true;
			return true;
		}
		else
		{
			// hide any currently-visible popups
			hideCurrentPopup();
			// stop event from bubbling up any further
			e.cancelBubble = true;

			// and make it visible
			if (changeObjectVisibility(targetObjectId, 'block')) {
				window.currentlyVisiblePopup = targetObjectId;
				return true;
			} else {
				return false;
			}
		}
	} else {
		// there was no event object, so we won't be able to position anything, so give up
		return false;
	}
}

function hideCurrentPopup()
{
	// note: we've stored the currently-visible popup on
	// the global object window.currentlyVisiblePopup
	if (window.currentlyVisiblePopup) {
		changeObjectVisibility(window.currentlyVisiblePopup, 'none');
		window.currentlyVisiblePopup = false;
	}
} // hideCurrentPopup

// setup an event handler to hide popups for generic clicks on the document
document.onclick = hideCurrentPopup;

// utilities

function changeObjectVisibility(objectId, displayStatus)
{
	if (objectId)
	{
		document.getElementById(objectId).style.display = displayStatus
		return true;
	} else {
		// we couldn't find the object, so we can't change its visibility
		return false;
	}
}

function myLighthouseLogin()
{
        var expire = new Date();
        expire.setDate(expire.getDate()+30);
        setCookie('defaultLoginId', document.login.userid.value, expire, '/', '', true);
        document.login.submit();
}

function myLighthouseLoginScreen()
{
        var token = readCookie('PS_TOKEN');
        var home_test = location.href.search('psp');

        if (token != null && home_test < 0) {
                // redirect user to default tab
                var env_test = location.href.search('8252');

                if (env_test > 0) {
                        location.href = '/psp/dvp9/EMPLOYEE/EMPL/h/?tab=EWS_MY_WORKSPACE';
                }
                else {
                        location.href = '/psp/prpr/EMPLOYEE/EMPL/h/?tab=EWS_MY_WORKSPACE';
                }

                return true;
        }

        var loginId = readCookie('defaultLoginId');

        if (loginId > 0) {
                document.login.userid.value = loginId;
                document.login.pwd.focus();
        }
        else {
                document.login.userid.focus();
        }

        clearPortalCookies();
}

