var dtCh= "/";
var minYear=1900;
var maxYear=2100;
var imageWin = "";

function isInteger(s){
	var i;
    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;
}


function jsDataManagement(thisData,thisType,thisName){
	if (thisData){
		var tempArray = thisData.split(",")
			for(i=0;i<tempArray.length;i++){
				if (thisType == "Select"){
					document.writeln ('<option value="' + tempArray[i] + '">'+tempArray[i]+'</option>')
				}else if(thisType == "Radio"){
					document.writeln ('<input type=radio name="'+thisName+'" id="'+thisName+'" value="'+tempArray[i]+'"> ' + tempArray[i]) 
				}
			}
	}

}

function ValidateFormOnClose(PassedForm){
	// checks to see if current form is of type Add
	// if any images exist, user must delete images before closing
	var caught = false;

		for(i=0;i<PassedForm.elements.length;i++){
			var thisElement = PassedForm.elements[i]
			if (thisElement.id.indexOf('Image') > -1){
				// check value if not <> then stop user
				if(((thisElement.value != "") && (PassedForm.id == "fromAdd")) || ((thisElement.value == "") && (PassedForm.id == "fromUpdate"))) {
					if (PassedForm.id == "fromAdd"){
						alert('Please delete the image before closing');
					}else{
						alert('Please upload an image and then click update');
					}
				caught = true;
				return false;
				}
			}else if(thisElement.id.indexOf('Video') > -1){
				// check value if not <> then stop user
				if(((thisElement.value != "") && (PassedForm.id == "fromAdd")) || ((thisElement.value == "") && (PassedForm.id == "fromUpdate"))) {
					if (PassedForm.id == "fromAdd"){
						alert('Please delete the file before closing');
					}else{
						alert('Please upload a file and then click update');
					}
					caught = true;
					return false;
				}
			}
		}

	// if still here return true
	if (caught == false){
		return true;	
	}

}


function ValidateTextbox(thisField,thisType){

if (thisField.value == "" || thisField == null){
	return true;
}else{

	if (thisType == "Date"){
		if (isDate(thisField.value)==false){
			thisField.value = "";
			thisField.focus();
			return false;
		}
		return true;
	} else if (thisType == "Integer"){
		if (isInteger(thisField.value)==false){
			alert("Please enter numbers only");
			thisField.value = ""
			thisField.focus();
			return false
		}
	} else if (thisType == "Currency"){
		 thisField.value = isCurrency(thisField.value);
	} else if (thisType == "Zip Code"){
		var temp = isZipCode(thisField.value);
		if (temp != thisField.value){
			thisField.value = ""
			thisField.focus();
		}
	} else if (thisType == "Social Security Number"){
		var temp = isSSN(thisField.value);
		if (temp != thisField.value){
			thisField.focus();
		}
	} else if (thisType == "Phone"){
		var temp = isPhone(thisField.value);
		if (temp != thisField.value){
			thisField.value = temp
			thisField.focus();
		}
	} else if (thisType == "Email"){
		var temp = isEmail(thisField.value);
		if (temp == false){
			thisField.focus();
		}
	} else if (thisType == "Website"){
		var temp = isWebsite(thisField.value);
		if (temp != thisField.value){
			thisField.focus();
		}			
	} else {
		alert("Currently " + thisType + " is not supported.")
		return true
	}
 }
}


function isWebsite(thisVal){
	if (thisVal.substring(0,7) == "http://" || thisVal.substring(0,8) == 'https://'){
		return thisVal;
	}else{
		alert("Prefix the website with http://")
		return "";
	}
}


function isEmail(thisVal){
	// number of characters before @
		var at="@"
		var dot="."
		var str = thisVal
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid Email Address")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid Email Address")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid Email Address")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid Email Address")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid Email Address")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid Email Address")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid Email Address")
		    return false
		 }

 		 return true				


}

function HandlePassword(thisField){
	if (thisField.value == ""){
		return;
	}else if (thisField.value.length < 6){
		alert("Password must be greater then 6 characters")
		thisField.value = ""
		thisField.focus();
	}else if (thisField.value.length > 12){
		alert("Password cannot be greater then 12 characters")
		thisField.value = ""
		thisField.focus();
	}else if (thisField.value != "**********"){
		var x = window.showModalDialog("code/PopUp/checkPassword.asp","","dialogHeight:100px;dialogWidth:300px;center:yes;resizable:no;status:no;");
		if (x != thisField.value){
			alert("Passwords do not match")
			thisField.value = ""
			thisField.focus();
		}
	}
}

function isPhone(thisVal){
	var temp = "";
	var thisTemp = "";
	thisTemp = thisVal.replace(/\(/g,'')
	thisTemp = thisTemp.replace(/\)/g,'')
	thisTemp = thisTemp.replace(/\s/g,'')
	thisTemp = thisTemp.replace(/\-/g,'')
	for(i=0;i<thisTemp.length;i++){
	
		var zchar = thisTemp.charAt(i)
		var charInt = thisTemp.charCodeAt(i)
		if (charInt < 47 || charInt > 58){
			alert("Please enter only numbers or '(' '-'")
			return "";
			break;	
		}
	
		
		if (temp.length == 0){
			temp = "(" + zchar
		}else if (temp.length == 4){
			temp = temp + ') ' + zchar
		}else if (temp.length == 9){
			temp = temp + '-' + zchar
		}else if (temp.length > 13){
		alert("Phone # cannot be larger than (000)-000-0000")
		return "";
		}
		else{
			temp = temp + zchar
		}
		
		
	}

	return temp;

}

function isSSN(thisVal){
	if (thisVal.length == 11 && thisVal.indexOf('-') == 3){
		return thisVal;
	}else if (thisVal.length >= 11){
		alert("Social Security # must be formatted 000-00-0000")
		return "";
	}else if (thisVal.length < 9){
		alert("Social Security # must be formatted 000-00-0000")
		return "";
	} else {
			
		var temp = "";
		for(i=0;i<thisVal.length;i++){
			var zchar = thisVal.charCodeAt(i)
				if ((zchar < 47 || zchar > 58) && zchar != 45){
					alert("Social Security # can only contain numbers and '-'")
					thisVal = ""
					return thisVal;
					break;
					} else {
						if (temp.length == 3){
							temp = temp + "-" + thisVal.charAt(i)
						}else if (temp.length == 6){
							temp = temp + "-" + thisVal.charAt(i)
						}else{
							temp = temp + thisVal.charAt(i)
						}
				}
					
			
		}
	if (temp != ""){
				return temp;
			}
	
	} 
	
}


 function VerifyPassword(Password2,Password){
            if (Password.value == Password2.value){
                return true;
            }else{
                alert("Passwords do not match");
				Password2.value = ""
				Password.value = ""
                Password.focus();
               return false;
            }
    }

function isZipCode(thisVal){

	for(i=0;i<thisVal.length;i++){
		var zchar = thisVal.charCodeAt(i)
			if ((zchar < 47 || zchar > 58) && zchar != 45){
				alert("Zip Code can only contain numbers and '-'")
				thisVal = "00000"
				return thisVal;
				break;
			}
	} 

	if(thisVal.length == 5){
		return thisVal;
	} else if (thisVal.length == 9 && thisVal.indexOf("-") != 4){
		return thisVal.substr(0,5) + "-" + thisVal.substr(6,9); 
	} else{
	
		if (thisVal.length < 5){
			alert("Zip Codes must be at least five characters in length")
			return "00000";
		} else if (thisVal.length < 10){
			var temp = thisVal.substr(0,5)
			temp = temp + "-0000"
			return temp;
		} else if (thisVal.length > 10){
			var temp = thisVal.substr(0,5) + "-" + thisVal.substr(6,9)
			return temp;
		} else {
			return thisVal;
		}

	}		
}

function isCurrency(thisVal){
	var temp = thisVal.replace(/\$/g,'')
	for(i=0;i<temp.length;i++){
		var zchar = temp.charCodeAt(i)
		if ((zchar < 47 || zchar > 58) && zchar != 46){
			alert("Please enter only numbers and one decimal point")
			return "";
		} 
	}
	
	return temp;
}


function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}


