// Ajax 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.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;
	}	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   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.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;
		
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   AJAX 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_stockSearch = function( str ){
		var xt = '';
		if(str){ xt = '?q='+str; }
		this.launchPop("/admin/stock/stock_find.php"+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');
		}
	}

////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   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=yes";
			
			//alert (url);
			Call.doGet(url,this.responseToCancellation);
		}
	}
	
	this.responseToCancellation = function(str){
		Call.stopProcessing('admin-body',(!str),true);
	}
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   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.userCheckSession = function(){
		var url = "/action/user_checksession.php";
		Call.doGet(url,this.responseCheckSession);	
	}
	
	this.responseCheckSession = function(str){
		if(str!='1'){
			document.location = this.rootUrl+'/admin/userlogin.php?logout=true';	
		}
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   JOB     FUNCTIONS   /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

	this.testForActiveJobs = function(){
		var url = "/action/job_alert_test.php";
		Call.doGet(url,this.responseToActiveJobSearch);	
	}
	
	this.responseToActiveJobSearch = function(str){
		if(str.length > 1){
			alert(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);
	}

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



}


