/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

var xmlhttp = new sack();
var xmlhttployalty = new sack();
var xmlhttpcost = new sack();

var is_valid = 0;		
	
function redeem()
{
	var couponcode = document.getElementById('coupon_code').value;
	if(couponcode.length>1){
		
		xmlhttp.requestFile = 'checkcode.php?couponcode='+couponcode;	// Specifying which file to get
		xmlhttp.onLoading = showLoad;
		xmlhttp.onCompletion = showClientData;	// Specify function that will be executed after file has been found
		xmlhttp.runAJAX();		// Execute AJAX function			
	}
	
}

function showLoad()
{	
	document.getElementById("couponvalid").innerHTML = "<img src='ajax-loader.gif' width='16' height='16' border='0' />";
}

function showClientData()
{
	/*eval(xmlhttp.response);*/
	var xmlDoc=xmlhttp.responseXML.documentElement;
	is_valid = xmlDoc.getElementsByTagName("is_valid")[0].childNodes[0].nodeValue;
	
	if(is_valid == 0)
	{
		document.getElementById("couponvalid").innerHTML = "Invalid Coupon Code";
		document.getElementById("coupon_id").value =  "";
		document.getElementById("coupon_amount").value =  "";
		document.getElementById("coupon_type").value =  "";
		//document.getElementById("expiry_date").innerHTML =  "";
		document.getElementById("coupontotal").innerHTML = "";	
		document.getElementById("couponlabel").style.display = 'none';
	}
	else
	{	  
		document.getElementById("couponvalid").innerHTML = "";
		document.getElementById("coupontotal").innerHTML = xmlDoc.getElementsByTagName("coupon_total")[0].childNodes[0].nodeValue;
		document.getElementById("coupon_amount").value =  xmlDoc.getElementsByTagName("coupon_amount")[0].childNodes[0].nodeValue;
		document.getElementById("coupon_type").value =  xmlDoc.getElementsByTagName("coupon_type")[0].childNodes[0].nodeValue;
		//document.getElementById("expiry_date").innerHTML =  xmlDoc.getElementsByTagName("expiry_date")[0].childNodes[0].nodeValue;
		document.getElementById("coupon_id").value =   xmlDoc.getElementsByTagName("coupon_id")[0].childNodes[0].nodeValue;		
		document.getElementById("couponlabel").style.display = 'block';
	}
	calcAmount();
}

function counterUpdate(opt_countedTextBox, opt_countBody, opt_maxSize) {
	var countedTextBox = opt_countedTextBox ? opt_countedTextBox : "counttxt";
	var countBody = opt_countBody ? opt_countBody : "countBody";
	var maxSize = opt_maxSize ? opt_maxSize : 1024;
	var replaceWith = ' ';

	var field = document.getElementById(countedTextBox);

	if (field && field.value.length >= maxSize) {
			field.value = field.value.substring(0, maxSize);
	}
	var txtField = document.getElementById(countBody);
			if (txtField) { 
			txtField.innerHTML = field.value.length;
	}
	
	
	strMultiLineText = escape(field.value);

	//replace new lines with space
	for(i=0; i<strMultiLineText.length; i++){
		if(strMultiLineText.indexOf("%0D%0A") > -1){
			
			strMultiLineText=strMultiLineText.replace("%0D%0A",replaceWith);
			field.value=unescape(strMultiLineText);
		}
		else if(strMultiLineText.indexOf("%0A") > -1){		
			strMultiLineText=strMultiLineText.replace("%0A",replaceWith);
			field.value=unescape(strMultiLineText); 
		}
		else if(field.value.indexOf("%0D") > -1){		
			strMultiLineText=strMultiLineText.replace("%0D",replaceWith);
			field.value=unescape(strMultiLineText); 
		}
	
	}

}

	
function checkemail(oid)
{
		
	var email = document.getElementById('email').value;
	 if(!echeck(email))
	 	return;
	
	if(email.length>1){
		document.getElementById("loyaltymsg").style.visibility = 'hidden';
		xmlhttployalty.requestFile = 'getloyalty.php?email='+email+'&oid='+oid;	// Specifying which file to get
		xmlhttployalty.onLoading = showLoadLoyalty;
		xmlhttployalty.onCompletion = showLoyaltyData;	// Specify function that will be executed after file has been found
		xmlhttployalty.runAJAX();		// Execute AJAX function			
	}
	
}

function showLoadLoyalty()
{	
	document.getElementById("loyaltyprogress").innerHTML = "<img src='ajax-loader.gif' width='16' height='16' border='0' />";
}

