
/**
 * @author Rigre G. Garciandia Sonora
 * 
 */
var ajaxInitialize = false;
var detectedActiveX = "";
var commandDivName = "commandPlaceholder";
var actionDivName = "actionPlaceholder";
var hexVals = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
var unsafeString = "\"<>%\\^[]`+$,&";
var executingAJAXActionCount = 0;
whereX = 0;
whereY = 0;
var nn = (navigator.appName.indexOf("Netscape") != -1);
var dD = document, dH = dD.html, dB = dD.body, px = dD.layers ? "" : "px";
function floatSS(iX, iY, id) {
    var L = dD.getElementById ? dD.getElementById(id) : dD.all ? dD.all[id] : dD.layers[id];
    this[id + "O"] = L;
    if (dD.layers) {
        L.style = L;
    }
    L.nX = L.iX = iX;
    L.nY = L.iY = iY;
    L.P = function (x, y) {
        this.style.left = x + px;
        this.style.top = y + px;
    };
    L.Fss = function () {
        var pX, pY;
        pX = (this.iX >= 0) ? 0 : nn ? innerWidth : nn && dH.clientWidth ? dH.clientWidth : dB.clientWidth;
        pY = nn ? pageYOffset : nn && dH.scrollTop ? dH.scrollTop : dB.scrollTop;
        if (this.iY < 0) {
            pY += nn ? innerHeight : nn && dH.clientHeight ? dH.clientHeight : dB.clientHeight;
        }
        this.nX += (pX + this.iX - this.nX);
        this.nY += (pY + this.iY - this.nY);
        this.P(this.nX, this.nY);
        setTimeout(this.id + "O.Fss()", 33);
    };
    return L;
}
//AJAX
function $() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == "string") {
            element = document.getElementById(element);
        }
        if (arguments.length == 1) {
            return element;
        }
        elements.push(element);
    }
    return elements.length != 0 ? elements : null;
}
function AJAXRequest(url, data, async, process, error, postAction, method) {
    if (typeof $("AJAXLoading") != "undefined" && $("AJAXLoading") != null) {
        if (!ajaxInitialize) {
            ajaxInitialize = true;
            floatSS(whereX, whereY, "AJAXLoading").Fss();
        }
        setVisible("AJAXLoading", true);
        executingAJAXActionCount++;
    }
    var self = this;
    if (window.XMLHttpRequest) {
        self.ajaxContext = new XMLHttpRequest();
    } else {
        if (window.ActiveXObject) {
            if (detectedActiveX) {
                self.ajaxContext = new ActiveXObject(detectedActiveX);
            } else {
                var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
                for (var i = 0; i < versions.length; i++) {
                    try {
                        self.ajaxContext = new ActiveXObject(versions[i]);
                        if (self.ajaxContext) {
                            detectedActiveX = versions[i];
                            break;
                        }
                    }
                    catch (objException) {
                    }
                }
            }
        }
    }
    self.process = process;
    self.error = error;
    self.postAction = postAction;
    self.ajaxContext.onreadystatechange = function () {
        if (self.ajaxContext.readyState == 4) {
            if (typeof $("AJAXLoading") != "undefined" && $("AJAXLoading") != null) {
                executingAJAXActionCount--;
                if (executingAJAXActionCount == 0) {
                    setVisible("AJAXLoading", false);
                }
            }
            if (self.ajaxContext.status == 200) {
                if (self.ajaxContext.responseText.indexOf("<!--" + commandDivName + ":") == -1) {
                    if (typeof self.process != "undefined" && self.process != null) {
                        self.process(self.ajaxContext);
                    }
                    if (typeof self.postAction != "undefined" && self.postAction != null) {
                        self.postAction(self.ajaxContext);
                    }
                    var responseText = self.ajaxContext.responseText;
                    var commandPrefix = "<!--" + actionDivName + ":";
                    var initialPosition = responseText.indexOf(commandPrefix);
                    while (initialPosition != -1) {
                        var lastPosition = responseText.indexOf("-->", initialPosition);
                        eval(responseText.substring(initialPosition + commandPrefix.length, lastPosition));
                        initialPosition = lastPosition + 3;
                    }
                } else {
                    var responseText = self.ajaxContext.responseText;
                    var commandPrefix = "<!--" + commandDivName + ":";
                    eval(responseText.substring(responseText.indexOf(commandPrefix) + commandPrefix.length, responseText.indexOf("-->")));
                    if (typeof self.postAction != "undefined" && self.postAction != null) {
                        self.postAction(self.ajaxContext);
                    }
                }
            } else {
                if (typeof self.error == "undefined" || self.error == null) {
                    alert("There was a problem retrieving the :\n" + self.ajaxContext.statusText);
                } else {
                    self.error(self.ajaxContext);
                }
            }
        }
    };
    if (!method) {
        method = "POST";
    }
    method = method.toUpperCase();
    if (typeof async == "undefined" || async == null) {
        async = true;
    }
    self.ajaxContext.open(method, url, async);
    if (method == "POST") {
        self.ajaxContext.setRequestHeader("Connection", "close");
        self.ajaxContext.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.ajaxContext.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }
    if (!data) {
        data = "";
    }
    self.ajaxContext.send(data);
    return self.ajaxContext;
}
//URL enconde
function isUnsafe(compareChar) {
    return unsafeString.indexOf(compareChar) != -1;
}
function decToHex(num, radix) {
    var hexString = "";
    while (num >= radix) {
        temp = num % radix;
        num = Math.floor(num / radix);
        hexString += hexVals[temp];
    }
    hexString += hexVals[num];
    return reversal(hexString);
}
function reversal(s) {
    var len = s.length;
    var trans = "";
    for (var i = 0; i < len; i++) {
        trans = trans + s.substring(len - i - 1, len - i);
    }
    s = trans;
    return s;
}
function convert(val) {
    return "%" + decToHex(val.charCodeAt(0), 16);
}
function encode(val) {
    var len = val.length;
    var backlen = len;
    var i = 0;
    var newStr = "";
    var frag = "";
    var encval = "";
    var original = val;
    for (var i = 0; i < len; i++) {
        if (val.substring(i, i + 1).charCodeAt(0) < 255) {
            if (isUnsafe(val.substring(i, i + 1)) == false) {
                newStr = newStr + val.substring(i, i + 1);
            } else {
                newStr = newStr + convert(val.substring(i, i + 1));
            }
        } else {
            alert("Found a non-ISO-8859-1 character at position: " + (i + 1) + ",\nPlease eliminate before continuing.");
            newStr = original;
            i = len;
        }
    }
    return newStr;
}
// Common functions
function unloadContent(file) {
    var head = document.getElementsByTagName("head").item(0);
    var scriptTag = document.getElementById("loadScript");
    if (scriptTag) {
        head.removeChild(scriptTag);
    }
}
function loadContentFromArray(files) {
    var head = document.getElementsByTagName("head").item(0);
    var scriptTag = document.getElementById("loadScript");
    if (scriptTag) {
        head.removeChild(scriptTag);
    }
    for (var i = 0; i < files.length; i++) {
        script = document.createElement("script");
        script.src = files[i];
        script.type = "text/javascript";
        script.id = "loadScript";
        head.appendChild(script);
    }
}
function loadContent(file) {
    var head = document.getElementsByTagName("head").item(0);
    var scriptTag = document.getElementById("loadScript");
    if (scriptTag) {
        head.removeChild(scriptTag);
    }
    script = document.createElement("script");
    script.src = file;
    script.type = "text/javascript";
    script.id = "loadScript";
    head.appendChild(script);
}
function createFlowURL(flowExecutionId, eventId) {
    return "wine.html?_flowExecutionId=" + flowExecutionId + "&_eventId=" + eventId;
}
function executeScriptFromDIV(divid) {
    eval($(divid).innerHTML);
}
function createFormParameters(formName, parameters) {
    var generatedParameter = "";
    for (var i = 0; i < parameters.length; i++) {
        eval("var type = document." + formName + "." + parameters[i] + ".tagName");
        if (type == "INPUT" || type == "TEXTAREA") {
            eval("var temp = document." + formName + "." + parameters[i] + ".value");
            generatedParameter += parameters[i] + "=" + escape(temp);
        } else {
            if (type == "SELECT") {
                eval("var count = document." + formName + "." + parameters[i] + ".options.length;");
                if (count > 0) {
                    eval("var temp = document." + formName + "." + parameters[i] + ".options[document." + formName + "." + parameters[i] + ".options.selectedIndex].value");
                }
                generatedParameter += parameters[i] + "=" + Url.encode((count != 0 ? temp : ""));
            } else {
                alert("Error, expecting an input type not registered: " + parameters[i]);
            }
        }
        if (i < parameters.length - 1) {
            generatedParameter += "&";
        }
    }
    return generatedParameter;
}
//Util functions
function setVisible(divName, visible) {
    $(divName).style.visibility = visible ? "visible" : "hidden";
}
function isVisible(divName) {
    return $(divName).style.visibility == "visible";
}
function booleanToDivVisible(visible) {
    return visible ? "visible" : "hidden";
}
function cleanDiv(divName) {
    $(divName).innerHTML = "";
}
function populateDiv(divName, text) {
    $(divName).innerHTML = text;
}
function submitAJAXFormPlaceholder(url, data, postAction) {
    new AJAXRequest(url, data, true, postAction, null, null, "POST");
}
function populateAJAXFormPlaceholder(url, data, divId) {
    new AJAXRequest(url, data, true, function (ajaxContext) {
        $(divId).innerHTML = ajaxContext.responseText;
    }, null, null, "POST");
}
function populateAJAXFormPlaceholderWithPostAction(url, data, divId, postAction) {
    new AJAXRequest(url, data, true, function (ajaxContext) {
        $(divId).innerHTML = ajaxContext.responseText;
    }, null, postAction, "POST");
}
function populateAJAXFormPlaceholderWithPostActionAndError(url, data, divId, postAction, error) {
    new AJAXRequest(url, data, true, function (ajaxContext) {
        $(divId).innerHTML = ajaxContext.responseText;
    }, error, postAction, "POST");
}
function populateAJAXPlaceholder(url, divId) {
    new AJAXRequest(url, null, true, function (ajaxContext) {
        $(divId).innerHTML = ajaxContext.responseText;
    });
}
function populateAJAXPlaceholderWithPostAction(url, divId, postAction) {
    new AJAXRequest(url, null, true, function (ajaxContext) {
        $(divId).innerHTML = ajaxContext.responseText;
    }, null, postAction);
}
function executeAJAXCommandWithPostAction(url, postAction) {
    new AJAXRequest(url, null, true, null, null, postAction);
}
function executeAJAXCommand(url) {
    new AJAXRequest(url, null, true);
}
function executeAJAXPostCommand(url, data) {
    new AJAXRequest(url, data, true, null, null, null, "POST");
}
function requestAJAXData(url, data, postAction) {
    new AJAXRequest(url, data, true, postAction);
}
function requestAJAXSyncData(url, data, postAction) {
    new AJAXRequest(url, data, false, postAction);
}

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

} 