function ShowForm(thisAction,thisOID,thisIDname,thisIDvalue,OtherArgs,ShowPrefix){
	var oArgs = OtherArgs
	if (oArgs != undefined && oArgs != ''){
		if(oArgs.substring(1,1) != "&"){
		oArgs = '&'+oArgs
		}
	}else{
		oArgs = ''
	}
	
	
	if (ShowPrefix){
		var myShowForm = window.open('Show'+ShowPrefix+'Form.asp?a='+thisAction+'&b='+thisOID+'&c='+thisIDname+'&d='+thisIDvalue+oArgs,'ShowForm','toolbars=no,scrollbars=yes,status=yes,location=no,width=600,height=575,resizable=yes,left=10,top=10');
		myShowForm.focus();
		}else{
		var myShowForm = window.open('ShowForm.asp?a='+thisAction+'&b='+thisOID+'&c='+thisIDname+'&d='+thisIDvalue+oArgs,'ShowForm','toolbars=no,scrollbars=yes,status=yes,location=no,width=600,height=575,resizable=yes,left=10,top=10');
		myShowForm.focus();
	}
}




function ConfirmDelete(alertName,thisOID,thisIDname,thisIDvalue,theseArgs){
	if(confirm("Are you sure you want to delete " + alertName + "?") == true){
		// process delete
		var oArgs = ""
		if (theseArgs == undefined){
			oArgs = ""
			}else{
			if (oArgs.substring(0,1) != "&"){
				oArgs = "&" + theseArgs
				}else{
				oArgs = theseArgs
			}
		}
		var DeleteWin = window.open('DeleteForm.asp?a='+thisOID+'&b='+thisIDname+'&c='+thisIDvalue+oArgs,'DeleteWin','toolbars=no,width=350,height=250,resizable=yes,status=yes,location=no');
		DeleteWin.focus()
	}
}


function ChangeObject (thisOID,thisIDname,thisIDvalue,retVal,OtherArgs){
	var temp = 'adminIndex.asp?OID='+thisOID
	if (thisIDname != undefined && thisIDname != ''){
		temp = temp + '&thisIDname='+thisIDname+'&thisIDvalue='+thisIDvalue
		}
	if (retVal != undefined){
		temp = temp + '&retVal='+retVal
	}
	if (OtherArgs != undefined){
		temp = temp + '&'+OtherArgs
	}
	window.location.href=temp
}



function DisplayPopUp(thisFileName,theseArgs,confirmAction,fullSize){
	if ((confirmAction) && (confirm != "-1")){
		if (confirm(confirmAction) == false){
			return false;
		}
	}
			var Args = '?pFn='+thisFileName+'&'+theseArgs
			Args = Args.replace(/&&/g,'&')
			if(fullSize){
				var myPopUp = window.open('/admin/PopUpController.asp'+Args,thisFileName,'fullscreen=yes, scrollbars=yes');
			}else{
				var myPopUp = window.open('/admin/PopUpController.asp'+Args,thisFileName,'toolbar=no,scrollbars=yes,status=yes,location=no,width=300,height=250,resizable=yes');
			}
			myPopUp.focus();
		
}



function MoveRow(thisAction,thisRowID){
	var TotalRows = document.getElementById('TotalRows').value
	var FieldVal = document.getElementById('Field'+thisRowID).value
	if (thisAction == "Up"){
		if (thisRowID == 0 || FieldVal == ""){
			return
		} else {
			var RowDown = parseInt(thisRowID - 1)
		}
	}else if (thisAction == "Down"){
		if (thisRowID == TotalRows || FieldVal == ""){
			return
		} else {
			var RowDown = parseInt(thisRowID + 1)
		}	
	}
		FieldUp = document.getElementById('Field'+thisRowID).value
		TableUp= document.getElementById('Table'+thisRowID).value
		OrderByUp= document.getElementById('OrderBy'+thisRowID).value
		WhereClauseUp= document.getElementById('WhereClause'+thisRowID).value
		ColumnNameUp = document.getElementById('ColumnName'+thisRowID).value
		
		document.getElementById('Field'+thisRowID).value = document.getElementById('Field'+RowDown).value
		document.getElementById('Table'+thisRowID).value = document.getElementById('Table'+RowDown).value
		document.getElementById('OrderBy'+thisRowID).value = document.getElementById('OrderBy'+RowDown).value
		document.getElementById('WhereClause'+thisRowID).value = document.getElementById('WhereClause'+RowDown).value
		document.getElementById('ColumnName'+thisRowID).value = document.getElementById('ColumnName'+RowDown).value

		document.getElementById('Field'+RowDown).value = FieldUp
		document.getElementById('Table'+RowDown).value = TableUp
		document.getElementById('OrderBy'+RowDown).value = OrderByUp
		document.getElementById('WhereClause'+RowDown).value = WhereClauseUp
		document.getElementById('ColumnName'+RowDown).value = ColumnNameUp

}


function UpdateQuery(thislocation,thisValue,thisId,thisTable){
	var myParent = thislocation 
	// determine opened field
	if (thisValue == false){
		for(i=0;i<50;i++){
			var thisName = "Field"+i
			var myField = myParent.getElementById(thisName).Tag
			if (myField == thisId){
				myParent.getElementById('Field'+i).value = ""
				myParent.getElementById('Table'+i).value = ""
				myParent.getElementById('OrderBy'+i).value=""
				myParent.getElementById('WhereClause'+i).value=""
				myParent.getElementById('ColumnName'+i).value=""
				break;
			}	
		}
	}else{
		for (i=0;i<50;i++){
			var thisName = "Field"+i
			var myField = myParent.getElementById(thisName).value
			if (myField == ""){
				myParent.getElementById('Field'+i).value = thisId
				myParent.getElementById('Field'+i).Tag = thisId
				myParent.getElementById('Table'+i).value = thisTable
				myParent.getElementById('ColumnName'+i).value = "0||" + thisId
				break;
			}
		}
	}	
	

}

function NoSpaces(thisField){
var retVal = ""
var x = thisField.value
	for(i=0;i<x.length;i++){
		if(x.charCodeAt(i) != 32){
			retVal = retVal + x.charAt(i)
		}
	}
	thisField.value = retVal
}


function ProcessMCheckbox(thisVal, ColumnName,thisData){
	if (document.getElementById(ColumnName)){
		var thisField = document.getElementById(ColumnName)
		if (thisVal == true){			// add 
			thisField.value = thisField.value + ',' + thisData				
		}else if (thisVal == false){			// remove
			thisField.value = thisField.value.replace(','+thisData,'')
		}
	}else{
		alert("Error incorrect setup of Multiple Checkbox field")
	}

}

function ValidateForm(PassedForm){
var browserType = navigator.appName
var required = 0;
var errorMessage = "";
var caught = false;


if(document.getElementById('isWYSIWYG')){
	if (document.getElementById('isWYSIWYG').value=='true'){
		if (UpdateWYSIWYGEditor() == false){
			caught = false;
			return false;
		}
	}
}


  for(i=0;i<PassedForm.elements.length;i++){
  
  	if (PassedForm.elements[i].accessKey){
		required = PassedForm[i].accessKey.substring(0,1)
		}else{
		required = 0
		}		

   if (required == 1){
			if (document.getElementById('Cell_'+PassedForm[i].id)){
				errorMessage = document.getElementById('Cell_'+PassedForm[i].name).innerHTML
				errorMessage = errorMessage.replace('&nbsp;','');
				}else{
				errorMessage = PassedForm[i].name
				}

		 if ((PassedForm[i].value == "") || ((PassedForm[i].value == 0) && (PassedForm[i].type == "select-one"))){
			alert(errorMessage + " is a required field.")
			if (PassedForm[i].type != "hidden"){
				PassedForm[i].focus()
			}
			var caught = true;
		 	return false;
			}
   		}
  }
  	if (caught==false){
  		return true;
	 	}else{
		return false;
		}
}



function CheckAll(thisFieldPrefix,TotalRows){
	if (TotalRows){
			for(i=0;i<TotalRows;i++){
				document.getElementById(thisFieldPrefix+i).checked = true
			}
	}else{
		alert("Error -> in code, seek administrator!!!")
	}
}

function PreviewProject(){
	if (document.getElementById('CurrentClient')){
		var currClient = document.getElementById('CurrentClient').innerHTML

		currClient = currClient.substring(9,currClient.length)
		var clientName = currClient.substring(0,currClient.indexOf("#"))
		var clientID = currClient.substring(currClient.indexOf("#")+1,currClient.indexOf("&gt;")-1)
		var clientProject = currClient.substring(currClient.indexOf("&gt;")+5,currClient.length)
		var preWin = window.open('http://192.168.0.52:'+clientID+'/'+clientProject+'/index.asp','preWin','width=600,height=600,status=yes,resizable=yes,scrollbars=yes,location=yes,toolbar=yes');
		preWin.focus();	
		}else{
		alert('You must first select a Client and then a Project to Preview');
		}
}

