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 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 statusRefundTypeToggle(){
form=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(){
vGo = true;	
form=document.update_status;

if(  (form.status.value=='Refunded') || (form.status.value=='Cancelled')                  ||                 (form.status.value != '' && form.idBatchFromAdmin.value != '')             ){
//
if(form.status.value=='Shipment' && form.shippingVendor.value==''){alert('Select Shipping Vendor!');return false;};

if(form.status.value=='Refunded')
{
// start 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];
							//alert(value);
						
						if(trimMeCheck(value, 'update_status',0)==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;
	
}
	
	}



// end refunded	
}

return vGo;




if(confirm('Update Status?')){return true;}else{return false;};
//
}
else
{
	
	
	
	if(form.idBatchFromAdmin.value == '')
	{
		alert('Select Batch!');
	return false;
	}
	
	if(form.status.value == '')
	{
		alert('Select Status!');
	return false;
	}
	 
	
	
	
	
	};	
// ------------------------------------------------------------------------------------ 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 showLB_Select(id){

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 js_email(id) {

if(trimMeCheck('email', 'email_form',1)==false)
{return false;}
nuShowClose(); 
document.email_form.action = "public_actions.php?pmode=email_photo&pid="+id;
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, bool, formname, fieldname, fieldbool) {
fld='';
if(fieldbool==1){

fld = eval('document.'+formname+'.'+fieldname);
}
if(bool==1){	
document.getElementById(id).innerHTML=error;
document.getElementById(id).style.display="block";
if(fieldbool==1){
fld.style.background = errColor;
//fld.focus();
}
//return false;

}
else
{
if(fieldbool==1){
	
document.getElementById(id).style.display="none";
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() {

if(trimMeCheck('email', 'email_form',1)==false)
{return false;}
				
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;}

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 trimMeCheck(fieldname, formname, 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);
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 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");
arr.forEach(
function(item) { 
if(trimMeCheck(item, 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");
arr.forEach(
function(item) { 
if(trimMeCheck(item, 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;}


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 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
}



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
  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
  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 addAddress(redirect)

{
//if(redirect == 'cart')
//{
document.cardform_for_cancel.action = "address.php";
document.cardform_for_cancel.submit();
//}
//else
//{
//window.location="address.php";
//}
// --------------------------------------------------------------- end func
}






function deleteAddress(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)
{
	
//alert();	
	
form = eval('document.'+nameForm);
form.idAddress.value = idAddress;
nuShow(idDiv,'auto','auto','','');

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

function deleteAddressJQConfirm(nameForm)
{

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

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


function goToRedirect(redirect){
window.location="https://www.fillprints.com/"+redirect+".php";
// --------------------------------------- end func
}
	


function addEditCard(id,redirect,formname)
{


if(redirect == '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();
}
else
{
if(id)
{
	window.location="https://www.fillprints.com/card.php?idCard="+id+"&redirect=account";
}
else
{
	//window.location="https://www.fillprints.com/card.php";
	document.cardform_for_cancel.action = "https://www.fillprints.com/card.php";
document.cardform_for_cancel.submit();
	
	}



}
// --------------------------------------------------------------- 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,'auto','auto','','');

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

function deleteCardJQConfirm(nameForm)
{

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 makeAddressBillingShipping(idAddress, nameForm, isBilling, isShipping)
{

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+"&idAddress="+idAddress;
form.submit();
//alert(form.action);
// --------------------------------------- end func
}



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



redirect = form.redirect.value;
//alert(redirect);

if(redirect)
{form.action = redirect + ".php";}
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 dropdownPrintsDetailsPage(mySel,loggedIn)
{
var myVal;

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


//public_actions.php?pmode=add_cart&ptype=p&gid=313&sgid=&pid=10094&prid=91428&bw=&op=crop&ratio=2&anchor=left

if(myVal){

if (loggedIn == 0) {


//

var myValRedirect = myVal.replace('public_actions.php?pmode=add_cart', 'login.php?message=cart_redirect');
//alert(myValRedirect);
//return false;
//

var myString = myVal;
var mySplitResult = myString.split("prid=");
var prid_js = mySplitResult[1]; 



window.location = myValRedirect;
//window.location = "login.php?message=cart_redirect&pmode_redirect=add_cart&ptype=p&gid=<?PHP echo $_GET['gid']; ?>&sgid=<?PHP echo $_GET['sgid']; ?>&pid=<?PHP echo $package->id; ?>&prid=" + prid_js;
return false;
}
else
{
//alert(myVal);	
window.location = myVal;
return false;
}

}

//document.print_drop.prints.focus();
return false;
// -------------------------------------------------------------------- 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;
	
	}	
	
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
//document.payform.action = "account.php";
document.payform.action = "address.php?select="+billing_or_shipping;
document.payform.submit();

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

function editAddress(id,formname,redirect){

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


switch(redirect){


case 'cart':
// cart
form.x_card_code_from_cart.value = form.x_card_code.value;

//document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
//document.payform.redirect.value = "cart";
//document.payform.action = "address.php?idAddress=" + id;
//document.payform.submit();
break;
	

}

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


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

function addAddressFromCart(op){
if(op == 1)
{strAdd = 'isBillingAdd';}
else
{strAdd = 'isShippingAdd';}
document.payform.x_card_code_from_cart.value = document.payform.x_card_code.value;
document.payform.redirect.value = "cart";
document.payform.action =  "address.php?idAddress=0&"+strAdd+"=true";
document.payform.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 changePrintID(prid,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_id&prid="+prid+"&cid="+cid;
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 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.submit();
// --------------------------------------------------------------- end func
}

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

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);
	  
	  
	  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 one countCart
}
else
{
if(document.itemSubmitList.itemCheck.checked){selected = document.itemSubmitList.itemCheck.value;}
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;
	}
//
}


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



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

var closedialog =1;
var jq_pop_div = '';

function nuShow(id,vheight,vwidth,vtitle,vclass,vtop,vProcessing,vForm) {

if(vtop)
{
// do nothing
}
else
{
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'}
//open: function(){closedialog = 1;},
//focus: function(){closedialog = 0;},
//close: function(){$(document).unbind('click');},

});

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

// if the contents have been hidden with css, you need this
if(vProcessing)
// pop in quick no fade
{$myWindowNu.show();
closedialog = 1;

}
else
// fade in fast
{$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");

// 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();

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


$(document).bind('click',
//alert(closedialog);
function overlayclickclose() {
	//alert(closedialog);
if (closedialog==0 ) {
var target = $(event.target);
if (target.is('.ui-dialog') || target.parents('.ui-dialog').length) {
//do nothing;
//alert('on');
}
else
{
	//alert('off');
//$myWindowNu.dialog('close');
nuShowClose();
closedialog = 1;
}



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

// end bind document click							
);				 









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(id){
document.cardform.redirect.value = "cart";
document.cardform.action = "card.php?idCard=" + id;
document.cardform.submit();

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


function toggleUseNewFromCart(){

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



function toggleCardAddressNewExisting(op){
	uncheckAllBoxes('opNewExistingAddress','cardform');
	switch(op)
	{
	case "New":
		document.getElementById('useNewAddress').checked=true;;
		document.getElementById('divNewAddress').style.display='';
		document.getElementById('divExistingAddress').style.display='none';
		document.getElementById('divButtons').style.width='250px';
		uncheckAllBoxes('address_id','cardform');
	  break;
	case "Existing":
		document.getElementById('useExistingAddress').checked=true;;
		document.getElementById('divNewAddress').style.display='none';
		document.getElementById('divExistingAddress').style.display='';
		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 keypressCoupon(e)
{
var Ucode=e.keyCode? e.keyCode : e.charCode
if (Ucode == 13)
{
validateCoupon();
}
//------------------------------------------------------------------------------ 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');
	arr.forEach(
	
	function(item) { 
	input = eval('document.payform.'+item);
	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';
	//
		arr = new Array('x_card_type','x_card_num','x_exp_date_month','x_exp_date_year','x_card_code','x_card_store_nick');
		arr.forEach(
		
		function(item) { 
		input = eval('document.payform.'+item);
		input.value='';
		}
		
		);
	//

		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();
		}
		
//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';
		}
		

}

//
		arr = new Array('divCardGIF','divCardType','divCardNum','divCardExp','divCardCode','divCardStoreCheckbox');
		
		if(document.payform.countStoredCards.value>0){
		arr.push('divCardStoreSelect');
		}
		
		arr.forEach(
		
		function(item) { 
		//input = eval('document.payform.'+item);
		document.getElementById(item).style.display=ccSwitchVal;
		}
		
		);
	//

// --------------------------------------- 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){	

if(idCard==0)
{
idDivAddressBilling='billing_address_OG';
idAddressBilling = document.payform.billing_address_id_OG.value;
opDisplay="";
document.getElementById('divCardStoreSummary').style.display='none';
innerDisplay = "";
}
else
{
	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;
	}


document.payform.x_card_num.value='';
document.payform.x_card_type.value='';
document.payform.x_exp_date_month.value='';
document.payform.x_exp_date_year.value='';
document.payform.x_card_code.value='';
document.payform.x_card_store.checked=0;
document.payform.x_card_store_nick.value='';
document.getElementById('divCardNick').style.display='none';

//document.getElementById('divCardStoreCheckbox').style.display='';
//document.getElementById('divCardExp').style.display='';
//document.getElementById('divCardNum').style.display='';
//document.getElementById('divCardType').style.display='';
//document.getElementById('divCardStoreSummary').style.display='none';

//
		arr = new Array('divCardStoreCheckbox','divCardType','divCardNum','divCardExp');
		
		arr.forEach(
		
		function(item) { 
		document.getElementById(item).style.display=opDisplay;
		}
		
		);
	//



document.getElementById('divCardStoreSummary').innerHTML=innerDisplay;


document.payform.billing_address_id.value=idAddressBilling;
document.getElementById('billing_address_wrapper').innerHTML = document.getElementById(idDivAddressBilling).innerHTML;



// ----------------------------------------- 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");
arr.forEach(
		function(item) { 
		// process
			if(trimMeCheck(item, 'cardform',0)==false)
			{go = false;}
		}
// end loop
);
//

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");
arr.forEach(
		function(item) { 
		// process
			if(trimMeCheck(item, 'cardform',0)==false)
			{go = false;}
		}
// end loop
);
//


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){
//
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)
{
//
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 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
}