<!--
//
//      Global variables needed by event handlers
//
var thisButton = "";
var outId = "";
var progress = "n";
var oldButtonValue = "";
var globalAfterFunc;
var thisButtonFormName = "";
//
//    utility function used to launch an ajax function or straight http redirect
//    and makes available various functionality for user during longer response
//    time functions
//
//    it is invoked by "onclick="buttonDo(params)" on whatever button you want to activate it
//    there are minimum of 11 parameters(it is variable based on the last param which is the
//    number of params being passed to the eventual php function (can be 0). For those that
//    are optional (see below), simply substitute the empty set ("" or '') in the list
//
//
//    after performing any specified js edit function you requested, it will format
//    all data as a post request and always launches php program "activate_php.php"
//    which takes the params you passed to it for passing to the ultimate php "function"
//    and builds an array of params which is passed to the php function as needed
//    (this intermediate step was needed as there is no way to directly pass variables as
//    function params to php from js. You can only send post variables or get variables
//    and in this system we only use post for security reasons)
//
//     Parameter details:
//     (in order)
//
//     1) thisButton - Keyword - this - no quotes around it, just the word (this).
//        this makes the current element easy for the function to find
//        in the DOM by passing it the reference for it
//     2) editf - if you need the screen input validated before launching the
//        ajax request, provide the name of the function her that does the validation
//        Make sure the function you supply for this returns "true" when all fields
//        valid and returns "false" if there are any errors. If any errors, this function will
//        not proceed to launch the ajax
//        *****  DO NOT PUT QUOTES AROUND THIS PARAMETER ******
//     3) mode - this specifies if it is 'ajax' or 'redirect' - it is required
//     4) progress - this indicates if you want a "progress report" of the ajax function as it is
//        running. Possible values are 'y' and 'n'
//****************************************************************************************************************
//        HTML NOTE: In order to display the progress, this function assumes an element with an "id" of
//        the same name as the id of the button with a suffix of "pro" (for progress) and this is where
//        it will place this info (usually just under the button or image if one was supplied)
//****************************************************************************************************************
//     5)  url - this is the url of the php program you want to call using ajax or the page you want to redirect to
//        (if doing a straight redirect) it is required
//     6) image - this is optional and if supplied is the url of an image you would like to replace
//        the button for the duration of the ajax process
//     7) outId - this is the "id" of the element on your page to which any returned output from
//        the ajax app should be directed
//     8) disable - this indicates if you want the button disabled for the duration of the ajax
//        process (to prevent user from clicking it again while waiting for the repsonse) -
//        possible values are 'true' (yes, disable it) and 'false' (no, do not disable it) to
//        mirror the values of this attribute of the element (eg, thisElement.disabled = true)
//     9) newValue - this is optional and specifies, as an alternative to a new image, to simply
//        change the text on the button for the duration of the process
//    10) imageLoc - this determines where image is to be placed:
//              b = under button/onclick link
//       *******   NOTE RE HTML  *******  this expects an id of the button with a suffix of "img" in the HTML
//              o = output location (outId)
//        if not specified, defaults to 'b'
//    11) This is an optional argument which contains the name of a js function to be executed
//        after the ajax call has returned. This is because it may need the DOM elements created by the
//        AJAX call and can't be execjuted before then and browser will not execute javascript
//        that is echo'd by the ajax function
//
function buttonDo(thisButton,editf,mode,progress,url,image,outId,disable,newValue,imageLoc,afterFunc) {  
//    alert("Start of buttonDo");
   if (arguments.length  !== 10 && arguments.length !== 11) {
        alert("Invalid arguments. Received " + arguments.length + " . Must be 10 or 11 arguments.");
        return false;
    }
    if (typeof editf != "function" && editf != "") {
        alert("Invalid function name  of " + editf + " passed as 2nd parameter");
        return false;
    }
    if (mode != 'ajax' && mode != 'redirect') {
        alert('3rd param, mode, must be "ajax" or "redirect"');
        return false;
    }
    if (progress != 'y' && progress != 'n') {
        alert('4th param, progress, must be "y" or "n"');
        return false;
    }
    if (progress == 'y' && !$(thisButton.id+'pro')) {
        alert("Screen id of " + thisButton.id+"pro" + " missing from screen layout");
        return false;
    }
    if (disable != 'true' && disable != 'false' && disable != "") {
        alert('8th param, disable, if specified, must be "true" or "false"');
        return false;
    }
    if (url == "" ) {
        alert('url is required');
        return false;
    }
    //if (mode == 'ajax' && outId == "") {
        //alert("outId is required when doing ajax calls");
        //return false;
    //}
    if (outId !== "" && !$(outId)) {
        alert("outId of" + outId + " is not a valid element id on this screen");
        return false;
    }
    if (imageLoc !== "" && imageLoc !== 'b' && imageLoc !== "o"){
        alert('10th param imageLoc must be "b" for button or "o" for output Id if supplied');
        return false;
    }
    if (imageLoc == "") {
        imageLoc = "b";
    }
    if (typeof afterFunc != "undefined") {
        if (typeof afterFunc != "function" && afterFunc != "") {
            alert("Invalid after function name  of " + afterFunc + " passed as 11th parameter");
            alert("Type of for afterFunc is " + typeof afterFunc);
            return false;
        }
        else {
            globalAfterFunc = afterFunc;
        }
    }



//
//   now that all input parameters have been validated,
//   invoke the js edit function if one was supplied
//
//   if errors are found (edit function returns false in that case)
//   do not launch any php, but return with false
//
    if (typeof editf == "function") {  
        if (!editf(thisButton)) {
//        //alert("edits failed");
        return false;
        }
    }
//
//   save original button values so you can restore them at the end
//
    oldButtonValue = thisButton.value;
    oldButton = thisButton;
//  hl
    var el = thisButton;
    while(el !== document && el.tagName.toUpperCase() !== 'FORM') {
          el = el.parentNode;
    }
    thisButtonFormName = el.name;
//    alert("form name = " + thisButtonFormName);
    oldButtonFormName = thisButtonFormName;
// hl
    if (newValue != "") {
        thisButton.value = newValue;
    }
    if (image !== "") {
        if (imageLoc == 'b') {
            if (!$(thisButton.id + "img")) {
                alert("Screen ID of " + thisButton.id + "img" + " missing from screen layout")
                return false;
            }
            else {  
                $(thisButton.id + "img").innerHTML = '<img src="' + image + '">';
            }    
        }
        else {
             $(outId).innerHTML = '<img src="' + image + '">'; 
        }
    }
	
    if (disable == 'true') {
        thisButton.disabled = true;
    }
    switch(mode) {
        case "ajax" :
            runAjax(thisButton,url,outId,progress,oldButton,oldButtonFormName);
            break;
        case "redirect" :
            sendRedirect(thisButton,url);
            break;
        default :
            //alert("invalid mode of " + mode + " was received");
            break;
    }
    
}
//
//    this urltion simply sends to another page by changing the action= attribute
//    of the form the button was on to the 
//
function sendRedirect(thisButton,url) {
//    alert("About to check form");
    if (typeof thisButton.form != 'undefined') {
//        alert("object has form");
        var thisForm = thisButtonFormName;
        document.forms[thisForm].action = url;
        document.forms[thisForm].submit();
        return true;
    }
    else {
//      alert("object has no form");
      window.location=url;
    }
}
//
//     this function launches asynchronous ajax
//     and deposits the output in the id specified on the params when
//     buttonDo was called
//
function runAjax(thisButton,url,outId,progress,oldButton,oldButtonFormName){  
//    alert("entered runAjax");
    var postData;
//
//   define xmlhttp here so new copy is created each time
//   function is called so can handle multiple AJAX requests
//   overlapping without confusing the separate requests
//
    var xmlhttp;
//
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }//
//     set up event handler for when asynchronous request completes
//     successfully to output results to screen element with ID of
//     "output"
//

    xmlhttp.onreadystatechange=function() {
        //alert("Checking readystate = " + xmlhttp.readyState);
        //alert("Event handler: progress = " + progress);
        //alert("Event handler button value" + thisButton.value);
        if (progress == "y") {  
            switch(xmlhttp.readyState) {
                case 1 :
                    $(thisButton.id + "pro").innerHTML = "Sending.....";
                    break;
                case 2 :
                    $(thisButton.id + "pro").innerHTML = "Processing.....";
                    break;
                case 3 :
                    $(thisButton.id + "pro").innerHTML = "Receiving.....";
                    break;
                case 4 :
                    $(thisButton.id + "pro").innerHTML = "Completed!";
//                    alert("Status on return " + xmlhttp.status);
//                    alert("Response: " + xmlhttp.responseText);
                    break;
                default :
                    break;
            }
        }
//
//     once process is complete, re-enable the button
//     by setting disabled to false
//

        if (xmlhttp.readyState==4 && xmlhttp.status==200) {

			if (outId == "category" || outId == "manufacturer") {
				while ($(outId).length > 0) {
					$(outId).removeChild($(outId)[0]);
				}	
				
				addOption($(outId),"Any","","True");
				var resultdata = xmlhttp.responseText;
				var resultdata_array = resultdata.split("#|#");

					for (i=0; i < resultdata_array.length; i++) {
						addOption($(outId), resultdata_array[i], resultdata_array[i],"");
					}
			}
			else {
				if (outId == "sku_list_div" && xmlhttp.responseText == "")
					$(outId).style.display='none';
				else if (outId == "sku_list_div" && xmlhttp.responseText != "")
					$(outId).style.display='block';
				
				$(outId).innerHTML = xmlhttp.responseText;
			}
			// alert("Response: " + xmlhttp.responseText);
            thisButton.disabled = false;
            thisButton.value = oldButtonValue;
            if ($(thisButton.id + "img")) { 
                $(thisButton.id + "img").innerHTML = "";
            }
//
//      check to see if in input parameters it was specified to run another
//      js function after receiving the output from the ajax function
//
            if (typeof globalAfterFunc == "function") {
                globalAfterFunc();
            }
        }
    }
