errColor = "#FFE4E1"; //facebook salmon
errColor = "#F8F8FF"; //subtle blue
errColor = "#FFFFF0"; //
errColor = "#ffebe8"; //facebook pink
//errColor = "#FFC0CB"; //pink
//errColor = "#FAFAD2"; //subtle yellow
//errColor = "#FFF0F5"; //pink

var ogColor = "#f9f9f9";


function getQuery(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));

// ------------------ end func
}





function toggleBatchItems(id)
{
// OLD
if(document.getElementById('batchItems_'+id).style.display=='block')
{document.getElementById('batchItems_'+id).style.display='none';}
else
{document.getElementById('batchItems_'+id).style.display='block';}

// -------------------------------------- end func
}

function toggleBatch(id)
{
// OLD
	//alert(id);
if(document.getElementById('batch_'+id).style.display=='block')
{document.getElementById('batch_'+id).style.display='none';}
else
{document.getElementById('batch_'+id).style.display='block';}

// -------------------------------------- end func
}

function toggleSubCatJQ(id){

//list = "#subCatShell288,#subCatShell350,#subCatShell352,#subCatShell278,#subCatShell333,#subCatShell301,#subCatShell358,#subCatShell353";
//alert(list);
//$(list).hide();

	//$("div:not('.sub'+id)").slideToggle("fast");
	
	$(".sub"+id).slideToggle("fast");

// -------------------------------------- end func
}

function toggleSubCat(id){
// OLD	
if(document.getElementById('sub'+id).style.display=='block')
{document.getElementById('sub'+id).style.display='none';}
else
{document.getElementById('sub'+id).style.display='block';}
// -------------------------------------- end func
}


function sqlCMD(id) {
if(id){
//'''''''

if(id==1){
//delete all orders
alert('This Script Is Disabled');
return false;
	var answer = confirm("For Real?")
	if (answer){
		window.location = "?op=1";
	}
	else{
	}
}

if(id==2 || id==3 || id==4){


if(trimMeCheck('imgListForm', 'form',0)==false)
{return false;}

if(id==2)
{strOp='Delete';}
if(id==3)
{strOp='Disable';}
if(id==4)
{strOp='Enable';}




	if (confirm(strOp + " Images?")){
		
		
if(id==2){
if (confirm(strOp + " Images - For Real?"))
{
//
}
else
{return false;}
}

		
		//submit
		return true;
		
		}
		else
		{
		return false;
		}

//
}




//'''''''''''''
}
else
{
		setTimeout(
function() 
{
var mytext = document.getElementById("op");
mytext.focus();
mytext.select();
}
, 1);
		
		
		
	//alert(id);
return false;
}


// -------------------------------------- end func
}


function deleteOrder(id){
if(confirm('Delete Order?'))	
{
	
window.location = "?delete="+id;	
	
	}


	
// -------------------------- end func	
}

function deleteStatusItem(idItem,idOrder){
if(confirm('Delete Status Item?'))	
{
	
window.location = "?delete="+idItem+"&id="+idOrder;	
	
	}


	
// -------------------------- end func	
}

function datePick(idInput, idForm){
	//formname = eval(formname);
	//input = eval(input);
	//jqStr = '#'+idForm+' input#'+idInput;

//alert(jqStr);
	
	
//$(jqStr).datepicker({ dateFormat: 'm/d/yy', showOn: 'button', buttonImage: '../images/choose_date.gif', buttonImageOnly: false}); 


// wire more than one field!
//$('#trip input#leavedate, #trip input#returndate').datepicker({ dateFormat: 'D, M d, yy', showOn: 'button', buttonImage: 'calendar.gif', buttonImageOnly: true }); // format: Thurs, Jan 31, 2008, only show when the user clicks the calendar

	
	//$('#trip input#leavedate').datepicker({ dateFormat: 'M d, yy' }); // Jan 31, 2008
	//$('#trip input#leavedate').datepicker({ dateFormat: 'MM d, yy' }); // January 31, 2008
	//$('#trip input#leavedate').datepicker({ dateFormat: 'D, M d, yy' }); // Thurs, Jan 31, 2008
	
// -------------------------- end func	
}




function statusDivClear() {
document.getElementById('divShipping').style.display='none';
document.update_status.shippingVendor.value='';
document.update_status.shippingMethod.value='';
document.update_status.track.value='';

document.getElementById('divRefund').style.display='none';
document.update_status.refundType.value='';
document.update_status.refundNumCheck.value='';
document.update_status.amtRefund.value='';
document.update_status.refundCardType.value='';
document.update_status.refundCardLastFour.value='';
document.update_status.refundDateProcessed.value='';
document.update_status.refundAuthCode.value='';

document.update_status.errorFromAdmin.style.display='none';
document.getElementById('errorFromAdminLabel').style.display='none';
document.update_status.errorFromAdmin.value='';

document.update_status.noteFromAdmin.style.display='none';
document.getElementById('noteFromAdminLabel').style.display='none';
document.update_status.noteFromAdmin.value='';

// end func	
}





function statusChange(){
input=document.update_status.status;

statusDivClear();

if(input.value=='Shipment')
{
document.getElementById('divShipping').style.display='block';
};

if(input.value=='Refunded')
{document.getElementById('divRefund').style.display='block';};

if(input.value=='orderfailed')
{document.update_status.errorFromAdmin.style.display='block';document.getElementById('errorFromAdminLabel').style.display='block';};

if(input.value!='Accepted' && input.value!='AssetsCollected' && input.value!='orderfailed' && input.value!='Printed' && input.value!='')
{
document.update_status.noteFromAdmin.style.display='block';
document.getElementById('noteFromAdminLabel').style.display='block';
}

// --------------------------- end func
}




function statusRefundCC_Clear() {
document.getElementById('divRefundCCInputs').style.display='none';
document.update_status.refundCardType.value='';
document.update_status.refundCardLastFour.value='';
document.update_status.refundAuthCode.value='';

// end func	
}

function statusRefundCheck_Clear() {
document.getElementById('divRefundCheckInputs').style.display='none';
document.update_status.refundNumCheck.value='';

// end func	
}


function statusPaymentTypeToggle(){
form=eval("document.submit_pay");

form.numCheck.value="";
form.paymentCardType.value="";
form.paymentCardLastFour.value="";
form.paymentAuthCode.value="";

op = form.paymentType.value;
switch (op){
case 'CC': 
document.getElementById("divPaymentCCInputs").style.display = "";	
document.getElementById("divPaymentCheckInputs").style.display = "none";
break;
case "Check":
document.getElementById("divPaymentCheckInputs").style.display = "";	
document.getElementById("divPaymentCCInputs").style.display = "none";
break;

default : 

break;
}

// --------------------------- end func
}

function statusRefundTypeToggle(){
form=eval("document.update_status");
statusRefundCheck_Clear()
statusRefundCC_Clear();
op = form.refundType.value;
switch (op){
case 'CC': 
document.getElementById("divRefundCCInputs").style.display = "";	
break;
case "Check":
//statusRefundCC_Clear();
document.getElementById("divRefundCheckInputs").style.display = "";	
break;

default : 

break;
}

// --------------------------- end func
}



function statusSubmit(){

form=eval("document.update_status");
vGo = true;	





switch(form.status.value){
case "Shipment":
	if(form.shippingVendor.value==''){alert('Select Shipping Vendor!');vGo = false;}
break;

case "Refunded":
		
		if(trimMeCheck('refundType', 'update_status',0)==false)
		{vGo = false;}
		
		op = form.refundType.value;
		switch (op){
		case 'CC': 
		var arr=new Array("amtRefund","refundCardType","refundCardLastFour","refundAuthCode","refundDateProcessed"); 
		break;
		case "Check":
		var arr=new Array("amtRefund","refundNumCheck","refundDateProcessed"); 
		break;
		
		default :
		//credit
		var arr=new Array("amtRefund","refundDateProcessed"); 
		break;
		}
		var len=arr.length;
		for(var i=0; i<len; i++) {
			var value = arr[i];
			if(trimMeCheck(value, 'update_status',0)==false)
			{vGo = false;}
			

}
		
		
		if(trimMeCheck('amtRefund', 'update_status',0,1)==false)
		{vGo = false;}
			
		// if cc limit last four to 4 characters
		// && document.update_status.refundCardLastFour.length > 0
		var lastFour = document.update_status.refundCardLastFour; 
		if(op=="CC" && lastFour.value.length>0)
		{
		if(lastFour.value.length != 4)
		{
		if(lastFour.value.length > 4){strAlert='Only Need Last 4 Digits Of Credit Card!';};
		if(lastFour.value.length < 4){strAlert='Need Last 4 Digits Of Credit Card!';};
		alert(strAlert);
		lastFour.style.backgroundColor=errColor;
		lastFour.focus();
		vGo = false;
		}
		}

break;

case "":
case null:
		alert('Select Status!');
		vGo = false;
break;

default:
vGo = true;
break;

// end switch status
}

if(vGo == false)
{return false;}

// 
if(form.status.value!='Refunded' && form.status.value!='Cancelled' &&   form.idBatchFromAdmin.value==0)
{
	alert('Select Batch!');
	return false;
}


if(form.status.value=='Refunded' || form.status.value=='Cancelled'){
	form.idBatchFromAdmin.value = "";
}


return (confirm('Update Status?'));
	
	
// ------------------------------------------------------------------------------------ end func	
}



function keypressQuantity(e,val,cid)
{
var Ucode=e.keyCode? e.keyCode : e.charCode
if (Ucode == 13)
{
//alert(val + ' ' + cid);
changeQuantity(val,cid);
return false;
}
//------------------------------------------------------------------------------ end func
}

function changeQuantity(quantity,cid){
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
document.payform.action = "public_actions.php?pmode=update_quantity&quantity="+quantity+"&cid="+cid;
document.payform.submit();
// --------------------------------------------------------------- end func
}


function updatePriceOverrideCart(price,idCart,currentPrice){
if(price){
//
proceed = confirm('Override Item Price?');


if(proceed){
		document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
		document.payform.redirect.value = "cart";
		document.payform.action = "public_actions.php?pmode=update_cart_price_override&price="+price+"&cid="+idCart;
		document.payform.submit();

}else{
document.getElementById('item_price_override'+idCart).value=currentPrice;
return false;
}


// end if thisval
}
// ---------------------------------------- end func
}



















function showLB_Select(idLightboxItem,imgPath,imgCaption){

document["select_move_img"].src=imgPath;
document.getElementById("select_move_img_caption").innerHTML=imgCaption;
document.select_move.id_lightbox_item.value=idLightboxItem;
        nuShow('move_lightbox','auto',372,'','');

//document.getElementById('l_move'+id).style.display='block';




// ----------------------------------------- end func ---------------------------------------
}


//function to show dialog OLD  
var showDialog = function() {

//if the contents have been hidden with css, you need this
$myWindow.show(); 
//open the dialog
$myWindow.dialog("open");
// ------------------------------------------ end func
}

//function to close dialog, probably called by a button in the dialog
var closeDialog = function() {
//$myWindow.dialog("close");
$myWindowNu.dialog("close");
// ------------------------------------------ end func
}





function validateEmailPhoto(){

go=true;

var string = document.email_form.email.value;
var arr = cbSplit(string,",");

$.each(arr, function(index, value) { 
//
if(trimMeCheckEmailMultiple(trim(value),'email', 'email_form')==false)
{go= false;}
//
});

if(go==false){
return false;
}

document.email_form.action = "public_actions.php?pmode=email_photo";
document.email_form.submit();

// ------------------------------------------ end func
}


function dropdown(mySel){
		
		var myWin, myVal;
			//myVal = mySel.options[mySel.selectedIndex].value;
			myVal = mySel.form.path.value + mySel.options[mySel.selectedIndex].value;
			
			
			if(myVal){
   		if(mySel.form.target)myWin = parent[mySel.form.target];
   				else myWin = window;
   		if (! myWin) return true;
		//alert(myVal);
   				myWin.location = myVal;
   			}
			return false;
// ------------------------------------------ end func
}


function errSmall(id, error, op, formname, fieldname, fieldbool) {

fld='';

if(fieldbool==1){fld = eval('document.'+formname+'.'+fieldname);}

if(op==1){
// error alert on	
	
				document.getElementById(id).innerHTML=error;
				//document.getElementById(id).style.display="block";
				document.getElementById(id).style.display="";
				
				if(fieldbool==1){
				fld.style.background = errColor;
				//fld.focus();
				}
				//return false;
}
else
{
// error alert off	
				document.getElementById(id).innerHTML="";
				document.getElementById(id).style.display="none";
				
				if(fieldbool==1){
				fld.style.background = ogColor;
				}
				
}

//-------------------------------------------------------------------------------------------------- end func	
}



function echeck(str) {

		
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		
		
		 //    
var last_char=str.charAt(lstr-1);
		 
		 
		 //
		
		
		
		if (str.indexOf(at)==-1){
		   //alert("Invalid Email!")
		   //alert("1")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   //alert("Invalid Email!")
		   //alert("2")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    //alert("Invalid Email!")
		   //alert("3")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid Email!")
		   //alert("4")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid Email!")
		   //alert("5")
		    return false
		 }
		 
		 if ( last_char =="."){
		    //alert("Invalid Email!")
		   //alert("6")
		    return false
		 }
		 
		
		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid Email!")
		   //alert("7")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid Email!")
		 //  alert("8")
		    return false
		 }

 		 return true					
//------------------------------------------------------------------------------ end func
}

function ValidateForm(){
	var emailID=document.frmSample.txtEmail
	
	if ((emailID.value==null)||(emailID.value=="")){
		alert("Please Enter your Email ID")
		emailID.focus()
		return false
	}
	if (echeck(emailID.value)==false){
		emailID.value=""
		emailID.focus()
		return false
	}
	return true
//------------------------------------------------------------------------------ end func
}


