/* 
Shopping Cart 
copyright 2010 Design Brooklyn Media Services
*/

var baseURL = "/";
var testDir = '';

/* ITEMS */

var item_options = new Array();
function changeOptions1(id) {
	if (document.getElementById("item_"+id+"_option1") != undefined) {
		var val = document.getElementById("item_"+id+"_option1").value;
		WriteByID('item_'+id+'_option2',null,"");
		var opt2 = document.getElementById('item_'+id+'_option2');
		for (var i in item_options[id][val]) {
			newOpt = document.createElement("option");
			newOpt.setAttribute("value",i);
			newOpt.innerHTML = i;
			opt2.appendChild(newOpt);
		}
		changeOptions2(id);
	}
}
function changeOptions2(id) {
	var val1 = document.getElementById("item_"+id+"_option1").value;
	var val2 = document.getElementById("item_"+id+"_option2").value;
	WriteByID('item_'+id+'_option3',null,"");
	var opt3 = document.getElementById('item_'+id+'_option3');
	for (var i in item_options[id][val1][val2]) {
		newOpt = document.createElement("option");
		newOpt.setAttribute("value",i);
		newOpt.innerHTML = i;
		opt3.appendChild(newOpt);
	}
	changePrice(id);
}
function changePrice(id) {	
	var val1 = document.getElementById("item_"+id+"_option1").value;
	var val2 = document.getElementById("item_"+id+"_option2").value;
	var val3 = document.getElementById("item_"+id+"_option3").value;
	var item_price = item_options[id][val1][val2][val3];
	document.getElementById('item_'+id+'_price').value = item_price;
	WriteByID('item_'+id+'_display_price',null,item_price);
}


function add_item_to_cart(item_id) {
	var item_options = '';
	if (document.getElementById('item_'+item_id+'_option1') != undefined) {
		item_options += document.getElementById('item_'+item_id+'_option1').value;
	}
	item_options += "|-|";
	if (document.getElementById('item_'+item_id+'_option2') != undefined) {
		item_options += document.getElementById('item_'+item_id+'_option2').value;
	}
	item_options += "|-|";
	if (document.getElementById('item_'+item_id+'_option3') != undefined) {
		item_options += document.getElementById('item_'+item_id+'_option3').value;
	}
	item_options += "|-|";
	if (document.getElementById('item_'+item_id+'_price') != undefined) {
		item_options += document.getElementById('item_'+item_id+'_price').value;
	}
	add_item(item_id,item_options,1);
}

function add_item(id,item_options,qty) {
	if (qty == undefined) {
		qty = 1;
	}
	ajaxRequest('item_id='+id+'&item_options='+item_options+'&qty='+qty,testDir+'/shopping/addItem.php',update_cart);
	cartUpdateMessage = "Item Added Successfully";
}

function remove_item(id,item_options) {
	ajaxRequest('item_id='+id+'&item_options='+item_options,testDir+'/shopping/removeItem.php',update_cart);
	cartUpdateMessage = "Item Removed Successfully";
}

function update_quantity(id,item_options,qty) {
	if (qty == undefined) {
		qty = document.getElementById('update_quantity_'+id+'_'+item_options).value;
	}
	ajaxRequest('item_id='+id+'&item_options='+item_options+'&qty='+qty,testDir+'/shopping/updateItem.php',update_cart);
	cartUpdateMessage = "Item Updated Successfully";
}

/* DISCOUNTS */
function add_promo_code() {
	document.getElementById('add_promo_code_button').style.display = "none";
	document.getElementById('add_promo_code_field').style.display = "block";
}
function apply_promo_code() {
	var promo_code = document.getElementById('promo_code').value;
	ajaxRequest('promo_code='+promo_code,testDir+'/shopping/applyPromoCode.php',show_update_status);
}
function remove_promo_code() {
	var promo_code = document.getElementById('promo_code').value;
	ajaxRequest('promo_code='+promo_code,testDir+'/shopping/removePromoCode.php',show_update_status);
}

/* CREDITS */
function enter_gift_certificate() {
	document.getElementById('add_gift_certificate').style.display = "none";
	document.getElementById('enter_gift_certificate').style.display = "block";
}
function apply_gift_certificate() {
	saveThenAct(function() {
		var gift_certificate = document.getElementById('gift_certificate').value;
		ajaxRequest('gift_certificate='+gift_certificate,testDir+'/shopping/applyGiftCertificate.php',show_update_status);
	});
}

