// SIMPLE AJAX FUNCTIONS
// Should support multiple AJAX calls from same page now.

//var targetID = 'ajaxdata';

function AJAXInteraction(url, targetID, callback) {

    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    
    function processRequest () {
      if (req.readyState == 4) {
        if (req.status == 200) {
          if (callback) callback(targetID, req.responseText);
        }
      }
    }

    this.doGet = function() {
      req.open("GET", url, true);
      req.send(null);
    }
    
    this.doPost = function(body) {
      req.open("POST", url, true);
      req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      req.send(body);
    }
}

function ajaxLoad(sourceURL,currentTargetID) {
	//alert(sourceURL + " " + currentTargetID);
  	var ai = new AJAXInteraction(sourceURL, currentTargetID, validateResponse);
  	ai.doGet();
	//ai.doPost();
}

function validateResponse(targetID, myResponse){
	if(myResponse != ''){
		document.getElementById(targetID).innerHTML = parseScript(myResponse);
	}
}


// For evaluating JS in AJAX CALL
// Needs more work and testing
function parseScript(_source) {
		var source = _source;
		var scripts = new Array();
 
		// Strip out tags
		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);
 
			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}
 
		// Loop through every script collected and eval it

		for(var i=0; i<scripts.length; i++) {
			if(scripts[i] != ''){
				try {
					eval(scripts[i]);
				}
				catch(ex) {
					// do what you want here when a script fails
				}
			}
		}
		// Return the cleaned source
		return source;
}

function ddChangeEvent(dd){
	if(!dd){
		var idx = document.getElementById('catID');
		var val = idx.value;
	}else{
		var idx = dd.selectedIndex;
 		var val = dd[idx].value;
  	}
		//alert(val);
	ajaxLoad('/sales/quicksearch.pl?pc='+val,'ajaxdata8');
	ajaxLoad('/sales/quicksearch.pl?pc='+val+'&item=2','ajaxdata9');
}