function trim(str){
	
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');	
//------------------------------------------------------------------------------ end func
}

// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
 
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
 
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
 
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
 
 
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
 
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
 
 
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
 
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
 
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
 
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
 
}
 
 
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
 
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
 
} else {
 
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
 
}
 
 
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
 
// Return the parsed data.
return( arrData );
// ---------------------------------------------- end fucn
}
 





function validateEmailLightbox() {

myString = document.email_form.email.value;
valueArray = myString.split(",");

for(var i=0; i<valueArray.length; i++){

if(trimMeCheckEmailMultiple(trim(valueArray[i]),'email', 'email_form')==false)
{return false;}

}

document.email_form.action = "public_actions.php?pmode=email_lightbox";
document.email_form.submit();
//------------------------------------------------------------------------------ end func
}







function validateEmailAdmin() {
var go =  true;

myString = document.email_form.email.value;
valueArray = myString.split(",");

for(var i=0; i<valueArray.length; i++){

if(trimMeCheckEmailMultiple(trim(valueArray[i]),'email', 'email_form')==false)
{go =  false;}

}

if(trimMeCheck('subject', 'email_form',0)==false)
{go =  false;}

if(trimMeCheck('message', 'email_form',0)==false)
{go =  false;}


if(go ==  false){
return false;
}else{
return true;	
}

//------------------------------------------------------------------------------ end func
}


function validateEmailPassword() {

if(trimMeCheck('email', 'recover_password',1)==false)
{return false;}
				
return true;

//------------------------------------------------------------------------------ end func
}












function validateLogin(){
var go = true;

if(trimMeCheck('email', 'login',1)==false)
{go = false;}
if(trimMeCheck('password', 'login',0)==false)
{go = false;}

//alert(go);	 


if(go == false){
return false;
}	 

return true;
//------------------------------------------------------------------------------ end func
}

function validateAccount(){
	 
if(trimMeCheck('email', 'login',1)==false)
{return false;}
if(trimMeCheck('password', 'login',0)==false)
{return false;}

return true;
//------------------------------------------------------------------------------ end func
}



function clearMeCheckByID(id){

var input=document.getElementById(id);
input.value=="";
input.style.backgroundColor=ogColor;


// ---------- end func
}

function trimMeCheckByID(id, isEmail){
// use this for text input data including a single email input NOT for comma delimited email input
var proceed=true;
//var input=eval('document.'+formname+'.'+fieldname);
var input=document.getElementById(id);
input.value = trim(input.value);
if ((input.value==null)||(input.value=="")){
proceed=false;
}

if(isEmail==1)
{
//
//alert('echeck');
if (echeck(input.value)==false){
proceed=false;
}
//	
}

//alert(proceed);

if(proceed==false)
{
input.style.backgroundColor=errColor;
//input.focus();
return false;
}
else
{
input.style.backgroundColor=ogColor;
return true;
}
//------------------------------------------------------------------------------ end func
}



function trimMeCheck(fieldname, formname, isEmail,isCurrency){
// use this for text input data including a single email input NOT for comma delimited email input
var proceed=true;
var input=eval('document.'+formname+'.'+fieldname);
input.value = trim(input.value);
if ((input.value==null)||(input.value=="")){
proceed=false;
}

if(isEmail==1)
{
//
//alert('echeck');
if (echeck(input.value)==false){
proceed=false;
}
//	
}

//alert(proceed);

if(isCurrency==1)
{
//
	input.value=formatCurrency(input.value);
	if (input.value==0){
	proceed=false;
	}
//	
}











if(proceed==false)
{
input.style.backgroundColor=errColor;
//input.focus();
return false;
}
else
{
input.style.backgroundColor=ogColor;
return true;
}
//------------------------------------------------------------------------------ end func
}
	
function trimMeCheckEmailMultiple(val,fieldname, formname){
// use this for comma delimited email input
var input=eval('document.'+formname+'.'+fieldname);

var proceed=true;
val=trim(val);
if ((val==null)||(val=="")){
proceed=false;
}

if (echeck(val)==false){
proceed=false;
}

//alert(proceed);

if(proceed==false)
{
input.style.backgroundColor=errColor;
input.focus();
return false;
}
else
{
input.style.backgroundColor=ogColor;
return true;
}
//------------------------------------------------------------------------------ end func
}




function validateAddressFormInputsSub(formname){

var go = true;

form = eval("document."+ formname);

arr = new Array("name", "address1", "city");

$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, formname,0)==false)
{go =  false;}
//
});



if(form.country.value == "USA" || form.country.value == "CAN"){
//
if(trimMeCheck('state', formname,0)==false)
{
	go =  false;
	}
// end if
}
else
{
form.state.style.backgroundColor=ogColor;
}



arr = new Array("zip", "country");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, formname,0)==false)
{go =  false;}
//
});





if(form.country.value == "XXX"){
form.country.style.backgroundColor=errColor;
go =  false;
}

if(trimMeCheck('phone', formname,0)==false)
{go =  false;}
else
{
//	
if(form.phone.value.length < 10)
{
errSmall('errPhone', '10 Digit Phone Number Required!', 1);
form.phone.style.backgroundColor=errColor;
go =  false;

}
else
{
clearDiv('errPhone');	
}


//	
}




if(trim(form.email.value) != ""){
if(trimMeCheck('email', formname,1)==false)
{go =  false;}
}
else
{form.email.style.backgroundColor=ogColor;}

//alert(go);

if(go ==  false)
{return false;}
else
{return true;}

	
	
//------------------------------------------------------------------------------ end func
}

function validateAddressForm() {

var go = true;

if(validateAddressFormInputsSub('AddressForm')==false)
{go = false;}

//alert(go);
if(go ==  false)
{return false;}

//return false;




document.AddressForm.action = "public_actions.php?pmode=address_add_edit";
document.AddressForm.submit();
// --------------------------------------------------------------- end func
}



function validateContact() {

var go = true;

if(trimMeCheck('name', 'contact_form', 0)==false)
{go = false;}
if(trimMeCheck('spam_stop', 'contact_form',1)==false)
{go = false;}
if(trimMeCheck('comments', 'contact_form',0)==false)
{go = false;}

if(go == false)
{
return false;
}



if(document.contact_form.email.value=="")
{
//set email field for real
document.contact_form.email.value=document.contact_form.spam_stop.value;
}
else
{
//stop form spam
return false;
}

document.contact_form.action="public_actions.php?pmode=send_mail";
document.contact_form.submit();
return true;

//------------------------------------------------------------------------------ end func
}


function clearDiv(id){
	
document.getElementById(id).style.display="none";
document.getElementById(id).innerHTML="";
document.getElementById(id).style.background = ogColor;
//fld.focus();
//------------------------------------------------------------------------------ end func
}


function contact_click_submit() {
var b=document.getElementById('contact_form').onsubmit();
if (b) {
document.getElementById('contact_form').submit();
}
//------------------------------------------------------------------------------ end func
}
		

/*
the function applyDropShadows takes one argument - a css selector
that refers to the element(s) to which you want to apply drop shadows.

Call this function from each page that you wish to apply drop shadows
cssSelector = element as well as class or ID attributes
shadowStyle = different shadow styles that are available

window.onload = function(){
	applyDropShadows(cssSelector,shadowStyle);
	}
*/
function applyDropShadows(cssSelector,shadowStyle){
	if(document.getElementsByTagName && document.createElement){
		// get all elements that match the specified css selector
		var elements = document.getElementsBySelector(cssSelector);
	
		// loops through the list of matching elements
		for(i=0;i<elements.length;i++){
		
			var element = elements[i];
			
			// create the wrapper divs
			var wrap1 = document.createElement('div');
			var wrap2 = document.createElement('div');
			var wrap3 = document.createElement('div');
			wrap1.className = shadowStyle;
			
			// duplicate the image to be shadowed
			var newElement = element.cloneNode(true);
			
			// nest the new image and wrapper divs
			wrap3.appendChild(newElement);
			wrap2.appendChild(wrap3);
			wrap1.appendChild(wrap2);
			var shadowedElement = wrap1;
			
			// replace the old image with the new div-wrapped version
			element.parentNode.replaceChild(shadowedElement,element);
			}
		}
	}

