// Ajax Document
function Ajax(){
	this.systemRootUrl = 'http://www.rt.luggagegear.com.au/';
	this.req = null;
	this.url = null;
	this.method = 'GET';
	this.async = true;
	this.status = null;
	this.statusText = '';
	this.postData = null;
	this.readyState = null;
	this.responseText = null;
	this.responseXML = null;
	this.handleResp = null;
	this.responseFormate = 'text'; //'test','xml',or'object'
	this.mimeType = null;
	this.thisWin=null;
	
	this.init = function(){	
		if(!this.req){
			try{
				//try to create obj for firefox, safari ie7 etc...
				//alert('1');
				this.req = new XMLHttpRequest();
			}
			catch (e) {
				try {
					//Try to create obj for later versions of ie
					//alert('2');
					this.req = new ActiveXObject('MSXML2.XMLHTTP');
				}
				catch (e) {
					try {
						//try to create for earlier versions of ie
						//alert('3');
						this.req = new ActiveXObject('Microsoft.XMLHTTP');
					}
					catch (e) {
						// Could not create the XMLHttpRequest object
						return false;
					}
				}
			}
		}
		return this.req;
	};
	this.setMimeType = function(mimeType){
		this.mimeType = mimeType;
	};
	this.doReq = function(){
		
		if(!this.init()) {
			alert('Could not create XMLHttpRequest Object.');
			return;			
		}
		this.req.open(this.method,this.url, this.async);  
		if(this.method == 'POST'){
				this.req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		}
		// set mimetype override if ie 7 +
		if (this.mimeType){
			try{
				req.overrideMimeType(this.mimeType);
			}
			catch (e) {
				// could not override - ie6 or opera
			}
		};
		// handle the error object
		this.handleErr = function() {
			var errorWin;
			try {
				errorWin = window.open('','errorWin');
				errorWin.document.body.innerHTML = this.responseText;
			}
			catch (e) {
				alert ('An error occured. \n'
					   +'Status Code: '+ this.req.status + '\n'
					   +'Status Description: '+this.req.statusText);
			}
		};		

		//Hande onReadyStateChange Event
		var self = this; //Fix loss of scope in inner function
		this.req.onreadystatechange = function(){
			var resp = null;
			switch (self.req.readyState) {
				case 1: break;
				case 2: break;
				case 3: break;
				case 4: switch (self.responseFormat){
							case 'text':	
								resp = self.req.responseText;
								break;
							case 'xml':		
								resp = self.req.responseXML;
								break;
							case 'object':
								resp = req;
								break;
						}
						
						if (self.req.status >= 200 && self.req.status <= 299) {
							self.handleResp(resp);
						}else{
							self.handleErr(resp);
						}
						break;
				default:alert('ReadyState - uninitialise');
			}
		}
		//Sending Request
		this.req.send(this.postData);
	};
	//abort the request
	this.abort = function() {
		if(this.req){
			this.req.onreadystatechange = function(){}
			this.req.abort();
			this.req = null;
		}
	};
	this.doGet = function(url, hand, format){
		this.url = url;
		this.handleResp = hand;
		this.responseFormat = format || 'text';
		this.doReq();
	};
	this.doPost = function(url, postData, hand, format){
		this.url = url;
		this.handleResp = hand;
		this.responseFormat = format || 'text';
		this.method= 'POST';
		this.postData = postData;
		this.doReq();		
	};
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   CART     FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.handleCartRefresh = function (str){
		alert(str);
		if(top.document.getElementById('layout_cartview')){this.refreshCart();}//top.document.getElementById('layout_cartview').innerHTML = str;}
	};
	this.handleRefreshCart = function (str){
		if(top.document.getElementById('layout_cartview')){top.document.getElementById('layout_cartview').innerHTML = str;}
	};
	this.refreshCart = function() {
		top.document.getElementById('layout_cartview').innerHTML = '... refreshing.<img src="'+this.refineUrl('images/indicator.gif')+'" width="16" height="16" />';
		var url = this.rootUrl+this.version+'/action/cart_refresh.php';
		this.doGet(url,this.handleRefreshCart);
	};
	this.killCart = function(){
		var url = this.rootUrl+'inc/v1_addItem.php?action=kill';
		this.doGet(url,this.handleCartRefresh);
	}

	this.removeItem = function(index,clear){
		//var url = this.rootUrl+'inc/v1_addItem.php?i='+index+'&action=del';
		var url = this.rootUrl+this.version+'/action/cart_addItem.php?action=del&i='+index;
		if(clear)url+='&clear=true';
		this.doGet(url,refreshPage);
	}
	this.amendItem = function(index,field,value){
		var url = this.rootUrl+this.version+'/action/cart_addItem.php?action=amd&i='+index+'&f='+field+'&v='+value;
		this.doGet(url,refreshPage);
	}

	this.validateItem = function(e){
	if(isNaN(e.getAttribute('prdID'))){alert('Invalid Product ID.');return false;}
	if(Number(e.getAttribute('qty'))<1){alert('Invalid Quantity.');return false;}
	if(e.getAttribute('prdColour')=='-'){alert('Invalid Colour Selection.');return false;}
	if(e.getAttribute('prdSize')=='-'){alert('Invalid Size Selection.');return false;}
	return true;
}

 	this.addItem_v2 = function(e){
		var ok = false;
		var bo = '';
		var stock = '';
		
		if(this.validateItem_v2(e)){
		
		switch(Number(e.getAttribute('prdAlertFlag'))){
			case 1: ok = confirm("Item NOT available until "+this.fdate(e.getAttribute('prdStockFrom'))+"\n\nPlease confirm if you wish to proceed with a BACKORDER purchase?");
					stock = '&stk='+e.getAttribute('prdStockFrom');
					break;
			case 0: ok = true;break;
		}
		if(ok){
			
				if(!e.getAttribute('prdColour')){e.setAttribute('prdColour','');}
				if(!e.getAttribute('prdSize')){e.setAttribute('prdSize','');}
				var url = this.rootUrl+this.version+'/action/cart_addItem.php?action=add&prdOID='+e.getAttribute('prdOID')
																			 //+'&c='+e.getAttribute('prdColour')
																			 //+'&s='+e.getAttribute('prdSize')
																			 //+'&q='+e.getAttribute('qty')
																			 +'&q='+document.getElementById(e.id.replace('addToCart','prdQty')).value
																			 +stock
																			 //+'&cd='+e.getAttribute('prdCode')
																			 //+'&cp='+e.getAttribute('prdCost')
																			 +'&sp='+e.getAttribute('prdSellPrice');
				this.doGet(url,this.handleCartRefresh);
			}
	}
}
	this.validateItem_v2 = function(e){
	if(isNaN(e.getAttribute('prdOID'))){alert('Invalid Product ID.');return false;}
	if(Number(e.getAttribute('qty'))<1){alert('Invalid Quantity.');return false;}
	if(e.getAttribute('prdColour')==null){alert('Invalid Colour Selection.');return false;}
	if(e.getAttribute('prdSize')==null){alert('Invalid Size Selection.');return false;}
	return true;
}

 
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   ORDER     FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	
	this.createOrder = function(){
		var url = this.rootUrl+this.version+'/action/order_create.php';
		this.doGet(url,responseOrderCreate);
	}
	this.customerCancelOrder = function(oid){
		if(confirm('Are you sure you want to CANCEL this order?')){
				var url = this.rootUrl+this.version+'/action/order_cancel.php?oID='+oid;
				this.doGet(url, responseOrderCancellation);	
		}
	}	
	this.launchOrder = function(oID){
		var url = this.rootUrl+'orders/orderPrint.php?oID='+oID;
		this.launchPop(url,690,700,3,'win');
	}
	// log into view order page
 	this.loginOrder = function(){
	
		var oid = document.getElementById('oID').value;
		var eml = document.getElementById('_email').value;
		//alert('Loging in with '+oid+' : '+eml);
		if((oid>0)&&(this.validEmail(eml))){
			var url = this.rootUrl+'inc/v1_action.php?execute=4&o='+oid+'&e='+eml;
			this.doGet(url, this.responseOrderLogin);
		}else{
			alert('Please ensure that your Order Id number is entered\nas well as your registered email address at the time of placing the order.')
		}
	}

 	this.responseOrderLogin = function(str){
		if(str){
			location.href="order_view.php?oID="+str;
		}else{
			alert('Invalid Order Number and Email combination.\nPlease contact administration for access.');
		}
	}
	
	this.order_requestPayPal = function( oID ){
		url = this.rootUrl+this.version+"/action/order_requestPayPal?a=pp&oID="+oID;
		//alert(url);
		this.doGet( url, this.doNothing );
	}
	
		
	this.doNothing = function(str){
		return false;
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   FIND CUSTOMER          /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.findCustomer = function(str) {
		str = str.replace(/^\s+|\s+$/g, '')
		if(str+''!=''){
			document.getElementById('findDisplay').className = 'show';
			document.getElementById('findDisplay').innerHTML = '<img src="'+this.refineSystemUrl('images/indicator.gif')+'" width="16" height="16" />searching...';
			var url = this.rootUrl+this.version+'/action/get_customer.php?str='+str;
			
			this.doGet(url,foundCustomer);
		}
	};

////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   LOCALITY   FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.findLocality = function(str) {
		str = str.replace(/^\s+|\s+$/g, '')
		if(str+''!=''){
			document.getElementById('locDisplay').className = 'show';
			document.getElementById('locDisplay').innerHTML = '<img src="'+this.refineSystemUrl('images/indicator.gif')+'" width="16" height="16" />searching...';
			var url = (this.rootUrl+this.version+'/action/get_locality.php?str='+str);
			this.doGet(url,this.displayLocality);
		}
	};

	this.displayLocality = function(str){
		document.getElementById('locDisplay').className = 'show';
		document.getElementById('locDisplay').innerHTML = str;
		
	};
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   URL FIXING FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.root = function(){
		//var root = 'http://natsys.com.au/v3/';
		var root = this.rootUrl;
		return root;
	}
	this.systemRoot = function(){
		//var root = 'http://natsys.com.au/v3/';
		var root = this.systemRootUrl;
		return root;
	}
	
	this.cacheBloc = function() {
		var t = new Date();
		var bc = 'bc='+t.getTime();
		return bc;
	}
	this.refineUrl = function(url){
		var argSplitIndex = url.indexOf('?');	
		var target = url;
		var argString = '';
		if(argSplitIndex>0){
			target = url.substring(0,argSplitIndex);
			argString = url.substring(argSplitIndex+1);
			if( argString.length  > 0){argString = argString+'&'+this.cacheBloc();	
			}else{argString = this.cacheBloc();}
		}else{
			argString = this.cacheBloc();	
		}
		url = this.root()+target+'?'+argString;
		return url;
	}
	this.refineSystemUrl = function(url){
		var argSplitIndex = url.indexOf('?');	
		var target = url;
		var argString = '';
		if(argSplitIndex>0){
			target = url.substring(0,argSplitIndex);
			argString = url.substring(argSplitIndex+1);
			if( argString.length  > 0){argString = argString+'&'+this.cacheBloc();	
			}else{argString = this.cacheBloc();}
		}else{
			argString = this.cacheBloc();	
		}
		url = this.systemRoot()+target+'?'+argString;
		return url;
	}	
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   LAUNCH POP FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.toggleContentFrame = function(e){
		if(e){
				top.document.getElementById('mainFrame').src="load.php";
				top.document.getElementById('bodyFrame').className="show";
				top.document.getElementById('catalogueFrame').className="hide";
		}else{
				top.document.getElementById('bodyFrame').className="hide";
				top.document.getElementById('catalogueFrame').className="show";
		}
		
	}
	
	this.setModalScreen = function (status){
		var obol= top.document.getElementById("modscreen");
		if (status == 'true'){
			obol.className = "open";
			}else{
			obol.className = "closed";
			}
	};
	this.launchPop = function (url,width,height,format){
	
			attributeStr = 'height='+height+',width='+width+',resizable=yes,scroll=yes';
			this.thisWin = window.open(url,'popWindow',attributeStr);
			this.thisWin.focus();

	};
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   POST FORM DATA  FUNCTIONS  /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

this.setFormData = function(docForm, formatOpts) {
  
  var opts = formatOpts || {};
  var str = '';
  var formElem;
  var lastElemName = '';
  
  for (i = 0; i < docForm.elements.length; i++) {
    formElem = docForm.elements[i];
    
    switch (formElem.type) {
      // Text fields, hidden form elements
      case 'text':
      case 'hidden':
      case 'password':
      case 'textarea':
      case 'select-one':
        str += formElem.name + '=' + encodeURI(formElem.value) + '&'
        break;
        
      // Multi-option select
      case 'select-multiple':
        var isSet = false;
        for(var j = 0; j < formElem.options.length; j++) {
          var currOpt = formElem.options[j];
          if(currOpt.selected) {
            if (opts.collapseMulti) {
              if (isSet) {
                str += ',' + encodeURI(currOpt.value);
              }
              else {
                str += formElem.name + '=' + encodeURI(currOpt.value);
                isSet = true;
              }
            }
            else {
              str += formElem.name + '=' + encodeURI(currOpt.value) + '&';
            }
          }
        }
        if (opts.collapseMulti) {
          str += '&';
        }
        break;
      
      // Radio buttons
      case 'radio':
        if (formElem.checked) {
          str += formElem.name + '=' + encodeURI(formElem.value) + '&'
        }
        break;
        
      // Checkboxes
      case 'checkbox':
        if (formElem.checked) {
          // Collapse multi-select into comma-separated list
          if (opts.collapseMulti && (formElem.name == lastElemName)) {
            // Strip of end ampersand if there is one
            if (str.lastIndexOf('&') == str.length-1) {
              str = str.substr(0, str.length - 1);
            }
            // Append value as comma-delimited string
            str += ',' + encodeURI(formElem.value);
          }
          else {
            str += formElem.name + '=' + encodeURI(formElem.value);
          }
          str += '&';
          lastElemName = formElem.name;
        }
        break;
        
    }
  }
  // Remove trailing separator
  str = str.substr(0, str.length - 1);
  return str;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   AJAX UPDATE RECORD         /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.updateRecord = function(e){
		//updateRecord(table,field,value,uniqueField,uniqueValue)
		var url=this.refineUrl("code/action.php?execute=5&t="+e.getAttribute('table')+"&f="+e.getAttribute('field')+"&v="+e.value+"&uf="+e.getAttribute('uniqueField')+"&uv="+e.getAttribute('uniqueValue'));	
		this.doGet(url,this.responseUpdateRecord);
	}
	this.responseUpdateRecord = function(str){
		if(!str){alert('Error! Record unchanged.\n'+str)}
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   PRODUCT LIST BOX ELEMENT   /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	 this.setThisCell = function (prdID,field,count,index){
		//alert(prdID+' - '+index);
		this.recalcIndex(prdID,index);
		var url=this.refineUrl("code/action.php?execute=5&t=prd_products&f="+field+"&v="+this.returnAsString(prdID,field,count)+"&uf=prdID&uv="+prdID);
		this.doGet(url,this.responseUpdateRecord);
		
	}
 	this.returnAsString = function (prdID,field,count){
		var txt = "";
		for(i=0;i<count;i++){
			txt += document.getElementById("_"+prdID+field+i).value+",";
		}
		txt = txt.slice(0,-1);
		return txt;
	} 
	
	this.recalcIndex = function(prdID,index){
		//alert('_'+prdID+'prdCost'+index);
		var c = Number(document.getElementById('_'+prdID+'prdCost'+index).value);
		var r = Number(document.getElementById('_'+prdID+'prdRetail'+index).value);
		var s = Number(document.getElementById('_'+prdID+'prdSellPrice'+index).value)/1.1;
		document.getElementById('_'+prdID+'prdGP'+index).value = this.dbl(((s-c)/s)*100);
	}
	this.recalcByGp = function(prdID,field,count,index){
		//alert('_'+prdID+'prdCost'+index);
		if(Number(document.getElementById('_'+prdID+'prdGP'+index).value)){
			var c = Number(document.getElementById('_'+prdID+'prdCost'+index).value);
			var gp = 1-Number(document.getElementById('_'+prdID+'prdGP'+index).value/100);
			document.getElementById('_'+prdID+'prdSellPrice'+index).value = this.dbl((c/gp)*1.1);
			
			//alert('_'+prdID+'prdCost'+index);
			this.setThisCell(prdID,field,count,index);
		}else{
			alert("Must be a number.")
			this.recalcIndex(prdID,index);
		}
	}
		

////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   FORMATTING       FUNCTIONS  /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.getArrayVal = function(str,i){
		var thisArray = str.split(",");
		return thisArray[i];
	}
	this.fixStr = function(s) {
		var regex = /tow/ig;
		s = s.replace(regex,"111");
		var regex = /\n/ig;
		s = s.replace(regex,"222");
		var regex = /\r/ig;
		s = s.replace(regex,"333");
		return s;
	}
	
	this.curr = function(num){
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	}
	
	this.perc = function(num){
		return (Number(num)*100).toFixed(2)+'%';	
	}
	this.dbl = function(num){
		num = Number(num);
		return num.toFixed(2);	
	}
	this.fdate = function(phpDate){
		var aDate = phpDate.split("-");
		return aDate[2]+"/"+aDate[1]+"/"+aDate[0];
	}
	this.dateForm = function(input){
		var validformat=/^\d{4}\-\d{2}\-\d{2}$/ //Basic check for format validity
		var returnval=false;
		if (!validformat.test(input.value)){
			alert("Invalid Date Format.\nRequires YYYY-MM-DD");
		}else{ //Detailed check for valid date ranges
			var yearfield=input.value.split("-")[0];
			var monthfield=input.value.split("-")[1];
			var dayfield=input.value.split("-")[2];
			
			var dayobj = new Date(yearfield, monthfield-1, dayfield);
	
			if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)){
				alert("Invalid Date detected. Please correct and submit again.");
			}else{
				returnval=true;
			}
		}
		return returnval;		
	}
	
	this.validateText = function(str){
		this.recordActivity();
			
			var xTxt = '&,",/,\',;,:';
			var xArr = xTxt.split(",");
			for(var i=0;i<xArr.length;i++){
				if(str.value.search(xArr[i]) >-1){
					//alert('lookiing for '+xArr[i]+' in '+str.value+' = '+str.value.search(xArr[i]));
					alert('Invalid character forund. ( '+xArr[i]+' )\nEnsure there is NO usage of the following characters - '+xTxt);
					str.value = str.value.slice(0,-1);
					return false;
				}
			}
			return true;		
	}
	
	this.validEmail = function (str){
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){return false;}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){return false;}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){return false;}
		if (str.indexOf(at,(lat+1))!=-1){return false;}
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){return false;}
		if (str.indexOf(dot,(lat+2))==-1){return false;}
		if (str.indexOf(" ")!=-1){return false;}
 		return true	;				
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   ELEMENT CONTROL FUNCTIONS  /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.setSelectValue = function(selectID, Value) {
         eval('SelectObject = document.getElementById("' + selectID + '");');
         for(i = 0;i< SelectObject.length;i++)
            {
            if(SelectObject[i].value == Value)
               SelectObject.selectedIndex = i;
            }
    }
	this.returnMuliSelect = function(ob){
		var str='';
		for(i=0;i<ob.length;i++){if (ob.options[i].selected) str += ob.options[i].value+',';}
		if(str.length>0)str=','+str;
		return str;
		
	}
	
	this.showItemFlag = function(id,type){
		alert(type);
		var flag = document.createElement('DIV');
		flag.id = 'flag'+id;
		flag.style.position="absolute";
		flag.style.top = 300;
		flag.style.left = 300;
		flag.style.zIndex=99;
		flag.innerHTML = '<img src="'+this.root()+'/images/outofstock.png" />';
		var target = document.getElementById("rowresult"+id);
		alert(target.style.top);
		document.body.appendChild(flag);
		
		
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   EMAIL FORM FUNCTIONS  /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.validateContact = function(){
	
		var msg="";
		if(document.getElementById('cName').value+""=="")msg+="Contact Name\n";
		if(!Ajax.validEmail(document.getElementById('cEmail').value))msg+="Contact Email\n";
		if(document.getElementById('cSubject').value+""=="")msg+="Subject Matter\n";
		if(document.getElementById('cComments').value+""=="")msg+="Comments\n";
		if(msg+''!=''){ msg = 'The following fields have invalid entries.\n\n'+msg;alert(msg);return false;}
		return true;
	}
	
	this.sendEmail = function(){
		if(this.validateContact()){
			document.getElementById('emailStatus').innerHTML = "Sending...";
			var from = document.getElementById('cName').value+" <"+document.getElementById('cEmail').value+">";
			var subject = document.getElementById('cSubject').value;
			var message = document.getElementById('cComments').value;
			var url= this.rootUrl+"inc/v1_action.php?execute=8&f="+from+"&s="+subject+"&msg="+message.replace(/\n/g, '|');
			this.doGet(url,this.responseEmail);
		}
	}
	this.responseEmail = function(str){
		document.getElementById('emailStatus').innerHTML = str;
		document.getElementById('cName').value = "";
		document.getElementById('cEmail').value = "";
		document.getElementById('cSubject').selectedIndex = 0;
		document.getElementById('cComments').value = "";
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   COOKIE CONTROL FUNCTIONS  /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////


	this.setCookie = function(name,value) {
		var date = new Date();
		date.setTime(date.getTime()+(30*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	this.getCookie = function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	this.delCookie = function(name) {
		setCookie(name,"",-1);
	}




////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   RESULTS AND DETAIL OPTION SELECT FUNCTIONS  ////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////


	this.setDropBox_Size = function(Index,Display,Key){
		//alert(Display);
		var displayValueCount = 0;
		var prdSize_Array = eval('prdSize'+Key+'_Array');
	
		var returnString = "<select name=\"db_SizeSelect_"+Key+"\" id=\"db_SizeSelect_"+Key+"\" onChange=\"if(Ajax.validSelect(this.options[this.selectedIndex].value)){Ajax.setDropBox_Colour(this.options[this.selectedIndex].value,\'"+Display+"\',\'"+Key+"\');Ajax.setPricing(\'addToCart_"+Key+"\',this.options[this.selectedIndex].value,\'"+Display+"\',\'"+Key+"\')}else{Ajax.setDropBox_Colour();setPricing(\'addToCart_"+Key+"\',false,\'"+Display+"\',\'"+Key+"\');}\">";
			
		//if(prdSize_Array.length>1){returnString+="<option value='x'>>Sizes</option>";}
		var thisValue = 'x';
		var selected = '';
	
		for(var i=0;i<prdSize_Array.length;i++){
				if(prdSize_Array[i]!=thisValue && prdSize_Array[i]+''!=''){
						displayValueCount ++;
						if(Index==i){selected = " selected ";Ajax.setPricing('addToCart_'+Key,Index,'<?php echo $_display;?>',Key);}else{selected = ""};	
						returnString+="<option value='"+i+"' "+selected+">"+prdSize_Array[i]+"</option>";
						thisValue = prdSize_Array[i];
				}
		}
		returnString+="</select>";
		
		if(displayValueCount>0){document.getElementById('selectDiv1_'+Key).innerHTML = returnString;}
		
	}
	this.setDropBox_Colour = function(Index,Display,Key){
		var displayValueCount = 0;
		
		var prdColour_Array = eval('prdColour'+Key+'_Array');
		var prdSize_Array = eval('prdSize'+Key+'_Array');
		var Size = prdSize_Array[Index];
		var selectedSize = null
		var selectedSizeIndex = 0;
		if(document.getElementById('db_SizeSelect_'+Key)){
			selectedSize = document.getElementById('db_SizeSelect_'+Key);
			selectedSizeIndex = selectedSize.options[selectedSize.selectedIndex].value;
		}
		
		var returnString = "<select name=\"db_ColourSelect_"+Key+"\" id=\"db_ColourSelect_"+Key+"\" onChange=\"if(Ajax.validSelect(this.options[this.selectedIndex].value)){Ajax.setPricing(\'addToCart_"+Key+"\',this.options[this.selectedIndex].value,\'"+Display+"\',\'"+Key+"\')}else{Ajax.setPricing(\'addToCart_"+Key+"\',null,\'"+Display+"\',\'"+Key+"\');}\">";
		
		//if(prdColour_Array.length>1){returnString+="<option value='"+selectedSizeIndex+"'>>Colours</option>";}
		
		if(Size){
			//loop size array to get index array
			for(var i=0;i<prdSize_Array.length;i++){
				if(prdSize_Array[i]==Size && prdColour_Array[i]+''!=''){
					displayValueCount ++;
					returnString+="<option value='"+i+"'>"+prdColour_Array[i]+"</option>";
				}
			}
		}else{
			for(var i=0;i<prdSize_Array.length;i++){
					if(prdColour_Array[i]+''!=''){
						displayValueCount ++;
						returnString+="<option value='"+i+"'>"+prdColour_Array[i]+"</option>";
					}
				}		
		}
		returnString+="</select>";
		if(displayValueCount>0){
			document.getElementById('selectDiv2_'+Key).innerHTML = returnString;
			document.getElementById('selectDiv2Label_'+Key).innerHTML = "Select Colour";
		}else{
			document.getElementById('selectDiv2_'+Key).innerHTML = "";
			document.getElementById('selectDiv2Label_'+Key).innerHTML = "";
		}
	}
	this.setPricing = function(button,index,display,Key){
		//alert('set pricing');
		var prdRRP_Array = eval('prdRRP'+Key+'_Array');
		var prdSellPrice_Array = eval('prdSellPrice'+Key+'_Array');
		var promoTitle_Array = eval('promoTitle'+Key+'_Array');
		var prdStockFrom_Array = eval('prdStockFrom'+Key+'_Array');
		var prdAlertFlag_Array = eval('prdAlertFlag'+Key+'_Array');
		var prdStatusID_Array = eval('prdStatusID'+Key+'_Array');
		var prdID_Array = eval('prdID'+Key+'_Array');
		var prd_OptionID_Array = eval('prd_OptionID'+Key+'_Array');
		var prdSellPrice_Array = eval('prdSellPrice'+Key+'_Array');
		var prdCode_Array = eval('prdCode'+Key+'_Array');
		var prdColour_Array = eval('prdColour'+Key+'_Array');
		var prdSize_Array = eval('prdSize'+Key+'_Array');
		var promoPriceVar_Array = eval('promoPriceVar'+Key+'_Array');
		
		var add = document.getElementById(button);
		add.setAttribute('qty',document.getElementById('prdQty_'+Key).value);
		var alertDiv = document.getElementById('priceAlert_'+Key);
		
		switch(display){
			case "results" :retailTag = "RRP ";
							saveTag = "SAVE ";
							saleTag = "NOW ";
							break;
							
			default : 		retailTag = 'Retail Price&nbsp;&nbsp;&nbsp;AUD';
							saleTag = 'Our Price&nbsp;&nbsp;&nbsp;AUD';
							saveTag = 'SAVE&nbsp;&nbsp;&nbsp;';
							break;
		}
		
			if(index>-1){
				document.getElementById("priceRetail_"+Key).innerHTML = retailTag+Ajax.curr(prdRRP_Array[index]);
				document.getElementById("priceSellPrice_"+Key).innerHTML = saleTag+Ajax.curr(prdSellPrice_Array[index]);
				
				
				if(document.getElementById("priceFreeDel_"+Key)){
					if( prdSellPrice_Array[index] > 80 && prdRRP_Array[index] > 80 ){
						document.getElementById("priceFreeDel_"+Key).innerHTML = "FREE DELIVERY";
					}else{
						document.getElementById("priceFreeDel_"+Key).innerHTML = "";
					}
				}
				
				//alert(Number(prdRRP_Array[index]) +"!="+ Number(prdSellPrice_Array[index]));
				if(Number(prdRRP_Array[index]) > Number(prdSellPrice_Array[index])){
					if(Number(promoPriceVar_Array[index]) > 0){
						document.getElementById("priceSave_"+Key).innerHTML = Call.percCeil(1 - promoPriceVar_Array[index])+' OFF';
					}else{
						document.getElementById("priceSave_"+Key).innerHTML = saveTag+Ajax.curr(prdRRP_Array[index] - prdSellPrice_Array[index]);
					}
				}else{
					document.getElementById("priceSellPrice_"+Key).innerHTML = "AUD "+Ajax.curr(prdSellPrice_Array[index]);
					document.getElementById("priceSave_"+Key).innerHTML ="";
					document.getElementById("priceRetail_"+Key).innerHTML ="";
				}
				
				if(alertDiv){
					if(promoPriceVar_Array[index]>0){
						document.getElementById("priceAlert_"+Key).innerHTML = promoTitle_Array[index];
					}else{
						document.getElementById("priceAlert_"+Key).innerHTML = "";
					}
				}
				
				add.setAttribute('prdStockFrom',prdStockFrom_Array[index]); 
				add.setAttribute('prdAlertFlag',prdAlertFlag_Array[index]);
				add.setAttribute('prdStatusID',prdStatusID_Array[index]);
				add.setAttribute('prdID',prdID_Array[index]);
				add.setAttribute('prdOID',prd_OptionID_Array[index]);
				//add.setAttribute('prdCost',Ajax.dbl(prdUnitCost_Array[index]));
				add.setAttribute('prdSellPrice',Ajax.dbl(prdSellPrice_Array[index]));
				add.setAttribute('prdCode',prdCode_Array[index]);
				add.setAttribute('prdColour',prdColour_Array[index]);
				add.setAttribute('prdSize',prdSize_Array[index]);
				add.setAttribute('prdAlertFlag',prdAlertFlag_Array[index]);
				
			}else{
				document.getElementById("priceRetail_"+Key).innerHTML = "";
				document.getElementById("priceSellPrice_"+Key).innerHTML = "";
				document.getElementById("priceSave_"+Key).innerHTML = "";
				if(alertDiv)document.getElementById("priceAlert_"+Key).innerHTML = "";
				
				add.setAttribute('prdStockFrom',null);
				add.setAttribute('prdAlertFlag',null);
				add.setAttribute('prdStatusID',null);
				add.setAttribute('prdID',null); 
				add.setAttribute('prdCost',null);
				add.setAttribute('prdSellPrice',null);
				add.setAttribute('prdCode',null);
				add.setAttribute('prdColour',null);
				add.setAttribute('prdSize',null);
				add.setAttribute('prdAlertFlag',0);
			}
			
			//alert(add.getAttribute('prdSellPrice'))
		}
	this.validSelect = function(value){
		if(value!='x')return true;
		return false;
		}



/////////////////////////////////   CLASS END   ////////////////////////////////////////////////////

 

}


 
