
String.prototype.trim = function() {
	return this.replace(/(^\s+)|(\s+$)/g, "");
}

function addParamToAction(formName, paramName, paramValue) {
	document.getElementsByName(formName)[0].attributes.action.value += '&' + paramName + '=' + paramValue;
	return true;
}

//Moves serial numbers from from box to other
function moveSelectItems(sFromList, sToList)
{
	var selectFrom = document.getElementById(sFromList);
	var selectTo = document.getElementById(sToList);

	var selectFromLength = selectFrom.length;
	var selectToLength = selectTo.length;

	var strShow = ""

	//Loop through and move all selected items to other list box.
	for (var j=0; j<selectFromLength; j++)
	{
		if (selectFrom.options[j].selected)
		{
			//strShow += "\n " + selectBoxOne.options[j].text;
			selectTo.options[selectToLength++] = new Option(selectFrom.options[j].text,selectFrom.options[j].value);
			selectFrom.options[j] = null;
			--j;
			--selectFromLength;
		}
	}
	//selectBoxOne.sort();
	selectFrom.selectedIndex = 0;

	return true;	
}

//Validates that an Item was selected.		
function returnPartial(errMsgNoneSelected, errMsgNotNumber)
{
	var strResult = "";
	var strSelectedSerial = "";
	var strDelectedSerial = "";

	//Loop through all the elements
	for (var i=0; i<frmRMADetail.elements.length; i++)
	{
		var oneElement = frmRMADetail.elements[i];
		
		//check if quantity text box is not empty
		if (oneElement.type == "text" && oneElement.name.indexOf("Quantity") > -1 && oneElement.value != "")
		{
			strResult = strResult + "\n " + oneElement.name + " is a " + oneElement.type
			var tempElement = frmRMADetail.elements[i + 1];  //This is the max value the quantity can be
				
			strSelectedSerial = strSelectedSerial +  "|";					
			strDelectedSerial = strDelectedSerial +  "|";					
				
		}
		//Check if Serial To List box is not empty
		else if (oneElement.type.indexOf("select") > -1 && oneElement.name.indexOf("SerialTo") > -1)
		{
			strResult = strResult + "\n " + oneElement.name + " is a " + oneElement.type
			var selectBoxOne = oneElement;
			var selectBoxOneLength = selectBoxOne.length ;

			for (var j=0; j<selectBoxOneLength; j++)
			{
				strSelectedSerial = strSelectedSerial + selectBoxOne.options[j].value + "~";
				selectBoxOne.options[j].selected = true;
			}
			strSelectedSerial = strSelectedSerial +  "|";					
		}
		//Check if Serial To List box is not empty
		else if (oneElement.type.indexOf("select") > -1 && oneElement.name.indexOf("SerialFrom") > -1)
		{
			strResult = strResult + "\n " + oneElement.name + " is a " + oneElement.type
			var selectBoxOne = oneElement;
			var selectBoxOneLength = selectBoxOne.length ;

			for (var j=0; j<selectBoxOneLength; j++)
			{
				strDelectedSerial = strDelectedSerial + selectBoxOne.options[j].value + "~";
				selectBoxOne.options[j].selected = true;
			}
			strDelectedSerial = strDelectedSerial +  "|";					
		}
		//Empty Quantity Box
		else if(oneElement.type == "text")
		{
			strDelectedSerial = strDelectedSerial +  "|";					
			strSelectedSerial = strSelectedSerial +  "|";					
		}
	}
	frmRMADetail.txtSelectedSerial.value = strSelectedSerial;
	frmRMADetail.txtDelectedSerial.value = strDelectedSerial;

	return true;
}

function checknumber(value,errMsg, maxValue)
{
	var x=value;
	var testresult;
	var anum=/^[1-9]+[0-9]*$/
	if (anum.test(x))
	{
		if(parseInt(value) <= parseInt(maxValue))
			testresult=true;
		else
			alert(errMsg);
	}
	else
	{
		//alert("Please input a valid quantity.");
		alert(errMsg);
		testresult=false;
	}
	return (testresult);
}	
  
function validateLength(oSrc, args){
	args.IsValid = (args.Value.length <= 250);
}