function MoveFile(Destination,thisName,thisPath,thisSize,thisType,thisDateCreate){
	if ((Destination) && (thisName)){
			Destination.src = thisName
	}
	
	if ((document.getElementById('thisName')) && (thisName != undefined)){
		document.getElementById('thisName').innerHTML = thisName
	}
	
	if ((document.getElementById('thisPath')) && (thisPath != undefined)){
		document.getElementById('thisPath').innerHTML = thisPath
	}
	
	if ((document.getElementById('thisSize')) && (thisSize != undefined)){
		document.getElementById('thisSize').innerHTML = thisSize
	}
	
	if ((document.getElementById('thisType')) && (thisType != undefined)){
		document.getElementById('thisType').innerHTML = thisType
	}
	
	if ((document.getElementById('thisDateCreated')) && (thisDateCreated != undefined)){
		document.getElementById('thisDateCreated').innerHTML = thisDateCreate
	}
}

function HideAndSeekRow(thisElement,thisSeek,thisTotal){
	// if thisTotal is empty find total by TotalRows
	if (thisTotal){
		var thisCount = parseInt(thisTotal) + 1
	}else{
		if (document.getElementById('TotalRows')){
			var thisCount = document.getElementById('TotalRows').value
		}else{
			alert('No Count was passed and Total Rows could not be found')
			return;
		}
	}
		// hide

		for(i=0;i<thisCount;i++){
			if (document.getElementById(thisElement+i)){
				var thisItem = document.getElementById(thisElement+i).innerHTML
				var thisRow = document.getElementById('Row'+i)
					if (thisSeek != -1){
						if (thisItem.indexOf("&nbsp;") > -1){
							thisItem = thisItem.replace(/\&nbsp\;/g,"")
						}

						if (thisItem == thisSeek){
							thisRow.style.display = 'block'
						}else{
							thisRow.style.display = 'none'
						}
					}else{
						thisRow.style.display = 'block';
					}
				}else{
				// do nothing 
				window.status = "error - unable to find " + thisElement+i
			}
		}

}

function MoveValueFromChildToParent(thisParentElement,thisValue){
	if (thisValue){
		if (window.opener.document.getElementById(thisParentElement)){
			var thisParent = window.opener.document.getElementById(thisParentElement)
			thisParent.value = thisValue
		}else{
			return false;
		}

	}else{
		return false;
	}

}


function HideAndSeek(thisElement,thisSeek,thisTotal){

	// if thisTotal is empty find total by TotalRows
	if (thisTotal){
		var thisCount = parseInt(thisTotal) + 1
	}else{
		if (document.getElementById('TotalRows')){
			var thisCount = document.getElementById('TotalRows').value
		}else{
			alert('No Count was passed and Total Rows could not be found')
			return;
		}
	}
		

	// hide
		for(i=0;i<thisCount;i++){
			if (document.getElementById(thisElement+i)){
					var thisItem = document.getElementById(thisElement+i)
					if (thisSeek != -1){
						if (i == thisSeek){
							thisItem.style.display = 'block'
						}else{
							thisItem.style.display = 'none'
						}
					}else{
						thisItem.style.display = 'none';
					}
				}else{
				// do nothing 
				window.status = "error - unable to find " + thisElement+i
			}
		}

}

function PreviewImage(thisPath){
	if (!thisPath){
		return false;
	}else if(thisPath == 'pub/images/noimage.gif'){
		return false;
	}
	
	if (imageWin){
		imageWin.close()
	}
	// opens a window and writes to the document
	imageWin = window.open('','imageWin','toolbars=no,resizable=yes,scrollbars=yes,status=no,location=no')
	imageWin.document.writeln('<p></p><input type=button name=cmdAction style="color:#FFFFFF;font-family:arial;font-size:12px;color:#00000;border:1px solid #CCCCC;" value="Close" onClick="window.close();""><BR>')
	imageWin.document.writeln('<img src="'+thisPath+'" id=thisImage name=thisImage>')
	imageWin.document.writeln('<p></p><input type=button name=cmdAction style="color:#FFFFFF;font-family:arial;font-size:12px;color:#00000;border:1px solid #CCCCC;" value="Close" onClick="window.close();"">')
	imageWin.document.writeln(unescape('%3C') + 'script>\n')
	imageWin.document.writeln('var thisH = thisImage.height\n')
	imageWin.document.writeln('var thisW = thisImage.width\n')
	imageWin.document.writeln('if(thisW > 600){\n')
	imageWin.document.writeln('var widthChange = parseInt(thisW - 600)\n')
	imageWin.document.writeln('thisImage.height = parseInt(widthChange * (parseFloat(thisImage.height/ widthChange)))\n')
	imageWin.document.writeln('thisImage.width = 600;\n')
	imageWin.document.writeln('}\n')
	imageWin.document.writeln('window.resizeTo(thisImage.width+100,thisImage.height+100)\n'+unescape('%3C')+'/script>')
	imageWin.focus();

}


function UpdateHiddenField(thisElement,thisBoolean,thisValue,seperator){

	if (document.getElementById(thisElement)){
		if (seperator == undefined){
			seperator = ";"
		}


		// get string
		var thisStr = document.getElementById(thisElement)
	
		if (thisBoolean == true){
			// add this value to list
			thisStr.value = thisStr.value + seperator + thisValue			
		}else{
			// remove this value from list
			var findStr = seperator+thisValue
			if (thisStr.value.indexOf(findStr) > -1){
				thisStr.value = thisStr.value.replace(findStr,"")
				}
		}
	}else{
		return false;
	}
}

function ProcessHyperLink(){
	var thisLinkType = document.getElementById('LinkType').value
	var retVal = "";
	
	if (thisLinkType == 'Internal'){
		var thisInternalType = document.getElementById('InternalLinkType').value
		
		if (thisInternalType == 'Page'){
			var thisValue = document.getElementById(InternalPage).value
			var thisText = document.getElementById(InternalPageText).value
			var thisTarget = document.getElementById(InternalPageTarget).value
			
		}else if (thisInternalType == 'Image'){
			var thisText = document.getElementById(InternalImageText).value
			var thisTarget = document.getElementById(InternalImageTarget).value
			var thisValue = document.getElementById(InternalImagePath).value
			
		}else if (thisInternalType == 'File'){
			var thisText = document.getElementById(InternalFileText).value
			var thisTarget = document.getElementById(InternalFileTarget).value
			var thisValue = document.getElementById(InternalFilePath).value
			
		}else{
			alert('Please select an Internal Link Type')
			return false;
		}

		
		
	}else if (thisLinkType == 'External'){
		ExternalUrl
		ExternalText
		ExternalTarget


	}else{

		alert('Please select a Link Type');
		return false;
	}

}

function ValidateByDataType(thisField,thisDataType){
	// process the field value by the data type
	

}


function PreviewFile(thisFileName){
	var thisFile = window.open(thisFileName,'thisFile','resizable=yes,width=600,height=600,toolbars=yes,scrollbars=yes,status=yes');
	thisFile.focus();
}

               
function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
		} 
		else
		return true;
	}      

function DisplayGetJavaScript(thisField){
	var JavaWin = window.open('GetJSFunctionCall.asp?retVal='+thisField,'JavaWin','height=100,width=400,resizable=yes,status=yes,location=no,toolbars=no,scrollbars=yes');
	JavaWin.focus();
}	

function ShowThisHideThat(showMe,hideMe){
	
	if (document.getElementById(showMe)){
		document.getElementById(showMe).style.display='block';
	}
	
	if (document.getElementById(hideMe)){
		document.getElementById(hideMe).style.display='none';
	}
}

function ShowPortfolio(thisUsername){
	if (thisUsername != ""){
		thisUsername = "p=" + thisUsername
	}else{
//		thisUsername = "p=" + window.status.substring(14,window.status.length)
	}

	var myPortfolio = window.open('/admin/ShowPortfolio.asp?'+thisUsername,'myPortfolioView','width=825,height=600,scrollbars=yes,status=yes,location=yes,address=no,toolbar=yes,resizable=yes');
	myPortfolio.focus();

}
function ValidateTextarea(thisField,thisMaxLength){
	if (thisField.value.length > thisMaxLength){
		alert('Max Length for this text area is ' + thisMaxLength + ', your data has been shortened.');
		thisField.value = thisField.value.substring(0,parseInt(thisMaxLength-1))
		thisField.focus();
	}
}



