/*
 * Copyright 2006 SitePoint Pty. Ltd, www.sitepoint.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS;
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

function Ajax() {
  this.req = null;
  this.url = null;
  this.status = null;
  this.statusText = '';
  this.method = 'GET';
  this.async = true;
  this.dataPayload = null;
  this.readyState = null;
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'xml', // 'text', 'xml', 'object'
  this.mimeType = null;
  this.headers = [];

  
  this.init = function() {
    var i = 0;
    var reqTry = [ 
      function() { return new XMLHttpRequest(); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP') },
      function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];
      
    while (!this.req && (i < reqTry.length)) {
      try { 
        this.req = reqTry[i++]();
      } 
      catch(e) {}
    }
    return true;
  };
  this.doGet = function(url, hand, format) {
    this.url = url;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.doReq();
  };
  this.doPost = function(url, dataPayload, hand, format) {
    this.url = url;
    this.dataPayload = dataPayload;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.method = 'POST';
    this.doReq();
  };
  this.doReq = function() {
    var self = null;
    var req = null;
    var headArr = [];
    
    if (!this.init()) {
      alert('Could not create XMLHttpRequest object.');
      return;
    }
    req = this.req;
    req.open(this.method, this.url, this.async);
    if (this.method == "POST") {
      this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    if (this.method == 'POST') {
      req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    self = this;
    req.onreadystatechange = function() {
      var resp = null;
      self.readyState = req.readyState;
      if (req.readyState == 4) {
        
        self.status = req.status;
        self.statusText = req.statusText;
        self.responseText = req.responseText;
        self.responseXML = req.responseXML;
        
        switch(self.responseFormat) {
          case 'text':
            resp = self.responseText;
            break;
          case 'xml':
            resp = self.responseXML;
            break;
          case 'object':
            resp = req;
            break;
        }
        
        if (self.status > 199 && self.status < 300) {
          if (!self.handleResp) {
            alert('No response handler defined ' +
              'for this XMLHttpRequest object.');
            return;
          }
          else {
            self.handleResp(resp);
          }
        }
        
        else {
          self.handleErr(resp);
        }
      }
    }
    req.send(this.dataPayload);
  };
  this.abort = function() {
    if (this.req) {
      this.req.onreadystatechange = function() { };
      this.req.abort();
      this.req = null;
    }
  };
  this.handleErr = function() {
    var errorWin;
    // Create new window and display error
    try {
      //errorWin = window.open('', 'errorWin');
      //errorWin.document.body.innerHTML = this.responseText;
    }
    // If pop-up gets blocked, inform user
    catch(e) {
      alert('An error occurred, but the error message cannot be' +
      ' displayed because of your browser\'s pop-up blocker.\n' +
      'Please allow pop-ups from this Web site.');
    }
  };
  this.setMimeType = function(mimeType) {
    this.mimeType = mimeType;
  };
  this.setHandlerResp = function(funcRef) {
    this.handleResp = funcRef;
  };
  this.setHandlerErr = function(funcRef) {
    this.handleErr = funcRef; 
  };
  this.setHandlerBoth = function(funcRef) {
    this.handleResp = funcRef;
    this.handleErr = funcRef;
  };
  this.setRequestHeader = function(headerName, headerValue) {
    this.headers.push(headerName + ': ' + headerValue);
  };
  
}

//General function area:
function check_webcode(wbfa,number){
   	 var poststr = '';
	poststr = poststr + "number=" + number + "&";
	poststr = poststr + "wbfa=" + wbfa;
      		
 		strhand = function(strings) {
   	 		return strings;
   	 		exit;
   	 	}
		var xmlajax = new Ajax();
	  xmlajax.setMimeType('text/text');
      xmlajax.doPost('../scripts/phpscripts/check_webfilingcode.php', poststr, strhand, 'text');
	  poststr = '';	
}


function select_existing_company(){
    //this function loops through the combo box until it hits the right company.
    var str_split = '';
    //document.getElementById("company_names").options[selIndex].value != "x"
    var objCompany_list = document.getElementById("company_names"); 
    var intCounter; 
    var str_results;
    for (intCounter = 0; intCounter < objCompany_list.length; intCounter++) { 
        str_split = objCompany_list.options[intCounter].value.split(",");
        
        if(str_split[1]==document.getElementById("user_incorpnumber").value){
            //then select this one
            
            objCompany_list.selectedIndex = intCounter;
            //now call the populate from combo function.
            populate_inputs_from_combo();
        }
    }
    
}
    
    
function check_details() {
   	 var poststr = '';
     document.getElementById("submit").style.visibility = 'hidden';
   	 var fieldvalue = document.getElementById("user_incorpnumber").value;
	if (fieldvalue.length == 7){
		document.getElementById("user_incorpnumber").value = "0" + fieldvalue;
	}
	poststr = poststr + "number=" + document.getElementById("user_incorpnumber").value + "&";
	poststr = poststr + "userid=" + document.getElementById("userid").value + "&";
	poststr = poststr + "wbfa=" + document.getElementById("user_wbfa").value;
      		
        
       
       
       strhand = function(strings) {
            var str_company = "";
            if (strings.substring(0,1)===" "){
                str_company = strings.substring(1,strings.length);
            } else {
                str_company = strings;
            }
            
            if (strings.length>18){
               strings = strings.substring(0,15); 
            }
            
            
   	 		switch (strings){
            case " INVALID":
                document.getElementById("error").innerHTML = "<BR><BR><BR><BR><BR>PLEASE ENTER A VALID WEB FILING CODE";
                document.getElementById("result").innerHTML = "";
                document.getElementById("select").style.display = 'block';
                document.getElementById("search").style.display = 'block';
                document.getElementById("select").style.visibility = 'hidden';
                document.getElementById("search").style.visibility = 'hidden';
                break;
            case " INCORRECT DATA":
                document.getElementById("error").innerHTML = "<BR><BR><BR><BR><BR>COMPANY NOT REGISTERED FOR WEB FILING";
                document.getElementById("result").innerHTML = "";
                //document.getElementById("user_name").innerHTML = "";
                document.getElementById("select").style.display = 'block';
                document.getElementById("search").style.display = 'block';            
                document.getElementById("select").style.visibility = 'hidden';
                document.getElementById("search").style.visibility = 'hidden';
                break;
            case " ALREADY IN SYSTEM":
                select_existing_company();
                document.getElementById("error").innerHTML = "<BR><BR><BR><BR><BR>COMPANY FOUND - LOADING FROM DATABASE";
    			document.getElementById("result").innerHTML = "";
    	        //document.getElementById("user_name").innerHTML = "";
       	 		document.getElementById("select").style.display = 'block';
       	 		document.getElementById("search").style.display = 'block';            
       	 		document.getElementById("select").style.visibility = 'hidden';
       	 		document.getElementById("search").style.visibility = 'hidden';
                break;
            case " NOT REGISTERED":   
                
                document.getElementById("error").innerHTML = str_company + " is not registered for web filing, please contact us on 01302 729041 for us to arrange this for you.";
                
    			document.getElementById("result").innerHTML = "";
    			document.getElementById("user_incorpnumber").value = "";
                document.getElementById("user_wbfa").value = "";
       	 		document.getElementById("select").style.display = 'none';
       	 		document.getElementById("search").style.display = 'none';    
                document.getElementById('updatecode').style.display = 'none';       
       	 		document.getElementById("select").style.visibility = 'hidden';
       	 		document.getElementById("search").style.visibility = 'hidden';            
    			document.getElementById('updatecode').style.visibility = 'hidden';
                break;
            default:
               var submit_button = document.getElementById('select');
				submit_button.style.visibility = 'visible';
                submit_button.style.display = 'block';    
   	 			document.getElementById("error").innerHTML = "";
   	 			document.getElementById("name_title").innerHTML = "Name: " + str_company;
                document.getElementById("user_name").value = str_company;
   	 			document.getElementById("select").disabled = false;
       }
   	 	}
		var xmlajax = new Ajax();
	  xmlajax.setMimeType('text/text');
      xmlajax.doPost('../scripts/phpscripts/check_details.php', poststr, strhand, 'text');
	  poststr = '';
   }
   
   function save_new_details(wbfa,number,userid) {
   	 var poststr = '';
		poststr = poststr + "number=" + number + "&";
		poststr = poststr + "wbfa=" + wbfa + "&";
		poststr = poststr + "userid=" + userid + "&";
   	 	strhand = function(strings) {
   	 		document.getElementById("incorp_id").value = strings;
   	 	}
		var xmlajax = new Ajax();
	  xmlajax.setMimeType('text/text');
	  
      xmlajax.doPost('../scripts/phpscripts/save_new_details.php', poststr, strhand, 'text');
	  poststr = '';
   }
   function update_code() {
   	 var poststr = '';
		poststr = poststr + "wbfa=" + document.getElementById("user_wbfa").value + "&";
		poststr = poststr + "incorp_id=" + document.getElementById("incorpid").value;
   	 	strhand = function(strings) {
   	 		document.getElementById("error").innerHTML = "";
   	 		document.getElementById("result").innerHTML = "";
   	 		document.getElementById("wbfa").value = document.getElementById("user_wbfa").value;
   	 		document.getElementById("result").innerHTML = "Company name:<BR>" + document.getElementById("companyname").value + "<BR><BR>Company Number:<BR>" + document.getElementById("incorpnumber").value + "<BR><BR>Web Filing Code:<BR>" + document.getElementById("wbfa").value;
   	 		document.getElementById('submit').style.visibility = 'visible';
   	 		document.getElementById('updatecode').style.visibility = 'hidden';
   	 		document.getElementById("user_wbfa").value = "";
   	 		document.getElementById("user_incorpnumber").value = "";
   	 	}
		var xmlajax = new Ajax();
	  	xmlajax.setMimeType('text/text');
	  
      xmlajax.doPost('../scripts/phpscripts/update_code.php', poststr, strhand, 'text');
	  poststr = '';
   }

   function update_database(name,wbfa,number,userid) {
   	 var poststr = '';
 		poststr = poststr + "number=" + document.getElementById("incorpnumber").value + "&";
		poststr = poststr + "wbfa=" + document.getElementById("wbfa").value + "&";
		poststr = poststr + "userid=" + userid + "&";
		poststr = poststr + "name=" + document.getElementById("companyname").value + "&";
		poststr = poststr + "incorpid=" + document.getElementById("incorpid").value;
   	 	strhand = function(strings) {
			//alert("complete");
   	 	}
		var xmlajax = new Ajax();
		
	  xmlajax.setMimeType('text/text');
      xmlajax.doPost('../scripts/phpscripts/update_details.php', poststr, strhand, 'text');
	  poststr = '';
   }
   function myPopup2(int_orderid) {
        window.open( "popup.php?id=" + int_orderid, "myWindow","status = 1, height = 200, width = 200, resizable = 0" )
}