/*
everything below this point is Simon Willison's getElementsBySelector script,
located on his site: http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/

/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names, 
     class names and ids and can be nested. For example:
     
       elements = document.getElementsBySelector('div#main p a.external')
     
     Will return an array of all 'a' elements with 'external' in their 
     class attribute that are contained inside 'p' elements that are 
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/

//------------------------------------------------------------------------------ end func



String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
//------------------------------------------------------------------------------ end func
};

//alert('?');

function continue_shopping(){	
var lastpage=document.referrer;
var lastpage_array=lastpage.split("/");
var i=0;
while (i < lastpage_array.length)
 {
 lastpageQuery = lastpage_array[i]; 
  i+=1;
  }	
lastpage_array=lastpageQuery.split("?");
lastpageQuery = lastpage_array[0];
if(lastpageQuery == "login.php"){window.location="index.php";}else{history.go(-1);}
// --------------------------------------------------------------- end func
}

function NewWindow(page, name, w, h, location, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',location='+location+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(page, name, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
// --------------------------------------------------------------- end func
}


// old way
var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "";
ccErrors [1] = "Card Number Required!";
ccErrors [2] = "Card Number Format Invalid!";
ccErrors [3] = "Card Number Invalid!";
ccErrors [4] = "Card Number Has An Inappropriate Number Of Digits!";
ccErrors [5] = "Unknown Credit Card Type!";


	
	



function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305, 36, 38, 54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
	
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card

string = cards[cardType].prefixes;
prefix = cbSplit(string,",");
//prefix = cards[cardType].prefixes.split(",");
    
	  
 
	  
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
string = cards[cardType].length;
lengths = cbSplit(string,",");
//lengths = cards[cardType].length.split(",");


for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
 
  return true;
// --------------------------------------------------------------- end func
}















function deleteAddress_OLD(id,formname)
{
go = (confirm ("Delete Address?")); 

if(go == true)
{
//
if(formname){
form = eval('document.'+formname);
if(formname=='cardform'){form.redirect.value='card';};
}
else
{form = eval('document.cardform_for_cancel');}
	
form.action = "public_actions.php?pmode=address_delete&idAddress="+id;
form.submit();
//
}

// --------------------------------------- end func
}

function deleteAddressJQClick(idAddress, nameForm, idDiv)
{
	
form = eval('document.'+nameForm);
form.idAddress.value = idAddress;
nuShow(idDiv,150,300,'','');

$(document).keyup(function(e) {

	if (e.keyCode == 13) {deleteAddressJQConfirm(nameForm);}   
});

// --------------------------------------- end func
}

function deleteAddressJQConfirm(nameForm)
{



$("#delete_address_buttons").hide();
$("#delete_address_processing").show();

form = eval('document.'+nameForm);
form.action = "public_actions.php?pmode=address_delete&idAddress="+form.idAddress.value;
form.submit();

// --------------------------------------- end func
}

function emptyCart()
{
	
setTimeout("nuShow('empty_cart',150,300,'','')",3);	


$(document).keyup(function(e) {

	if (e.keyCode == 13) {emptyCartConfirm();}   
});

return false;

// --------------------------------------- end func
}

function emptyCartConfirm(){

window.location = 'public_actions.php?pmode=empty_cart';
return false;
// -------------------------------------- end func	
}


function cartShipFreeAlert(id)
{
//
//if(   (document.couponForm.coupon_id.value == 1)  && (id !=7)  )
if(   (document.couponForm.coupon_id.value == 1)  && (id !='PM')  )

{
	nuShow('shipFree_alert','auto','auto','','',50,true);
	
	$(document).keyup(function(e) {
		if (e.keyCode == 13) {cartShipFreeAlertConfirm();}   
	});
	
	return false;
}
else
{
	changeShipping(id);
}
// --------------------------------------- end func
}


function cartShipFreeAlertConfirm()
{
changeShipping(document.getElementById('shipping_method').value);
// --------------------------------------- end func
}

function changeShipping(id){
	
	
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
//document.payform.action = "cart.php?shipping_id="+id;
document.payform.action = "cart.php?idShip="+id;

document.payform.submit();
// --------------------------------------------------------------- end func
}











function goToRedirect(page,query){
if(query){query="?"+query}else{query="";}	
window.location="https://www.fillprints.com/"+page+".php"+query;
// --------------------------------------- end func
}
	


function addEditCard(id,redirect,formname)
{


if((!id) || id==0)
{

		if(formname)
		{
		form=eval('document.'+formname);
		form.action = "https://www.fillprints.com/card.php";
		form.submit();
		}
		else
		{
		window.location="https://www.fillprints.com/card.php";
		}
return false;
}


switch(redirect){

case "cart":
		if(formname)
		{form=eval('document.'+formname);form.redirect.value = "cart";form.x_card_code_from_cart.value = form.x_card_code.value;}
		else
		{form=eval('document.cardform_for_cancel');}

		form.action = "https://www.fillprints.com/card.php";
		form.submit();
break;



case "order":
		form=eval('document.'+formname);
		form.x_card_code_from_cart.value = form.x_card_code.value;
		form.action = "https://www.fillprints.com/card.php";
		form.submit();

case "account":
//alert(1+redirect);return false;
//alert(1);
		form=eval('document.'+formname);
		form.action = "https://www.fillprints.com/card.php";
		form.submit();

break;

default:
// account
			
		//	alert(0);
			//return false;
			window.location="https://www.fillprints.com/card.php?idCard="+id+"&redirect=account";
				
break;
// end switch
}


// --------------------------------------------------------------- end func
}










function deleteCard(id,redirect)
{


var answer = confirm ("Delete Card?")
if (answer)
{
//
if(redirect == 'cart')
{
document.cardform_for_cancel.action = "public_actions.php?pmode=stored_card_delete&idCard="+id;
document.cardform_for_cancel.submit();
}
else
{
window.location="public_actions.php?pmode=stored_card_delete&idCard="+id+"&redirect=account";
}
// end if
}
// --------------------------------------------------------------- end func
}

function deleteCardJQClick(idCard, nameForm, idDiv)
{
	
form = eval('document.'+nameForm);
form.idCard.value = idCard;
nuShow(idDiv,150,300,'','');


$(document).keyup(function(e) {

	if (e.keyCode == 13) {deleteCardJQConfirm(nameForm);}   
});


// --------------------------------------- end func
}

function deleteCardJQConfirm(nameForm)
{


$("#delete_card_buttons").hide();
$("#delete_card_processing").show();




if(nameForm){
form = eval('document.'+nameForm);
}
else
{
	form = eval('document.cardform_for_cancel');
}
	
form.action = "public_actions.php?pmode=stored_card_delete&idCard="+form.idCard.value;
form.submit();

// --------------------------------------- end func
}



function addressSetType(idAddress, nameForm, isBilling, isShipping,isPO)
{

if(nameForm){
form = eval('document.'+nameForm);
if(nameForm=='cardform'){form.redirect.value='card';};
}
else
{form = eval('document.cardform_for_cancel');}
//alert(isBilling);
//alert(isShipping);
//alert(nameForm);
	
form.action = "public_actions.php?pmode=address_add_edit&bypass=1&isBilling="+isBilling+"&isShipping="+isShipping+"&isPO="+isPO+"&idAddress="+idAddress;
form.submit();
//alert(form.action);
// --------------------------------------- end func
}



function cancelFromCart(formname, redirect, query){

if(formname){
form = eval('document.'+formname);
}
else
{form = eval('document.cardform_for_cancel');}

if(!redirect){
redirect = form.redirect.value;
}

if(query)
{query="?"+query}else{query="";}	


if(redirect)
{form.action = redirect + ".php"+query;}
else
{
	form.action = "cart.php";
}

//alert(form.action);

form.submit();

//document.cardform_for_cancel.action = "cart.php";
//document.cardform_for_cancel.submit();

// --------------------------------------------------------------- end func
}



function cc_gif_pop(choice)
{
if (document.payform.x_card_stored_id.value==0)
{document.payform.x_card_type.value=choice;}
// ----------------------------------------------------- end func
}

function changeAddress(op){

switch(op){
case 1:
billing_or_shipping="billing";
break;
	
case 0:
billing_or_shipping="shipping";
break;

case 2:
billing_or_shipping="po";
break;

	}	

//alert(billing_or_shipping);

document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
document.payform.action = "address.php?select="+billing_or_shipping;
document.payform.submit();

// --------------------------------------------------------------- end func
}

function editAddress(id,formname,redirect,redirectSecondary){
//
form = eval('document.'+formname);
form.redirect.value = redirect;
if(redirectSecondary){
form.redirectSecondary.value = redirectSecondary;
}

if(redirect == "cart" || redirect == "order"){
form.x_card_code_from_cart.value = form.x_card_code.value;
}


form.action = "address.php?idAddress=" + id;
form.submit();


// --------------------------------------------------------------- end func
}






function addAddress_OLD(redirect){

document.cardform_for_cancel.action = "address.php";
document.cardform_for_cancel.submit();

// --------------------------------------------------------------- end func
}

function addAddress(op,formname,redirect,redirectSecondary){

switch(op)
{
case 0:
  strQuery = '?shipping=true';
  break;
case 1:
  strQuery = '?billing=true';
  break;
case 2:
  strQuery = '?po=true';
  break;
default:
strQuery="";
  break;

//
}

form = eval('document.'+formname);
form.redirect.value = redirect;
if(redirectSecondary){
form.redirectSecondary.value = redirectSecondary;
}

if(redirect == "cart"){
form.x_card_code_from_cart.value = form.x_card_code.value;
}

form.action =  "address.php"+strQuery;
form.submit();
// --------------------------------------------------------------- end func
}

function changeAddressCC(id){
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
//idCard="+id+"&
document.payform.action = "card.php?op=change_address";
document.payform.submit();

// --------------------------------------------------------------- end func
}
	
function addAddressCC(id){
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
//idCard="+id+"&
document.payform.action = "card.php?op=add_address";
document.payform.submit();

// --------------------------------------------------------------- end func
}


function changePrintFinish(print_finish,cid){
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
document.payform.action = "public_actions.php?pmode=update_print_finish&print_finish="+print_finish+"&cid="+cid;
document.payform.submit();
// --------------------------------------------------------------- end func
}






function validateSendCustomCropApprovalEmailOpen(){

document.form_SendCustomCropApprovalEmail.note.value="";
uncheckAllBoxes('itemCheck','form_SendCustomCropApprovalEmail');
nuShow('div_SendCustomCropApprovalEmail','auto',500);
return false;


// --------------- end func	
}


function validateSendCustomCropApprovalEmail(count,countFiles){


form=eval("document.form_SendCustomCropApprovalEmail");
// emails
					var emailList = '';
						var emailListAlert = '';
						
						
						iChecked = 0;
						for (var i = 0; i < form.elements.length; i++ ) {
								
								if (form.elements[i].type == 'checkbox' && form.elements[i].id == 'checkboxEmail') {
									if (form.elements[i].checked == true) {
									
									iChecked++;
									
										if(iChecked > 1){emailList = emailList + '_';}
										emailList += form.elements[i].value;
										
										if(iChecked > 1){emailListAlert = emailListAlert + ', ';}
										emailListAlert += form.elements[i].value;
										
									}
								}
						  
							}
							
							
						if(!emailList){
						alert('No Email Selected!');
						return false;
						}
						else
						{
						form.emailList.value=emailList;
							}

// end emails









//
checkbox=eval("document.form_SendCustomCropApprovalEmail.itemCheck");

var selected = "";
if(count > 1){
for (var i=0; i < checkbox.length; i++)
   {
   if (checkbox[i].checked)
      {
      selected = selected + checkbox[i].value + ",";
	  }
// end for loop
}

selected =  String(selected).substring(0,( String(selected).length - 1));
// end if one countCart
}
else
{
if(checkbox.checked){selected = checkbox.value;}
}

if(!selected)
{alert('No Items Selected!');
	return false;

	}
document.form_SendCustomCropApprovalEmail.itemList.value = selected;

//

if(countFiles == 0)
{
	if(!(confirm('\n\nSome Items Do Not Have Custom Crop File Made!\n\nProceed?')))
	{return false;}

	}





















return true;

// --------------------------------------------------------------- end func
}


function validateMakeBatchAdminOpen(){

uncheckAllBoxes('itemCheck','MakeBatchAdmin');
uncheckAllBoxes('idVendor','MakeBatchAdmin');
nuShow('MakeBatchAdmin','auto',500);
return false;


// --------------- end func	
}



function validateMakeBatchAdmin(countCart,countVendors){

//
checkbox=eval("document.MakeBatchAdmin.itemCheck");

var selected = "";
count=countCart;
if(count > 1){
for (var i=0; i < checkbox.length; i++)
   {
   if (checkbox[i].checked)
      {
      selected = selected + checkbox[i].value + ",";
	  }
// end for loop
}
selected =  String(selected).substring(0,( String(selected).length - 1));
// end if one countCart
}
else
{
if(checkbox.checked){selected = checkbox.value;}
}

if(!selected)
{alert('No Items Selected!');
	return false;

	}
document.MakeBatchAdmin.itemList.value = selected;

//

checkbox=eval("document.MakeBatchAdmin.idVendor");

var selected = "";
count=countVendors;
if(count > 1){
for (var i=0; i < checkbox.length; i++)
   {
   if (checkbox[i].checked)
      {
      selected = selected + checkbox[i].value + ",";
	  }
// end for loop
}
selected =  String(selected).substring(0,( String(selected).length - 1));
// end if one countCart
}
else
{
if(checkbox.checked){selected = checkbox.value;}
}



if(!selected)
{alert('No Vendor Selected!');
	return false;
}

//


//alert(document.MakeBatchAdmin.itemList.value);
return true;

// --------------------------------------------------------------- end func
}













function validateSubmitXML(needed,made,countCart){
//
var submitted = 0;
var selected = "";
var countSelected = 0;

if(countCart > 1){
for (var i=0; i < document.itemSubmitList.itemCheck.length; i++)
   {
   if (document.itemSubmitList.itemCheck[i].checked)
      {
      selected = selected + document.itemSubmitList.itemCheck[i].value + ",";
	  //alert(document.itemSubmitList.itemCheck[i].value);
	  countSelected = (countSelected + 1);
	  
	  if(document.itemSubmitList.submitted[i].value)
	  {
	  //alert(document.itemSubmitList.submitted[i].value);
	  submitted = 1;
	  }
      	  
	  }
// end for loop
}
selected =  String(selected).substring(0,( String(selected).length - 1));
// end if countCart > 1
}
else
{
if(document.itemSubmitList.itemCheck.checked){selected = document.itemSubmitList.itemCheck.value;countSelected = (countSelected + 1);}
if(document.itemSubmitList.submitted.value){submitted = 1;}
}

//alert(selected + ' ' + submitted);
//return false;

document.submit_xml.itemList.value = selected;
//
if(made == 0)
{
//
 alert('No Deliverables Made!');
return false;
//
}

//
if(selected == "")
{
//
 alert('No Items Selected!');
return false;
//
}

if(needed > 0)
{
//
 if( (confirm(needed+' Deliverable(s) Still Needed To Fulfill Order!!\n\nProceed?')) == false)
 {return false;}
//
}

if(submitted > 0)
{
//
	 if( (confirm('Some Print Order Items Already Submitted!\n\nSubmit Again?')) == false)
	 {
	//uncheck all boxes
							for (var i=0; i < document.itemSubmitList.itemCheck.length; i++)
						   {
							//   
						   if (document.itemSubmitList.itemCheck[i].checked)
							  {
							  document.itemSubmitList.itemCheck[i].checked=false;
								  
							  }
						// end for loop
						}

	
	
	// end uncheck all boxes 
	 return false;
	 }
	else
	{
	nuShow("reprint");
	return false;
	}
//
}


if(submitted == 0 && needed == 0)
{
//
if( (confirm(countSelected+' Items Selected\n\nSubmit XML Order?')) == false)
 {return false;}
	//
	
	}
// clean submit confirm anyway


return true;
// ------------------------------------ end func
}



//--------------------------------------------------------------------------------------------

var closedialog =1;
var jq_pop_div = '';

function nuShow(id,vheight,vwidth,vtitle,vclass,vtop,vProcessing,vForm,scriptStop) {
// '''''''''''''''''''''''''
// jq initiate
$(function() {

closedialog = 1;

if(!vtop){vtop = 100;}

vAutoOpen = false;
vCloseOnEscape = true;
vDraggable = true;

if(vProcessing)
{
vAutoOpen = true;
vCloseOnEscape = false;
vDraggable = false;
}
jq_pop_div = '#'+id;
$myWindowNu = jQuery('#'+id);

$myWindowNu.dialog({ 

height: vheight,
width: vwidth,
modal: true,
position:  ['center',vtop],
closeOnEscape: vCloseOnEscape,
resizable: false,
autoOpen:vAutoOpen,
draggable: vDraggable,
title: vtitle,
overlay: { opacity: 0.5, background: '#e9e8e8'}

});

////////////////

// if the contents have been hidden with css, you need this

if(vProcessing){
// pop in quick no fade no close on escape or click
$myWindowNu.show();
closedialog = 1;
//
}
else
{
// fade in fast close on escape or click
$myWindowNu.fadeIn('fast');
closedialog =0;

$(document).keyup(function(e) {
//  if (e.keyCode == 13) { $('.save').click(); }     // enter
  if (e.keyCode == 27) { nuShowClose(); }   // esc
});





// end if vProcessing
}


//open the dialog
$myWindowNu.dialog("open");

//if(callbackFunction){

//$(document).keyup(function(e) {
	
	//if (e.keyCode == 13) {alert(0);}   
	
	//});	
//}


// hide the defaut title bar
$myWindowNu.parents(".ui-dialog:first").find(".ui-dialog-titlebar").css("display","none");

// de-select anchors and inputs

$('a').blur();
$('input').blur();
$('select').blur();


if(scriptStop)
{return false;}
else
{return true;}


// end jq initiate
}); 
// '''''''''''''''''''''''''''''''''''''''''''''''''
// ------------------------------------------ end func
}


$(document).ready(function() {

    //$(".linkPreviewEmailPhoto").click(function() {
      //  nuShow('email_photo','auto','auto','','');
	//});

//
});


function overlayclickclose() {
			if (closedialog) {
				nuShowClose();
				$(document).unbind('click');
          		}
			//set to one because click on dialog box sets to zero
			closedialog = 1;
// ------------------------------------------ end func
}



function nuShowClose() {
	
//$myWindowNu.dialog("close");
$myWindowNu.dialog('destroy');
//$myWindowNu.dialog.remove();
//$myWindowNu.dialog.({hide:"fade"});
// ------------------------------------------ end func
}
  
//--------------------------------------------------------------------------------------------

function launchWindow(id)
{  //select all the a tag with name equal to modal  
    //$('a[name=modal]').click(function(e) {  
        //Cancel the link behavior  
      //  e.preventDefault();  
        //Get the A tag  
        //var id = $(this).attr('href');  
      
        //Get the screen height and width  
        var maskHeight = $(document).height();  
        var maskWidth = $(window).width();  
      
        //Set height and width to mask to fill up the whole screen  
        $('#mask').css({'width':maskWidth,'height':maskHeight});  
          
        //transition effect       
        $('#mask').fadeIn(250);      
        //$('#mask').fadeTo("fast",0.8);    
      
        //Get the window height and width  
        var winH = $(window).height();  
        var winW = $(window).width();  
                
        //Set the popup window to center  
        //$(id).css('top',  winH/2-$(id).height()/2);  
        $(id).css('top',  50);  
        $(id).css('left', winW/2-$(id).width()/2);  
      
        //transition effect  
        $(id).fadeIn(250);   
      
  //  });  
    // --------------------------------------- end func
	}  

$().ready( function () {
					 
					 
//
});



function changeCC_IMG(){
	
		var ct_val = document.cardform.x_card_type.value;
		switch (ct_val) 
		{
		case "AmEx":
		document.getElementById('imgCC').src = 'images/_cc_amex.gif';
		break;
		case "Discover":
		document.getElementById('imgCC').src = 'images/_cc_disc.gif';
		break;
		case "MasterCard":
		document.getElementById('imgCC').src = 'images/_cc_mc.gif';
		break;
		case "Visa":
		document.getElementById('imgCC').src = 'images/_cc_visa.gif';
		break;
		default:
		document.getElementById('imgCC').src = 'images/_cc_blank.gif';
		break;
		}
// --------------------------------------------------------------- end func
}



function js_cardform_validate_address_select(){
// existing address ---------------------

//if(go ==  false)
//{return false;}

// --------------------------------------------------------------- end func
}



function js_cardform_change_address() {

var go = true;
////
var c_value = "";
if(document.cardform.address_id.length)
			{
							for (var i=0; i < document.cardform.address_id.length; i++)
							   {
										if (document.cardform.address_id[i].checked)
										{
										c_value = c_value + document.cardform.address_id[i].value;
										}
							   }
			}else{
										if (document.cardform.address_id.checked)
										{
										c_value = c_value + document.cardform.address_id.value;
										}
				
			}
			
if(c_value == "")
{
	error = 'No Billing Address Selected!';
	errSmall('errAddress', error, 1, null, null, 0);
	go =  false;
}
else
{errSmall('errAddress', '', 1, null, null, 0);}
////
if(go == false)
{

return false;}
				document.cardform.action = "public_actions.php?pmode=stored_cards_change_address";
				document.cardform.submit();
// --------------------------------------------------------------- end func
}


function editCard_OLD(id){
document.cardform.redirect.value = "cart";
document.cardform.action = "card.php?idCard=" + id;
document.cardform.submit();

// --------------------------------------------------------------- end func
}


function editAddressCC(idAddress){

toggleCardAddressNewExisting('New');
document.getElementById('useNewAddress').checked=false;
document.getElementById('useExistingAddress').checked=true;

inputs = 'name,name_company,address1,address2,city,state,zip,country,phone,email,sendEmailToShipping';
var string = inputs;
var arr = cbSplit(string,",");
$.each(arr, function(index, value) { 
//
inputTarget =  eval('document.cardform.'+value);
inputSourceValue = eval('document.cardform.'+value+idAddress+'.value');
inputTarget.value = inputSourceValue;
//
});

document.cardform.idAddress.value=idAddress;

// --------------------------------------------------------------- end func
}


function toggleUseNewFromCart(){

toggleCardAddressNewExisting('New');
				
// --------------------------------------------------------------- end func
}



function resetPaySub(){
	
	errSmall('errAddressPaySub', null, 0);

if(document.payform.countStoredCards.value>0){
document.payform.x_card_stored_id.options[0]=new Option("Select Card", 0, true, false);
}
	document.payform.x_card_stored_id.value=0;
	toggleCheckboxPay('balance_due');
	populateFromStored(0,'paySub');
	//toggleCardAddressNewExisting('Existing','payform');
	nuShowClose();
// --------------------------------------------------------------- end func
}
	


function toggleCardAddressNewExisting(op,formname){
	if(!formname){formname='cardform';}
	form = eval("document."+formname);
	uncheckAllBoxes('opNewExistingAddress',formname);
	
if(formname=='cardform'){
	document.getElementById('errAddress').style.height='20px';
	document.getElementById('errAddress').style.paddingTop='0px';
	document.getElementById('errAddress').style.color='#FF0000';
	document.getElementById('errAddress').innerHTML='&nbsp;';
}
else
{
	
document.getElementById('errAddressPaySub').style.color='#FF0000';
	document.getElementById('errAddressPaySub').innerHTML='';
	document.getElementById('errAddressPaySub').style.paddingTop='3px';
	}

switch(op)
	{
	case "New":
		
if(formname=='cardform'){
if(form.idAddress.value)
{clearTheseInputs('idAddress,name,name_company,address1,address2,city,state,zip,country,phone,email,sendEmailToShipping',formname);}
}

		
if(formname=='cardform'){
document.getElementById('errAddress').style.color='#999999';
		document.getElementById('errAddress').style.paddingTop='3px';
		document.getElementById('errAddress').innerHTML='<em>Name exactly as it appears on credit card.<br>Address of credit card billing statement.</em>';
}
else
{
document.getElementById('errAddressPaySub').style.color='#999999';
		document.getElementById('errAddressPaySub').style.paddingTop='3px';
		document.getElementById('errAddressPaySub').innerHTML='<em>Name exactly as it appears on credit card.<br>Address of credit card billing statement.</em>';
	
	}





document.getElementById('useNewAddress').checked=true;
		document.getElementById('divNewAddress').style.display='';
		document.getElementById('divExistingAddress').style.display='none';
		if(formname=='cardform'){
		document.getElementById('divButtons').style.width='250px';
		}
		uncheckAllBoxes('address_id',formname);
	  break;
	case "Existing":
		document.getElementById('useExistingAddress').checked=true;
		document.getElementById('divNewAddress').style.display='none';
		document.getElementById('divExistingAddress').style.display='';
		if(formname=='cardform'){
		document.getElementById('divButtons').style.width='372px';
		}
	  break;
	}
// --------------------------------------------------------------- end func
}



function revealCheckout(){	
document.payform.response_form_active.value=1;
document.payform.Checkout.style.display='none';
document.payform.Purchase.style.display='';
document.getElementById('divCheckoutAll').style.display='';
// --------------------------------------------------------------- end func
}

function removeCoupon(){
document.payform.redirect.value = "cart";
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.action = "cart.php?coupon=remove"; 
document.payform.submit();
return false;
// -------------------- end func
}

function stopEvent(e) {
	if(!e) var e = window.event;
	
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = false;

	//e.stopPropagation works only in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
	return false;
}

function validateCoupon(){



input=document.getElementById('code');
input.value = trim(input.value);
if ((input.value==null)||(input.value=="")){
return false;
}

//if(input.value == "shipFree" && document.getElementById('shipping_method').value != 7)
if(input.value == "shipFree" && document.getElementById('shipping_method').value != 'PM')
{
// ===============================
  //nuShow(id,vheight,vwidth,vtitle,vclass,vtop,vProcessing,vForm,scriptStop)
	
	nuShow('shipFree_coupon_alert','auto','auto',null,null,50,true,null,null);
return false;
//stopEvent(e);
	//$(document).keyup(function(e) {
	
	//if (e.keyCode == 13) {cartCouponConfirm(input.value);}   
	
	//});
	
return false;
// ===============================
}
else
{
	cartCouponConfirm(input.value);
//document.payform.redirect.value = "cart";
//document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
//document.payform.action = "public_actions.php?pmode=coupon&code="+input.value;
//document.payform.submit();
//return false;	
}
//------------------------------------------------------------------------------ end func
}


function cartCouponConfirm(couponCode)
{
document.payform.redirect.value = 'cart';
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.action = 'public_actions.php?pmode=coupon&code='+couponCode;
document.payform.submit();
return false;
// --------------------------------------- end func
}



function keypressCoupon(e)
{
var Ucode=e.keyCode? e.keyCode : e.charCode
if (Ucode == 13)
{
//validateCoupon();
}
//------------------------------------------------------------------------------ end func
}

function keypressCouponRemove(e)
{
var Ucode=e.keyCode? e.keyCode : e.charCode
if (Ucode == 13)
{
removeCoupon();
}
//------------------------------------------------------------------------------ end func
}

function clearValidation(){
//
	arr = new Array('x_card_type','x_card_num','x_exp_date_month','x_exp_date_year','x_card_code','numClientJob','numClientPO');
		$.each(arr, function(index, value) { 
		//
		input = eval('document.payform.'+value);
		input.style.backgroundColor=ogColor;
		//
	});

//

//------------------------------------------------------------------------------ end func
}

function togglePO_CC(){
clearValidation();
var ccSwitchVal = '';
if(document.payform.togglePO_CC.value=='CC'){
// ---- po
		document.payform.togglePO_CC.value='PO';
		document.getElementById('anchorTogglePO_CC').innerHTML = 'Use Credit Card';
		document.getElementById('divPONum').style.display='';
		ccSwitchVal = 'none';
	//

clearTheseInputs('x_card_type,x_card_num,x_exp_date_month,x_exp_date_year,x_card_code,x_card_store_nick','payform');

		document.payform.x_card_store.checked=0;
		document.getElementById('divCardNick').style.display='none';

		if(document.payform.countStoredCards.value>0){
			document.payform.x_card_stored_id.value=0;
			document.getElementById('divCardStoreSummary').style.display ='none';
		
			//populateFromStored();
		}

		// clear card num error
		errSmall('div_x_card_num_error', '', 0, 'payform', 'x_card_num', 1);

		// set to PO address
		document.getElementById('billing_address_wrapper').innerHTML = document.getElementById('billing_address_PO').innerHTML;

//alert('ccSwitchVal = '+ccSwitchVal);
}else{
// ----- cc
		document.payform.togglePO_CC.value='CC';
		document.getElementById('anchorTogglePO_CC').innerHTML = 'Use PO Account';
		document.payform.numClientPO.value='';
		document.getElementById('divPONum').style.display='none';
		ccSwitchVal = '';
		
		
		if(document.payform.countStoredCards.value>0){
		document.getElementById('divCardStoreSummary').style.display ='none';
		}
		
		document.getElementById('billing_address_wrapper').innerHTML = document.getElementById('billing_address_OG').innerHTML;
		



}

//
//if(1==0){
		arr = new Array('divCardGIF','divCardType','divCardNum','divCardExp','divCardCode','divCardStoreCheckbox');
		
		if(document.payform.countStoredCards.value>0){
		arr.push('divCardStoreSelect');
		}
		

$.each(arr, function(index, value) { 
//
		document.getElementById(value).style.display=ccSwitchVal;
//
});
//
//}

//if(document.payform.togglePO_CC.value=='CC'){
//}
//else
//{
//$('#divCCWrapper').slideDown('slow', function() {
    // Animation complete.
  //});
//}
		
	//
// --------------------------------------- end func
}


function toggleDisplay(id)
{
if(document.getElementById(id).style.display=='none')
{document.getElementById(id).style.display='';}
else
{document.getElementById(id).style.display='none';}
// --------------------------------------- end func
	}


function populateFromStored(idCard,page){	

if(idCard==0)
{

idDivAddressBilling='billing_address_OG';
		idAddressBilling = document.payform.billing_address_id_OG.value;
		opDisplay="block";
		document.getElementById('divCardStoreSummary').style.display='none';
		innerDisplay = "";
}
else
{

document.payform.x_card_stored_id.options[0]=new Option("Use New Card", 0, true, false);
idDivAddressBilling='billing_address_CC_'+idCard;
	idAddressBilling = eval('document.payform.id_billing_address_CC_'+idCard+'.value');
	opDisplay="none";
	
	document.getElementById('divCardStoreSummary').style.display='';
	innerDisplay = document.getElementById('divCardSum_'+idCard).innerHTML;
	//alert(innerDisplay);
}

if(page!='adminProcessCC'){
// if adminProcessCC
	clearTheseInputs('x_card_num,x_card_type,x_exp_date_month,x_exp_date_year,x_card_code,x_card_store_nick','payform');
document.payform.x_card_store.checked=0;
document.getElementById('divCardNick').style.display='none';

}else{


var formname = 'payform';
var string = 'x_card_num,x_card_type,x_exp_date_month,x_exp_date_year,x_card_code,x_card_store_nick';
var arr = string.split(',');
for(var i = 0; i<arr.length; i++){
	input = trim(arr[i]);            
	$('#'+input).val('');
	inputForm = eval('document.'+formname+'.'+input);
	inputForm.style.backgroundColor=ogColor;
}

$('#divCardNick').hide();
$("#x_card_store").removeAttr("checked"); 

// end if adminProcessCC
}

//
var string = 'divCardStoreCheckbox,divCardType,divCardNum,divCardExp';
var arr = string.split(',');
for(var i = 0; i<arr.length; i++){
	div = trim(arr[i]);            
	$('#'+div).css('display', opDisplay)
	//alert(div);

}


if(page=="paySub"){

//
arr = new Array('divCardInputsWrapper','divCardInputsStoredWrapper');
$.each(arr, function(index, value) { 
document.getElementById(value).style.display=opDisplay;
//
});

// end if page = paySub
}


//document.getElementById('divCardStoreSummary').innerHTML=innerDisplay;
$('#divCardStoreSummary').html(innerDisplay);
//document.payform.billing_address_id.value=idAddressBilling;
$('[name="billing_address_id"]').val(idAddressBilling);



if(page=="paySub"){

//toggleCardAddressNewExisting('Existing','payform');
	matchValueCheckBox('address_id','payform',idAddressBilling);
	
	}
else
{
//	document.getElementById('billing_address_wrapper').innerHTML = document.getElementById(idDivAddressBilling).innerHTML;
	matchValueCheckBox('address_id','payform',idAddressBilling);

}




// ----------------------------------------- end func
}







function errorExp(){
if((document.cardform.x_exp_date_month.value)&&(document.cardform.x_exp_date_year.value)){

var today = new Date();

	var month=new Array(12);
	month[0]="01";
	month[1]="02";
	month[2]="03";
	month[3]="04";
	month[4]="05";
	month[5]="06";
	month[6]="07";
	month[7]="08";
	month[8]="09";
	month[9]="10";
	month[10]="11";
	month[11]="12";
	
	thisMonth = month[today.getMonth()];
	thisYear = today.getFullYear();
	thisVal =thisYear+thisMonth;
	expMonth = document.cardform.x_exp_date_month.value;
	expYear = "20" + document.cardform.x_exp_date_year.value
	expVal= expYear + expMonth; 
	if ((thisVal <= expVal)) {
document.cardform.x_exp_date_month.style.backgroundColor=ogColor;
document.cardform.x_exp_date_year.style.backgroundColor=ogColor;
	document.getElementById("divErrorExp").style.display="none";
}
	else{
document.cardform.x_exp_date_month.style.backgroundColor=errColor;
document.cardform.x_exp_date_year.style.backgroundColor=errColor;
document.getElementById("divErrorExp").style.display="";
return false;
	}

}
else
{
	document.getElementById("divErrorExp").style.display="none";
return true;
}

// ------------------ end func
}





function js_cardform_add_address() {

var go = true;

if(validateAddressFormInputsSub('cardform')==false)
{go = false;}



if(go == false)
{
return false;
}
				document.cardform.action = "public_actions.php?pmode=stored_cards_add_address";
				document.cardform.submit();
// --------------------------------------------------------------- end func
}

function js_cardform() {

var go = true;


arr = new Array("x_card_type", "x_card_num");
$.each(arr, function(index, value) { 
//
			if(trimMeCheck(value, 'cardform',0)==false)
			{go = false;}
//
});

myCardNo = document.cardform.x_card_num.value;
myCardType = document.cardform.x_card_type.value;

if(myCardNo){
// ---- check card number format etc						
if (checkCreditCard (myCardNo,myCardType)) 
{
	errSmall('errCardNum', '', 0, 'cardform', 'x_card_num',1);
} 
else 
{
	error = (ccErrors[ccErrorNo]);
	if(error){
		errSmall('errCardNum', error, 1, 'cardform', 'x_card_num',1);
	}
	go =  false;
}
// ---- end check card number format etc
}


//
arr = new Array("x_exp_date_month", "x_exp_date_year");
$.each(arr, function(index, value) { 
//
			if(trimMeCheck(value, 'cardform',0)==false)
			{go = false;}
//
});

	
	
if(errorExp()==false)
{go = false;}





if(trimMeCheck('x_card_code', 'cardform',0)==false)
{go = false;}
else
{
	if(IsNumeric(document.cardform.x_card_code.value)==false)
	{
	document.cardform.x_card_code.style.backgroundColor=errColor;
	go = false;
	}
}





// existing address
if(document.getElementById('useExistingAddress').checked == true && document.cardform.idAddress.value==""){
//
var c_value = "";

if(document.cardform.address_id.length)
			{
							for (var i=0; i < document.cardform.address_id.length; i++)
							   {
										if (document.cardform.address_id[i].checked)
										{
										c_value = c_value + document.cardform.address_id[i].value;
										}
							   }
			}else{
										if (document.cardform.address_id.checked)
										{
										c_value = c_value + document.cardform.address_id.value;
										}
				
			}
if(c_value == "")
{
	error = 'No Billing Address Selected!';
	errSmall('errAddress', error, 1, null, null, 0);
	go =  false;
}
else
{errSmall('errAddress', '', 1, null, null, 0);}
// end if existing address
}

// new address
if(document.getElementById('useNewAddress').checked == true ||  (document.cardform.idAddress.value) )
{
//
if(validateAddressFormInputsSub('cardform')==false)
{go = false;}
// end if
}
// end if new address



if(go == false)
{

return false;}


document.cardform.action = "public_actions.php?pmode=stored_cards_add_edit";
document.cardform.submit();
// --------------------------------------------------------------- end func
}

function radioCheck(me) 
{ var checked = me.checked;
// <?PHP echo $strJava;?>
//me.checked = checked; // checkbox action 
me.checked = true; // radiobox action 
// --------------------------------------------------------------- end func
} 






function matchValueCheckBox(fieldName,formName,valCompare){

checkbox = eval("document."+formName+"."+fieldName);

if(checkbox.length){
for (i = 0; i < checkbox.length; i++)
	{
		if(checkbox[i].value==valCompare)
		{checkbox[i].checked = true ;}
		else
		{checkbox[i].checked = false ;}
		
	}
}else{



		if(checkbox.value==valCompare)
		{checkbox.checked = true ;}
		else
		{checkbox.checked = false ;}




}



// --------------------------------------------------------------- end func
} 



function uncheckAllBoxes(fieldName,formName){

checkbox = eval("document."+formName+"."+fieldName);

if(checkbox.length){
//
for (i = 0; i < checkbox.length; i++)
	{
		checkbox[i].checked = false ;
	}
//
}else{
checkbox.checked = false ;	
}

// --------------------------------------------------------------- end func
} 

function checkThisBoxOnly(thisBox,fieldName,formName){

uncheckAllBoxes(fieldName,formName);


//me.checked = checked; // checkbox action 
thisBox.checked = true; // radiobox action 
// --------------------------------------------------------------- end func
} 




function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
// --------------------------------------------------------------- end func
}


function addAddressResellerToggle(){
if(document.getElementById("divExistingAddress").style.display=="none"){
	//existing
	document.getElementById("divExistingAddress").style.display="";
	document.getElementById("divNewAddress").style.display="none";
	document.getElementById("divButtons").style.width="372px";
	document.signup.opAddressNewExisting.value=1;
				
				arr = new Array("address1", "city", "state","zip","country");
				
				$.each(arr, function(index, value) { 
//
							input = eval('document.signup.'+value);
							input.value="";
							input.style.backgroundColor=ogColor;
//
});

				
				
				
				
				
				//
				document.signup.country.value="USA";
	
	
	
	
}
else
{
	//new
	document.getElementById("divExistingAddress").style.display="none";
	document.getElementById("divNewAddress").style.display="";
	document.getElementById("divButtons").style.width="250px";
	document.signup.opAddressNewExisting.value=0;
	uncheckAllBoxes('address_id','signup');
	errSmall('errAddress', '', 1, null, null, 0);

}
// --------------------------------------------------------------- end func
}
	


function closeAndClear(inputs,formname){
clearTheseInputs(inputs,formname);
nuShowClose();
// --------------------------------------------------------------- end func
}


function clearTheseInputs(inputs,formname)
{
		

var string = inputs;
var arr = cbSplit(string,",");
$.each(arr, function(index, value) { 
//
input = trim(value);
input = eval('document.'+formname+'.'+input);
input.value="";
input.style.backgroundColor=ogColor;
//
});

// --------------------------------------------------------------- end func
}

function toggleLightboxPrintSelectOrderHistory(id){

hideAllDivsExceptThisOne('lightbox_order_history',id);

// --------------------------------------------------------------- end func
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
// --------------------------------------------------------------- end func
}

function hideAllDivsExceptThisOne(classname,id){
//
arr = getElementsByClass(classname,null,'div');


$.each(arr, function(index, value) { 
//
							value.style.display="none";
//
});






document.getElementById(id).style.display='block';
// --------------------------------------------------------------- end func
}


function addToCartPrintsSub(mySel,loggedIn,idForm)
{

var myVal;
myVal = mySel.options[mySel.selectedIndex].value;

//public_actions.php?pmode=add_cart&pid=8929&prid=91412&bw=&op=&ratio=3&anchor=
//alert(myVal);
//return false;

if(myVal){
//

if(1==0){
// disable custom crop stuff
	var crop_request = $('#opCustomCropRequest' + idForm).val();
	if( crop_request == "::Enter Custom Crop Request::" || crop_request == "" ){
		// do nothing
	}else{


		myVal =  myVal + "&opCustomCrop=1&opCustomCropRequest=" + crop_request;
		//send opCustomCrop
	}
// end disable custom crop stuff
}
//alert('OK');
if (loggedIn == 0) {
	//
	var myValRedirect = myVal.replace('public_actions.php?pmode=add_cart', 'login.php?message=cart_redirect&pmode_redirect=add_cart');
	var myString = myVal;
	var mySplitResult = myString.split("prid=");
	var prid_js = mySplitResult[1]; 
	
	window.location = myValRedirect;

	return false;
}
else
{

	form = eval("document.print_drop"+idForm);
	form.action = myVal;
	form.submit();
	
}


// end if myVal
}

return false;
// -------------------------------------------------------------------- end func
}



function pageName(){
filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1,location.pathname.length);
whereDot = filename.lastIndexOf('.');
filename = filename.substring(0, whereDot);
return filename;
// end func
}

function togglePrintHistory(selectOptionToggle,idImageToggle,thisPageToggle){
	
	switch(thisPageToggle){

	case "details":
	case "image":
	case "lightbox":
		mySplitResultToggle = selectOptionToggle.split("prid=");
		mySplitResultToggle = mySplitResultToggle[1].split("&");
		pridToggle = mySplitResultToggle[0]; 
		
	break;	
	
	case "cart":
//	
	break;	
	
	// end switch	
	}
	
if($('.order_image_history_'+idImageToggle).length > 0){
	hideAllDivsExceptThisOne('order_image_history_'+idImageToggle,pridToggle+'_'+idImageToggle);	
}

// -------------------------------------------------------------------- end func
}


function js_checkout() {

var go = true;


if(document.payform.togglePO_CC.value=='CC'){
// -- start disable cc validation if po client

if(document.payform.x_card_stored_id.value==0){
// -- start disable cc validation if stored card

arr = new Array("x_card_type", "x_card_num");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});


myCardNo = document.payform.x_card_num.value;
myCardType = document.payform.x_card_type.value;
if (checkCreditCard (myCardNo,myCardType)) 
{
//valid
document.getElementById('div_x_card_num_error').style.display='none';
} 
else 
{
//alert(ccErrors[ccErrorNo]);

// firefox
if(!ccErrors[ccErrorNo]){document.payform.x_card_num.style.background = errColor;}

if( (ccErrors[ccErrorNo] !='Unknown Credit Card Type!') && (ccErrors[ccErrorNo] !='Card Number Required!') && (ccErrors[ccErrorNo])    ){

errSmall('div_x_card_num_error', ccErrors[ccErrorNo], 1, 'payform', 'x_card_num', 1);
//document.payform.x_card_num.focus();
}
//return false;
go = false;

}






//exp
arr = new Array("x_exp_date_month", "x_exp_date_year");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});


// -- end disable cc validation if stored card
}

if(trimMeCheck('x_card_code', 'payform',0)==false)
{
//return false;
go = false;
}



// -- end disable cc validation if po client
}



if(document.payform.togglePO_CC.value=='PO'){
// -- start job num and po num validation if po client

		arr = new Array("numClientPO", "numClientJob");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});

// -- end job num and po num validation if po client
}

var errorAddressCode=0;


if(document.payform.togglePO_CC.value=='PO'){
// po address
if(document.payform.po_address_id.value == "")
{
errorAddressCode = (errorAddressCode + 1);
//errSmall('div_address_error', 'Billing Address Required!', 1, null, null, 0);
go = false;
}					



}else{

//billing address
if(document.payform.billing_address_id.value == "")
{
errorAddressCode = (errorAddressCode + 1);
//errSmall('div_address_error', 'Billing Address Required!', 1, null, null, 0);
go = false;
}					

// -- end if po client or billing
}



//shipping address
if(document.payform.shipping_address_id.value == "")
{
errorAddressCode = (errorAddressCode + 2);
go = false;
}					
else
{
//shipping country code
		if(document.payform.shippingCountryCode.value == "")
		{
		errorAddressCode = (errorAddressCode + 4);
		go = false;
		}					
		
//
}



errorAddress = "";

switch (errorAddressCode)
{
   case 1:  
errorAddress = "Billing Address Required";
   break;

case 2:  
errorAddress = "Shipping Address Required";
   break;

case 3:  
errorAddress = "Billing &amp; Shipping Address Required";
   break;

case 4:  
errorAddress = "Shipping Address - Country Required";
   break;

case 5:  
errorAddress = "Billing Address Required - Shipping Address Country Required";
   break;

  default: 
errorAddress = "";
  break;
}





if(errorAddress)
{
errSmall('div_address_error', errorAddress, 1, null, null, 0);
//return false;
go = false;
}					
else
{
document.getElementById('div_address_error').style.display='none';
}


//tc checkbox
if(!document.payform.tc_agree.checked)
{
errSmall('div_TC_error', 'Agreement With Terms And Conditions Required!', 1, 'payform', 'tc_agree', 1);
document.payform.tc_agree.focus();
go = false;
}					
else
{
document.getElementById('div_TC_error').style.display='none';
}


//final confirmation					
if(   (document.payform.confirmation.value==0) && (go == true) )
{					
nuShow('divConfirmPurchase',190,600,'','','','','payform');

	$(document).keyup(function(e) {
	if (e.keyCode == 13) {return false;}   
	});


return false; 
}
//					



if(go == false){
return false;
}	

nuShow('processing',190,600,'','','',true);
	$(document).keyup(function(e) {
	if (e.keyCode == 13) {return false;}   
	});

document.payform.action = "checkout.php";
document.payform.submit();


// --------------------------------------------------------------- end func
}

	
function addAllToCart(countLightboxItems)
{

i = 0;
str = "";
while (i < countLightboxItems) 
{
i = i +1;

strRep = document.forms['print_drop' + i].prints.value;
strRep = strRep.replace("public_actions.php?pmode=add_cart&","");
strRep = strRep.replace(/&/g, "_");
strRep = strRep.replace("pid=","");
strRep = strRep.replace("prid=","");
strRep = strRep.replace("bw=","");
strRep = strRep.replace("op=","");
strRep = strRep.replace("ratio=","");
strRep = strRep.replace("anchor=","");

//if(document.forms['print_drop' + i].opCustomCrop.value){opCustomCrop=1;}else{opCustomCrop=0;}
if(document.forms['print_drop' + i].opCustomCrop.checked==true){opCustomCrop=1;strCustomCropRequest=document.forms['print_drop' + i].opCustomCropRequest.value;}else{opCustomCrop=0;strCustomCropRequest='';}


if(strCustomCropRequest)
{strCustomCropRequest = strCustomCropRequest.replace("|","");strCustomCropRequest = strCustomCropRequest.replace("_","");strCustomCropRequest = strCustomCropRequest.replace("&","");}


strCustomCrop = "_" + opCustomCrop; 
strCustomCrop = strCustomCrop + "_" + strCustomCropRequest; 

strCustomCrop = strCustomCrop.replace("|","");


str = str + strRep + strCustomCrop + "|";
}
//alert(str);

window.location = "public_actions.php?pmode=add_all_cart&list=" + str;

// ------------------------- end func
}

function lightboxRename(){

document.getElementById('rename_lightbox_link').style.display = 'none';
document.getElementById('select_lightbox_id').style.display = 'none';
document.getElementById('rename_lightbox_id').style.display = '';
document.rename.name.focus()
// ------------------------- end func
}
	
	
	function goToDetails(id){
		window.location="/details.php?pid="+id;
		// ------------------------- end func
}

function toggleIDs(idOn,idOff){
if(document.getElementById(idOn).style.display=="block")
{document.getElementById(idOn).style.display="none";document.getElementById(idOff).style.display="block";}
else
{document.getElementById(idOff).style.display="none";document.getElementById(idOn).style.display="block";}

// ------------------------- end func
}




/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */

var cbSplit;

// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {

cbSplit = function (str, separator, limit) {
    // if `separator` is not a regex, use the native `split`
    if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
        return cbSplit._nativeSplit.call(str, separator, limit);
    }

    var output = [],
        lastLastIndex = 0,
        flags = (separator.ignoreCase ? "i" : "") +
                (separator.multiline  ? "m" : "") +
                (separator.sticky     ? "y" : ""),
        separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
        separator2, match, lastIndex, lastLength;

    str = str + ""; // type conversion
    if (!cbSplit._compliantExecNpcg) {
        separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
    }

    /* behavior for `limit`: if it's...
    - `undefined`: no limit.
    - `NaN` or zero: return an empty array.
    - a positive number: use `Math.floor(limit)`.
    - a negative number: no limit.
    - other: type-convert, then use the above rules. */
    if (limit === undefined || +limit < 0) {
        limit = Infinity;
    } else {
        limit = Math.floor(+limit);
        if (!limit) {
            return [];
        }
    }

    while (match = separator.exec(str)) {
        lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser

        if (lastIndex > lastLastIndex) {
            output.push(str.slice(lastLastIndex, match.index));

            // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
            if (!cbSplit._compliantExecNpcg && match.length > 1) {
                match[0].replace(separator2, function () {
                    for (var i = 1; i < arguments.length - 2; i++) {
                        if (arguments[i] === undefined) {
                            match[i] = undefined;
                        }
                    }
                });
            }

            if (match.length > 1 && match.index < str.length) {
                Array.prototype.push.apply(output, match.slice(1));
            }

            lastLength = match[0].length;
            lastLastIndex = lastIndex;

            if (output.length >= limit) {
                break;
            }
        }

        if (separator.lastIndex === match.index) {
            separator.lastIndex++; // avoid an infinite loop
        }
    }

    if (lastLastIndex === str.length) {
        if (lastLength || !separator.test("")) {
            output.push("");
        }
    } else {
        output.push(str.slice(lastLastIndex));
    }

    return output.length > limit ? output.slice(0, limit) : output;
};

cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;

} // end `if (!cbSplit)`

// for convenience...
String.prototype.split = function (separator, limit) {
    return cbSplit(this, separator, limit);
};

function approveCustomCrop(idCart,idOrder){
window.location = "public_actions.php?pmode=approve_custom_crop&idCart="+idCart+"&idOrder="+idOrder;
// --------------- end func
}

function toggleCheckboxPay(op){

uncheckAllBoxes('checkboxPay','payform');
		
switch(op)
{
case "entry":
document.getElementById('x_card_amount_entry_checkbox').checked = 1;	
document.getElementById('divAmountEntry').style.display='';
break;

case "balance_due":
document.getElementById('x_card_amount_balance_due_checkbox').checked = 1;	
document.getElementById('divAmountEntry').style.display='none';
document.payform.x_card_amount_entry.value='';
break;
}

// -------------- end func
}

function openPayWindow(){
nuShow('pay_sub','auto',400,'','',10);
return false;
// -------------- end func
}



function openPayWindowAdmin(){
nuShow('pay_sub','auto',370,'','',10);
return false;
// -------------- end func
}

























function js_checkout_pay_sub(){

//alert(1);

var go = true;

if(document.getElementById('x_card_amount_entry_checkbox').checked == 1){
	if(trimMeCheck('x_card_amount_entry', 'payform',0)==false)
	{
	go = false;
	}
	else
	{
		
document.payform.x_card_amount_entry.value =	formatCurrency(document.payform.x_card_amount_entry.value);	
		
		if(document.payform.x_card_amount_entry.value == 0.00)
		{go = false;
		document.payform.x_card_amount_entry.style.backgroundColor=errColor;

		}
		else
		{
			document.payform.x_card_amount_entry.style.backgroundColor=ogColor;

			}
		
		}
	
	
}



if(document.payform.x_card_stored_id.value==0){
// -- start disable cc validation if stored card

arr = new Array("x_card_type", "x_card_num");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});


