function stopRKey(evt) {
	var evt  = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text")) { return false; }
}
document.onkeypress = stopRKey;


function getUrlVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	 
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}


function formSend(formName, nextPage, writepage) {

		var sendData = Form.serialize(formName);
		nextPage = nextPage+'.php';
		//alert (sendData);		
		new Ajax.Request(writepage, { method: 'post', postBody: sendData, onComplete: window.location = nextPage+'?'+sendData});
} 	
function checkform()
{
  msg = 'required field';
  errors = 0;
  if ($F('fname') ==""){
	$('fname_error').update(msg);
	errors++;
  }else{
	$('fname_error').update('');
  }
  if ($F('lname') ==""){
	$('lname_error').update(msg);
	errors++;
  }else{
	$('lname_error').update('');
  }
  if ($F('email') ==""){
	$('email_error').update(msg);
	errors++;
  }else{
	$('email_error').update('');
  }
  if ($F('phone') ==""){
	$('phone_error').update(msg);
	errors++;
  }else{
	$('phone_error').update('');
  }
  formSend('userinfo','user_write','user_write');
  return (errors == 0);
}	

function checkformpro()
{

  msg = 'required field';
  errors = 0;
  if ($F('fname') ==""){
	$('fname_error').update(msg);
	errors++;
  }else{
	$('fname_error').update('');
  }
  if ($F('lname') ==""){
	$('lname_error').update(msg);
	errors++;
  }else{
	$('lname_error').update('');
  }
  if ($F('email') ==""){
	$('email_error').update(msg);
	errors++;
  }else{
	$('email_error').update('');
  }
  if ($F('phone') ==""){
	$('phone_error').update(msg);
	errors++;
  }else{
	$('phone_error').update('');
  }
  if ($F('bizname') ==""){  
	$('bizname_error').update(msg);
	errors++;
  }else{
	$('bizname_error').update('');
  }
  if ($F('bizsite') ==""){
	$('bizsite_error').update(msg);
	errors++;
  }else{
	$('bizsite_error').update('');
  }  
  formSend('userinfo','user_write','user_write');
  return (errors == 0);
}
function checkformgift()
{
	msg = 'required field';
	errors = 0;
  if ($F('fname') ==""){
	$('fname_error').update(msg);
	errors++;
  }else{
	$('fname_error').update('');
  }
  if ($F('lname') ==""){
	$('lname_error').update(msg);
	errors++;
  }else{
	$('lname_error').update('');
  }
  if ($F('email') ==""){
	$('email_error').update(msg);
	errors++;
  }else{
	$('email_error').update('');
  }
  if ($F('amount') == "") {
	$('amount_error').update(msg);
	errors++;
  }else if(!parseFloat($F('amount')) || parseFloat($F('amount')) <= 0) {
	$('amount_error').update("must be a number greater than 0");
	errors++;
  }else{
	$('amount_error').update('');
  }
  formSend('giftinfo','gift_write','gift_write');
  return (errors == 0);
}	
	
function orderForm(row,sessid){
	
	var url = 'order_form.php';
	if (row == 0){
		target = 'show';
	}
	else{
		var target = 'show'+row;
	}	
	var pars = 'row='+row+'&sessid='+sessid;
	//alert('pars = '+pars);
	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars});	
}

function cartUpload(sessid){

	var url = 'cartupload.php';
	var pars = 'sessid='+sessid;
	var target = 'show';
	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars});

}

