// Call Document
function Call(){

	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.responseArg = null;
	this.responseXML = null;
	this.handleResp = null;
	this.responseFormate = 'text'; //'test','xml',or'object'
	this.mimeType = null;
	this.thisWin=null;
	this.rootUrl = "http://www.rt.luggagegear.com.au";
	
	this.now = new Date();
	this.timestamp = this.now.getTime();

	
	
	
	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 = self.req;
								break;
						}
						
						
						
						if (self.req.status >= 200 && self.req.status <= 299) {
							if(self.responseArg)self.req.responseArg = self.responseArg;
							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){
		//alert(url);
		this.url = this.antiCache(url);
		this.handleResp = hand;
		this.responseFormat = format || 'text';
		this.doReq();
	};
	
	this.doGetArg = function(url, hand, arg){
		//alert(url);
		this.url = this.antiCache(url);
		this.handleResp = hand;
		this.responseFormat = "object";
		this.responseArg = arg;
		this.doReq();
	};
	
	this.doPost = function(url, postData, hand, format){
		this.url = this.antiCache(url);
		this.handleResp = hand;
		this.responseFormat = format || 'text';
		this.method= 'POST';
		this.postData = postData;
		this.doReq();		
	};
	this.antiCache = function(url) {
		var t = new Date();
		var i = url.indexOf('?');
		if(i>0){
			url += '&bc='+t.getTime();
		}else{
			url += '?bc='+t.getTime();
		}
		return url;
	}	
	
	this.doNothing = function(){
		return false;	
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   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;
	}

	this.playSound = function( state ){
		switch(state){
			case "error" 	:  document.all.sound.src = "/admin/sound/error.wav"; break;
			case "success" 	:  document.all.sound.src = "/admin/sound/success.wav"; break;
		}
	}

	this.setfocus = function( e ){
		if(document.getElementById(e)){
			document.getElementById(e).focus();	
		}else{
			window.focus();	
		}
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   SHOW PROCESSING            /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.setModal = function( msg ){
		 //top.document.getElementById('modal-header');
		top.window.frames['mainFrame'].location.hash = "TOP";

		if(top.window.frames['topFrame']){
			
			var h = top.window.frames['topFrame'].document.getElementById('modal-screen');
			var m = top.window.frames['mainFrame'].document.getElementById('modal-screen');
			var d = top.window.frames['mainFrame'].document.getElementById('dialog');
			
			h.className = 'modal-screen-show';
			m.className = 'modal-screen-show';

		}else{
			var w = document.getElementById('modal-screen');
			var d = document.getElementById('dialog');
			w.className = 'modal-screen-show';
		}

		d.innerHTML = msg+"<p></p><p class='link_hover cMdBlue' onclick='Call.clearModal()'>[OK]</p>";

	}

	this.clearModal = function(){
		
		if(top.window.frames['topFrame']){
			
			var h = top.window.frames['topFrame'].document.getElementById('modal-screen');
			var m = top.window.frames['mainFrame'].document.getElementById('modal-screen');
			var d = top.window.frames['mainFrame'].document.getElementById('dialog');
			
			h.className = 'modal-screen-hide';
			m.className = 'modal-screen-hide';

		}else{
			var w = document.getElementById('modal-screen');
			var d = document.getElementById('dialog');
			w.className = 'modal-screen-hide';
		}

		d.innerHTML = "";	
	}

	this.isModal = function(){
		return document.documentElement.className === 'modal';	
	}

	this.startProcessing = function( div ){
		
		var msg = "<img src='/images/indicator.gif' width='16' height='16' border='0' />";
		
		document.getElementById(div).innerHTML = msg;
		
	}
	
	this.stopProcessing = function( div , fail , _reload){
		
		var _class = "process-complete";
		var	result = "<img src='/images/icons/status_true.png' width='16' height='16' border='0' />";
		
		if(fail){
			_class = "process-error";
			result = "<img src='/images/icons/cancel.png' width='16' height='16' border='0' />";
			
		}
		
		var msg = result;
		
		if(_reload)msg += "Please wait while page reloads...";
		
		document.getElementById(div).className = _class;
		document.getElementById(div).innerHTML = msg;
		
		if(_reload)document.location = location.href;
		
	}
	
	this.responseAlertOnly = function ( str ){
		if(str.length > 1) alert(str);
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////  ADD ITEM TO ORDER         /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////


 	this.addItem = function(e){
		var ok = false;
		var bo = '';
		var stock = '';
		
		if(this.validateItem(e)){
		
		switch(Number(e.getAttribute('prdAlertFlag'))){
			
			//out of stock
			case 1: ok = confirm("Item NOT available until "+Ajax.fdate(e.getAttribute('prdStockFrom'))+"\n\nPlease confirm to proceed with a BACKORDER purchase?");
					stock = '&stk='+e.getAttribute('prdStockFrom');
					break;
					
			// discontinued but in stock - less than 2		
			case 2: ok = confirm("WARNING... If you hurry, you can still secure some of our final stock.");
					stock = '&lstk=true';
					break;
					
			case 0: ok = true;break;
		}
		if(ok){
			
				if(!e.getAttribute('prdColour')){e.setAttribute('prdColour','');}
				if(!e.getAttribute('prdSize')){e.setAttribute('prdSize','');}
				var url = Ajax.rootUrl+Ajax.version+'/action/cart_addItem.php?action=add&prdOID='+e.getAttribute('prdOID')
																			 +'&q='+document.getElementById(e.id.replace('addToCart','prdQty')).value
																			 +stock
																			 +'&sp='+e.getAttribute('prdSellPrice');
				this.doGet(url,this.handleCartRefresh);
			}
	}
}
	this.validateItem = 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;
}

	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="'+Ajax.refineUrl('images/indicator.gif')+'" width="16" height="16" />';
		var url = Ajax.rootUrl+Ajax.version+'/action/cart_refresh.php';
		this.doGet(url,this.handleRefreshCart);
	};
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   Call UPDATE RECORD         /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.toggleTab = function(e , _count ){
		if(_count>0){
			if(e=='all'){
				var div = document.getElementById('itemTab0');
				if(div.className =="hide"){
					var tabClassName="show";
					var imgSrc="/images/icons/open.png";
				}else{
					var tabClassName="hide";
					var imgSrc="/images/icons/closed.png";	
				}
				for(i=0;i<_count;i++){
					document.getElementById('itemTab'+i).className = tabClassName;
					document.getElementById('imgTab'+i).src = imgSrc;
				}
			
			}else{
				var div = document.getElementById('itemTab'+e.getAttribute('tabid'));
				if(div.className =="hide"){
					div.className="show";
					e.src="/images/icons/open.png";
				}else{
					div.className="hide";
					e.src="/images/icons/closed.png";	
				}
			}
		}
	}
	
	this.pop_productSearch = function( str ){
		var xt = '';
		if(str){ xt = '?q='+str; }
		this.launchPop("/admin/product/product_option_management.php"+xt,1000,800);
		
	}	
	
	this.pop_productOrder = function( oID ){
		
		this.launchPop("/admin/orders/orders_product_management.php?oID="+oID,1000,800);
		
	}	
	this.pop_purchaseOrderItemAdd = function( supID ){
		
		this.launchPop("/admin/orders/orders_product_management.php?supID="+supID,1000,800);
		
	}	
	this.pop_stockSearch = function( str ){
		var xt = '';
		if(str){ xt = '?q='+str; }
		this.launchPop("/admin/stock/stock_find.php"+xt,1000,800);
		
	}
	
	this.pop_stockSearchThis = function( str ){
		var xt = '';
		if(str){ xt = '&prdID='+str; }
		
		var d = new Date();
		var date = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
		
		this.launchPop("/admin/stock/stock_count.php?r=true&date="+date+xt,1000,800);
		
	}
	
	this.pop_jobAmend = function( jobID , oID ){
		
		this.launchPop("/admin/jobs/job_amend.php?jobID="+jobID+"&oID="+oID,1000,800);
		
	}

	this.pop_orderAmend = function( oID ){
		
		this.launchPop("../orders/order_amend.php?oID="+oID,1000,800);
		
	}
	
	this.pop_itemAmend = function( prdID ){
		
		this.launchPop("/admin/product/product_insert.php?prdID="+prdID,1000,800);
		
	}
	


	this.batch_orderPrint = function(str){
				
		if( typeof str != 'string'){
			if(confirm("Confirm printing of "+str.length+" orders.")){
				window.open('order_print.php?admin=true&oID='+str,'Order');
				//this.launchPop("../order_amend.php?oID="+oID,1000,800);
			}
		}else{
				window.open('order_print.php?admin=true&oID='+str,'Order');
		}
	}

	this.batch_eParcelFile = function(str){
		if(confirm("Confirm generating eParcel file for "+str.length+" orders.")){
			window.open('/admin/eparcel/default.php?oID='+selectedItems,'eparcel');
		}
	}
	
	this.batch_FreightFile = function(str , type){
		if(confirm("Confirm generating eParcel file for "+str.length+" orders.")){
			window.open('/admin/freight_exports/'+type+'freight.php?oID='+selectedItems,'export');
		}
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   ORDER PROCESSING FUNCTIONS   ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////


	this.order_activatePaidOrder = function( oID ){
		url = "action_activatePaidOrder.php?oID="+oID
		Call.doGet(url,responseToCall);
	}
	
	this.order_cancel_thisOrder = function( oID ){
		if(confirm("Please confirm Cancellation request for order "+oID)){
			Call.startProcessing('admin-body');
			
			url = "/action/order_cancel.php?oID="+oID;
			
			if(confirm("Do you wish a confirmation email to be sent to the customer?")) url += "&conf=true";
			
			//alert (url);
			Call.doGet(url,this.responseToCancellation);
		}
	}
	
	this.responseToCancellation = function(str){
		Call.stopProcessing('admin-body',(!str),true);
	}
	
	this.set_tracking_id = function( e ){
		url = "/action/order_set_tracking_id.php?oID="+e.getAttribute('oID')+"&delTypeID="+e.getAttribute('delTypeID')+"&str="+e.value;
		//alert(url);
		Call.doGet(url,this.responseAlertOnly);
	}	
	
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   PRICING MATRIX FUNCTIONS   /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.percCeil = function(num){
		return (Number(num)*100).toFixed(0)+'%';	
	}


////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   EMAIL     FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.validateContact = function(){
	
		var msg="";
		if(document.getElementById('cName').value+""=="")msg+="Contact Name\n";
		if(!Call.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(frm){
		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;
			
			frm.submit();
		}
	}

////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   SESSION    FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.showClockTime = function(){
		   var now    = new Date();
		   var hour   = now.getHours();
		   var minute = now.getMinutes();
		   var second = now.getSeconds();
		   var ap = "AM";
		   if (hour   > 11) { ap = "PM";             }
		   if (hour   > 12) { hour = hour - 12;      }
		   if (hour   == 0) { hour = 12;             }
		   if (hour   < 10) { hour   = "0" + hour;   }
		   if (minute < 10) { minute = "0" + minute; }
		   if (second < 10) { second = "0" + second; }
		   var timeString = hour +
							':' +
							minute +
							':' +
							second +
							" " +
							ap;
		   if(document.getElementById('displayTime')){document.getElementById('displayTime').innerHTML = timeString;}
		   
		   var thistime = now.getTime();
		   var timediff = thistime - this.timestamp;
		  // if(timediff>300000){ alert(this.timestamp); }
	}

	

	this.userCheckSession = function(){
		var url = "/action/user_checksession.php";
		Call.doGet(url,this.responseCheckSession);	
	}
	
	this.responseCheckSession = function(str){
		if(str!='1'){
			Call.clearModal();
			top.window.document.location = this.rootUrl+'/admin/userlogin.php?logout=true';	
		}
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   JOB     FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.testForActiveJobs = function(){
		//alert(this.isModal());
		if(!this.isModal()){
			var url = "/action/job_alert_test.php";
			Call.doGet(url,this.responseToActiveJobSearch);	
		}
	}
	
	this.responseToActiveJobSearch = function(str){
		if(str.length > 1){
			this.setModal(str);
		}
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   LAUNCH POP FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.launchPop = function (url,width,height){
		//alert('launchPOP')
		/*width = width + 25;
		attributeStr = 'dialogHeight:'+height+'px;dialogWidth:'+width+'px;dialogLeft:10px;dialogTop:10px;help:no;resizable:yes;scroll:auto;status:no;';
		window.showModalDialog(url,window,attributeStr);
		
		alert('launchPop');*/
		
		var t = new Date();
		var bc = t.getTime();
		
		
			attributeStr = 'height='+height+',width='+width+',resizable=yes,scrollbars=yes';
			this.thisWin = window.open(url,bc,attributeStr);
			this.thisWin.focus();

	};

	this.reloadCallerPage = function(){
		//alert('reload')
		var msg = "<p class='txt10'><img src='http://rt.luggagegear.com.au/images/indicator.gif' width='16' height='16' border='0' /> Requesting page refresh...</p>";
		window.opener.document.body.innerHTML = msg;
		
		setTimeout( window.opener.location.href = window.opener.document.location, 100);
			
	}
	
	this.callerPageRefresh = function(str){
		//alert('refresh')
		
		
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   FORMATTING       FUNCTIONS  /////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
	this.getArrayVal = function(str,i){
		alert('getArrayVal');/*
		var thisArray = str.split(",");
		return thisArray[i];*/
	}
	
	this.fixStr = function(s) {
		alert('fixStr');/*
		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.dateForm = function(input){
		alert('dateForm');/*
		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){
		alert('validateText');/*
		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.nl2br = function(str){
		return str.replace(/\n/gi, '<br />');
	}
	
	this.br2nl = function(str){
		return str.replace(/\<br(\s*)?\/?\>/gi, '\n');	
	}
	
	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	;			}

////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   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(Call.validSelect(this.options[this.selectedIndex].value)){Call.setDropBox_Colour(this.options[this.selectedIndex].value,\'"+Display+"\',\'"+Key+"\');Call.setPricing(\'addToCart_"+Key+"\',this.options[this.selectedIndex].value,\'"+Display+"\',\'"+Key+"\')}else{Call.setDropBox_Colour();Call.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 ";Call.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(Call.validSelect(this.options[this.selectedIndex].value)){Call.setPricing(\'addToCart_"+Key+"\',this.options[this.selectedIndex].value,\'"+Display+"\',\'"+Key+"\')}else{Call.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;&nbsp;&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+Call.curr(prdRRP_Array[index]);
				document.getElementById("priceSellPrice_"+Key).innerHTML = saleTag+Call.curr(prdSellPrice_Array[index]);
				
				if(document.getElementById("priceFreeDel_"+Key)){
					if( prdSellPrice_Array[index] > 80 && prdRRP_Array[index] > 80 ){
						document.getElementById("priceFreeDel_"+Key).innerHTML = "inc. 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+Call.curr(prdRRP_Array[index] - prdSellPrice_Array[index]);
					}
				}else{
					document.getElementById("priceSellPrice_"+Key).innerHTML = "AUD "+Call.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',Call.dbl(prdUnitCost_Array[index]));
				add.setAttribute('prdSellPrice',Call.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;
		}

	this.getURL = function(show_querystring_only){
		var fullURL = document.URL;
		if(show_querystring_only)fullURL = fullURL.substring(fullURL.indexOf('?')+1, fullURL.length);
		return fullURL;
	
	}


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



}