function ShowHiddenItem(thisField){
	if ((thisField != undefined) && (thisField != '')){
		if(document.getElementById(thisField)){
			if (document.getElementById(thisField).className == "hiddenInput"){
				document.getElementById(thisField).className = "pageContent";
			}else if(document.getElementById(thisField).className == "pageContent"){
				document.getElementById(thisField).className= "hiddenInput";
			}
		}
	}
}



function jsDataManagement(thisData,thisType,thisName){
	if (thisData != undefined){
		var tempArray = thisData.split(",")
			for(i=0;i<tempArray.length;i++){
				if (thisType == "Select"){
					document.writeln ('<option value="' + tempArray[i] + '">'+tempArray[i]+'</option>')
				}else if(thisType == "Radio"){
					document.writeln ('<input type=radio name="'+thisName+'" id="'+thisName+'" value="'+tempArray[i]+'"> ' + tempArray[i]) 
				}
			}
	}

}


function Get_Cookie(name) { 
   var start = document.cookie.indexOf(name+"="); 
   var len = start+name.length+1; 
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
   if (start == -1) return null; 
   var end = document.cookie.indexOf(";",len); 
   if (end == -1) end = document.cookie.length; 
   return unescape(document.cookie.substring(len,end)); 
} 

function Set_Cookie( name, value, expires, path, domain, secure ){
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/

if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function Delete_Cookie(name,path,domain) { 
   if (Get_Cookie(name)) document.cookie = name + "=" + 
      ( (path) ? ";path=" + path : "") + 
      ( (domain) ? ";domain=" + domain : "") + 
      ";expires=Thu, 01-Jan-70 00:00:01 GMT"; 
} 

function ValidateBrowser(){
	var BrowserName = navigator.appName
	var Platform = navigator.platform
	var Cookies_On = navigator.cookieEnabled
	if(Cookies_On == false){
		BrowserErrorMessage("Cookies",BrowserName,Platform,Cookies_On)
		return false;
	}else{
		return true;
	}
}

function BrowserErrorMessage(MessageType,BrowserName,Platform,CookiesOn){
	if (MessageType == "Cookies"){
		alert("*** It appears you do not have cookies enabled in your browser ***\n\nUnable to add this item to your cart.\nPlease enable cookies in your browser before continuing.")
		return true
	}else if(MessageType == "Old Browser" && Platform.substring(0,3) == "Mac"){
		alert("*** It appears your browser is not compatible with this shopping cart ***\n\nYou are current using:\n\nBrowser: "+BrowserName+"\n*** We recommend Firefox of Safari. ***")
		return true
	}else if(MessageType == "Old Browser" && Platform.substring(0,3) == "Win"){
		alert("*** It appears your browser is not compatible with this shopping cart ***\n\nYou are current using:\n\nBrowser: "+BrowserName+"\n*** We recommend updating to a later version. ***")
		return true
	}
}

function AddToChart(thisField,thisProductNumber,thisDescription,thisUnitCost,thisQuantity,thisTableName,thisDiscount,thisShippingWeight,thisURL,Increment){
	
	if(ValidateBrowser() == false){
		return false;
	}
	
	
	var thisMessage = thisDescription.replace('Size:','\nSize: ')
	thisMessage = thisMessage.replace('Weight:','\nWeight: ')
	if(!Increment){
		Increment = ""
	}
	
	if (confirm('Would you like to add the following to your cart?\n\nProduct Name: '+thisMessage+' \nPrice: '+formatCurrency(thisUnitCost)+' \n\nYou may change quantities at any time from your shopping cart.')==true){	
		var partDelimit = "||@#|!~"
		var lineDelimit = "%^&*@#@"
	// get free cookie for cart
		var currCart = Get_Cookie(thisField)

		if (navigator.platform.substring(0,3) == 'Mac' && navigator.appName == 'Microsoft Internet Explorer'){
			if (thisDiscount != 0){thisDiscount = 0;}
		}else{
			if(thisDiscount == undefined){thisDiscount = 0;}
		}

		if (currCart == null){
			currCart = thisProductNumber + partDelimit + thisDescription + partDelimit + thisUnitCost  + partDelimit + thisTableName + partDelimit + thisDiscount + partDelimit + thisShippingWeight +partDelimit + thisURL + partDelimit + Increment + partDelimit + thisQuantity + lineDelimit 
			}else{
			currCart = currCart + thisProductNumber + partDelimit + thisDescription + partDelimit + thisUnitCost + partDelimit + thisTableName + partDelimit + thisDiscount + partDelimit + thisShippingWeight + partDelimit + thisURL + partDelimit + Increment + partDelimit + thisQuantity + lineDelimit
		}

		if (currCart.length <= 2300){
			Set_Cookie(thisField,currCart,30)
			}else{
			alert('Cart is full, please checkout');
		}
		
	}
}


function ManageQuantity(thisField,thisLine,oldVal,newVal){
	if (ValidateTextbox(newVal,'Integer') == false){
		newVal.value = 1
		return true;
	}
	
	if (oldVal != newVal.value){
		if(newVal.title){
			if (isInteger(newVal.title)==true){
				if(newVal.title > 0){
					if(newVal.value % newVal.title > 0){
						alert('Please enter in increments of '+newVal.title);
						newVal.value = oldVal;
						return false;
					}
				// 
				var partDelimiter = "||@#|!~"	
				var tempArray = thisLine.split(partDelimiter);
				var oldShippingWeight = tempArray[5];
				var newShippingWeight = parseFloat(parseFloat(parseFloat(1000 * oldShippingWeight)/oldVal) * parseFloat(newVal.value/1000))
				var tempLine = thisLine;
				thisLine = "";
				for(i=0;i<tempArray.length;i++){
					if(i>0){
						thisLine += partDelimiter
					}
						if (i == 5){
							thisLine += newShippingWeight
						}else{
							thisLine += tempArray[i];
						}
					}
					
				var newLine = thisLine.substring(0,thisLine.length - oldVal.length)
				newLine = newLine + newVal.value
				var currCart = Get_Cookie(thisField)
				currCart = currCart.replace(tempLine,newLine)
				Set_Cookie(thisField,currCart);
				document.location.href = document.location.href;
				return;
				}
			}
		}
		
		var newLine = thisLine.substring(0,thisLine.length - oldVal.length)
		newLine = newLine + newVal.value
		var currCart = Get_Cookie(thisField)
		currCart = currCart.replace(thisLine,newLine)
		Set_Cookie(thisField,currCart);
		document.location.href = document.location.href;
	}
}

function ManageCartTotals(){
// Tax1, SubTotal0,SubTotal1
if (document.getElementById('TotalRows')){
	var TotalRows = document.getElementById('TotalRows').value
	var Tax = 0
	var SubTotal = 0
		for(i=0;i<TotalRows;i++){
			if (document.getElementById('linecost'+i)){
				var thisValue = document.getElementById('linecost'+i).innerHTML
				thisValue = thisValue.replace('$',"")
				thisValue = thisValue.replace(/,/g,"")
				SubTotal = SubTotal + parseFloat(thisValue)
			}
		}
			if (document.getElementById('TotalCostTop')){
				document.getElementById('TotalCostTop').innerHTML = formatCurrency(SubTotal)
			}
	
			if (document.getElementById('TotalCostBottom')){
				document.getElementById('TotalCostBottom').innerHTML = formatCurrency(SubTotal)
			}
			
			if (document.getElementById('xTotalCost')){
				document.getElementById('xTotalCost').value = SubTotal
			}
					
		}
}


function RemoveChartRow(thisField,thisLine,refreshPage){
	if(confirm('Click Ok to remove this item from your order.')==true){
		var currCart = Get_Cookie(thisField)
		currCart = currCart.replace(thisLine,"")
		Set_Cookie(thisField,currCart);
		if(refreshPage != false){
			document.location.href=document.location.href	
		}
	}
}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
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);
}


function UpdateFieldsOnCheck(thisBoolean,theseFields){
	var tempArray = theseFields.split('&')
	for(i=0;i<tempArray.length;i++){
		var thisSource = tempArray[i].substring(0,tempArray[i].indexOf('='))
		var thisDestination = tempArray[i].substring(tempArray[i].indexOf('=')+1,tempArray[i].length)
		if(document.getElementById(thisDestination)){
			if(document.getElementById(thisSource)){
				document.getElementById(thisDestination).value = document.getElementById(thisSource).value
				}
			}
	}
}


