get_vars();// placed here rather than onload it gets the full cart codes

function getXmlHttpRequestObject(){
  var xhr;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xhr = false;
      }
    }
  @else
  xhr = false;
  @end @*/
  if (!xhr && typeof XMLHttpRequest != 'undefined') {
    try {
      xhr = new XMLHttpRequest();
    } catch (e) {
      xhr = false;
    }
  }
  return xhr;
}

function getajax(page, mode, sendparams, do_on_return, no_cache){

	var verification = Math.floor(Math.random()*10000000+1);

	if(! no_cache == true)
	{
		page = (page.indexOf('?') == -1) ? page+'?verify='+verification : page+'&verify='+verification;
	}

    var xmlhttp = false;

    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    try {
        xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch (E) {
		xmlhttp = false;
		}
    }
    @end @*/

    if(!xmlhttp)
	{
		xmlhttp=new XMLHttpRequest();
	}

    xmlhttp.open(mode, page, true);
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4) { 

			eval(do_on_return+'(xmlhttp.responseText);');

		}
    }
xmlhttp.send(sendparams);
}

function get_vars() {

	var get_filename	= 'functions/returncode.php'; // The php file ajax will collect information from
	var get_method		= 'GET'; // use method get to retrieve the information
	var post_params		= null;
	var return_function	= 'process_get_vars'; // function to run when information is retrieved

	getajax(get_filename, get_method, post_params, return_function);

}

// All the global variables
var valid_code, amount, is_percent, code_return, code_uses, restrict_use, final_count;
var is_restricted, code_uses, is_used, inArray, is_reusable, full_discount, is_shipping, ship_free, apply_item;
var com_code, com_code2, com_dis_amt, com_des; // Comment Variables
var pre_code = new Array();
var restricted_codes = new Array();
// Array of all the buy one get one free codes
var free_array = new Array("B1G1F","B2G1F","B3G1F","B4G1F","B5G1F","B6G1F","B7G1F","B8G1F","B9G1F","B10G1F","B1G2F","B2G2F","B3G2F","B4G2F","B5G2F","B6G2F","B7G2F","B8G2F","B9G2F","B10G2F");
function process_get_vars(response) {
	
	// Process the information received from the ajax script
	var variables_arr = response.split(','); // split the returned variable by ,
	var saved_code = variables_arr[0]; // This is a code that was saved for use on all items in cart
	if( variables_arr.length >=2 ){
		restricted_codes = variables_arr[1].split('-');// all codes found are restricted and have been entered
	}
	var get_obj = getXmlHttpRequestObject();
	get_obj.open('POST', 'functions/checkcode.php', true);
	get_obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	get_obj.onreadystatechange = function()	{
		if(get_obj.readyState == 4)	{
			var resp = get_obj.responseText;
			if(resp.charAt(0) == 0){
				// There was no responce from the ajax script
				valid_code = 0; // no valid code entry
			}
			else
			{ 
				valid_code = 1; // Code was valid
				code_uses = 0;
				var resp	= eval( '(' + resp + ')' );
				amount		= resp.coupon[0].amount; // amount the code is worth
				is_percent	= resp.coupon[0].is_percent; // true false is the code a percent
				code_return = resp.coupon[0].code_return; // returns the code entered
				is_reusable = resp.coupon[0].is_reusable; // returns if code is reusable
				
				// check if there are multiple forms if so exit script
				find_forms();
				if (final_count>1){
					return false;
				}
				
				var amt = document.pp_form.baseamt.value; // value of base amount in button
				if( resp.coupon[0].is_reusable == true ){
					// the code is reusable for all items
					if (is_percent == false){
						var full_discount=amount; // amount the discount is for
					}

					else {
						var full_discount= (amt*(amount/100)); // amount the discount is for
					}					
				}
				else{
					// the code is not reusable
					if (is_percent == false){
						var full_discount=amount;// amount the discount is for
					}
					else {
						var full_discount= (amt*(amount/100));// amount the discount is for
					}	
				}
				pre_code = new Array(code_return,full_discount,is_percent,amount,is_reusable); // set the previously used code;
			}
		}
	}
	var post_params = 'coupon=' + saved_code;
	
	get_obj.send(post_params);

}