myCardNo = document.payform.x_card_num.value;
myCardType = document.payform.x_card_type.value;
if (checkCreditCard (myCardNo,myCardType)) 
{
//valid
document.getElementById('div_x_card_num_error').style.display='none';
} 
else 
{
//alert(ccErrors[ccErrorNo]);

// firefox
if(!ccErrors[ccErrorNo]){document.payform.x_card_num.style.background = errColor;}

if( (ccErrors[ccErrorNo] !='Unknown Credit Card Type!') && (ccErrors[ccErrorNo] !='Card Number Required!') && (ccErrors[ccErrorNo])    ){

errSmall('div_x_card_num_error', ccErrors[ccErrorNo], 1, 'payform', 'x_card_num', 1);
//document.payform.x_card_num.focus();
}
//return false;
go = false;

}






//exp
arr = new Array("x_exp_date_month", "x_exp_date_year");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});


// -- end disable cc validation if stored card
}

if(trimMeCheck('x_card_code', 'payform',0)==false)
{
//return false;
go = false;
}




if(1 == 1){
//if(document.getElementById('useExistingAddress').checked == 1){        NOT USING THIS ANYMORE
// existing address
				var c_value = "";
				if(document.payform.address_id.length)
							{
											for (var i=0; i < document.payform.address_id.length; i++)
											   {
														if (document.payform.address_id[i].checked)
														{
														c_value = c_value + document.payform.address_id[i].value;
														}
											   }
							}else{
														if (document.payform.address_id.checked)
														{
														c_value = c_value + document.payform.address_id.value;
														}
								
							}
							
				if(c_value == "")
				{
				//document.getElementById('errAddressPaySub').style.color='#FF0000';
						//document.getElementById('errAddressPaySub').style.paddingTop='3px';
						//document.getElementById('errAddressPaySub').innerHTML='No Billing Address Selected!';
				
				
				errSmall('errAddressPaySub', 'No Address Selected!', 1);
				go =  false;
				}
				else
				{
//				document.getElementById('errAddressPaySub').style.color='#FF0000';
		//				document.getElementById('errAddressPaySub').style.paddingTop='3px';
						//document.getElementById('errAddressPaySub').innerHTML='';
				errSmall('errAddressPaySub', null, 0);
	
					
				}
				
				////

//
}
else
{
// new address NOT USING THIS ANYMORE
					if(validateAddressFormInputsSub('payform')==false)
					{go = false;}
					//
}

//		document.getElementById('dev').innerHTML=go;

	
if(go == false){
return false;
}	

	$(document).keyup(function(e) {
	if (e.keyCode == 13) {return false;}   
	});

//return false;

document.payform.action = "checkout_pay_sub.php";
document.payform.submit();
	
// -------------- end func
}
	
	
	
function formatCurrency(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);
}
	
	

function customCropRequestCancel(idCart){
idCheckbox = "opCustomCrop"+idCart;
clearMeCheckByID('custom_crop_request');
document.getElementById(idCheckbox).checked = false;
nuShowClose();	

return false;
// -------------- end func
}		
	
function customCropRequestConfirm(opCustomCropRequest,idCart, opCustomCrop){

//alert(requestCrop);
//alert(idCart);
//alert(opCustomCrop);
if(opCustomCrop==1){
if(trimMeCheckByID('custom_crop_request',0)==false)
						{return false;}
}
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
strAction = "public_actions.php?pmode=update_custom_crop_request&opCustomCrop="+opCustomCrop+"&idCart="+idCart+"&opCustomCropRequest="+opCustomCropRequest;
//alert(strAction);
document.payform.action = strAction;
document.payform.submit();


// -------------- end func
}	
	


function getParameterByName(name)
{
	
	
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  //var results = regex.exec( window.location.href );
  var results = regex.exec( top.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));

// --------------------------------------- end func	
}

function dupeVals(op,idCart,idOrder){

if(confirm("Update All "+ op.replace("_", " ") +" Values?")){
	

if(op == "Submit_XML"){
//

$('.SubmitXML').each(function(i, obj){
//
if (!$(this).is(':disabled')) {
$(this).attr('checked', $('#SubmitXML'+idCart).attr('checked')  );
}
//
});


return false;
}

if(op == "Float_Widget"){
//
	
	if($('.SP_Checkbox'+idCart).is(':checked')){
		op="Float_Values";
		window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&dupeVals="+op+"&idCart="+idCart;
	}else{
		op="SP_Off";
		window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&dupeVals="+op+"&idCart="+idCart;
	}




return false;
}



//
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&dupeVals="+op+"&idCart="+idCart;








}//alert(op);
// ---------------------------------------- end func
}

function updateCustomCrop(val,idCart,idOrder){
//alert('val='+val+'id='+id);
if(val){upd=1}else{upd=0};
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCrop=true&opCustomCrop="+upd+"&idCart="+idCart;
// ---------------------------------------- end func
}

function updateCustomCropPrint(prid,idCart,idOrder){
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCropPrint=true&prid="+prid+"&idCart="+idCart;
// ---------------------------------------- end func
}

function updateCustomCropQuantity(q,idCart,idOrder){
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCropQuantity=true&quantity="+q+"&idCart="+idCart;
// ---------------------------------------- end func
}

function updateCustomCropFit(val,idCart,idOrder){
//alert('val='+val+'id='+id);
if(val){upd=1}else{upd=0};
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCropFit=true&opCustomCropFit="+upd+"&idCart="+idCart;

// ---------------------------------------- end func
}


function toggleCustomCropHeightWidth(idCart,idOrder,vc){
var idCart;
var vc;
//alert('val='+val+'id='+id);
//if(val){upd=1}else{upd=0};
//window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCropFit=true&opCustomCropFit="+upd+"&idCart="+idCart;
//alert(idCart);
$('#divCustomCropHeightWidth'+idCart).toggle();
on = $('#divCustomCropHeightWidth'+idCart).is(":visible");
if(on==false)
{
//$('#opCustomCropWidth'+idCart).val('');	
//$('#opCustomCropHeight'+idCart).val('');	
window.location = "_km_orders_detail_admin.php?id="+idOrder+"&idCart="+idCart+"&opCustomCropHeightWidthClear=true";
	}
else
{
$('#opCustomCropWidth'+vc).val('');	
$('#opCustomCropHeight'+vc).val('');	
	}
	
// ---------------------------------------- end func
}



function validateInvoiceEmailReminder(idOrder,paid){

	var emailList = '';
	var emailListAlert = '';
	
	var form = eval('document.form_invoice_email_reminder');
	
	iChecked = 0;
	for (var i = 0; i < form.elements.length; i++ ) {
			
			if (form.elements[i].type == 'checkbox' && form.elements[i].id == 'checkboxEmail') {
				if (form.elements[i].checked == true) {
				
				iChecked++;
				
					if(iChecked > 1){emailList = emailList + '_';}
					emailList += form.elements[i].value;
					
					if(iChecked > 1){emailListAlert = emailListAlert + ', ';}
					emailListAlert += form.elements[i].value;
					
				}
			}
	  
		}
		
		
	if(!emailList){
	alert('No Email Selected!');
	$('#button_invoice_email_reminder').blur();
	return false;}
	
	
	if(paid=='Paid'){
		
		if(confirm('No Balance Due!! Email Invoice Reminder Anyway?\n\n'+emailListAlert)==false){return false;}
	
	}else{
	
		if(confirm('Email Invoice Reminder?\n\n'+emailListAlert)==false){return false;}
	
	}
	
	window.location='/manager/_km_orders_detail_admin.php?send_reminder=true&id='+idOrder+'&emailList='+emailList;
	
	return false;

// ---------------------------------------- end func
}