function ManageFinalCart(){
	var subTotal = document.getElementById('SubTotal')
	var taxRate = document.getElementById('TaxRate')
	var taxCost = document.getElementById('Tax')
	var shippingType = document.getElementById('ShippingType')
	var shippingCost = document.getElementById('ShippingCost')
	var totalCost = document.getElementById('TotalCost')
	var residental = 2.5;
	if(document.getElementById('xShippingWeight')){
		var shippingWeight = document.getElementById('xShippingWeight').value
		}else{
		var shippingWeight = 0
	}
	
	if (shippingType.value == -1){
		document.getElementById('xComments').value = "Shipping is greater then 100lbs, please call to confirm"
	}
	
	// tax rate
	taxCost.innerHTML = formatCurrency(parseFloat(unFormatPercent(taxRate.innerHTML) * unFormatCurrency(subTotal.innerHTML)))
	// shipping
	if (document.getElementById('ResidentialDelivery')){
		if (document.getElementById('ResidentialDelivery').checked == true){
			shippingCost.innerHTML = formatCurrency(parseFloat(shippingType.value) + residental); ///parseFloat(document.getElementById('ResidentialDelivery').value))	
		}else{
			shippingCost.innerHTML = formatCurrency(parseFloat(shippingType.value))
		}
	}else{
		shippingCost.innerHTML = formatCurrency(shippingType.value)
	}
	// total
	totalCost.innerHTML = formatCurrency(parseFloat(unFormatCurrency(shippingCost.innerHTML)) + parseFloat(unFormatCurrency(subTotal.innerHTML)) + parseFloat(unFormatCurrency(taxCost.innerHTML)));
	// update pVal
	if(document.getElementById('pVal')){
		document.getElementById('pVal').value= unFormatCurrency(subTotal.innerHTML)+"||"+unFormatPercent(taxRate.innerHTML)+"||"+unFormatCurrency(taxCost.innerHTML)+"||"+shippingType.options[shippingType.selectedIndex].text+"||"+unFormatCurrency(shippingCost.innerHTML)+"||"+unFormatCurrency(totalCost.innerHTML)+"||"+shippingWeight
	}


}

function unFormatCurrency(thisVal){
	var retVal = thisVal;
	retVal = retVal.replace('&nbsp;',"")
	retVal = retVal.replace('$',"")
	retVal = retVal.replace(/,/g,"")
	return retVal;
}

function unFormatPercent(thisVal){
	var retVal = thisVal;
	retVal = retVal.replace('&nbsp;',"")
	retVal = retVal.replace('%',"")
	retVal = parseFloat(retVal/100)
	return retVal;
}


function ShowCVV(){
	if (x){
		x.close()
	}
	var x = window.open('','CVV','width=520,height=275,scrollbars=no,resizable=no,statusbar=no,location=no,history=no');
	x.document.writeln('<title>What is CVV?</title>\n');
	x.document.writeln('<div align=center><img src="/pub/images/CVV.jpg"><br>\n');
	x.document.writeln('<input type=button name=Close value=Close onclick="window.close();"></div><p></p>\n');
	x.focus();
}

function ValidateCCExpiration(thisField,thisVal){
	var d = new Date()
	var thisMonth = d.getMonth() + 1
	if(navigator.appName == "Microsoft Internet Explorer"){
		var thisYear = d.getYear()
		}else{
		var thisYear = d.getYear() + 1900	
	}
	var currMonth = parseInt(thisVal.substring(0,thisVal.indexOf('/')))
	var currYear = parseFloat(thisVal.substring(thisVal.indexOf('/')+1,thisVal.length))

	if((currMonth == "") || (currYear == "")){
		return true;
	}else if((currMonth < thisMonth) && (currYear <= thisYear)){
		alert('Your card has already expired!')
		thisField.options.selectedIndex = 0;
		thisField.focus();
		return false;
	}else if(currYear < thisYear){
		alert('Your card has already expired!')
		thisField.options.selectedIndex = 0;
		thisField.focus();
		return false;
	}

}


function ValidateCartTotals(){
// determine if the sub-total is the same as the cookie sub-total
var thisData = Get_Cookie('abcOrder12345')
var partDelimiter = "||@#|!~"
var lineDelimiter = "%^&*@#@"

var screenTotal = parseFloat(unFormatCurrency(document.getElementById('SubTotal').innerHTML))
var newTotal = 0;
var tempArray = thisData.split(lineDelimiter);
	for(i=0;i<tempArray.length;i++){
		if(tempArray[i] != ""){
			var lineArray = tempArray[i].split(partDelimiter);
			if(lineArray.length >= 2){
					var thisLineCost = parseFloat(parseFloat(lineArray[8]) * parseFloat(lineArray[2]))
					newTotal = parseFloat(newTotal) + parseFloat(thisLineCost)
				}	
		}
	}

	if(formatCurrency(newTotal) != formatCurrency(screenTotal)){
		alert("It seems you have modified your the items in your cart.\nThe system will update your cart now.");
		document.getElementById('SubTotal').innerHTML = formatCurrency(newTotal);
		ManageFinalCart();
		return false;
	}

	return true;
}




function ValidateFormCart(theseArgs){

if(ValidateCartTotals() == false){
	return false;
}
	


// check shipping type if applicable
if (document.getElementById('ShippingType')){
	if(document.getElementById('ShippingType').value == ""){
		alert('Please select a shipping type');
		return false;
	}
}

var tempArray = theseArgs.split("&")
for(i=0;i<tempArray.length;i++){
		if(tempArray[i] != ""){
		var thisName = tempArray[i].substring(0,tempArray[i].indexOf('='))
		var thisType = tempArray[i].substring(tempArray[i].indexOf('=')+1,tempArray[i].length)

		if (thisType != "Expiration"){
			if(document.getElementById(thisName)){
				var thisObj = document.getElementById(thisName)
				}else{
					alert(thisName + ' does not exist.');
					return false;
				}
		}
		
		if (thisType == "Name"){
			if(thisObj.value == ""){
				alert('Billing Name is required.');
				thisObj.focus();
				return false;
			}else if(thisObj.value.indexOf(' ') == -1){
				alert('Billing Name must contain a first name and last name');
				thisObj.focus();
				return false;
			}
		}else if(thisType == "CCN"){
			if(thisObj.value == ""){
				alert('Credit Card Number is required');
				thisObj.focus();
				return false;
			}else if(ValidateTextbox(thisObj,"Integer") == false){
				thisObj.focus();
				return false;
			}else if(thisObj.value.length < 12){
				alert('Credit Card Number must be greater then 11 numbers');
				thisObj.focus();
				return false;
			}
		
		}else if(thisType == "CVV"){
			if(thisObj.value == ""){
				alert("CVV number is required.")
				thisObj.focus();
				return false;
			}else if(ValidateTextbox(thisObj,"Integer") == false){
				thisObj.focus();
				return false;
			}else if(thisObj.value.length < 3){
				alert("CVV number must be greater then 2 numbers");
				thisObj.focus();
				return false;
			}		
		}else if(thisType == "Type"){
			if(thisObj.value == ""){
				alert("Please select a Credit Cart Type")
				thisObj.focus();
				return false;
			}else if(thisObj.options[thisObj.selectedIndex] == ""){
				alert("Please select a Credit Card Type")
				thisObj.focus();
				return false;
			}
		}else if(thisType == "Expiration"){
			var thisMonth = thisName.substring(0,thisName.indexOf('|'))
			var thisYear = thisName.substring(thisName.indexOf('|')+1,thisName.length)
			var objMonth = document.getElementById(thisMonth)
			var objYear = document.getElementById(thisYear)
		
			if(objMonth.value == ""){
				alert('Expiration Month is required')
				objMonth.focus();
				return false;
			}else if(objYear.value == ""){
				alert('Expiration Year is required');
				objYear.focus();
				return false;
			}else if(ValidateCCExpiration(objMonth,objMonth.value+'/'+objYear.value) == false){
				objMonth.focus();
				return false;
			}
		
		}else{
			alert('Unable to find thisType ' + thisType);
			return false;
		}	
	}

	}
	return true;

}