function check_coupon(){
	if (!document.getElementById('discount').value){ 
	 	// code input was left empty do not return and alert to fill in box
		demon_show(10,0,0,0,0,0,0,0);
		return false;
	}
	if (document.getElementById('discount').value==code_return){
		// code input was the same as the previously entered code / do not return and alert of mistake
		demon_show(11,0,0,0,0,0,0,0);
		return false;
	}
	isValueInArray(restricted_codes, document.getElementById('discount').value);// Check if value of code entered is in the restricted_codes array
	if(inArray==true){
		var com_code = document.getElementById('discount').value; // value entered into coupon form
		demon_show(9,0,com_code,0,0,0,0,0);
		return false;
	}
	find_forms();
	if (final_count==0){
		demon_show(14,0,0,0,0,0,0,0);
		return false;
	}
	var get_obj = getXmlHttpRequestObject();
	get_obj.open('POST', 'functions/checkcode.php', true);
	get_obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	get_obj.onreadystatechange = function(){
		if(get_obj.readyState == 4){
			var resp = get_obj.responseText;
			if(resp.charAt(0) == 0){
				valid_code = 0;
				demon_show(0,0,0,0,0,0,0,0);
				return false;
			}
			else{
				valid_code = 1; // The code is valid and apply the following information
				code_uses = 0; // set the number of code uses to 0
				var resp	  = eval( '(' + resp + ')' );
				amount		  = resp.coupon[0].amount; // the amount the discount is worth
				is_percent	  = resp.coupon[0].is_percent; // true false whether the discount is a percent
				code_return   = resp.coupon[0].code_return;	// returns the code that was entered
				is_restricted = resp.coupon[0].is_restricted; // true false is the code restricted
				is_used       = resp.coupon[0].is_used; // true false was the code used if restricted
				is_reusable   = resp.coupon[0].is_reusable; // true false is the coupon reusable for cart
				apply_item    = resp.coupon[0].apply_item; // items this code applies to
				is_shipping	  = resp.coupon[0].is_shipping;
				var coupon_code = document.getElementById('discount').value; // value entered into coupon form
				com_code = coupon_code;
				com_dis_amt = amount;
				com_des = des;
				if(final_count > "1"){	// check whether there are more than one product button
					isValueInArray(free_array, code_return);// check if code_return is in the free coupon array
					if (inArray==true && amount==0){
						var remove1 = code_return.replace("B",""); // Remove the B from the code
						var remove2 = remove1.replace("F",""); // remove the F from the code
						var num_vars = remove2.split('G'); // Split the buy and get by G
						var com_buy = num_vars[0];// Number of items the customer must buy to get free items
						var com_get = num_vars[1];// Number of free items
						if (com_buy ==1 && com_get==1){
							demon_show(12,1,com_code,0,0,0,com_buy,com_get);
						}
						else{
							demon_show(18,1,com_code,0,0,0,com_buy,com_get);
						}
						return false;
					}
					else{

						com_code = coupon_code;
						com_dis_amt = amount;
						if( resp.coupon[0].is_reusable == true ){
							if (is_percent == false){
								demon_show(5,1,com_code,com_dis_amt,0,com_code2,0,0);
								full_discount=amount;
							}
							else {
								demon_show(6,1,com_code,com_dis_amt,0,com_code2,0,0);
								full_discount= (amt*(amount/100));
							}					
						}
						else{
							if (is_percent == false){
								demon_show(16,1,com_code,com_dis_amt,0,0,0,0);
								full_discount=amount;
							}
							else {
								demon_show(17,1,com_code,com_dis_amt,0,0,0,0);
								full_discount= (amt*(amount/100));
							}	
						}
						pre_code = new Array(code_return,full_discount,is_percent,amount,is_reusable);
						document.getElementById('discount').value = "";
						return false;						
					}
				}
				
				var des = document.pp_form1.basedes.value; // Base discription of product
				var amt = document.pp_form1.baseamt.value; // Base amount of product
								
				if(apply_item!=""){
					var item_array = apply_item.split(',');
					var search_item = document.getElementById('demon_item').value;
					isValueInArray(item_array, search_item);
				}				
				if(apply_item!="" && inArray==false ){
					// Code is valid but does not apply to this product
					valid_code = 0;
					demon_show(13,0,com_code,0,0,0,0,0);
					return false;
				}
				
				if(is_used == true){
					// Code is restricted and has been used by this person before
					valid_code = 0;
					demon_show(9,0,com_code,0,0,0,0,0);
					return false;
				}
							
				isValueInArray(free_array, code_return);// check if code_return is in the free coupon array
				
				if (inArray==true && amount==0){
					var remove1 = code_return.replace("B",""); // Remove the B from the code
						var remove2 = remove1.replace("F",""); // remove the F from the code
						var num_vars = remove2.split('G'); // Split the buy and get by G
						var com_buy = num_vars[0];// Number of items the customer must buy to get free items
						var com_get = num_vars[1];// Number of free items
						if (com_buy ==1 && com_get==1){
							demon_show(12,1,com_code,0,0,0,com_buy,com_get);
						}
						else{
							demon_show(18,1,com_code,0,0,0,com_buy,com_get);
						}
						return false;
				}
				else{
					if( pre_code.length==5){
						var code2 = pre_code[0];
						com_code2 = code2;
						var pre_ful = pre_code[1];
						var pre_per = pre_code[2];
						var pre_amt = pre_code[3];
						var pre_reu = pre_code[4];
						if(is_percent==false){
							var new_discount=amt;
						}
						else{
							var new_discount=(amt*(amt/100))
						}
						if (new_discount < pre_ful){
							if( pre_reu == true ){
								if(pre_per==false){// check if it is percent
									com_dis_amt=pre_amt;
									demon_show(3,1,com_code,com_dis_amt,0,com_code2,0,0);
								}
								else{
									com_dis_amt=pre_amt;
									demon_show(4,1,com_code,com_dis_amt,0,com_code2,0,0);
								}
							}
							else{
								if(pre_per==false){// check if it is percent
									com_dis_amt=pre_amt;
									demon_show(1,1,com_code,com_dis_amt,0,com_code2,0,0);
								}
								else{
									com_dis_amt=pre_amt;
									demon_show(2,1,com_code,com_dis_amt,0,com_code2,0,0);
								}
							}
							process_get_vars(code2);
							document.getElementById('discount').value = "";
						}
						else{
							if( resp.coupon[0].is_reusable == true ){
								if (is_percent == false){
									demon_show(5,1,com_code,com_dis_amt,0,com_code2,0,0);
									full_discount=amount;
								}
								else {
									demon_show(6,1,com_code,com_dis_amt,0,com_code2,0,0);
									full_discount= (amt*(amount/100));
								}					
							}
							else{
								if (is_percent == false){
									demon_show(7,1,com_code,com_dis_amt,0,com_code2,0,0);
									full_discount=amount;
								}
								else {
									demon_show(8,1,com_code,com_dis_amt,0,com_code2,0,0);
									full_discount= (amt*(amount/100));
								}	
							}
							pre_code = new Array(code_return,full_discount,is_percent,amount,is_reusable);
							document.getElementById('discount').value = "";
						}
					}
					else{
						if( resp.coupon[0].is_reusable == true ){
							if (is_percent == false){
								demon_show(5,1,com_code,com_dis_amt,0,0,0,0);
								full_discount=amount;
							}
							else {
								demon_show(6,1,com_code,com_dis_amt,0,0,0,0);
								full_discount= (amt*(amount/100));
							}					
						}
						else{
							if (is_percent == false){
								demon_show(7,1,com_code,com_dis_amt,0,0,0,0);
								full_discount=amount;
							}
							else {
								demon_show(8,1,com_code,com_dis_amt,0,0,0,0);
								full_discount= (amt*(amount/100));
							}	
						}
						pre_code = new Array(code_return,full_discount,is_percent,amount,is_reusable);
						document.getElementById('discount').value = "";
					}
				}
			}
		}
	}
	var post_params = 'coupon=' + document.getElementById('discount').value;
	post_params += '&item=' + document.getElementById('demon_item').value;
	get_obj.send(post_params);
}