function remove_gift_certificate(gift_certificate) {
	saveThenAct(function() {
		ajaxRequest('gift_certificate='+gift_certificate,testDir+'/shopping/removeGiftCertificate.php',show_update_status);
	});
}

/* TAX */


/* SHIPPING */
function select_shipping_option(value) {
	if (value != '' && value != undefined) {
		var words = value.split(" ");
		var shipping_total = Number(words[0].replace("$",""));
		var shipping_method = value.replace(words[0],"");
		ajaxRequest('shipping_total='+shipping_total+'&shipping_method='+shipping_method,testDir+'/shopping/setShippingTotal.php',update_cart);
	}
}
function copyBillingAddress() {
	var fromArr = Array('billing_first_name','billing_last_name','billing_address1','billing_address2','billing_city','billing_state','billing_zip','billing_country');
	var toArr = Array('shipping_first_name','shipping_last_name','shipping_address1','shipping_address2','shipping_city','shipping_state','shipping_zip','shipping_country');
	for (i=0; i<fromArr.length; i++) {
		document.getElementById(toArr[i]).value = document.getElementById(fromArr[i]).value;
	}
}
function change_shipping_method() {
	document.getElementById('shipping_total_holder').style.display = "none";
	document.getElementById('shipping_options_holder').style.display = "block";
}
function shipping_info_changed() {
	document.getElementById('validate_btn').style.display = "none";
	document.getElementById('tax_and_shipping_btn').style.display = "inline";
}

/* CART */

var cartUpdateMessage = '';

var d = new Date();
var cur_date = d.getDate();
var cur_month = d.getMonth();
var cur_year = d.getFullYear();

var cart_summary_fields = Array('sub_total','item_count','promo_codes','tax','shipping','shipping_method','credits','total');

var cart_fields = Array('billing_first_name','billing_last_name','billing_address1','billing_address2','billing_city','billing_state','billing_zip','billing_country',
					   'shipping_first_name','shipping_last_name','shipping_address1','shipping_address2','shipping_city','shipping_state','shipping_zip','shipping_country',
					   'email',
					   'credit_card_type','credit_card_1','cvv2','expiration_month','expiration_year'
					   );

var paypay_cart_fields = Array('shipping_first_name','shipping_last_name','shipping_address1','shipping_address2','shipping_city','shipping_state','shipping_zip','shipping_country','email');

var misc_fields = Array('gift','gift_from','gift_to','gift_note','gift_instructions','notes','mailing_list','payment_method');

var cart_validation = Array(
							new Array('billing_first_name','String'),
							new Array('billing_last_name','String'),
							new Array('billing_address1','String'),
							new Array('billing_city','String'),
							new Array('billing_state','String'),
							new Array('billing_zip','String'),
							new Array('billing_country','String'),
							new Array('shipping_first_name','String'),
							new Array('shipping_last_name','String'),
							new Array('shipping_address1','String'),
							new Array('shipping_city','String'),
							new Array('shipping_state','String'),
							new Array('shipping_zip','String'),
							new Array('shipping_country','String'),
					   		new Array('email','Email'),
							new Array('credit_card_type','String'),
							new Array('credit_card_1','Credit Card','credit_card_type'),
							new Array('cvv2','Number','000','9999'),
							new Array('expiration_month','Number','01','12'),
							new Array('expiration_year','Number',cur_year,(Number(cur_year)+10)),
							new Array('gift_from','String'),
							new Array('gift_to','String')
							);

var paypal_cart_validation = Array(
							new Array('shipping_first_name','String'),
							new Array('shipping_last_name','String'),
							new Array('shipping_address1','String'),
							new Array('shipping_city','String'),
							new Array('shipping_state','String'),
							new Array('shipping_zip','String'),
							new Array('shipping_country','String'),
					   		new Array('email','Email'),
							new Array('gift_from','String'),
							new Array('gift_to','String')
							);

