// Form Confirm -----------------------------------------
function confirmSubmit(frm, btnVal) {
	if (confirm('Are you sure you want to do this?')) {
		if (!btnVal) {
			btnVal='delete';
		}
		frm.button.value=btnVal;
		frm.submit();
	} else {
		return;
	}
}

// AJAX Call Support ------------------------------------
var req;

function asyncRequest(url) {
	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		if (url.indexOf('?') == -1) {
			url = url + ';' + new Date().getTime();
		} else {
			urlArray = url.split('?');
			url = urlArray[0] + ';' + new Date().getTime() + '?' + urlArray[1];
		}
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send("");
	}

	function processReqChange() {
	    // only if req shows "loaded"
	    if (req.readyState == 4) {
	        // only if "OK"
	        if (req.status == 200) {
	            // ...processing statements go here...
	            processAjaxResponse(); //Implement this function in the page
	        } else {
	            alert("There was a problem retrieving the XML data:\n" + req.statusText);
	        }
	    }
	}
}

function asyncPOSTRequest(url, parameters) {
	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		if (url.indexOf('?') == -1) {
			url = url + ';' + new Date().getTime();
		} else {
			urlArray = url.split('?');
			url = urlArray[0] + ';' + new Date().getTime() + '?' + urlArray[1];
		}
		req.onreadystatechange = processReqChange;
		req.open('POST', url, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", parameters.length);
		req.setRequestHeader("Connection", "close");
		req.send(parameters);
	}

	function processReqChange() {
	    // only if req shows "loaded"
	    if (req.readyState == 4) {
	        // only if "OK"
	        if (req.status == 200) {
	            // ...processing statements go here...
	            processAjaxResponse(); //Implement this function in the page
	        } else {
	            alert("There was a problem retrieving the XML data:\n" + req.statusText);
	        }
	    }
	}
}

function syncPOSTRequest(url, parameters) {
	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		if (url.indexOf('?') == -1) {
			url = url + ';' + new Date().getTime();
		} else {
			urlArray = url.split('?');
			url = urlArray[0] + ';' + new Date().getTime() + '?' + urlArray[1];
		}

		req.open('POST', url, false);  // 3rd parameter false makes this synchronous
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", parameters.length);
		req.setRequestHeader("Connection", "close");
		req.send(parameters);
		return req.responseText;
	}
}