function urlEncode(plaintext) {
    var SAFECHARS = "0123456789" +  // Numeric
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +  // Alphabetic
    "abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()";                    // RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+";             // x-www-urlencoded, rather than %20
        } else {
            if (SAFECHARS.indexOf(ch) != -1) {
                encoded += ch;
            } else {
                var charCode = ch.charCodeAt(0);
                if (charCode > 255) {
                    //alert("Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" + "(URL encoding only supports 8-bit characters.)\n" + "A space (+) will be substituted.");
                    encoded += "+";
                } else {
                    encoded += "%";
                    encoded += HEX.charAt((charCode >> 4) & 15);
                    encoded += HEX.charAt(charCode & 15);
                }
            }
        }
    } // for
    return encoded;
}
function urlDecode(encoded) {
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
        var ch = encoded.charAt(i);
        if (ch == "+") {
            plaintext += " ";
            i++;
        } else {
            if (ch == "%") {
                if (i < (encoded.length - 2) && HEXCHARS.indexOf(encoded.charAt(i + 1)) != -1 && HEXCHARS.indexOf(encoded.charAt(i + 2)) != -1) {
                    plaintext += unescape(encoded.substr(i, 3));
                    i += 3;
                } else {
                    alert("Bad escape combination near ..." + encoded.substr(i));
                    plaintext += "%[ERROR]";
                    i++;
                }
            } else {
                plaintext += ch;
                i++;
            }
        }
    } // while
    return plaintext;
}