function show_update_status(responseText) {
	if (responseText.search(/error/i) == -1) {
		update_cart(responseText);
	} else {
		handleError(responseText);
	}
}
function update_cart(responseText) {
	if (responseText.search(/error/i) != -1) {
		handleError(responseText);
	}
	if (String(window.location).search(/view-cart.php/) != -1) {
		ajaxRequest('',testDir+'/shopping/updateCart.php',displayCart);
	} else if (String(window.location).search(/checkout.php/) != -1) {
		ajaxRequest('',testDir+'/shopping/displayCheckoutCart.php',displayCart);
		ajaxRequest('',testDir+'/shopping/displayCheckoutForm.php',displayForm);
	} else if (String(window.location).search(/confirm-payment.php/) != -1) {
		ajaxRequest('',testDir+'/shopping/displayConfirmationCart.php',displayCart);
	}
	ajaxRequest('','/shopping/updateMiniCart.php',displayMiniCart);
}
function displayCart(responseText) {
	if (responseText.search(/error/i) != -1) {
		handleError(responseText);
	} else {
		writeContent("cartContents",responseText);
	}
}
function displayForm(responseText) {
	if (responseText.search(/error/i) != -1) {
		handleError(responseText);
	} else {
		writeContent("checkoutForm",responseText);
	}
}
function displayMiniCart(responseText) {
	if (responseText.search(/error/i) != -1) {
		handleError(responseText);
	} else {
		writeContent("miniCartContents",responseText);
		if (cartUpdateMessage != '' && checkoutPage == false) {
			notify('<p align="center">'+cartUpdateMessage+'<br /><span class="button" onclick="javascript:redirect(\''+baseURL+'view-cart.php\');">View Cart</span></p>', { Continue_Shopping: true } );
		}
	}
}
function calculateTaxAndShipping() {
	var credit_req_fields = Array('billing_zip','shipping_zip','shipping_country','billing_state');
	var paypal_req_fields = Array('shipping_address1','shipping_city','shipping_state','shipping_zip','shipping_country');
	var req_fields = (document.getElementById('payment_method_paypal').checked == true) ? paypal_req_fields : credit_req_fields;
	var err = false;
	for (i=0; i<req_fields.length; i++) {
		if (document.getElementById(req_fields[i]).value == '') {
			err = true;
		}
	}
	if (err == false) {
		var params = getCartFormValues();
		ajaxRequest(params,testDir+'/shopping/saveCartForm.php',update_cart);
	} else {
		handleError('Please enter all required fields');
	}
}
function getCartFormValues() {
	var params = "";
	for (i=0; i<cart_fields.length; i++) {
		params += "&"+cart_fields[i]+"="+document.getElementById(cart_fields[i]).value;
	}
	if (document.getElementById('payment_method_credit').checked == true) {
		params += "&payment_method=credit";
	} else {
		params += "&payment_method=paypal";
	}
	if (document.getElementById('gift') != undefined && document.getElementById('gift').checked == true) {
		params += "&gift=true";
	}
	if (document.getElementById('gift_from') != undefined) {
		params += "&gift_from="+urlencode(document.getElementById('gift_from').value);
	}
	if (document.getElementById('gift_to') != undefined) {
		params += "&gift_to="+urlencode(document.getElementById('gift_to').value);
	}
	if (document.getElementById('gift_note') != undefined) {
		params += "&gift_note="+urlencode(document.getElementById('gift_note').value);
	}
	if (document.getElementById('gift_instructions') != undefined) {
		params += "&gift_instructions="+urlencode(document.getElementById('gift_instructions').value);
	}
	if (document.getElementById('notes') != undefined) {
		params += "&notes="+urlencode(document.getElementById('notes').value);
	}
	if (document.getElementById('mailing_list') != undefined && document.getElementById('mailing_list').checked == true) {
		params += "&mailing_list=true";
	}
	return params;
}
function getCartSummaryValues() {
	var params = "";
	for (i=0; i<cart_summary_fields.length; i++) {
		if (document.getElementById(cart_summary_fields[i])) {
			params += "&"+cart_summary_fields[i]+"="+document.getElementById(cart_summary_fields[i]).value;
		}
	}
	return params;
}
function saveAndRedirect(url) {
	var params = "redirectURL="+url+getCartFormValues()+getCartSummaryValues();
	ajaxRequest(params,testDir+'/shopping/saveCartForm.php',redirect);	
}
function saveThenAct(endAction) {
	var params = getCartFormValues()+getCartSummaryValues();
	ajaxRequest(params,testDir+'/shopping/saveCartForm.php',endAction);
}
function validateAndPay() {
	validate_fields();
}
function showValidationError(id) {
	var ele = document.getElementById(id);
	removeClass(ele,"input");
	addClass(ele,"inputError");
}
function hideValidationError(id) {
	var ele = document.getElementById(id);
	removeClass(ele,"inputError");
	addClass(ele,"input");
}
function limitChars(ID,limit,displayID) {
	var curVal = document.getElementById(ID).value;
	var charlen = String(curVal).length;
	var remaining = limit - charlen;
	if (charlen > limit) {
		remaining = 0;
		document.getElementById(ID).value = curVal.substr(0,limit);
	}
	writeContent(displayID,remaining);
}
function selectPaymentMethod(type) {
	if (type == 'paypal') {
		writeContent('validate_btn',"Pay with PayPal");
		for (i=0; i<cart_fields.length; i++) {
			if (!in_array(cart_fields[i],paypay_cart_fields)) {
				if (cart_fields[i].search(/credit_card_[0-9]+/) != -1) {
					document.getElementById("credit_card_1_tr").style.display = "none";
				} else {
					document.getElementById(cart_fields[i]+"_tr").style.display = "none";
				}
			}
		}
	} else {
		writeContent('validate_btn',"Review Order");
		for (i=0; i<cart_fields.length; i++) {
			if (document.getElementById(cart_fields[i]+"_tr") != undefined) {
				document.getElementById(cart_fields[i]+"_tr").style.display = "table-row";
			}
		}
	}
}