function deleteBatch(idOrder,idBatch){

if(confirm('Delete Batch?'))
{

window.location = "/manager/_km_orders_detail_admin.php?id="+idOrder+"&deleteBatch="+idBatch;}

// ---------------------------------------- end func
}


function updateCustomCropHeight(thisVal,idCart,idOrder,paperVal,oldVal,thisId){

var thisVal;
var paperVal;
var oldVal;
var thisId;

if(thisVal>paperVal){
alert('Error!\n\nCrop Value Is Bigger Than Paper Size!');$('#'+thisId).val(oldVal);return false;	
}

if(!thisVal || thisVal<0){thisVal=0.00;}
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCropHeight=1&opCustomCropHeight="+thisVal+"&idCart="+idCart;
// ---------------------------------------- end func
}

function updateCustomCropWidth(thisVal,idCart,idOrder,paperVal,oldVal,thisId){
var thisVal;
var paperVal;
var oldVal;
var thisId;

//alert(thisVal);alert(paperVal);alert(oldVal);alert(thisId);

if(thisVal>paperVal){
alert('Error!\n\nCrop Value Is Bigger Than Paper Size!');$('#'+thisId).val(oldVal);return false;	
}

if(!thisVal || thisVal<0){thisVal=0.00;}
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&updCustomCropWidth=1&opCustomCropWidth="+thisVal+"&idCart="+idCart;
// ---------------------------------------- end func
}





function validateExportDeliverablesList(op,filename,countCartItems){


var i;
for (i = 1; i <= countCartItems; i++) 
 { 
//
if($('#toggleCustomCropHeightWidthCheckbox'+i+':checked').val() !== undefined){
//

		if((   !$('#opCustomCropHeight'+i).val() ||  $('#opCustomCropHeight'+i).val()==0 ) || (     !$('#opCustomCropWidth'+i).val()   ||  $('#opCustomCropWidth'+i).val()==0                ))
		
		{alert("Error!\n\nSome SP Float Values Not Populated!!");return false;}
		//else{alert('Both Have Value');}
//
}
//

//
}

//$.each($(".items"),function(i,e){
	
	//alert(e.value);
		//});
	


//end check for empty float values

if(op){    if(confirm('Download FMP Deliverables List Again?')==false){return false;}   ;};

if(alert('::::::::::::::::::::::::::::::::::::::::::::::\n\nGo to FileMaker->Images->Home\n\nClick button \'Make FP.com Deliverables\'\n\nWhen prompted to Open File select\n\n'+filename+'\n\nfrom your desktop!\n\n::::::::::::::::::::::::::::::::::::::::::::::'  )){return true;};
// ---------------------------------------- end func
}



function updatePriceOverride(thisval,idCart,idOrder,currentPrice,isPaid){
if(thisval){
//
if(isPaid){
proceed = confirm('Order Is Fully Paid!! Change Item Price?!?');
}
else
{
proceed = confirm('Override Item Price?');
}

if(proceed){
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&opPriceOverride="+thisval+"&idCart="+idCart;
}else{
document.getElementById('item_price_override'+idCart).value=currentPrice;
}
return false;

// end if thisval
}
// ---------------------------------------- end func
}


function updateShippingOverride(thisval,idOrder,currentPrice,isPaid){
if(thisval){
//
if(isPaid){
proceed = confirm('Order Is Fully Paid!! Change Shipping Price?!?');
}
else
{
proceed = confirm('Override Shipping Price?');
}

if(proceed){
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&opShippingOverride="+thisval+"&updShipping=1";
}else{
document.getElementById('shipping_override').value=currentPrice;
}
return false;

// end if thisval
}
// ---------------------------------------- end func
}



function updateCouponOverride(thisval,idOrder,currentPrice,isPaid){
//if(thisval){
//

if(isPaid){
proceed = confirm('Order Is Fully Paid!! Override Coupon Amount?!?');
}
else
{
proceed = confirm('Override Coupon Amount?');
}

if(proceed){
window.location="/manager/_km_orders_detail_admin.php?id="+idOrder+"&opCouponOverride="+thisval+"&updCoupon=1";
}else{
document.getElementById('coupon_override').value=currentPrice;
return false;
}
return false;

// end if thisval
//}
// ---------------------------------------- end func
}

















function validateAdminPayment(){
var op = "";
var vGo = true;	
var form=eval("document.submit_pay");

// emails
					var emailList = '';
						var emailListAlert = '';
						
						
						iChecked = 0;
						for (var i = 0; i < form.elements.length; i++ ) {
								
								if (form.elements[i].type == 'checkbox' && form.elements[i].id == 'checkboxEmail') {
									if (form.elements[i].checked == true) {
									
									iChecked++;
									
										if(iChecked > 1){emailList = emailList + '_';}
										emailList += form.elements[i].value;
										
										if(iChecked > 1){emailListAlert = emailListAlert + ', ';}
										emailListAlert += form.elements[i].value;
										
									}
								}
						  
							}
							
							
						if(!emailList){
						alert('No Email Selected!');
						$('#add_payment_submit_button').blur();
						return false;
						}
						else
						{
						form.emailList.value=emailList;	
							}

// end emails

var arr=new Array("amtPaid","datePaid","paymentType"); 

var len=arr.length;
for(var i=0; i<len; i++) {
							var value = arr[i];
							//alert(value);
						
						if(trimMeCheck(value, 'submit_pay',0)==false)
						{vGo = false;}


}



form.amtPaid.value=formatCurrency(form.amtPaid.value);
						if(form.amtPaid.value==0.00)
						{
						form.amtPaid.style.backgroundColor=errColor;
						vGo = false;
						}

op = form.paymentType.value;
switch (op){
case 'CC': 
var arr=new Array("paymentCardType","paymentCardLastFour","paymentAuthCode"); 
break;

case "Check":
var arr=new Array("numCheck"); 
break;

default :
break;
}


if(op){
//
var len=arr.length;
for(var i=0; i<len; i++) {
							var value = arr[i];
							//alert(value);
						
						if(trimMeCheck(value, 'submit_pay',0)==false)
						{vGo = false;}


}
// end if op	
}

// if cc limit last four to 4 characters
var lastFour = form.paymentCardLastFour; 
if(op=="CC" && lastFour.value.length>0){
	if(lastFour.value.length != 4){
				if(lastFour.value.length > 4){strAlert='Only Need Last 4 Digits Of Credit Card!';};
				if(lastFour.value.length < 4){strAlert='Need Last 4 Digits Of Credit Card!';};
				alert(strAlert);
				lastFour.style.backgroundColor=errColor;
				lastFour.focus();
					
				vGo = false;
	}
}

return vGo;

// ------------------------------------------------------------------------------------ end func	
}






function validateCreditCardFee(){
var vGo = true;	
var form=eval("document.form_AddCreditCardFee");


var arr=new Array("amtCreditCardFee"); 

var len=arr.length;
for(var i=0; i<len; i++) {
							var value = arr[i];
							//alert(value);
						
						if(trimMeCheck(value, 'form_AddCreditCardFee',0)==false)
						{vGo = false;}


}



form.amtCreditCardFee.value=formatCurrency(form.amtCreditCardFee.value);
						if(form.amtCreditCardFee.value==0.00)
						{
						form.amtCreditCardFee.style.backgroundColor=errColor;
						vGo = false;
						}


return vGo;

// ------------------------------------------------------------------------------------ end func	
}


// --------------------------------------------------------------------------- POP CROP FUNCTIONS


function popCropCancel(id, selectOptionOriginal,idImage, opCustomCropOriginal){


$('#prints' + id).val(selectOptionOriginal);

if(pageName() == 'lightbox' || pageName() == 'image' || pageName() == 'preview' || pageName() == 'details'){
togglePrintHistory($('#prints' + id).val(),idImage,pageName());
}
	
//$('#crop_to_print_custom_crop_request' + id).hide();
$('#popCrop_CustomCropRequestWrapper' + id).hide();


if(opCustomCropOriginal){
// restore
$('#opCustomCrop' + id).attr('checked',true);
				switch(pageName()){
					
						case "details":
						case "image":
						case "preview":
						case "lightbox":
							$('#opCustomCropRequest' + id).val(         $('#opCustomCropRequest_Restore' + id).val()                            );
							toggleCustomCropRequest_Page(id);
	// do nothing				
						break;
					
						case "cart":
//alert(opCustomCropOriginal);
				//$('#opCustomCrop' + id_crop_request).attr('checked', true);
				$('#opCustomCrop' + id).attr('checked',true);

				$('#strCustomCropRequest' + id).html($('#opCustomCropRequest' + id).val());
//$('#strCustomCropRequest' + id_crop_request).html('Fun');
						
break;
				// end switch
				}

}
	
nuShowClose();



// ------------- end func
}



function popCropGo(id,num){

var theLink = $('#field_crop_to_print_' + num + '_link' + id).val();
var crop_request = trim($('#crop_to_print_custom_crop_request' + id).val());

if( crop_request == "::Enter Custom Crop Request::" || crop_request == ""){
// do nothing
}else{
theLink = theLink + "&crop_request=" + crop_request;

}

//alert(theLink);
switch(pageName()){
	
		case "details":
		case "image":
		case "preview":
		case "lightbox":
		window.location = theLink;
		break;
	
		case "cart":


nuShowClose();
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
document.payform.action = theLink;
document.payform.submit();



		break;

// end switch
}

// end func
}


function popCrop_toggleCustomCrop(id_crop_request){

input_crop_request = '#crop_to_print_custom_crop_request' + id_crop_request;
popCrop_CustomCropRequestWrapper = '#popCrop_CustomCropRequestWrapper' + id_crop_request;


//alert(divDisplay);
//return false;
if($('#link_popCrop_toggle_custom_crop' + id_crop_request).html()=='Need Custom Crop?'){

			$('#popCrop_CustomCropRequestWrapper'+id_crop_request).slideDown("fast", function() {
				$('#link_popCrop_toggle_custom_crop' + id_crop_request).html('Cancel Custom Crop');
			});
	
}
else
{
	//$(input_crop_request).slideUp("fast", function() {
	$(popCrop_CustomCropRequestWrapper).slideUp("fast", function() {
	
		$(input_crop_request).val('::Enter Custom Crop Request::');
		$('#link_popCrop_toggle_custom_crop' + id_crop_request).html('Need Custom Crop?');
	

	switch(pageName()){
	
		case "details":
		case "image":
		case "preview":
		case "lightbox":
				input_crop_request = '#opCustomCropRequest' + id_crop_request;	
				$(input_crop_request).val('::Enter Custom Crop Request::');
				$('#opCustomCrop' + id_crop_request).attr('checked', false);
				toggleCustomCropRequest_Page(id_crop_request);
		break;
	
		case "cart":
				$('#opCustomCrop' + id_crop_request).attr('checked', false);
				$('#strCustomCropRequest' + id_crop_request).html('');
	
		break;

	// end switch
	}



// end slideup function	
	});
// end if	
}


	$('#link_popCrop_toggle_custom_crop' + id_crop_request).blur();

// -------- end func
}


function toggleCustomCropRequest_Page(id){

	if($('#opCustomCrop'+id).attr('checked')==true){
		$("#opCustomCropRequest" + id).slideDown("fast");
	}
	else
	{
		$("#opCustomCropRequest" + id).slideUp("fast", function() {
			$("#opCustomCropRequest" + id).val('::Enter Custom Crop Request::');
$('#crop_custom_crop_request' + id).val('');
		});
	}
	$('#opCustomCrop'+id).blur();

// end func
}


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