function getSelect(row,size,elem,sessID){
	var url = 'get_'+elem+'.php';
	var target = 'div'+elem+row;
	var parms = 'row='+row+'&size='+size+'&session_id='+sessID;
	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: parms, asynchronous: false});
	$('quantity'+row).enable();
	$('cropping'+row).enable();
	$('color_correction'+row).enable();
	$('engraving'+row).enable();
	if($('logo'+row+'_with') != null) {
		$('logo'+row+'_with').enable(); $('logo'+row+'_with').checked = true; $('logo'+row+'_without').enable();
	}
}
function collectPrice(row){	
	var quantity = parseInt($F('quantity'+row));	
	var cropping = '';
	var color_correction = '';
	var engraving = '';
	
		if (null == $F('cropping'+row)){
			cropping = 0;
			$('crop_notes'+row).disable();
			$('crop_notes'+row).setValue('type your crop instructions here');
		}else{
			cropping = parseInt($F('cropping'+row));
			$('crop_notes'+row).enable();
			$('crop_notes'+row).setValue('');
		} 
		if (null == $F('color_correction'+row)){
			color_correction = 0;
		}else{
			color_correction = parseInt($F('color_correction'+row));
		} 
	
    /* No more engraving
	if (null == $F('engraving'+row)){		
		engraving = 0;
		$('engravetext'+row).disable();
		$('engravetext'+row).setValue('type your note here, 650 characters / about 110 words max');
	}else{		
		engraving = parseInt($F('engraving'+row));
		$('engravetext'+row).enable();
		$('engravetext'+row).setValue('');
	}
    */
	
	var newPrice = (
		parseFloat($F('finalprice_size'+row))
		+ parseFloat($F('finalprice_substrate'+row))
		//+ parseFloat($F('finalprice_laminate'+row))
		+ parseFloat($F('finalprice_finish'+row))
		+ parseFloat($F('finalprice_logo'+row))
		+ cropping
		+ color_correction
		+ engraving
	) * (quantity);
	return newPrice;
}
function updateRowPrice(row,info,elem){
		enforceRowRules(row);
		
		var tmp = 'rowprice'+row;	
		var wgt = 'rowweight'+row;
		var finalRowWgt='finalrowwieght'+row;
		var quantity = parseInt($F('quantity'+row));		
		var infoArray = info.split('|'); 
		var id = infoArray[0];
		var displayinfo = infoArray[1];
		var price = parseFloat(infoArray[2]);
		var weight;
		var weightString;

		if(elem == 'size'){		
			tempWeight = infoArray[3];
			weightString = '<input type="hidden" name="'+wgt+'" id="'+wgt+'" value="'+tempWeight+'">'			
		}else{
			tempWeight = $F(wgt);			
			weightString = '<input type="hidden" name="'+wgt+'" id="'+wgt+'" value="'+tempWeight+'">';		
		}
				
		if((elem != 'quantity') && (elem != 'cropping') && (elem != 'color_correction') && (elem != 'engraving')){
		    $('finalprice_'+elem+row).setValue(price);
		}		
		
		var newPrice = collectPrice(row);
		newPrice = newPrice.toFixed(2);

		$('div'+tmp).update('$'+newPrice+'<input type="hidden" name="'+tmp+'" id="'+tmp+'" value="'+newPrice+'">'+weightString);
		updateTotalPrice();
}
function enforceRowRules(row) {
	// 1. lustre finish is unavailable if UV laminate is selected
    /* No more laminate
	if($F('laminate' + row + '_uv')) {
		$('finish' + row + '_lustre').disable();
		$('finish' + row + '_lustre').checked = false;
		$('finish' + row + '_lustre' + '_label').addClassName('strikethrough');

		$('laminate' + row + '_uv' + '_error').update('<br />(not in lustre)');
		$('laminate' + row + '_uv' + '_error').show();
	} else {
		$('finish' + row + '_lustre').enable();
		$('finish' + row + '_lustre' + '_label').removeClassName('strikethrough');

		$('laminate' + row + '_uv' + '_error').hide();
	}
    */
	// end 1
	
	// 2. no-laminate, and therefore lustre, is not available on plywerks bigger than 16x20
	/*
	var infoArray = $F('size'+row).split('|'); 
	var m = /(\d+)"x(\d+)"/.exec(infoArray[1]);
	if (m != null) {
	  var w = parseInt(m[1]);
	  var h = parseInt(m[2]);
	  
	  if(w >= 16 && h >= 20 && (w > 16 || h > 20)) {
		$('laminate' + row + '_none').disable();
		$('laminate' + row + '_none').checked = false;
		$('laminate' + row + '_none' + '_label').addClassName('strikethrough');

		$('laminate' + row + '_uv').checked = true;
		$('laminate' + row + '_uv' + '_error').update('<br />(laminate required for this size)');
		$('laminate' + row + '_uv' + '_error').show();
		
		
		$('finish' + row + '_lustre').disable();
		$('finish' + row + '_lustre').checked = false;
		$('finish' + row + '_lustre' + '_label').addClassName('strikethrough');
	  } else if($F('laminate' + row + '_uv') == null)  {
		$('laminate' + row + '_none').enable();
		$('laminate' + row + '_none' + '_label').removeClassName('strikethrough');

		$('laminate' + row + '_uv' + '_error').hide();

		$('finish' + row + '_lustre').enable();
		$('finish' + row + '_lustre' + '_label').removeClassName('strikethrough');
	  }
	  
	  
	}
	*/
	// end 2
}