function ValidateAllZipCode(thisfield,thisCountry){

	if(thisfield.value == ""){
		return true;
	}

	if(thisCountry){
		if((thisCountry.toUpperCase() == "US") || (thisCountry.toUpperCase() == "United States")){
			// process US Zip Code
			return ValidateTextbox(thisfield,'Zip Code')

		}else if(thisCountry.toUpperCase() == "CANADA"){
			// PROCESS CANADIAN
			if (thisfield.value.length != 7){
				alert('Invalid Canadian Zip Code must be 7 characters formatted L#L #L#');
				thisfield.value = ""
				return false;
			}
			
			for(i=0;i<thisfield.value.length;i++){
				//LNL NLN, letter - number, space
				if(i == 3){
					if(thisfield.value.charAt(i) != " "){
						alert('Invalid Canadian Zip Code please format A2A 2A2');
						thisfield.value = ""
						return false;
					}
				}else if((i == 1) || (i == 4) || (i == 6)){
					if(isInteger(thisfield.value.charAt(i)) == false){
						alert('Invalid Canadian Zip Code please format A2A 2A2');
						thisfield.value = ""
						return false;
						}
				}else{
					if(isInteger(thisfield.value.charAt(i)) == true){
						alert('Invalid Canadian Zip Code please format A2A 2A2');
						thisfield.value = ""
						return false;
					}
				}
			}
		}		
	}else{
		alert('Please select a country!')
		thisfield.value = ""
		return;
	}

}

function CheckPromo(){
var thisData = Get_Cookie('abcOrder12345');
if (thisData == null){
	return false;
}
		if(document.getElementById('TotalCostBottom')){
			var cartValue = document.getElementById('TotalCostBottom').value
		}else{
			var cartValue = 0
		}
		
		var countItems = 0
		var countPromo = 0
		var otherItems = 0
		var MinCart = Get_Cookie('PromoMin')
		if(MinCart == null){
			MinCart = 0;
		}else{
			var tempArray = MinCart.split(',')
			MinCart = 0;
			for(j=0;j<tempArray.length;j++){
				if(parseFloat(tempArray[j]) > MinCart){
					MinCart = tempArray[j]
				}
			}
		}
		var partDelimit = "||@#|!~"
		var lineDelimit = "%^&*@#@"
		
		var tempArray = thisData.split(lineDelimit)
			for(i=0;i<tempArray.length;i++){
				if(tempArray[i] != ""){
					countItems++
					if(tempArray[i].indexOf('(PROMO)') > 0){
						countPromo++
					}else{
						var lineArray = tempArray[i].split(partDelimit)
						if(lineArray.length >= 2){
							otherItems += parseFloat(unFormatCurrency(lineArray[2]))
						}
					}
				}
			}
		
	
		if(countItems == countPromo){
			alert('In order to purchase a promotional item from Legion Paper you must have\na) One item in your cart\nb) A total order cost of '+formatCurrency(MinCart)+' (not including promotional items)');
			return false;
		}else if(countItems == 0){
			alert('You need at least 1 Item to checkout');
			return false;
		}else if((parseFloat(otherItems)<=MinCart) && (parseInt(countPromo) > 0)){
			alert('In order to purchase a promotional item from Legion Paper you must have\na) One item in your cart\nb) A total order cost of '+formatCurrency(MinCart)+' (not including promotional items)');
			return false;
		}else{
			return true;
		}		

}

function Set_MinimumPromoPrice(thisCookieString,thisCookiePrice,thisDesc,newPrice){
	// get cookie
	var fCookie = Get_Cookie(thisCookiePrice)
	var strCookie = Get_Cookie(thisCookieString)
	if(fCookie==null){fCookie="";}
	if(strCookie==null){strCookie="";}
	fCookie = fCookie+","+newPrice
	var tempArray = fCookie.split(",")
	tempArray.sort()
	Set_Cookie(thisCookiePrice,tempArray.join(","))
	strCookie=strCookie+","+thisDesc+"="+newPrice
	Set_Cookie(thisCookieString,strCookie)
}

function Update_MinimumCart(thisCookieString,thisCookiePrice,thisLine){
	var fCookie=Get_Cookie(thisCookiePrice);
	var strCookie=Get_Cookie(thisCookieString);
	var newStrVal = "";
	var newPriceString = "";
	thisLine=thisLine.replace("(PROMO) ","")
	if(fCookie==null){fCookie="";}
	if(strCookie==null){strCookie="";}
	var tempArray = strCookie.split(",")
	for(i=0;i<tempArray.length;i++){
		if((tempArray[i].indexOf(thisLine) > -1) && (tempArray[i] != "")){
			var removePrice = tempArray[i].substring(tempArray[i].indexOf('=')+1,tempArray[i].length)
			fCookie = fCookie.replace(removePrice,"")
			var newArray = fCookie.split(',')				
			newArray.sort();
			Set_Cookie(thisCookiePrice,newArray.join(','))
			thisLine = "!@#$%^&*("
		}else{
			newStrVal = newStrVal + ","+tempArray[i]
		}
	}
	Set_Cookie(thisCookieString,newStrVal)
		
}

function NoEqualSign(thisField){
	for(i=0;i<thisField.value.length;i++){
		if(thisField.value.charAt(i) == "="){
			thisField.value = thisField.value.replace(/=/g,'');
			alert('Equal signs are invalid characters');
			thisField.focus();
		}
	}
}

function Trim(str){	while(str.charAt(0) == (" ") )	{	str = str.substring(1);	}	while(str.charAt(str.length-1) == " " )	{	str = str.substring(0,str.length-1);	}	return str;}


function parseStyleValue(ElementName,thisValue){
// parse the following style elements
// font-family, font-size, font-weight,color
var ItemList = "font-family,font-size,font-weight,color,background-color,border,padding,text-align";
thisValue = thisValue.toLowerCase();
var myArray = thisValue.split(';');
var foundItem = false;
for(i=0;i<myArray.length;i++){
	
	var thisName = Trim(myArray[i].substring(0,myArray[i].indexOf(':')));
	var thisValue = Trim(myArray[i].substring(myArray[i].indexOf(':')+1,myArray[i].length));

	if(ItemList.indexOf(thisName) > -1){
		foundItem = true
		document.writeln('<tr>');
		document.writeln('<td style="width:100px;font-weight:bold;font-size:12px;" valign=top>'+thisName+'</td>');
		document.writeln('<td valign=top>');
		parseStyleInputType(ElementName,thisName,thisValue);
		document.writeln('</td>')
		document.writeln('</tr>');
	}		
}

	// hide any items that do not contain items
	if(foundItem == false){
		if(document.getElementById('Menu_'+ElementName)){
			document.getElementById('Menu_'+ElementName).style.display='none';
		}
	}
		

}