function is_NYS(state) {
	state = state.Trim();
	if ((state.search(/NY/i) != -1 && state.length == 2) || (state.search(/NYS/i) != -1 && state.length == 3) || state.search(/New[\s]York/i) != -1) {
		return true;
	} else {
		return false;
	}
}

/* VALIDATION */
var payment_in_progress = false;
function validate_fields() {
	var vErrors = Array();
	var fieldVal;
	var noError = false;
	
	var validation_array = (document.getElementById("payment_method_paypal").checked == true) ? paypal_cart_validation : cart_validation;
	
	for (i=0; i<validation_array.length; i++) {
		
		if (String(validation_array[i][0]).search('gift_') == -1 || document.getElementById('gift').checked == true) {
		
			fields = Array();
			fieldVal = '';
			if (validation_array[i][0].search(/\+/) != -1) {
				fields = validation_array[i][0].split(/\+/);
				for (j=0; j<fields.length; j++) {
					fieldVal += document.getElementById(fields[j]).value;
				}
			} else {
				fieldVal = document.getElementById(validation_array[i][0]).value;
			}
			
			limit1 = "";
			if (validation_array[i][2] != undefined) {
				if (validation_array[i][1] == "Credit Card") {
					limit1 = document.getElementById(validation_array[i][2]).value;
				} else {
					limit1 = validation_array[i][2];
				}
			}
			
			limit2 = "";
			if (validation_array[i][3] != undefined) {
				limit2 = validation_array[i][3];
			}
			noError = validate_field(fieldVal,validation_array[i][1],limit1,limit2);
			
			if (fields.length > 0) {
				for (j=0; j<fields.length; j++) {
					if (!noError) {
						showValidationError(fields[j]);
						vErrors[vErrors.length] = fields[j];
					} else {
						hideValidationError(fields[j]);
					}
				}
			} else {
				if (!noError) {
					showValidationError(validation_array[i][0]);
					vErrors[vErrors.length] = validation_array[i][0];
				} else {
					hideValidationError(validation_array[i][0]);
				}
			}
		
		}
		
	}
	
	if (vErrors.length == 0 && payment_in_progress == false) {
		payment_in_progress = true;
		if (document.getElementById("payment_method_paypal").checked == true) {
			saveAndRedirect("pay-with-paypal.php");
		} else {
			saveAndRedirect("confirm-payment.php");
		}
	} else {
		handleError("Please correct the highlighted errors");
	}
}