// AJAX Calls for Security tab ---------------------------
function makeAddApplicationAjaxCall() {
	var applicationName = trim(document.getElementById('applicationName').value);
	var typeCode = trim(document.getElementById('typeCode').value);
	if ('' == applicationName || null == applicationName ||
		'' == typeCode || null == typeCode) {
		alert("Please enter a value for both Name and Code.");
		return false;
	}
	var url = '../admincms/add.application.security';
	var params = 'fromForm=true&applicationName=' + applicationName + '&typeCode=' + typeCode;
	asyncPOSTRequest(url, params);
}
function makeAddSecurityRoleAjaxCall() {
	var securityRole = trim(document.getElementById('securityRole').value);
	if ('' == securityRole || null == securityRole) {
		alert("Please enter the name of the Security Role.");
		return false;
	}
	var url = '../admincms/securityrole.security';
	var params = 'fromForm=true&securityRole=' + securityRole;
	asyncPOSTRequest(url, params);
}
function makeDeleteSecurityRoleAjaxCall() {
	var securityRoles = document.getElementsByName('secRole');
	var checkedCount = 0;
	var elementId;
	var securityRoleId;
	for (i = 0; i < securityRoles.length; i++) {
		if (securityRoles[i].checked) {
			checkedCount++;
			if (checkedCount > 1) {
				alert("Please check only one Security Role to be deleted.");
				return false;
			}
			// Get the portion of the element's id that is the securityRoleId, 
			// i.e., the portion after 'secRole_'
			elementId = securityRoles[i].id.split('_');
			securityRoleId = elementId[1];
		}
	}
	if (checkedCount < 1) {
		alert("Please check a Security Role to be deleted.");
		return false;
	}
	var url = '../admincms/securityrole.security';
	var params = 'fromDelete=true&securityRoleId=' + securityRoleId;
	asyncPOSTRequest(url, params);
}
function makeSelectSiteAjaxCall() {
	var applicationId = getApplicationIdFromSelect();
	var url = '../admincms/appsecurityrole.security';
	var params = 'applicationId=' + applicationId;
	asyncPOSTRequest(url, params);
}
function makeAssignSiteAjaxCall() {
	var availableRoles = document.getElementsByName('availRole');
	var checkedCount = 0;
	var elementId;
	var securityRoleId;
	for (i = 0; i < availableRoles.length; i++) {
		if (availableRoles[i].checked) {
			checkedCount++;
			if (checkedCount > 1) {
				alert("Please check only one available Security Role to be assigned.");
				return false;
			}
			// Get the portion of the element's id that is the securityRoleId, 
			// i.e., the portion after 'availRole_'
			elementId = availableRoles[i].id.split('_');
			securityRoleId = elementId[1];
		}
	}
	if (checkedCount < 1) {
		alert("Please check an available Security Role to be assigned.");
		return false;
	}
	var applicationId = getApplicationIdFromSelect();
	var url = '../admincms/appsecurityrole.security';
	var params = 'fromForm=true&securityRoleId=' + securityRoleId + '&applicationId=' + applicationId;
	asyncPOSTRequest(url, params);
}
function makeUnassignSiteAjaxCall() {
	var assignedRoles = document.getElementsByName('assignRole');
	var checkedCount = 0;
	var elementId;
	var appSecurityRoleId;
	for (i = 0; i < assignedRoles.length; i++) {
		if (assignedRoles[i].checked) {
			checkedCount++;
			if (checkedCount > 1) {
				alert("Please check only one assigned Security Role to be unassigned.");
				return false;
			}
			// Get the portion of the element's id that is the securityRoleId, 
			// i.e., the portion after 'assignRole_'
			elementId = assignedRoles[i].id.split('_');
			appSecurityRoleId = elementId[1];
		}
	}
	if (checkedCount < 1) {
		alert("Please check an assigned Security Role to be unassigned.");
		return false;
	}
	var applicationId = getApplicationIdFromSelect();
	var url = '../admincms/appsecurityrole.security';
	var params = 'fromDelete=true&applicationSecurityRoleId=' + appSecurityRoleId + '&applicationId=' + applicationId;;
	asyncPOSTRequest(url, params);
}
function getApplicationIdFromSelect() {
	var elementId;
	var applicationId;
	var siteForRole = document.getElementById('siteForRole');
	for (i = 0; i < siteForRole.length; i++) { 
		if (siteForRole.options[i].selected) {
			// Get the portion of the element's id that is the applicationId, 
			// i.e., the portion after 'siteForRole_'
			elementId = siteForRole[i].id.split('_');
			applicationId = elementId[1];
		}
	}
	return applicationId;
}
function makeEditUserAjaxCall(employeeId) {
	var url = '../admincms/useredit.security?employeeId=' + employeeId;
	asyncRequest(url);
}
function makeSaveUserAjaxCall(employeeId) {
	// Harvest the values of the parameters
	var employeeId = document.getElementById('employeeId').value;
	var firstName = trim(document.getElementById('firstName').value);
	var lastName = trim(document.getElementById('lastName').value);
	var email = trim(document.getElementById('email').value);
	var logonId = trim(document.getElementById('logonId').value);
	var password = trim(document.getElementById('password').value);
	var confirmPassword = trim(document.getElementById('confirmPassword').value);
	var isActive = document.getElementById('isActive').checked;
	
	// Validate input - required fields and password matching, formatting, and length
	var errorMsg = '';
	errorMsg = validateRequired(firstName, 'First Name', errorMsg);
	errorMsg = validateRequired(lastName, 'Last Name', errorMsg);
	errorMsg = validateRequired(logonId, 'Logon Name', errorMsg);
	if (null == employeeId || '' == employeeId) {
		errorMsg = validateRequired(password, 'Password', errorMsg);
		errorMsg = validateRequired(confirmPassword, 'Confirm Password', errorMsg);
	}
	if ('' != trim(errorMsg)) {
		alert(errorMsg);
		return;
	}
	
	if (null != password && '' != password) {
		if (password.length < 7) {
			errorMsg = 'Password must be a minimum of 7 characters.'
			alert(errorMsg);
			return;
		}
		if (!checkPasswordFormat(password)) {
			return;
		}
	}

	if (password != confirmPassword) {
		errorMsg = 'Password and Confirm Password do not match.'
		alert(errorMsg);
		return;
	}

	// Assemble the parameters & make the AJAX call
	// Iterate over the ApplicationSecurityRoles available for selection
	var appSecRolesDiv = document.getElementById('roleList');
	var appSecRoles = appSecRolesDiv.getElementsByTagName('input');
	var appSecRole;
	var appSecRoleId;
	var appSecRoleParams = '';
	for (var i = 0; i < appSecRoles.length; i++) {
		appSecRole = appSecRoles[i];
		appSecRoleId = appSecRole.id.split('_')[1];
		if ('none' != appSecRoleId && appSecRole.checked) {
			appSecRoleParams += '&appSecurityRoleId=' + appSecRoleId;
		}
	}
	var params = 'fromForm=true&employeeId=' + employeeId +
				 '&firstName=' + firstName +
				 '&lastName=' + lastName +
				 '&email=' + email +
				 '&logonId=' + logonId +
				 '&password=' + password +
				 '&isActive=' + isActive + 
				 appSecRoleParams;
	var url = '../admincms/usersave.security';
	asyncPOSTRequest(url, params);
}
// End AJAX Calls for Security tab ---------------------------