function emailCheck (source, args) {
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	var emailStr = args.Value.trim();
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	/* Finally, let's start trying to figure out if the supplied address is
	valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		//alert("Email address seems incorrect (check @ and .'s)")
		args.IsValid = false; return;
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		//alert("The username doesn't seem to be valid.")
		args.IsValid = false; return;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				//alert("Destination IP address is invalid!")
	    		args.IsValid = false; return;
			}
		}
		args.IsValid = true;
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
		args.IsValid = false; return;
	}

	/* domain name seems valid, but now make sure that it ends in a
	three-letter word (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
		domArr[domArr.length-1].length>3) {
	// the address must end in a two letter or three letter word.
	//alert("The address must end in a three-letter domain, or two letter country.")
	args.IsValid = false; return;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	var errStr="This address is missing a hostname!"
	//alert(errStr)
	args.IsValid = false; return;
	}

	// If we've gotten this far, everything's valid!
	args.IsValid = true;
}

function highlightRMASerial(serial) {
	var selects = document.getElementsByTagName("select");
	
	for (var i=0; i<selects.length; i++) {
		var sl = selects[i];
		for (var j=0; j<sl.options.length; j++) {
			var op = sl.options[j];
			if (serial.trim() == op.value.trim()){
				op.className = "highlightRMADuplicate";
			}
		}
	}
}

function highlightRMASerials(serials) {
	for (var i=0; i<serials.length; i++)
		highlightRMASerial(serials[i]);
} 

//Dart functions
function dartChangeUploadType() {
	if (document.getElementById("ddlUploadType"))
	{
		uploadType = document.getElementById("ddlUploadType").selectedIndex;
		if (uploadType == 0)
			document.getElementById("regionTR").style.display = "none";
		else if (uploadType == 1)
			document.getElementById("regionTR").style.display = "inline";
	}
}
function format(str){
	for(i = 1; i < arguments.length; i++){
		str = str.replace('{' + (i - 1) + '}', arguments[i]);
	}
	return str;
}
function dartGetTranslationTable(region) {
	if (region == 0)
		return "CDP_Translation_WGNA";
	if (region == 1)
		return "CDP_Translation_WGEO";
	if (region == 2)
		return "CDP_Translation_CAU";
}

function dartGetRegionName(region) {
	return document.getElementById("ddlRegion").options[region].innerText;
}

function dartUploadConfirmation()
{
	fileNames = new  Array("CDPTranslationWGNA.xls", "CDPTranslationWGEO.xls", "CDPTranslationCAU.xls", "CDPDARTAllocation.xls");
	
	inputFile = document.getElementById("inputFile").value;
	uploadType = document.getElementById("ddlUploadType").selectedIndex;
	
	while(inputFile.indexOf("\\") != -1) {
		inputFile = inputFile.substring(inputFile.indexOf("\\") + 1, inputFile.length);
	}
	
	if (inputFile == "") {
		return false;
	}
	
	if (uploadType == 0) {
		if (inputFile == fileNames[3]) {
			msg = document.getElementById("lblAllocationConfirm").innerText;
			return confirm(format(msg, inputFile));
		}
		else {
			for(i = 0; i<fileNames.length -1; i++) {
				if (inputFile == fileNames[i]) {
					msg = document.getElementById("lblIncorrectAllocation").innerText;
					alert(format(msg, inputFile, dartGetRegionName(i)));
					return false;
				}
			}
			//not recognized filename
			msg = document.getElementById("lblUnknownAllocation").innerText;
			alert(format(msg, inputFile, fileNames[3]));
			return false;
		}
	}
	else if (uploadType == 1) {
		region = document.getElementById("ddlRegion").selectedIndex;
		
		for (i=0; i<fileNames.length - 1; i++) {
			if (inputFile == fileNames[i] && region == i) {
				msg = document.getElementById("lblTranslationConfirm").innerText;
				return confirm(format(msg, dartGetTranslationTable(region), dartGetRegionName(region), inputFile));
			}
			if (inputFile == fileNames[i] && region != i) {
				msg = document.getElementById("lblIncorrectTranslation").innerText;
				alert(format(msg, dartGetTranslationTable(region), dartGetRegionName(region), inputFile, dartGetRegionName(i)));
				return false;
			}
		}
		
		msg = document.getElementById("lblUnknownTranslation").innerText;
		alert(format(msg, dartGetTranslationTable(region), dartGetRegionName(region), inputFile, fileNames[region]));
		return false;
	}
}

function dartRestoreConfirmation() {
	uploadType = document.getElementById("ddlUploadType").selectedIndex;
	
	if (uploadType == 0) {
		msg = document.getElementById("lblRestoreAllocation").innerText;
	} else if (uploadType == 1) {
		region = document.getElementById("ddlRegion").selectedIndex;
		msg = format(document.getElementById("lblRestoreTranslation").innerText, dartGetTranslationTable(region), dartGetRegionName(region));
	}
	
	return confirm(msg);
}
//end dart

function openDownload(inNewWindow, param) {
	var lh = location.href;
	var url = lh + (lh.indexOf('?') == -1 ? '?' : '&') + 'showBinary=true&param=' + param;
	if (inNewWindow) {
		window.open(url); 
	} else {
		location.href = url;		
	}
	return false;
}