function parseStyleInputType(ElementName,thisInputType,thisValue){
	if (thisInputType == ''){
		return false;
	}else if(!StyleInputArray[thisInputType]){
		return false;
	}

	var currentObject = StyleInputArray[thisInputType]
	var thisType = currentObject['InputType']
	var thisNumericField = currentObject['NumericField']
	var thisMaxLength = currentObject['MaxLength']
	var thisInputSize = currentObject['thisInputSize']
	var thisExtraData = currentObject['ExtraData']
	
	if(thisType == 'GetColor'){
		document.writeln('<input type=text name="'+ElementName+'_'+thisInputType+'" id="'+ElementName+'_'+thisInputType+'" size="15" maxlength="7" value="'+thisValue.replace('"','"')+'"> <input type=button name=cmdAction value="Get Color" class=formButton onClick="GetColor('+unescape('%27')+ElementName+'_'+thisInputType+unescape('%27')+');">');
	}else if(thisType == 'GetFont'){
		document.writeln('<input type=text name="'+ElementName+'_'+thisInputType+'" id="'+ElementName+'_'+thisInputType+'" size="25" maxlength="25" value="'+thisValue.replace('"','"')+'"> <input type=button name=cmdAction value="Get Font" class=formButton onClick="GetFont('+unescape('%27')+ElementName+'_'+thisInputType+unescape('%27')+',document.getElementById('+unescape('%27')+ElementName+'_'+thisInputType+unescape('%27')+').value);">');
	}else if(thisType == 'Textbox'){
		document.writeln('<input type=text name="'+ElementName+'_'+thisInputType+'" id="'+ElementName+'_'+thisInputType+'" size="'+thisInputSize+'" maxlength="'+thisMaxLength+'" value="'+thisValue.replace('"','"')+'">');
	}else if(thisType == 'Select'){
		document.writeln('<select name="'+ElementName+'_'+thisInputType+'" id="'+ElementName+'_'+thisInputType+'">\n');
		var tempArray = thisExtraData.split(";")
		for(zItem=0;zItem<tempArray.length;zItem++){
			if (thisValue == tempArray[i]){
				document.writeln('<option value="'+tempArray[zItem]+'" selected>'+tempArray[zItem]+'</option>\n');		
			}else{
				document.writeln('<option value="'+tempArray[zItem]+'">'+tempArray[zItem]+'</option>\n');		
			}
		}
		document.writeln('</select>');
	}else if(thisType == 'Border'){
		var thisSize = Trim(thisValue.substring(0,thisValue.indexOf(' ')))
		var thisBorder = thisValue.substring(thisValue.indexOf(' ')+1,thisValue.length)
		thisBorder = Trim(thisBorder.substring(0,thisBorder.indexOf(' ')))
		var thisColor = Trim(thisValue.substring(thisValue.length,9))
		// display size
		document.writeln('<input type=text name="'+ElementName+'_'+thisInputType+'_size" id="'+ElementName+'_'+thisInputType+'_size" size="6" maxlength="4" value="'+thisSize+'" onBlur="UpdateComplexCSS('+unescape('%27')+ElementName+'_'+thisInputType+unescape('%27')+','+unescape('%27')+'size,border,color'+unescape('%27')+');">');
		// display border
		document.writeln('<select name="'+ElementName+'_'+thisInputType+'_border" id="'+ElementName+'_'+thisInputType+'_border" onChange="UpdateComplexCSS('+unescape('%27')+ElementName+'_'+thisInputType+unescape('%27')+','+unescape('%27')+'size,border,color'+unescape('%27')+');">\n');
		var tempArray = thisExtraData.split(";")
		for(zItem=0;zItem<tempArray.length;zItem++){
			if (thisBorder == tempArray[zItem]){
				document.writeln('<option value="'+tempArray[zItem]+'" selected>'+tempArray[zItem]+'</option>\n');		
			}else{
				document.writeln('<option value="'+tempArray[zItem]+'">'+tempArray[zItem]+'</option>\n');		
			}
		}
		document.writeln('</select>');
		// display color
		document.writeln('<input type=text name="'+ElementName+'_'+thisInputType+'_color" id="'+ElementName+'_'+thisInputType+'_color" size="8" maxlength="7" value="'+thisColor+'" onBlur="UpdateComplexCSS('+unescape('%27')+ElementName+'_'+thisInputType+unescape('%27')+','+unescape('%27')+'size,border,color'+unescape('%27')+');"> <input type=button name=cmdAction value="Get Color" class=formButton onClick="GetColor('+unescape('%27')+ElementName+'_'+thisInputType+'_color'+unescape('%27')+');">');
		document.writeln('<input type=hidden name="'+ElementName+'_'+thisInputType+'" id="'+ElementName+'_'+thisInputType+'" value="'+thisValue+'">\n');
		
	}


}

function GetColor(thisID){
	var myColor = window.open('/admin/PopUpController.asp?pFn=GetWebSafeColors&ID='+thisID,'WebSafeColors','width=225px,height=400px;resizeable=yes;scrollbars=no,menubar=no,location=no,address=no');
	myColor.focus();
}

function GetFont(thisID,CurrentValue){
	var myColor = window.open('/admin/PopUpController.asp?pFn=WebSafeFonts&ID='+thisID+'&Val='+CurrentValue,'WebSafeFonts','width=400px,height=225px;resizeable=yes;scrollbars=no,menubar=no,location=no,address=no,resizable=yes');
	myColor.focus();
}


function changecss(theClass,element,value,parentWindow) {

 var cssRules;
 if (document.all) {
  cssRules = 'rules';
 }
 else if (document.getElementById) {
  cssRules = 'cssRules';
 }

// create obj to determine if self or parent
var documentLocation;

	if(parentWindow){
		if(parentWindow == true){
			documentLocation = opener.document;
		}else{
			documentLocation = document;
		}
	}else{
		documentLocation = document;
	}


	 for (var S = 0; S < documentLocation.styleSheets.length; S++){
	  for (var R = 0; R < documentLocation.styleSheets[S][cssRules].length; R++) {
	   if (documentLocation.styleSheets[S][cssRules][R].selectorText == theClass) {
	   		if(documentLocation.styleSheets[S][cssRules][R].style[element]){
				documentLocation.styleSheets[S][cssRules][R].style[element] = value;
	   			}
	   }
	  }
	 }	

}


function UpdateCSSClass(StyleArray,FormName){
// this function will loop through the hash and determine which element is visibile
// then it will determine the elements of the current form and update the css classes
var currForm = "";
var currFormNameLength = 0;

for(var k in StyleArray){
	if (document.getElementById(k)){
		if(document.getElementById(k).style.display=='block'){
			currForm = k
		}
	}
}

currFormNameLength = currForm.length;

// process each element prefixed with currForm
var FormContainer = document.getElementById(FormName)
var ElementArray = FormContainer.elements
var ClassProperty = "";
var ClassValue = "";
var midChar = "";


for(i=0;i<FormContainer.length;i++){
	if(FormContainer.elements[i].id.substring(0,currFormNameLength)==currForm){
		// determine class property
		ClassProperty = Trim(FormContainer.elements[i].id.substring(parseFloat(currFormNameLength+1),FormContainer.elements[i].id.length))
		// determine if '-' exists, if so, remove each, and uppercase the following left
	//	alert(ClassProperty)
		if(ClassProperty.indexOf('-') > -1){
		//	while(ClassProperty.indexOf('-') > 0){
				midChar = ClassProperty.substring(ClassProperty.indexOf('-')+1,ClassProperty.length)
				midChar = midChar.substring(0,1).toUpperCase()
				ClassProperty = ClassProperty.substring(0,ClassProperty.indexOf('-')) + midChar + ClassProperty.substring(parseFloat(ClassProperty.indexOf('-')+2),ClassProperty.length)
		//	}
		}
		// determine class value
		ClassValue = FormContainer.elements[i].value
		// change values
		changecss("."+currForm,ClassProperty,ClassValue,true)
	}
}



alert('Successfully updated');

}





function UpdateComplexCSS(hiddenElement,ElementParts){
    var retVal = "";
    var tempArray = ElementParts.split(',')
    for(i=0;i<tempArray.length;i++){
       tempArray[i] = Trim(tempArray[i])
        if(document.getElementById(hiddenElement+'_'+tempArray[i])){
            if(retVal != ""){
                retVal = retVal + ' '
            }
            retVal = retVal + document.getElementById(hiddenElement+'_'+tempArray[i]).value
        }
    }
    if(document.getElementById(hiddenElement)){
        document.getElementById(hiddenElement).value = retVal
    }

}


function DisplayForm(ElementHash,ShowThisOne){
	for (var k in ElementHash){
		if (document.getElementById(k)){
			if (k == ShowThisOne){
				document.getElementById(k).style.display='block';
			}else{
				document.getElementById(k).style.display='none';
			}
		}
	}
}




function returnHyperLink(){
		var retVal = "";

		if (document.getElementById('ExternalLink').style.display == "block"){
			// process external link
			var myExternalUrl = document.getElementById('ExternalUrl')
			var myExternalText = document.getElementById('ExternalText')
			var myExternalTarget = document.getElementById('ExternalTarget')
			// validation
			if (myExternalUrl.value == ""){
				alert("Please enter the Url")
				myExternalUrl.focus();
				return false;
			}else if(myExternalText.value == ""){
				alert("Please enter text for the link")
				myExternalText.focus();
				return false;
			}
			
			// create the link
			retVal = '<a href="'+myExternalUrl.value+'" target="'+myExternalTarget.value+'">'+myExternalText.value+'</a>'
			
		}else if (document.getElementById('InternalLink').style.display == "block"){

			if (document.getElementById('Internal0').style.display == "block"){ // Select Page
				var myInternalPage =  document.getElementById('InternalPage')
				var myInternalPageText = document.getElementById('InternalPageText')
				var myInternalPageTarget = document.getElementById('InternalPageTarget')
				
				// validation
				if (myInternalPage.value == 0){
					alert("Please select a Page")
					myInternalPage.focus();
					return false;
				}else if(myInternalPageText.value == ""){
					alert("Please enter link text")
					myInternalPageText.focus();
					return false;
				}
			// create string
			retVal = '<a href="/index.asp?OID='+myInternalPage.value+'&PageType=Page" target="'+myInternalPageTarget.value+'">'+myInternalPageText.value+'</a>'

			}else if (document.getElementById('Internal1').style.display == "block"){ // Select Image
				var myInternalImageText = document.getElementById('InternalImageText')
				var myInternalImageTarget = document.getElementById('InternalImageTarget')
				var myInternalImagePath = document.getElementById('InternalImagePath')

				if (myInternalImageText.value == ""){
					alert("Please enter text for the link")
					myInternalImageText.focus();
					return false;
				}else if(myInternalImagePath.src == ""){
					alert("Please select an image from the list")
					myInternalImagePath.focus();
					return false;
				}
			
			// create string
			retVal = '<a href="'+myInternalImagePath.src.substring(myInternalImagePath.src.indexOf('/pub/images'),myInternalImagePath.src.length)+'" target="'+myInternalImageTarget.value+'">'+myInternalImageText.value+'</a>'

			}else if (document.getElementById('Internal2').style.display == "block"){ // Select File
				var myInternalFileText = document.getElementById('InternalFileText')
				var myInternalFileTarget =  document.getElementById('InternalFileTarget')
				var myInternalFilePath	 = document.getElementById('InternalFilePath')	
		
				if (myInternalFileText.value == ""){
					alert("Please enter text for the link")
					myInternalFileText.focus();
					return false;
				}else if(myInternalFilePath.innerHTML == ""){
					alert("Please select a file from the list")
					myInternalFilePath.focus();
					return false;
				}
				
			// create string
			retVal = '<a href="/pub/files/'+myInternalFilePath.innerHTML+'" target="'+myInternalFileTarget.value+'">'+myInternalFileText.value+'</a>'
			
			} // end internal selection
		}
		returnValue = retVal
		window.close();
}