function ReadForm(obj1) {  // apply the discount and values to main form if discount is enabled
		if(apply_item){
			if(apply_item && apply_item!= '' || apply_item!= '0' || apply_item!= ',0,'){
				var check_comma=apply_item.indexOf(',');
				if (check_comma>0){
					item_array = cur_item.split(',');
				}
				else{
					item_array = new Array('',apply_item);
				}
				isValueInArray(item_array, obj1.item_number.value);// Check if item_number is in apply_item array
				if(inArray==true){}
				else{ valid_code = '0'; }
			}
		}
		if(obj1.multi.value=='1'){// checks if the cart uses multiple prices
			var data_array = obj1.os0.value.split('^');
			if(data_array.length == 1){
				var des=obj1.basedes.value;//set description
				var amt=obj1.baseamt.value;//set discount amount
				var selectBox = obj1.os0;// set option box name
				var selectedItem = selectBox[selectBox.selectedIndex];// select the selected option
				selectedItem.value=data_array[1];//set the value of the option selected
				var amt = selectedItem.value;
				selectedItem.value=data_array[0]+'^'+data_array[1];
			}
			else{
				var des=obj1.basedes.value;// set description
				var amt=data_array[1];// set discount amount
				var selectBox = obj1.os0;// set option box name
				var selectedItem = selectBox[selectBox.selectedIndex];// select the selected option
				selectedItem.value=data_array[1];//set the value of the option selected
				var amt = selectedItem.value;
				selectedItem.value=data_array[0]+'^'+data_array[1];
			}	
		}
		else{
			var amt = obj1.baseamt.value; // base amount
			var des = obj1.basedes.value; // base description
		}
		if (is_restricted == true && code_uses == true){
			valid_code = '0';
			alert('is restricted or code_uses');
		}
		if (valid_code > '0'){ // Checks if code is valid
			if (is_percent == true){
				var amt_off = (amount / 100) * amt;
				amt = amt - amt_off;
				amt = amt.toFixed(2);
				
				var code_replace = code_return;
				des = des + "," + amount + "% off,Code=" + code_replace;
			}
			else {
				amt = amt - amount;
				amt = amt.toFixed(2);
				
				var code_replace = code_return;
				des = des + ",$" + amount + " off,Code=" + code_replace;
			}
			code_uses=code_uses+1;
		}
		obj1.amount.value = amt;
		obj1.item_name.value = des;
}

