

// getXMLHttpRequest object
function getXMLHttpRequestObject(){
	var xmlobj;
    // check for existing requests
    if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){
        xmlobj.abort();
    }
    try{
        // instantiate object for Mozilla, Nestcape, etc.
        xmlobj=new XMLHttpRequest();
    }
    catch(e){
        try{
            // instantiate object for Internet Explorer
            xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e){
            // Ajax is not supported by the browser
            xmlobj=null;
            return false;
        }
    }
	return xmlobj;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
function modcart(type,pid,price,key) {
	var qty = document.getElementById('qty_'+pid+"_"+key).value;
	var totalOutput = document.getElementById('totalPrice_'+pid+"_"+key);
	
	if(qty > 0) {
		if(type == 'update') doupdate = true;
		else if(type == 'remove') {
			var agree=confirm("Remove from cart?");
			if (agree) doupdate = true;
			else doupdate = false;
			
		}
		
		if(doupdate) {
			totalOutput.innerHTML = '<img src="images/loadingAnim.gif">';
			sendstr = "type="+type+"&pid="+pid+"&price="+price+"&qty="+qty+"&key="+key;
			modcartXMLHttpObj=getXMLHttpRequestObject();
			modcartXMLHttpObj.open("POST","includes/cart-update.php",true);
			modcartXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			modcartXMLHttpObj.send(sendstr);
			modcartXMLHttpObj.onreadystatechange=modcartStatusChecker;
		} 
	
	} else {
		alert('You must have at least 1 of any product');
		document.getElementById('qty_'+pid+"_"+key).value = 1;
	}
	return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function modcartStatusChecker(){
    // check if request is completed
    if(modcartXMLHttpObj.readyState==4){
        if(modcartXMLHttpObj.status==200) updateCartInline(modcartXMLHttpObj);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function updateCartInline(reqObj) {
	var response = reqObj.responseText;
	var starting1 = response.indexOf("|#=#|");
	var starting2 = response.indexOf("|##=##|");
	var starting3 = response.indexOf("|###=###|");
	
	var type = reqObj.responseText.substring(0, starting1);
	var pid = reqObj.responseText.substring((starting1+5), starting2);
	var key = reqObj.responseText.substring((starting2+7), starting3);
	var price = reqObj.responseText.substring((starting3+9), reqObj.responseText.length);
	
	var totalOutput = document.getElementById('totalPrice_'+pid+"_"+key);
	var cartRow = document.getElementById('cartrow_'+pid+"_"+key);
	
	if(type == 'update') {
		totalOutput.innerHTML = price;
	} else if(type == 'remove') {
		cartRow.style.display = "none";
	}
	
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function setCheckout(prevstep,step) {
	var container = document.getElementById('cart_container');
	var prev_tab = document.getElementById('step_'+prevstep);
	var this_tab = document.getElementById('step_'+step);
	
	if(prevstep == 2 && step == 3) {
		saveCustInfo();
	} else {
		
		container.innerHTML = '<img src="images/loadingAnim.gif" height="20" width="20">';
		prev_tab.className = "cart_tab";
		this_tab.className = "cart_tab selected";
		
		sendstr = "step="+step;
		checkoutXMLHttpObj=getXMLHttpRequestObject();
		checkoutXMLHttpObj.open("POST","includes/cart-checkout.php",true);
		checkoutXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		checkoutXMLHttpObj.send(sendstr);
		checkoutXMLHttpObj.onreadystatechange=checkoutStatusChecker;
	}
	
	return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function checkoutStatusChecker(){
    // check if request is completed
    if(checkoutXMLHttpObj.readyState==4){
        if(checkoutXMLHttpObj.status==200) updateCheckoutInline(checkoutXMLHttpObj);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function updateCheckoutInline(reqObj) {
	var response = reqObj.responseText;
	var container = document.getElementById('cart_container');
	container.innerHTML = response;
	if(document.getElementById('billCountryDefault')) initCountry();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function setBillInfo(thisItem) {
	if($('#useaddy').is(':checked')) {
		document.getElementById('firstName').value = document.getElementById('ship_firstName').value;
		document.getElementById('lastName').value = document.getElementById('ship_lastName').value;
		document.getElementById('bill_address').value = document.getElementById('ship_address').value;
		document.getElementById('bill_suite').value = document.getElementById('ship_suite').value;
		document.getElementById('bill_city').value = document.getElementById('ship_city').value;
		document.getElementById('bill_zip').value = document.getElementById('ship_zip').value;
		for(i=document.getElementById('shipCountrySelect').options.length-1;i>=0;i--) {
			if(document.getElementById('shipCountrySelect').options[i].selected) {
				document.getElementById('billCountrySelect').options[i].selected=true;
				updateState('billCountrySelect');
			}
		}
		if(document.getElementById('shipStateSelect').options) {
			for(i=document.getElementById('shipStateSelect').options.length-1;i>=0;i--) {
				if(document.getElementById('shipStateSelect').options[i].selected) {
					if(document.getElementById('billStateSelect').options) document.getElementById('billStateSelect').options[i].selected=true;
					else document.getElementById('billStateSelect').value = document.getElementById('shipStateSelect').options[i].value;
				}
			}
		} else {
			document.getElementById('billStateSelect').value = document.getElementById('shipStateSelect').value;
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function saveCustInfo() {
	var firstName = document.getElementById("firstName").value;
	var lastName = document.getElementById("lastName").value;
	var email = document.getElementById("email").value;
	var bill_address = document.getElementById("bill_address").value;
	var bill_suite = document.getElementById("bill_suite").value;
	var bill_city = document.getElementById("bill_city").value;
	var bill_state = document.getElementById("billStateSelect").value;
	var bill_country = document.getElementById("billCountrySelect").value;
	var bill_zip = document.getElementById("bill_zip").value;
	var ship_firstName = document.getElementById("ship_firstName").value;
	var ship_lastName = document.getElementById("ship_lastName").value;
	var ship_address = document.getElementById("ship_address").value;
	var ship_suite = document.getElementById("ship_suite").value;
	var ship_city = document.getElementById("ship_city").value;
	var ship_state = document.getElementById("shipStateSelect").value;
	var ship_country = document.getElementById("shipCountrySelect").value;
	var ship_zip = document.getElementById("ship_zip").value;
	
	var optin = document.getElementById("optin").value;
	var orderStatus = document.getElementById("orderStatus").value;
	
	var submit_type = document.getElementById("submit_type").value;
	
	sendstr = "step="+submit_type;
	sendstr += "&firstName="+firstName+"&lastName="+lastName+"&email="+email;
	sendstr += "&bill_address="+bill_address+"&bill_suite="+bill_suite+"&bill_city="+bill_city+"&bill_state="+bill_state+"&bill_zip="+bill_zip+"&bill_country="+bill_country;
	sendstr += "&ship_firstName="+ship_firstName+"&ship_lastName="+ship_lastName;
	sendstr += "&ship_address="+ship_address+"&ship_suite="+ship_suite+"&ship_city="+ship_city+"&ship_state="+ship_state+"&ship_zip="+ship_zip+"&ship_country="+ship_country;
	sendstr += "&optin="+optin+"&orderStatus="+orderStatus;

	sendinfoXMLHttpObj=getXMLHttpRequestObject();
	sendinfoXMLHttpObj.open("POST","includes/cart-checkout.php",true);
	sendinfoXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	sendinfoXMLHttpObj.send(sendstr);
	sendinfoXMLHttpObj.onreadystatechange=sendinfoStatusChecker;
	
	var container = document.getElementById('cart_container');
	//container.innerHTML = '<img src="images/loadingAnim.gif" height="20" width="20">';
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function sendinfoStatusChecker(){
    // check if request is completed
    if(sendinfoXMLHttpObj.readyState==4){
        if(sendinfoXMLHttpObj.status==200) updateSendInfoInline(sendinfoXMLHttpObj);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function updateSendInfoInline(reqObj) {
	var prev_tab = document.getElementById('step_2');
	var this_tab = document.getElementById('step_3');
	
	prev_tab.className = "cart_tab";
	this_tab.className = "cart_tab selected";
	
	sendstr = "step=3";
	checkoutXMLHttpObj=getXMLHttpRequestObject();
	checkoutXMLHttpObj.open("POST","includes/cart-checkout.php",true);
	checkoutXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	checkoutXMLHttpObj.send(sendstr);
	checkoutXMLHttpObj.onreadystatechange=checkoutStatusChecker;
	
	return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function setOption() {
	var option_sel = document.getElementById("options").selectedIndex;
	var option = document.getElementById("options").options[option_sel].value;
	if(option == "NONE") alert("Please choose an option");
	else $.post("includes/cart-option.php", { option: option });
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function calcGrandTotal(newship,obj) {
	grandTotal = parseFloat($("#productTotal").val()) + parseFloat($("#handle_fee").val()) + parseFloat($("#tax_charged").val()) + parseFloat(newship);
	$("#shipping_cost").val(newship);
	$("#grandTotal").val(grandTotal.toFixed(2));
	$("#shipping_type").val(obj.value);
	$("#grand_total_text").html("<h1>$"+grandTotal.toFixed(2)+"</h1>");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function checkShip() {
	if(parseInt($("#shipping_cost").val()) % 1 == 0) return true;
	else if($("#noship").val() == 'all') return true;
	else {
		alert("There is a problem with your shipping address. Please go back and correct");
		return false;
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function calcShipping(value,ship_zip,origin_zip,ship_country,weight,handle_fee) {
	var ship_cost = document.getElementById("ship_cost");
	ship_cost.innerHTML = '<img src="images/loadingAnim.gif">';
	sendstr = "value="+value+"&ship_zip="+ship_zip+"&origin_zip="+origin_zip+"&weight="+weight+"&ship_country="+ship_country+"&handle_fee="+handle_fee;
	calcshipXMLHttpObj=getXMLHttpRequestObject();
	calcshipXMLHttpObj.open("POST","includes/cart-calcship.php",true);
	calcshipXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	calcshipXMLHttpObj.send(sendstr);
	calcshipXMLHttpObj.onreadystatechange=calcshipStatusChecker; 
	
	return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function calcshipStatusChecker(){
    // check if request is completed
    if(calcshipXMLHttpObj.readyState==4){
        if(calcshipXMLHttpObj.status==200) calcshipInline(calcshipXMLHttpObj);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function calcshipInline(reqObj) {
	var response = reqObj.responseText;
	var starting1 = response.indexOf("|#=#|");
	var starting2 = response.indexOf("|##=##|");
	
	var quote = reqObj.responseText.substring(0, starting1);
	var total = reqObj.responseText.substring((starting1+5), starting2);
	var shipTotal = reqObj.responseText.substring((starting2+7), reqObj.responseText.length);
	
	var ship_cost = document.getElementById('ship_cost');
	if(document.getElementById('grand_total')) {
		var grand_total = document.getElementById('grand_total');
		var ship_total = document.getElementById('ship_total');
	} else var grand_total = document.getElementById('ship_total');
	var taxes = document.getElementById('taxes').value;
	
	ship_cost.innerHTML = quote;
	
	grandTotal = parseFloat(total)+parseFloat(taxes);
	grand_total.innerHTML = "<b>$"+roundNumber(grandTotal,2)+"</b>";
	
	if(ship_total) ship_total.innerHTML = "$"+roundNumber(shipTotal,2);
	
	document.getElementById('frm_total').value = roundNumber(grandTotal,2);
	document.getElementById('pp_total').value = roundNumber(grandTotal,2);
	
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function addDiscount() {
	var discount_code = document.getElementById("discount_code");
	if(discount_code.value != "" && discount_code.value != "Promo Code") {
		document.getElementById('discount_spin').innerHTML = '<img src="images/loadingAnim.gif">';
		sendstr = "discount_code="+discount_code.value;
		discountXMLHttpObj=getXMLHttpRequestObject();
		discountXMLHttpObj.open("POST","includes/cart-discount.php",true);
		discountXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		discountXMLHttpObj.send(sendstr);
		discountXMLHttpObj.onreadystatechange=discountStatusChecker; 
	} else alert("Please enter a proper Promo Code");
	
	return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function discountStatusChecker(){
    // check if request is completed
    if(discountXMLHttpObj.readyState==4){
        if(discountXMLHttpObj.status==200) discountInline(discountXMLHttpObj);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function discountInline(reqObj) {
	var response = reqObj.responseText;
	if(response == "fail") {
		alert("Please enter a proper Promo Code");
		document.getElementById('discount_spin').innerHTML = '<a href="javascript:void(0)" onclick="addDiscount()">Apply</a>';
	} else {
		setCheckout(3,3);
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function checkFinalStatus(us1,us2) {
	sendstr = "RESULT=0&USER2="+us2+"&USER1="+us1;
	finalXMLHttpObj=getXMLHttpRequestObject();
	finalXMLHttpObj.open("POST","includes/payflow_silent.php",true);
	finalXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	finalXMLHttpObj.send(sendstr);
	finalXMLHttpObj.onreadystatechange=finalStatusChecker; 
	return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
function finalStatusChecker(){
    // check if request is completed
    if(finalXMLHttpObj.readyState==4){
        if(finalXMLHttpObj.status==200) parent.document.location.href="http://pokerbrat.com/info/Payment-thanks";
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


/////////////////////////////////////////////////////////////////////////////////////////////////
function checkCartCheckoutForErrors(isupload) {
		var failed = false;
		
		if(document.getElementById("firstName").value == '') {
			document.getElementById("firstName_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("firstName_row").style.backgroundColor='transparent';
		
		if(document.getElementById("lastName").value == '') {
			document.getElementById("lastName_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("lastName_row").style.backgroundColor='transparent';
		
		if(document.getElementById("email").value == '') {
			document.getElementById("email_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("lastName_row").style.backgroundColor='transparent';
		
		if(document.getElementById("bill_address").value == '') {
			document.getElementById("bill_address_row").style.backgroundColor='#FFE5EA';
			failed = true;
		}  else document.getElementById("bill_address_row").style.backgroundColor='transparent';
		
		if(document.getElementById("bill_city").value == '') {
			document.getElementById("bill_city_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("bill_city_row").style.backgroundColor='transparent';
		
		//if(document.getElementById("billStateSelect").value == '') {
			//document.getElementById("bill_state_row").style.backgroundColor='#FFE5EA';
			//failed = true;
		//}  else document.getElementById("bill_state_row").style.backgroundColor='transparent';
		
		if(document.getElementById("billCountrySelect").value == '') {
			document.getElementById("bill_country_row").style.backgroundColor='#FFE5EA';
			failed = true;
		}  else document.getElementById("bill_country_row").style.backgroundColor='transparent';
		
		if(document.getElementById("bill_zip").value == '') {
			document.getElementById("bill_zip_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("bill_zip_row").style.backgroundColor='transparent';
		
		if(document.getElementById("ship_firstName").value == '') {
			document.getElementById("ship_firstName_row").style.backgroundColor='#FFE5EA';
			failed = true;
		}  else document.getElementById("ship_firstName_row").style.backgroundColor='transparent';
		
		if(document.getElementById("ship_lastName").value == '') {
			document.getElementById("ship_lastName_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("ship_lastName_row").style.backgroundColor='transparent';
		
		if(document.getElementById("ship_address").value == '') {
			document.getElementById("ship_address_row").style.backgroundColor='#FFE5EA';
			failed = true;
		}  else document.getElementById("ship_address_row").style.backgroundColor='transparent';
		
		if(document.getElementById("ship_city").value == '') {
			document.getElementById("ship_city_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("ship_city_row").style.backgroundColor='transparent';
		
		//if(document.getElementById("shipStateSelect").value == '') {
			//document.getElementById("ship_state_row").style.backgroundColor='#FFE5EA';
			//failed = true;
		//}  else document.getElementById("ship_state_row").style.backgroundColor='transparent';
		
		if(document.getElementById("shipCountrySelect").value == '') {
			document.getElementById("ship_country_row").style.backgroundColor='#FFE5EA';
			failed = true;
		}  else document.getElementById("ship_country_row").style.backgroundColor='transparent';
		
		if(document.getElementById("ship_zip").value == '') {
			document.getElementById("ship_zip_row").style.backgroundColor='#FFE5EA';
			failed = true;
		} else document.getElementById("ship_zip_row").style.backgroundColor='transparent';
		
		
		if(failed) {
			alert("Please fill in all required information!");
			
			return false;
		} else {
			return true;
		}
	}
	
	
	function runCheckCartSubmit() {
		if(checkCartCheckoutForErrors()) {
			setCheckout(2,3);
			return true;
		} else return false;
	}
	
	
	function checkShipForErrors() {
		var option_sel = document.getElementById("ship_type").selectedIndex;
		var option = document.getElementById("ship_type").options[option_sel].value;
		if(option == "") failed = true;
		else {
			var cost = document.getElementById("ship_cost").innerHTML;
			if(cost.indexOf("Cannot ship") >= 0) failed = true;
			else if(cost.indexOf("The requested service") >= 0) failed = true;
			else failed = false;
		}
		
		if(failed) {
			alert("Please choose a shipping method!");
			
			return true;
		} else {
			return false;
		}	
	}
	
	function runCheckShipSubmit(us1,us2) {
		
		if(checkShipForErrors()) {
			return false;
		} else {
			var grand_total = document.getElementById("grand_total").innerHTML
			console.log(grand_total+' / '+grand_total.indexOf("$0"));	
			if(grand_total.indexOf("$0") >=0 ) {
				checkFinalStatus(us1,us2);
				return false;
			} else return true;
		}
		
		
	}
	
	
	function runFinalSubmit(oid) {
		$.post("includes/checkout-paypal.php", { oid: oid });
	}

	
	function swapText(element,val,col,txtReplace,colReplace) {
		stripval = val;
		
		if(element.value == val) {
			if(txtReplace != '' && txtReplace != 'link') element.value = txtReplace;
			else element.value = "";
			element.style.color="#000";
			element.style.background="#ffffcc";
			//alert(element+' / '+val+' / '+col+' / '+txtReplace);
		} else if (element.value == "") {
			element.value = stripval;
			element.style.color=col;
			element.style.background="#ffffff";
			//
			if(element.value == "Title") element.style.color = "#999999";
			
		} else if(txtReplace == "link") {
			element.style.color="#333";
		} else {
			element.style.color="#333";
			element.style.background="#ffffff";
		}
	}