function ChangeProductsPerRow(selectObj){
	// detremine the current product table width
	// determine the current product image width
	// reset the columns
	
 var cssRules;
 if (document.all) {
  cssRules = 'rules';
 }
 else if (document.getElementById) {
  cssRules = 'cssRules';
 }

// create obj to determine if self or parent
var documentLocation = document;

	
	var ElementArray = new Array(2);
	var ClassArray = new Array(".productTable",".productImage",".productTableContainer");
	ElementArray[".productTable"] = new Array();
	ElementArray[".productImage"] = new Array();
	ElementArray[".productTableContainer"] = new Array();
	var currProducts = document.getElementById('ProductsPerRow').value
	var colPerRow = selectObj.value;
	for (i = 0;i<ClassArray.length;i++){
		for (var S = 0; S < documentLocation.styleSheets.length; S++){
			for (var R = 0; R < documentLocation.styleSheets[S][cssRules].length; R++) {
					if (documentLocation.styleSheets[S][cssRules][R].selectorText == ClassArray[i]) {
						ElementArray[ClassArray[i]]["width"] = documentLocation.styleSheets[S][cssRules][R].style["width"].replace('px','');
						ElementArray[ClassArray[i]]["height"] = documentLocation.styleSheets[S][cssRules][R].style["height"].replace('px','');
						ElementArray[ClassArray[i]]["padding"] = documentLocation.styleSheets[S][cssRules][R].style["padding"].replace('px','');
						ElementArray[ClassArray[i]]["margin"] = documentLocation.styleSheets[S][cssRules][R].style["margin"].replace('px','');
					}
			}
		}
	}


	// determine the new properties to set the item at which percent
	var currProductContainerWidth = ElementArray[".productTableContainer"]["width"]
	if (ElementArray[".productTableContainer"]["padding"]){currProductContainerWidth -= (colPerRow * ElementArray[".productTableContainer"]["padding"] * 2);}
	if (ElementArray[".productTable"]["margin"]){currProductContainerWidth -= (colPerRow * ElementArray[".productTable"]["margin"] * 2);}
	
	var currProductTablePercent = parseFloat(ElementArray[".productTable"]["width"]/ElementArray[".productTableContainer"]["width"])
	var currProductImagePercent = parseFloat(ElementArray[".productImage"]["width"]/ElementArray[".productTableContainer"]["width"]) 
	
	// set the proudct Table style
//	var thisValue = parseFloat(parseInt(ElementArray[".productTableContainer"]["width"]/colPerRow) * parseFloat(currProductTablePercent))
	thisValue = parseInt(currProductContainerWidth/colPerRow) - 100
	changecss(".productTable","width",thisValue)
	// set the product Image Percent
	var thisValue = parseFloat(parseInt(ElementArray[".productTableContainer"]["width"]/colPerRow) * parseFloat(currProductImagePercent))
	//alert(thisValue)
	thisValue = parseInt(currProductContainerWidth/colPerRow)
	changecss(".productImage","width",thisValue)
	

}

function GetStylesFromParent(thisData){
// obtain the styles from the passed data and return string
var retVal = thisData.substring(thisData.indexOf('<STYLE>')+7,thisData.indexOf('</STYLE>')-thisData.indexOf('<STYLE>'))
retVal = retVal.replace(/(\n|\r|\f|\t)/g,' ')
retVal = retVal.replace(/\"/g,'&quot;')
return retVal
}

function ShowProductInfo(thisURL){
	myProductWindow = window.open(thisURL,'MySpecialWindow','width=700,height=700,scrollbars=yes,resizable=yes,location=yes,url=yes');
	myProductWindow.focus();
}

function confirmOrderQuantity(rowID){
var CurrentIncrement = parseInt(document.getElementById('Increment'+rowID).innerHTML)
var CurrentQuantity = document.getElementById('Quantity'+rowID)
	// determine if quantity is a integer	
	if (isInteger(CurrentQuantity.value) == false){
		alert('Quantity needs to be a numeric');
		CurrentQuantity.value = CurrentIncrement;
		return false;
	}else if(CurrentQuantity.value % CurrentIncrement > 0 || CurrentQuantity.value == 0){
		alert('For this item, the quantity purchased must be in increments of ' + CurrentIncrement);
		CurrentQuantity.value = 0;
		return false;
	}else{
		return true;
	}

}


function ChangePage(currMenu,currLogo) {
var menuArray = new Array
	

	
	for (i=0;i<menuArray.length;i++){
		document.getElementById("menu" + menuArray[i]).style.display = "none";
	}
	
	if (currLogo != null){
		var x = document.images
		x['currLogo'].src = "" + currLogo
	}
	
	if (document.getElementById) {
	thisMenu = document.getElementById(currMenu).style
		if(thisMenu.display == "block") {
			thisMenu.display = "none"
			} else { 
			thisMenu.display = "block"
			}
	return false
	} else {
	return true
	}
}

function openWindow(url)
{
	var myWin = window.open(url, 'MyWin', 'width=500, height=500, scrollbars=yes, resizable=yes')
	myWin.focus()
}

function ViewLargeImage(passedElement){
	var url = passedElement.src
	var myTemp = new Array()
    var newImage = ""  
	var enlargedImage = ""
	
    myTemp = url.split("/")
    newImage = myTemp[myTemp.length-1]
	
		
	if 	((newImage.substring(0,4) == "2_2_") || (newImage.substring(0,4) == "1_2_"))
	{
		 enlargedImage = (newImage.substr(4,100))
	}
	else
	{
		enlargedImage = newImage
	}
	
	//	var myLargePix = window.open('','win','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=1,height=1');
	//	myLargePix.close()
		if (myLargePix != "none"){
			myLargePix.close()	
			}
	
		myLargePix = window.open('','win','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,height=600,width=600,left=200,top=50');
		myLargePix.document.writeln('<html><head><title>Legion Paper</title></head><body>');
		myLargePix.document.writeln('<div align=left><input type=button value=Close onClick="window.close()"></input><p></div><div align=center><img src="/pub/newdesign/enlarged/' + enlargedImage + ' " ></div></body></html>');
		myLargePix.focus();
	
}


function addspecial(sku,item,quantity,weight,min1,max1,cost1,min2,max2,cost2,min3,max3,cost3,incr){

//check the increments
if (quantity % incr > 0){
	alert('Error: Invalid Order Quantity\n\nYou must order this item in increments of '+incr);
	return false;
}

var a = new Array(3);
var price = 0;
a[0] = new Array(min1,max1,cost1);
a[1] = new Array(min2,max2,cost2);
a[2] = new Array(min3,max3,cost3);


for(j=0;j<a.length;j++){
	b = a[j];
	if(quantity>=b[0]&&quantity<=b[1]){
		price = b[2];
		break;
	}
}


	AddToChart('abcOrder12345',sku,item,price,quantity,'HH_Product_Data',0,weight,'/ProductSales.asp',1);		 

}

function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
}}


function startPlayer(obj){
	$f(obj).show();
	$f(obj).play();
	if(document.all){$f(obj).play();}
}