/*
 * 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
 *
 */

function Ajax() {
  this.req = null;           // XMLHttpRequest object
  this.url = null;
  this.status = null;        // 404, 200, etc.
  this.statusText = '';
  this.method = 'GET';
  this.async = true;
  this.dataPayload = null;
  this.readyState = null;    // Response state 1-4 - copied from req
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'text', // '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');
    }
    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;
        }
        // 404, 200, 500 etc.
        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);
  };

}

function setSessionCheckbox(obj) {
  var ajax = new Ajax();
  if (obj.checked) { on_off = 'ON'; }
  else { on_off = 'OFF'; }
  ajax.doGet(obj.value+on_off, hand);
}

// Added for PSshopping 11/14/2008 - Redo the styling on the chosen category
var hand = function(str) {
//  alert('Returned: '+str);
  var labelText = '';
  if (str == 'Set sale items TRUE' | str == 'Set sale items FALSE'){ return;}
  var pattern = new RegExp("(^| )category.*( |$)");
  var category_list = document.getElementById('categoryList');
  category_list.fromAjax = true;
	var numNodes = category_list.childNodes.length;
	for (var i = 0; i < category_list.childNodes.length; i++) {
    var label = category_list.childNodes[i];
    if (pattern.test(label.id)) {
//			alert("Node " + label.id + "  str: " + str);
//      var cat = document.getElementById(name.toString());
	    if ( label.id == "category" + str) {
			  var cat = document.getElementById(label.id);
//			  alert('Setting label with name: ' + label.id);
				cat.className = 'categoryON';
				num = findNum(label);
				if (num != "0") {
				  var onPanel = "CollapsiblePanel"+num;
          window[onPanel].open();
				}
				labelText = cat.firstChild.firstChild.nodeValue;
//        alert('Setting label text to: ' + labelText);
			}
			else {
				var cat = document.getElementById(label.id);
				cat.className = 'categoryOFF';
				num = findNum(label);
				if (num != "0") {
				  var offPanel = "CollapsiblePanel"+num;
				  //alert("Panel to be turned off: " + offPanel);
          window[offPanel].close();
				}
			}
		}
	}
	if (labelText != '') {
//    alert('Setting label text to: ' + labelText);
    searchTextID = document.getElementById('category00');
		searchTextID.innerHTML = labelText;
	}
}

// ***** Set Merchant Label ******
function setSessionMerchant(obj) {
  var ajax = new Ajax();
//  alert('doGet: /php/setSessionVar.php?merchant='+obj.value);
  ajax.doGet('/php/setSessionVar.php?merchant='+obj.value, handmerchant);
}

var handmerchant = function(str) {
  //alert('Setting Merchant to '+str);
  var merchantTextID = document.getElementById('merchantName');
  merchantTextID.className = 'merchantName';
	merchantTextID.innerHTML = str;
}
// ********************************

// **** Set SubCategory Options *****
function setSubCategory(obj) {
  var ajax = new Ajax();
//  alert('setSubCategory /php/setSessionVar.php?category='+obj.value);
  ajax.doGet('/php/setSubCategory.php?category='+obj.value, handSubCategory);
}

var handSubCategory = function(str) {
//  alert('Setting subcategories to '+str);
  var obj = document.getElementById('subCategorySelect');
  obj.length=0;
  if (str) {
    eval(str);
  }
  else {
    obj.options[obj.options.length] = new Option('Cannot Select','0');
  }
  var obj2 = document.getElementById('subSubCategorySelect');
  obj2.length=0;
  obj2.options[obj2.options.length] = new Option('Cannot Select','0');
//	subCategoryID.innerHTML = str;
}
// *******************************

// **** Set SubSubCategory Options *****
function setSubSubCategory(obj) {
  var ajax = new Ajax();
  //alert('doGet: /php/setSubSubCategory.php?subcategory='+obj.value);
  ajax.doGet('/php/setSubSubCategory.php?subcategory='+obj.value, handSubSubCategory);
}

var handSubSubCategory = function(str) {
  //alert('Setting subsubcategory to '+str);
  var obj = document.getElementById('subSubCategorySelect');
  obj.length=0;
  if (str) {
    eval(str);
  }
  else {
    obj.options[obj.options.length] = new Option('Cannot Select','0');
  }
}
// *******************************


function doSel(obj) {
  if (obj.checked) {
    eval(obj.value);
  }
}

function findNum (obj) {
  return obj.id.match(/\d+$/)[0];
}