function updateTotalPrice(){
	
	var totalprice = 0;
	var tempprice = 0;
	var totalweight = 0;
	var tempweight = 0;
	var filecount = parseInt($F('filecount'));
	var total_discount = 0;
	
	for (i=1;i<=filecount;i++) {
				
			var test;
			if ( (test = document.getElementById('image'+i) )){	//test to see if there is a missing row after user hits delete to prevent javascript 'undefined' error
				tempprice = parseFloat($F('rowprice'+i));				
				totalprice = totalprice + tempprice;
				tempweight = parseFloat($F('rowweight'+i) * $F('quantity'+i));				
				totalweight = parseFloat(totalweight) + tempweight;				
				totalweight = parseFloat(totalweight);
				totalweight = (totalweight).toFixed(2);	
			}
	}

	$('divsubtotal').update('$'+(totalprice).toFixed(2)); //update subtotal
	
	/*if(null != $F('sample')){
		//alert("apply sample discount");
		$('dis_code').disable();
		totalprice = totalprice - sampleDiscount();
		total_discount = parseFloat(total_discount) + sampleDiscount();
	}else{
		$('dis_code').enable();
	}
*/	
	//alert('line 236');
var tmpCertAmt = 0;
	if(null != $F('gift_cert')){
		tmpCertAmt = parseFloat($F('cert_amt'));
		if(tmpCertAmt > 0){
			if($F('cert_num') == '' || $F('cert_num') == 'Cert #'){
					alert('you must enter a gift certificate number');					
			}else{	
				if(tmpCertAmt > totalprice){ //if cert amount is greater than total, we don't want a negative amount
					tmpCertAmt = totalprice;
					//alert("tmpCertAmt = total price: "+tmpCertAmt);
					$('tot_cert').update('<input type="hidden" id="total_cert" name="total_cert" value="'+tmpCertAmt+'" >');
					totalprice = totalprice - tmpCertAmt;
					total_discount = parseFloat(total_discount) + tmpCertAmt;
				}else{
					$('tot_cert').update('<input type="hidden" id="total_cert" name="total_cert" value="'+tmpCertAmt+'" >');
					totalprice = totalprice - tmpCertAmt;
					total_discount = parseFloat(total_discount) + tmpCertAmt;
				}
					
			}
		}
		
	}else{
		$('tot_cert').update('<input type="hidden" id="total_cert" name="total_cert" value="0" >');
	}	
	
	
	var tempDisc = 0;
	if($F('valid_code') > 0){
		
		var codeArr = $F('valid_code').split('.');
		if(codeArr[0] == 0){  //if the  discount code starts with a decimal, it's a percentage.
			
			if(null != $F('dis_code')){				
				for (i=1;i<=filecount;i++) 
				{					
				   var test;
				   if ( (test = document.getElementById('image'+i) )){
					  tempDisc =  tempDisc + (($F('finalprice_size'+i) * $F('quantity'+i)) * $F('valid_code'));
					   tempDisc =  tempDisc + (($F('finalprice_substrate'+i) * $F('quantity'+i)) * $F('valid_code'));					  
					}
					
				}				
				total_discount = parseFloat(total_discount) + tempDisc;
				totalprice = totalprice - tempDisc;
			}
			
		}else{  //if it's not a percentage, it's a direct dollar amount
				if(null != $F('dis_code')){	
				
				for (i=1;i<=filecount;i++) 
				{	
					var test;
					if ( (test = document.getElementById('image'+i) )){
						if($F('rowprice'+i) > 0){
							//	alert("tempdisc = "+tempDisc);
							tempDisc =  tempDisc + ($F('valid_code') * $F('quantity'+i));
						}
					}	
				}
				//alert("tempdiscdoll = "+tempDisc);
				totalprice = totalprice - tempDisc;
			}
		}
	}
	// prodeal discount
	if($('dis_code_pro') != null && $F('dis_code_pro') != null) {
		for (i=1;i<=filecount;i++) 
		{					
		   var test;
		   if ( (test = document.getElementById('image'+i) )){
			   tempDisc =  tempDisc + (($F('finalprice_size'+i) * $F('quantity'+i)) * 0.20);
			   tempDisc =  tempDisc + (($F('finalprice_substrate'+i) * $F('quantity'+i)) * 0.20);
			}
			
		}				
		//alert("tempdisc = "+tempDisc);
		total_discount = parseFloat(total_discount) + tempDisc;
		totalprice = totalprice - tempDisc;
	}
	
	
	total_discount = (total_discount).toFixed(2);
	if(total_discount > 0){
		$('tot_dis').update('$'+total_discount+'<input type="hidden" id="total_discount" name="total_discount" value="'+total_discount+'" >');
	}else{
		$('tot_dis').update('$0.00<input type="hidden" id="total_discount" name="total_discount" value="0" >');
	}
	
	
	totalprice = (totalprice).toFixed(2);
	if(totalprice >= 0){
		if(totalprice == 0){
			totalprice = 1;			
		}
		$('divtotalprice').update('$'+totalprice+'<input name="totalprice" id="totalprice" value="'+totalprice+'" type="hidden">');				
		$('divtotalweight').update('<input name="weight" id="weight" value="'+totalweight+'" type="hidden">');
		//$('order_submit').enable();
	}else{
		if(totalprice < 0){		
			totalprice = 1;			
		}
		$('divtotalprice').update('$'+totalprice+'<input name="totalprice" id="totalprice" value="'+totalprice+'" type="hidden">');	
		$('divtotalweight').update('<input name="weight" id="weight" value="'+totalweight+'" type="hidden">');
		
		
		//alert('Your total is less than $1(the minimum order amount).  Please adjust your Gift Certificate amount.');
		//$('order_submit').disable();
		
		
	}
	 

}