// AJAX Call for content.jsp and files.jsp ---------------------------
function makeSetSessionAttributeAjaxCall(typeCode) {
	var url = '../admincms/session.set.attribute';
	var params = 'attribute=typecode&value=' + typeCode;
	syncPOSTRequest(url, params);
}
// End AJAX Calls for content.jsp and files.jsp ----------------------

// String trim function ---------------------------
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

// Required field validation function -------------
function validateRequired(value, name, errorMsg) {
	if (null == value || '' == trim(value)) {
		if ('' == errorMsg) {
			errorMsg += name + ' is required.';
		} else {
			errorMsg += '\n' + name + ' is required.';
		}
	}
	return errorMsg;
}

function callHasValue(call) {
	var callArray = call.split(':');
	if (callArray[1] == '') {
		return false;
	}
	return true;
}
function validateCurrencyField(fld) {
	var Chars = "0123456789.,$";
	for (var i = 0; i < fld.value.length; i++) {
		if (Chars.indexOf(fld.value.charAt(i)) == -1) {
			return false;
		}
	}
	return true; 			
}
function getOffset(topSpace) {
	return (document.documentElement.scrollTop + topSpace);
}
function working(flag) {
	if (flag) {
	document.getElementById('responseMessage').style.top = getOffset(250) + 'px';
	document.getElementById('pageFilter').style.top = getOffset(0) + 'px';
		document.getElementById('responseMessage').style.visibility='visible';
		document.getElementById('pageFilter').style.visibility='visible';
	} else {
		document.getElementById('responseMessage').style.visibility='hidden';
		document.getElementById('pageFilter').style.visibility='hidden';
	}
}	
function hideTable() {
	document.getElementById('tableDiv').style.visibility='hidden';
	document.getElementById('pageFilter').style.visibility='hidden';
}
function showTable() {
	document.getElementById('tableDiv').style.top = getOffset(120) + 'px';
	document.getElementById('pageFilter').style.top = getOffset(0) + 'px';
	document.getElementById('tableDiv').style.visibility='visible';
	document.getElementById('pageFilter').style.visibility='visible';
}
function copyToClipBoard(id) {
	var fld = document.getElementById(id);
	window.clipboardData.setData('Text',fld.value);
	//alert(fld.value + ' Copied to Clipboard');
}
function currentWidth() {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}	
function currentHeight() {
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		 //Non-IE
		 myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}