function popCrop(widthImage,heightImage,ratioImage, id){
// ------------------------------------------------------------------------ start func popCrop

selectOption = $('#prints' + id).val();
//alert(selectOption);

mySplitResult = selectOption.split("ratio=");
mySplitResult = mySplitResult[1].split("&");
ratioPrint = mySplitResult[0];

mySplitResult = selectOption.split("prid=");
mySplitResult = mySplitResult[1].split("&");
prid = mySplitResult[0]; 

mySplitResult = selectOption.split("pid=");
mySplitResult = mySplitResult[1].split("&");
pid = mySplitResult[0]; 

//alert(ratioPrint);
//alert(prid);
//alert(pid);
//return false;

if($('#prints' + id + ' option:selected').hasClass('crop')){
// '''''' if is crop
//alert('crop');
		//$('#crop_to_print_custom_crop_request' + id).hide();





				switch(pageName()){
					
						case "details":
						case "image":
						case "preview":
						case "lightbox":
if($('#opCustomCrop'+id).attr('checked')==true){
	$('#opCustomCropRequest_Restore' + id).val(         $('#opCustomCropRequest' + id).val()                            );
}					
	break;
				// end switch
				}








		//$('#popCrop_CustomCropRequestWrapper' + id).hide();



		selectText = $('#prints' + id + ' option:selected').text();
		mySplitResult = selectText.split(" - ");
		descPrint = mySplitResult[0];
		
		// set link text
		$('#crop_to_print' + id + ' h3').html("Crop " +  descPrint + " <span style='color:#999999;font-size:12px;'>" + ratioPrint + "/1 Ratio</span>");
		

		
if(widthImage >= heightImage){

// HORIZONTAL
		if(ratioImage > ratioPrint)
		{
		$('#crop_to_print_1_link' + id).html('Left');
		$('#crop_to_print_2_link' + id).html('Center');
		$('#crop_to_print_3_link' + id).html('Right');
		
		cropAnchor1 = 'left';
				cropAnchor2 = 'center';
				cropAnchor3 = 'right';
		
		
		
		amt = parseFloat(ratioPrint * heightImage);
		widthPrint = (amt.toFixed(0));
		
		$('#crop_to_print_1_img' + id).width(widthPrint+'px');
		$('#crop_to_print_1_img' + id).height(heightImage+'px');
		$('#crop_to_print_1_img' + id).css({'background-position': '0px 0px'});
		
		$('#crop_to_print_2_img' + id).width(widthPrint+'px');
		$('#crop_to_print_2_img' + id).height(heightImage+'px');
		$('#crop_to_print_2_img' + id).css({'background-position':  '-' + ((widthImage - widthPrint) / 2) + 'px 0px'});
		
		$('#crop_to_print_3_img' + id).width(widthPrint+'px');
		$('#crop_to_print_3_img' + id).height(heightImage+'px');
		$('#crop_to_print_3_img' + id).css({'background-position':  '-' + (widthImage - widthPrint)+'px 0px'});
		
		
		}
		else
		{
		$('#crop_to_print_1_link' + id).html('Top');
		$('#crop_to_print_2_link' + id).html('Middle');
		$('#crop_to_print_3_link' + id).html('Bottom');
		
		cropAnchor1 = 'top';
				cropAnchor2 = 'middle';
				cropAnchor3 = 'bottom';
		
		amt = parseFloat(widthImage / ratioPrint);
		heightPrint = (amt.toFixed(0));
		
		$('#crop_to_print_1_img' + id).width(widthImage+'px');
		$('#crop_to_print_1_img' + id).height(heightPrint+'px');
		$('#crop_to_print_1_img' + id).css({'background-position': '0px 0px'});
		
		$('#crop_to_print_2_img' + id).width(widthImage+'px');
		$('#crop_to_print_2_img' + id).height(heightPrint+'px');
		$('#crop_to_print_2_img' + id).css({'background-position':  '0px -' + ((heightImage - heightPrint) / 2) + 'px'});
		
		$('#crop_to_print_3_img' + id).width(widthImage+'px');
		$('#crop_to_print_3_img' + id).height(heightPrint+'px');
		$('#crop_to_print_3_img' + id).css({'background-position':  '0px -' + (heightImage - heightPrint)+'px'});
		//
		}
// end HORIZONTAL
}else{
// VERICAL
		if(ratioImage < ratioPrint)
		{
		$('#crop_to_print_1_link' + id).html('Left');
		$('#crop_to_print_2_link' + id).html('Center');
		$('#crop_to_print_3_link' + id).html('Right');
		
		cropAnchor1 = 'left';
		cropAnchor2 = 'center';
		cropAnchor3 = 'right';
		
		
		//amt = parseFloat(ratioPrint * heightImage);
		amt = parseFloat( heightImage / ratioPrint);
		widthPrint = (amt.toFixed(0));
		
		$('#crop_to_print_1_img' + id).width(widthPrint+'px');
		$('#crop_to_print_1_img' + id).height(heightImage+'px');
		$('#crop_to_print_1_img' + id).css({'background-position': '0px 0px'});
		
		$('#crop_to_print_2_img' + id).width(widthPrint+'px');
		$('#crop_to_print_2_img' + id).height(heightImage+'px');
		$('#crop_to_print_2_img' + id).css({'background-position':  '-' + ((widthImage - widthPrint) / 2) + 'px 0px'});
		
		$('#crop_to_print_3_img' + id).width(widthPrint+'px');
		$('#crop_to_print_3_img' + id).height(heightImage+'px');
		$('#crop_to_print_3_img' + id).css({'background-position':  '-' + (widthImage - widthPrint)+'px 0px'});
		
		
		}
		else
		{
		$('#crop_to_print_1_link' + id).html('Top');
		$('#crop_to_print_2_link' + id).html('Middle');
		$('#crop_to_print_3_link' + id).html('Bottom');
		
		
		cropAnchor1 = 'top';
		cropAnchor2 = 'middle';
		cropAnchor3 = 'bottom';
		
		amt = parseFloat(ratioPrint * widthImage);
		heightPrint = (amt.toFixed(0));
		
		$('#crop_to_print_1_img' + id).width(widthImage+'px');
		$('#crop_to_print_1_img' + id).height(heightPrint+'px');
		$('#crop_to_print_1_img' + id).css({'background-position': '0px 0px'});
		
		$('#crop_to_print_2_img' + id).width(widthImage+'px');
		$('#crop_to_print_2_img' + id).height(heightPrint+'px');
		$('#crop_to_print_2_img' + id).css({'background-position':  '0px -' + ((heightImage - heightPrint) / 2) + 'px'});
		
		
		$('#crop_to_print_3_img' + id).width(widthImage+'px');
		$('#crop_to_print_3_img' + id).height(heightPrint+'px');
		$('#crop_to_print_3_img' + id).css({'background-position':  '0px -' + (heightImage - heightPrint)+'px'});
		//
		}		
// end VERICAL
}		

		
		// 
		//alert((widthImage * 3));
		//$('#crop_to_print_custom_crop_request' + id).css({'width':  ((widthImage * 3)) + 'px'});
		
	switch(pageName()){
	
		case "details":
		case "image":
		case "preview":
			theLink1 = "details.php?prid=" + prid + "&pid=" + pid + "&anchor=" + cropAnchor1  + "&ratio=" + ratioPrint + "&op=crop";
			theLink2 = "details.php?prid=" + prid + "&pid=" + pid + "&anchor=" + cropAnchor2  + "&ratio=" + ratioPrint + "&op=crop";
			theLink3 = "details.php?prid=" + prid + "&pid=" + pid + "&anchor=" + cropAnchor3  + "&ratio=" + ratioPrint + "&op=crop";
		break;
	
		case "lightbox":
			

theLink1 = "public_actions.php?pmode=update_lightbox&id="+id+"&prid=" + prid + "&pid="+pid+"&anchor="+cropAnchor1+"&ratio="+ratioPrint+"&op=crop";
theLink2 = "public_actions.php?pmode=update_lightbox&id="+id+"&prid=" + prid + "&pid="+pid+"&anchor="+cropAnchor2+"&ratio="+ratioPrint+"&op=crop";
theLink3 = "public_actions.php?pmode=update_lightbox&id="+id+"&prid=" + prid + "&pid="+pid+"&anchor="+cropAnchor3+"&ratio="+ratioPrint+"&op=crop";



		break;


		case "cart":
			
////cartUpdatePrintCrop(cid,op,ratio,cropAnchor,pid);
//javascript:cartUpdatePrintCrop(cid,op,ratio,cropAnchor,pid);

theLink1 = "public_actions.php?pmode=update_cart_crop&prid=" + prid + "&pid=" + pid + "&id="+id+"&op=crop&ratio="+ratioPrint+"&anchor="+cropAnchor1;
theLink2 = "public_actions.php?pmode=update_cart_crop&prid=" + prid + "&pid=" + pid + "&id="+id+"&op=crop&ratio="+ratioPrint+"&anchor="+cropAnchor2;
theLink3 = "public_actions.php?pmode=update_cart_crop&prid=" + prid + "&pid=" + pid + "&id="+id+"&op=crop&ratio="+ratioPrint+"&anchor="+cropAnchor3;



		break;

	
	// end switch
	}
		


		$('#field_crop_to_print_1_link' + id).val(theLink1);
		$('#field_crop_to_print_2_link' + id).val(theLink2);
		$('#field_crop_to_print_3_link' + id).val(theLink3);
		
		
		


if(      $('#opCustomCropRequest' + id).val()  && (  trim($('#opCustomCropRequest' + id).val()) != "::Enter Custom Crop Request::")   ){
// if crop request already there
//alert('request');
$('#crop_to_print_custom_crop_request' + id).val($('#opCustomCropRequest' + id).val());
$('#link_popCrop_toggle_custom_crop'+id).html('Cancel Custom Crop');
$('#popCrop_CustomCropRequestWrapper'+id).css('display', 'block');
// end if crop request already there
}
else
{
//alert('no request');
$('#popCrop_CustomCropRequestWrapper' + id).css('display', 'none');
$('#link_popCrop_toggle_custom_crop'+id).html('Need Custom Crop?');

}
		
		


		nuShow('crop_to_print' + id,'auto','auto','','',null,1);

		$('#crop_to_print' + id + ' a').blur();







// '''''' end if crop
}
else
{
// '''''' if native redirect no pop
//alert('native');
	switch(pageName()){
	
		case "details":
		case "image":
		case "preview":
		theLink = "details.php?prid=" + prid + "&pid=" + getQuery('pid');
		break;
	
		case "lightbox":
		theLink = "public_actions.php?pmode=update_lightbox&id="+id+"&prid=" + prid + "&op=&ratio=&anchor=";
		break;
	
		case "cart":
		theLink = "public_actions.php?pmode=update_cart_crop&id="+id+"&prid=" + prid + "&op=&ratio=&anchor=";
		break;

	// end switch
	}

	var crop_request = trim( $('#opCustomCropRequest' + id).val() );
	
	if( crop_request == "::Enter Custom Crop Request::" || crop_request == ""){
	// do nothing
	}else{
	theLink = theLink + "&crop_request=" + crop_request;
	
	}
	//alert(theLink);

switch(pageName()){
	
		case "details":
		case "image":
		case "preview":
		case "lightbox":
		window.location = theLink;
		break;
	
		case "cart":

document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
document.payform.action = theLink;
document.payform.submit();

	break;

// end switch
}

// '''''' end if native
}



// ------------------------------------------------------------------------ end func popCrop
}





function popCustom(id){
// ------------------------------------------------------------------------ start func popCustom
nuShow('popCustom' + id,'auto','auto','','',null,1);
$('#crop_custom' + id + ' a').blur();
// ------------------------------------------------------------------------ end func popCustom
}

function popCustomCancel(id){

$('#opCustomCrop' + id).attr('checked',false);


switch(pageName()){

case "details":
case "image":
case "preview":
case "lightbox":
$('#crop_custom_crop_request' + id).val(       ''                      );
break;

case "cart":
break;
// end switch
}
nuShowClose();
// ------------- end func
}

function popCustomGo(id){

//$('#opCustomCrop' + id).attr('checked',false);

if(  trim( $('#crop_custom_crop_request' + id).val() ) ){

// crop request has value
switch(pageName()){

case "details":
case "image":
case "preview":
case "lightbox":
//$('#crop_custom_crop_request' + id).val(       ''                      );

$('#opCustomCropRequest' + id).val(         trim( $('#crop_custom_crop_request' + id).val() )          );
toggleCustomCropRequest_Page(id);

break;

case "cart":
break;
// end switch
}
// end if crop request has value
}
else
{
$('#opCustomCrop' + id).attr('checked',false);
}
nuShowClose();
// ------------- end func
}












function validate_process_cc_admin(){



var go = true;

if(document.getElementById('x_card_amount_entry_checkbox').checked == 1){
	if(trimMeCheck('x_card_amount_entry', 'payform',0)==false)
	{
	go = false;
	}
	else
	{
		
document.payform.x_card_amount_entry.value =	formatCurrency(document.payform.x_card_amount_entry.value);	
		
		if(document.payform.x_card_amount_entry.value == 0.00)
		{go = false;
		document.payform.x_card_amount_entry.style.backgroundColor=errColor;

		}
		else
		{
			document.payform.x_card_amount_entry.style.backgroundColor=ogColor;

			}
		
		}
	
	
}




if(document.payform.x_card_stored_id.value==0){
// -- start disable cc validation if stored card

arr = new Array("x_card_type", "x_card_num");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});



document.payform.x_card_num.value = document.payform.x_card_num.value.replace(/[a-z]/gi, '');

if(!checkLuhn(document.payform.x_card_num.value.replace(/[^\d]/g, ''))) {



			
			// firefox
			document.payform.x_card_num.style.background = errColor;
			
			errSmall('div_x_card_num_error', 'Invalid Credit Card Format!', 1, 'payform', 'x_card_num', 1);
			go = false;

}
else
{
//valid
document.getElementById('div_x_card_num_error').style.display='none';


} 



//exp
arr = new Array("x_exp_date_month", "x_exp_date_year");
$.each(arr, function(index, value) { 
//
if(trimMeCheck(value, 'payform',0)==false){go = false;}
//
});


// -- end disable cc validation if stored card
}



if(trimMeCheck('x_card_code', 'payform',0)==false)
{
//return false;
go = false;
}

if(document.getElementById('opNewExistingAddress').value == "Existing"){        
// existing address
				var c_value = "";
				if(document.payform.address_id.length)
							{
											for (var i=0; i < document.payform.address_id.length; i++)
											   {
														if (document.payform.address_id[i].checked)
														{
														c_value = c_value + document.payform.address_id[i].value;
														}
											   }
							}else{
														if (document.payform.address_id.checked)
														{
														c_value = c_value + document.payform.address_id.value;
														}
								
							}
							
				if(c_value == "")
				{
				errSmall('errAddressPaySub', 'No Address Selected!', 1);
				go =  false;
				}
				else
				{
				errSmall('errAddressPaySub', null, 0);
				}
				
//
}
else
{
// new address 
					if(validateAddressFormInputsSub('payform')==false)
					{go = false;}
					//
}







if(go == false){
return false;
}	

	$(document).keyup(function(e) {
	if (e.keyCode == 13) {return false;}   
	});

//return false;

document.payform.action = "_km_order_details_admin_process_cc_submit.php";
document.payform.submit();

// -------------- end func
}


function checkLuhn(input)
{
  var sum = 0;
  var numdigits = input.length;
  var parity = numdigits % 2;
  for(var i=0; i < numdigits; i++) {
    var digit = parseInt(input.charAt(i))
    if(i % 2 == parity) digit *= 2;
    if(digit > 9) digit -= 9;
    sum += digit;
  }
  return (sum % 10) == 0;
}