function sortPrice(a,b)
{
	return  b[1] - a[1];//sort by price 
}

function giftCert(){

	if(null != $F('gift_cert')){		
		//document.orderinfo.cert_apply.style.visibility='visible';	
		$('cert_apply').enable();
		$('cert_num').enable();
		$('cert_amt').enable();		
	}else{
		//document.orderinfo.cert_apply.style.visibility='hidden';
		$('cert_apply').disable();
		$('cert_num').disable();
		$('cert_amt').disable();
		updateTotalPrice();
	}

}

function disCode(){
	if($F('dis_code') != null){				
		$('code_apply').enable();	
		$('code').enable();	
		//$('sample').disable();	//can't apply discount code and sample code at the same time
		if($('dis_code_pro') != null){
			// prodeal selection is available, update price to remove prodeal discount when normal discount is applied
			updateTotalPrice();
		}
	}else{		
		$('code_apply').disable();	
		$('code').disable();
		//$('sample').enable();	
		updateTotalPrice();
	}

}
function verifyCode(){
	var url = 'verify_code.php';
	code = $F('code');	
	var pars = 'code='+code;
	var target = 'disCode';
	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars,onComplete:updateTotalPrice});
	
}
function sampleDiscount(){
	var totalDiscount = 0;
	var sizeDiscount = 0;
	var substrateDiscount = 0;
	var filecount = parseFloat($F('filecount'));
	var arr = new Array(filecount);
	var hash = getUrlVars(); 
	var sessID = hash['sessid'];
	//alert("1filecount = "+filecount);
	for (i=1;i<=filecount;i++) //build the array of row, size, substrate
	{
		var test;
		if ( (test = document.getElementById('image'+i) )){
			arr[i] = new Array(4);
			arr[i][0] = i;
			arr[i][1] = parseFloat($F('finalprice_size'+i));
			arr[i][2] = parseFloat($F('finalprice_substrate'+i));
			arr[i][3] = parseFloat($F('quantity'+i));
		}
		
	}	
	arr.sort(sortPrice);	
	var limit = arr.length;	
	if(sessID.indexOf("_pro") > 0) 
	{
		discount = .25;
	}else{
		discount = .25;
	}
	for(q=0;q<=2;q++){			
		if(null != arr[q]){			
			sizeDiscount = sizeDiscount + ((parseFloat(arr[q][1]) * parseFloat(arr[q][3])) * discount); //add size price * quantity * .25 discount to total discount	
			substrateDiscount = substrateDiscount + ((parseFloat(arr[q][2]) * parseFloat(arr[q][3])) * discount); //add substrate price * quantity * .25 discount to total discount	
		}
	}
	totalDiscount = sizeDiscount + substrateDiscount;		
	return totalDiscount;
	
}
function storePickup(){	
	if(null == $F('pickup')){		
		updateTotalPrice();
	}else{			
		$('divtotalweight').update('0 lbs<input name="weight" id="weight" value="0" type="hidden">');
	}	
}

function deleteRow(row, sessid){
    //$('show'+row).update('');
    var image = $('image'+row).value;
    new Ajax.Updater({ success: 'show'+row }, '/delete_image.php?i='+image+'&sessid='+sessid, {
        onComplete: function(transport) {
            updateTotalPrice();
        }
    });
}

function showResponse(req){
			$('show').innerHTML=req.responseText;
		}