function formatCurrency(num) {
	if(isNaN(num)) {
		num = '0';
	}
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10) {
		cents = "0" + cents;
	}
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	}
	
	//return (((sign)?'':'-') + '$' + num + '.' + cents);
	return (((sign)?'':'-') + num + '.' + cents);
}	
function displayVideoCustom(vid) {
	var URL = '../public/view.video?my_Video='+vid+'.flv&my_FeatureHold=default.jpg';
	var foo = window.open(URL, 'wplayer', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=342,height=295');
}
function displayVideo(productId) {
	var URL = '/web/public/static/flash.view?my_Video='+productId+'.flv&my_FeatureHold='+productId+'.jpg';
	var foo = window.open(URL, 'wplayer', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=342,height=295');
}
// Usage: onkeypress="capLock(event)"
function capLock(e){
	kc = e.keyCode?e.keyCode:e.which;
	sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
	if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)) {
		alert ( 'WARNING:\n\nCaps Lock is enabled\n\nThis field is case sensitive' );
	} else {

	}
}	

function confirmPasswordMatch(password, confirmPassword) {

	if (password != confirmPassword) {
		errorMsg = 'Password and Confirm Password do not match.';
		alert(errorMsg);
		return false;
	}
	
	return true;
}

function checkPasswordMinLength(password) {
	if (null != password && '' != password) {
		if (password.length < 7) {
			errorMsg = 'Password must be a minimum of 7 characters.';
			alert(errorMsg);
			return false; 
		}
	} else {
		errorMsg = 'Password must be a minimum of 7 characters.';
		alert(errorMsg);
		return false;
	}
	return true;
}

function checkPasswordMaxLength(password) {
	if (null != password && '' != password) {
		if (password.length > 20) {
			errorMsg = 'Password must be a maximum of 20 characters.';
			alert(errorMsg);
			return false; 
		}
	} else {
		errorMsg = 'Password must be a maximum of 20 characters.';
		alert(errorMsg);
		return false;
	}
	return true;
}

function checkPasswordFormat(password) {
	if (null != password && '' != password) {
		var myRegxp =  /^[A-Za-z0-9]*?([A-Za-z][0-9]|[0-9][A-Za-z])[A-Za-z0-9]*$/;
		if(!myRegxp.test(password)) {
			errorMsg = 'Password must be alphanumeric and contain at least 1 number and 1 letter.';
			alert(errorMsg);
			return false; 
		}
	} else {
		errorMsg = 'Password must be alphanumeric and contain at least 1 number and 1 letter.';
		alert(errorMsg);
		return false;
	}
	return true;
}
function verifyPassword(newPassword, confirmPassword) {
	if(!checkPasswordMinLength(newPassword)) {
		return;
	}
	
	if(!checkPasswordMaxLength(newPassword)) {
		return;
	}
	
	if(!confirmPasswordMatch(newPassword, confirmPassword)) {
		return;
	}
	
	if(!checkPasswordFormat(newPassword)) {
		return;
	}
	
	return true;
}

// Keeps links from being active on a page that calls this function in onload of body tag
// Used on decorators within CMS only to prevent all navigation from a previewed page
function suppressLinks() {
	var outLink;
	if (document.getElementsByTagName('a')) {
		for (var i = 0; (outLink = document.getElementsByTagName('a')[i]); i++) {
			outLink.setAttribute('href', '#');
			outLink.setAttribute('target', '_self');
    	}
	}
	if (document.getElementsByTagName('area')) {
		for (var i = 0; (outLink = document.getElementsByTagName('area')[i]); i++) {
			outLink.setAttribute('href', '#');
			outLink.setAttribute('target', '_self');
    	}
	}
} 	