// Code checks if someone hit enter to submit the coupon form
function testForEnter(e){
	check_coupon();
	return false;
}

// Checks if passed var is in passed array
function isValueInArray(arr, val) {
	inArray = false;
	for (i = 0; i < arr.length; i++){
		if (val == arr[i]){
			inArray = true;
		}
	}
	return inArray;
}

// relocates the popup when someone scrolls the page
function myPopupRelocate() {
 var scrolledX, scrolledY;
 if( self.pageYOffset ) {
   scrolledX = self.pageXOffset;
   scrolledY = self.pageYOffset;
 } else if( document.documentElement && document.documentElement.scrollTop ) {
   scrolledX = document.documentElement.scrollLeft;
   scrolledY = document.documentElement.scrollTop;
 } else if( document.body ) {
   scrolledX = document.body.scrollLeft;
   scrolledY = document.body.scrollTop;
 }

 var centerX, centerY;
 if( self.innerHeight ) {
   centerX = self.innerWidth;
   centerY = self.innerHeight;
 } else if( document.documentElement && document.documentElement.clientHeight ) {
   centerX = document.documentElement.clientWidth;
   centerY = document.documentElement.clientHeight;
 } else if( document.body ) {
   centerX = document.body.clientWidth;
   centerY = document.body.clientHeight;
 }

 var leftOffset = scrolledX + (centerX - 250) / 2-50;
 var topOffset = scrolledY + (centerY - 200) / 2-50;

 document.getElementById("demon_alert").style.top = topOffset + "px";
 document.getElementById("demon_alert").style.left = leftOffset + "px";
}

// Displays the dhtml popup and fills in the data
function demon_show(x,y,com_code,com_dis_amt,com_des,com_code2,com_buy,com_get){ //x=image y=comment
	
	myPopupRelocate();
	document.getElementById("demon_alert").style.display = "block";
	document.body.onscroll = myPopupRelocate;
	window.onscroll = myPopupRelocate;
	document.body.style.overflow="hidden";
	
	// create the title and include the stupid X button for those who wont click ok
	document.getElementById('demon_title_enclosure').innerHTML = com_header+com_headx;
	// display the correct comment
	document.getElementById('demon_message').innerHTML = eval(d_com[x]);
	// display close button
	document.getElementById('demon_buttons').innerHTML = com_buttons;
	// display image
	if(y==true){
		document.getElementById('demon_image').style.backgroundImage = com_info;
	}
	else{
		document.getElementById('demon_image').style.backgroundImage = com_error;
	}
}

// Hide the alert box
function demon_hide(){
	var y = document.getElementById( 'demon_alert' );
	y.style.display = '';
	document.body.style.overflow="auto";
}

// Detects how many forms are on a single page.
function find_forms(){
	var i=1;
	while(i<900){
		var form = "pp_form"+i;
		var check= typeof document.forms[form] != 'undefined';
		if (check==false){
			final_count=i-1;
			i=900;
		}
		else{i++;}
	}
}