//
//   format all form input into postData
//
    postData = formatPostData(thisButton,oldButton,oldButtonFormName);
//    alert('postData = ' + postData);
//
//      set up to send data to PHP function activate_php.php using "POST" method
//
//    alert("Opening AJAX connection");
//    alert("URL = " + url);
    xmlhttp.open("POST",url,true);
//    alert("Sending headers");
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//    alert("Sending AJAX request");
    xmlhttp.send(postData);
//    alert("Launched activate_php.php");
    return false;
}

function formatPostData(thisButton,oldButton,oldButtonFormName) {
//
//   first gather up all input and select tags to pass in $_POST
//   as the convention for PHP
//
    var postData = "";
    //alert("Finding all input and select tags");
    var allInput = $$("input","select","textarea");
//
//   while going through all the input fields,
//   only select those fields on the form where the button was clicked
//   by checking that the form name of the element == the form name of the button clicked
//
//   for radio and checkboxes you have to check the "checked" property to see
//   if it was selected before formastting the post variables
//
    for (var i=0;i<allInput.length;i++) {
   
	if(allInput[i].form)
	  {
	    if(allInput[i].form.name == oldButtonFormName) {  
            if (postData !== "") {
                postData += "&";
            }
            if(allInput[i].type == "radio" || allInput[i].type == "checkbox") {
                if(allInput[i].checked == "1") {
					mydata = allInput[i].value;
					if (mydata.indexOf("&") > -1)
					mydata = mydata.replace("&", "#|#");
					
                    postData += allInput[i].name + "=" + mydata;
                }
            }
			
            if(allInput[i].type !== "radio" && allInput[i].type !== "checkbox") {
					mydata = allInput[i].value;
					if (mydata.indexOf("&") > -1)
					mydata = mydata.replace("&", "#|#");

                    postData += allInput[i].name + "=" + mydata;
            }
            
        }
		}
    }
    
     return postData;
}

function addOption(selectbox,text,value,select)	{
	var optn = document.createElement("option");
	optn.text  = text;
	optn.value = value;

	if (select == "True")
		optn.selected = true;
		
	selectbox.options.add(optn);
}
//-->