function showLoyaltyData()
{
	
	var xmlDoc=xmlhttployalty.responseXML.documentElement;
	var count_number = xmlDoc.getElementsByTagName("count_number")[0].childNodes[0].nodeValue;
	var description = xmlDoc.getElementsByTagName("description")[0].childNodes[0].nodeValue;
	var count_left = xmlDoc.getElementsByTagName("count_left")[0].childNodes[0].nodeValue;
	var limit_date = xmlDoc.getElementsByTagName("limit_date")[0].childNodes[0].nodeValue;
	var valid_product = xmlDoc.getElementsByTagName("valid_product")[0].childNodes[0].nodeValue;
	
	document.getElementById("loyaltymsg").style.visibility = 'visible';
	
	if(valid_product == 1)
	{		
		document.getElementById("loyaltymsg").innerHTML = '<div class="rbroundbox"><div class="rbtop"><div></div></div><div class="rbcontent"><div style="font-size:14px;">You only have <span style="color:#ff0000;">'+ count_left +'</span> orders to go to get your free gift.</div>' + description+'</div><div class="rbbot"><div></div></div></div>';
	}
	else
	{
		document.getElementById("loyaltymsg").innerHTML = '<div class="rbroundbox"><div class="rbtop"><div></div></div><div class="rbcontent"><div style="font-size:14px;">Due to the nature of this product it does not qualify for the special Zelcovia Cookies Reward Program<br /></div></div><div class="rbbot"><div></div></div></div>';
	}
	document.getElementById("loyaltyprogress").innerHTML = "";
}


function postcode_lookup(out_of_town)
{
		
	var postcode = document.getElementById('postcode').value;
	 
	if(postcode.length>2){
		document.getElementById("postcost_msg").style.visibility = 'hidden';
		xmlhttpcost.requestFile = 'getpostcost.php?postcode='+postcode+'&out_of_town='+out_of_town;// Specifying which file to get
		xmlhttpcost.onLoading = showLoadPostCost;
		xmlhttpcost.onCompletion = showPostCostData;	// Specify function that will be executed after file has been found
		xmlhttpcost.runAJAX();		// Execute AJAX function			
	}
	
}

function showLoadPostCost()
{	
	document.getElementById("postcost_progress").innerHTML = "<img src='ajax-loader.gif' width='16' height='16' border='0' />";
}

function showPostCostData()
{
	
	var xmlDoc=xmlhttpcost.responseXML.documentElement;
	var lstart = xmlDoc.getElementsByTagName("lstart")[0].childNodes[0].nodeValue;
	var matched = xmlDoc.getElementsByTagName("matched")[0].childNodes[0].nodeValue;
	var pcost = xmlDoc.getElementsByTagName("pcost")[0].childNodes[0].nodeValue;
	var cityname = xmlDoc.getElementsByTagName("cityname")[0].childNodes[0].nodeValue;
	var out_of_town = xmlDoc.getElementsByTagName("out_of_town")[0].childNodes[0].nodeValue;
	
	
	document.getElementById("postcost_msg").style.visibility = 'visible';
	
	if(lstart == 1 && matched == 0)
	{		
		document.getElementById("postcost_msg").innerHTML = '<div class="rbroundbox"><div class="rbtop"><div></div></div><div class="rbcontent"><div style="font-size:14px;">We\'re Sorry! For some reason your postal code could not be properly validated in our system for your delivery zone. Please call use to confirm at 647-438-7772</div></div><div class="rbbot"><div></div></div></div>';
	}
	else if(lstart == 0 && out_of_town == 1 && matched == 0)
	{
		document.getElementById("postcost_msg").innerHTML = '<div class="rbroundbox"><div class="rbtop"><div></div></div><div class="rbcontent"><div style="font-size:14px;">You have entered in an out of town delivery postal code which is not within one of the zones for delivery. The order form may switch automatically to show the proper form for out of town orders.<br /></div></div><div class="rbbot"><div></div></div></div>';
	}
	else if(lstart == 0 && out_of_town == 0 && matched == 0)
	{
		document.getElementById("postcost_msg").innerHTML = '<div class="rbroundbox"><div class="rbtop"><div></div></div><div class="rbcontent"><div style="font-size:14px;">As your postal code is not within the zone for in-town delivery you are not able to order this product. If you would like see products that are available to be sent anywhere in Canada other than the areas listed above, please select from CookiegramZ, Long Stem Bouquets, Gift Boxes and Gift Boxes - Mini.<br /></div></div><div class="rbbot"><div></div></div></div>';
	}
	else if(matched == 1)
	{
			document.getElementById("postcost_msg").innerHTML = '<div class="rbroundbox"><div class="rbtop"><div></div></div><div class="rbcontent"><div style="font-size:14px;">You are in  '+cityname+' and the cost for delivery would be $'+pcost+'<br /></div></div><div class="rbbot"><div></div></div></div>';
	}
	
	document.getElementById("postcost_progress").innerHTML = "";
}



function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
	}

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
 }