function validate_field(value,type,limit1,limit2) {
	var valid = false;
	switch(type) {
		case 'String':
			len = value.Trim().length;
			if (len > 0) {
				valid = true;
				if ((limit1 != null && limit1 != "" && len < limit1) || (limit2 != null && limit2 != "" && len > limit2)) {
					valid = false;
				}
			}
		break;
		case 'Number':
			valid = true;
			if ((limit1 != "" && Number(value) < Number(limit1)) || (limit2 != "" && Number(value) > Number(limit2))) {
				valid = false;
			}
			if ((limit1 != "" && String(value).length < String(limit1).length) || (limit2 != "" && String(value).length > String(limit2).length)) {
				valid = false;
			}
		break;
		case 'Email':
			if (is_email(value)) {
				valid = true;
			}
		break;
		case 'Credit Card':
			if (value.Trim().length > 0) {
				if (luhn(value)) {// && is_valid_cc(value,limit1)) {
					valid = true;
				}
			}
		break;
	}
	
	return valid;
}
function validate_email(elementValue){  
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
	return emailPattern.test(elementValue);
}
function is_email(s) {
    var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_\.]+\.[\w\-\+_]{2,4}(\.[\w\-\+_]{2,4})*\s*$/;
	return String(s).search (isEmail_re) != -1;
}
function is_valid_cc(cctype, ccnumber) {
   var creditCardList = [
		//type      prefix   length
		["Amex",    "34",    15],
		["Amex",    "37",    15],
		["Discover",    "6011",  16],
		["MasterCard",      "51",    16],
		["MasterCard",      "52",    16],
		["MasterCard",      "53",    16],
		["MasterCard",      "54",    16],
		["MasterCard",      "55",    16],
		["Visa",    "4",     13],
		["visa",    "4",     16]
	];
   var cc = getdigits (ccnumber);
   if (luhn (cc)) {
      for (var i in creditCardList) {
         if (creditCardList [i][0] == (cctype)) {
            if (cc.indexOf (creditCardList [i][1]) == 0) {
               if (creditCardList [i][2] == cc.length) {
                  return true;
               }
            }
         }
      }
   }
   return false;
}
function luhn (cc) {
    var sum = 0;
    var i;
    for (i = cc.length - 2; i >= 0; i -= 2) {
       sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
    }
    for (i = cc.length - 1; i >= 0; i -= 2) {
       sum += parseInt (cc.charAt (i), 10);
    }
    return (sum % 10) == 0;
}

/* UI */

var downStrokeField;
function autojump(fieldName,nextFieldName,fakeMaxLength) {
	var myForm=document.getElementById("shop_cart");
	var myField=myForm.elements[fieldName];
	myField.nextField=myForm.elements[nextFieldName];
	
	if (myField.maxLength == null)
	myField.maxLength=fakeMaxLength;
	
	myField.onkeydown=autojump_keyDown;
	myField.onkeyup=autojump_keyUp;
}

function autojump_keyDown() {
	this.beforeLength=this.value.length;
	downStrokeField=this;
}

function autojump_keyUp() {
	if (
		(this == downStrokeField) &&
		(this.value.length > this.beforeLength) &&
		(this.value.length >= this.maxLength)
	)
	this.nextField.focus();
	downStrokeField=null;
}

function start_spinner() {
	document.body.style.cursor = "wait";
}
function stop_spinner() {
	document.body.style.cursor = "auto";
}


/* MISC FUNCTIONS */

var checkoutPage = false;
function setCheckoutPage() {
	checkoutPage = true;
}

function handleError(error) {
	notify(error,{ Close: false });
}
function notify(msg,buttons1,callback1) {
	$.prompt(msg,{ buttons: buttons1, callback: callback1 });
}
function redirect(url) {
	window.location = url;
}
function ajaxRequest(params, target, callback) {
	var xmlhttp;
	if (window.XMLHttpRequest) {
	  // code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	  // code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	} else {
	  alert("Your browser does not support XMLHTTP!");
	} xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4 && callback != null) {
			stop_spinner();
			callback(xmlhttp.responseText);
		}
	}
	start_spinner();
	xmlhttp.open('POST', target, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
}
function writeContent(ID,sText) {
	var	out = sText
	if (document.layers) {
		var oLayer;
		oLayer = document.layers[ID].document;
		oLayer.open();
		oLayer.write(out);
		oLayer.close();
	}
	else if (parseInt(navigator.appVersion)>=5&&navigator.appName=="Netscape") {
		document.getElementById(ID).innerHTML = out;
	}
	else if (document.all) document.all[ID].innerHTML = out;
}
String.prototype.Trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}
function urldecode( str ) {
    var ret = str;      
    ret = ret.replace(/\+/g, '%20');
    ret = decodeURIComponent(ret);
    ret = ret.toString();
    return ret;
}
function urlencode( str ) {
    var ret = str;   
    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, '+');
    return ret;
}
function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}
function setChecked(ID,state) {
	document.getElementById(ID).checked = state;
}
