//var httpObj = new Skava_Http_class();
var jx = (new Skava_Http_class()).jax;

function Skava_Http_class()
{
    this.jax = 
    {
        http : false,// We create the HTTP Object
        format : 'text',
        callback : function(data){},
        error: function(err) {alert(err);},
        //Create a xmlHttpRequest object - this is the constructor. 
        getHTTPObject : function() 
        {
            var http = false;

            //Use IE's ActiveX items to load the file.
            if(typeof ActiveXObject != 'undefined') 
            {
                try 
                {
                    http = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) 
                {
                    try 
                    {
                        http = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (E) 
                    {
                        http = false;
                    }
                }
            } 
            else if (XMLHttpRequest) 
            {
                try 
                {
                    http = new XMLHttpRequest();
                }
                catch (e) 
                {
                    http = false;
                }
            }
            return http;
        },
        load : function (url,callback,format, method, errcallback, body) 
        {
            this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
            if(!this.http||!url) 
                return;

            if(!method)
            {
                method="GET";
            }
            this.callback=callback;
            if(!format) format = "text/xml";//Default return type is 'text'
            this.format = format.toLowerCase();
            var ths = this;//Closure
            //Kill the Cache problem in IE.
            var now = "uid=" + new Date().getTime();
            url += (url.indexOf("?")+1) ? "&" : "?";
            url += now;
            this.http.open(method, url, true);

            this.http.onreadystatechange = function() 
            {   //Call a function when the state changes.
                if(!ths) return;
                var http = ths.http;
                if (http.readyState == 4) 
                {
                    var NETWORK_ERROR = "Please check your network connection and try again.";
                    var httpStatus = 0;
                    var httpStatusText = "";                 
                    
                    try
                    {
                        httpStatus = ((typeof(http.status) == "undefined" || !http.status) ? 500 : http.status);
                        httpStatusText = ((typeof(http.statusText) == "undefined" || !http.statusText || http.statusText == "Unknown") ? 
                            NETWORK_ERROR : http.statusText);
                    }
                    catch(e)
                    {
                        httpStatus = 500;
                        httpStatusText = NETWORK_ERROR;
                    }
                    
                    //Ready State will be 4 when the document is loaded.
                    if (httpStatus == 200) 
                    {
                        var result = "";
                        if(http.responseText) result = http.responseText;
                        //alert(result);
                        //If the return is in JSON format, eval the result before returning it.
                        if(ths.format.charAt(0) == "j") 
                        {
                            result = result.replace(/[\n\r]/g,"");//\n's in the text to be evaluated will create problems in IE
                            result = eval('('+result+')'); 
                        }                     
                        //Give the data to the callback function.
                        if(ths.callback) ths.callback(result, http);
                    }
                    else 
                    { 
                        //An error occured
                        if(errcallback)
                        {
                            errcallback(httpStatus, httpStatusText);
                        }                    
                        else if(ths.error) 
                        {
                            ths.error(httpStatus + " " + httpStatusText + " for url " + url + " and method " + method);
                        }
                    }
                }
            }

            if(method == "POST")
            {
                this.http.setRequestHeader("Content-Type", this.format);
            }
            this.http.send((body) ? body : null);
        },

        init:function()
        {
            this.http=this.getHTTPObject();
        }
    }    
}

Skava_Http_class.prototype.jax;    


function doAWSUpload(idForm, url, errorCallback)
{
    var form = document.getElementById(idForm);
    // need to encode the file name - if the filename has an '&' (or for ie, if anywhere in the full file path there is an '&'), 
    // that & is not url encoded in ff or ie. this is to fix that case.
    url = url + "&" + urlEncode({file: form.file.value}) + "&transport=direct";

    //alert(url);
    
    var afterUpload = function(result)
    {
        if(result.jsonerror)
        {
            if(errorCallback)
            {
                errorCallback(0, result.jsonerror);
            }    
            else
            {
                alert(result.jsonerror);
            }
        }
        else
        {
            // see http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434&categoryID=55
            form.key.value = result.key;
            form.AWSAccessKeyId.value = result.AWSAccessKeyId;
            form.acl.value = result.acl;
            form.success_action_redirect.value = result.success_action_redirect;
            form.policy.value = result.policy;
            form.signature.value = result.signature;
            form['Content-Type'].value = result['Content-Type'];
            var isIE = window.ActiveXObject ? true : false;
            // TODO: figure out why https doe snot work in IE - it does not work even when 
            // u do a simple html with the form action to https and rest of the inputs directly filled in the html (no java script use)

            // for safari also, it is an issue - will prompt to accept cert in an upload. If we are in an iframe, as we are for our fb apps, it causes incorrect navigation.
            //if(isIE)
            {
                var idx = result.action.indexOf("https:");
                if(idx == 0)
                {
                    result.action = "http:" + result.action.substring(6 /*length of https:*/);
                }
            }
            form.action = result.action;  
            
            /*
            alert(result.AWSAccessKeyId);
            alert(result.acl);
            alert(result.success_action_redirect);
            alert(result['Content-Type']);
            alert(result.policy);
            alert(result.signature);
            alert(form.action);
            */
            form.submit();
        }
    }
    //alert("url=" + url);
    if(errorCallback)
    {
        jx.load(url, afterUpload, "json", "GET", errorCallback);
    }
    else
    {
       jx.load(url, afterUpload, "json");
    }
}


function createDelegate(fn, scope, args)
{
    var fnDelegate = function()
    {
        // use fn.apply, not fn.call cos args is an array. fn.call does not unroll the array into multiple arguments, but fn.apply does
        // http://blog.metawrap.com/blog/TheVeryUsefulJavaScriptCallAndApplyFunctionsForOverridingThisForAGivenFunction.aspx
        fn.apply(scope, args);
    }
    return fnDelegate;
}

/*
function dumpObjectLevels(obj, levels)
{
    return  dump("","",obj, 0, levels, true);
}

function dump(strPrefix, indentStr, obj, curlevel, maxlevels, force)
{
    var strToReturn ="";
    if(maxlevels == -1 || curlevel < maxlevels)
    {
        if (obj == null)
        {
            strToReturn = "[null]";
        }
        else if (typeof(obj) == "function")
        {
            strToReturn = "[function]";
        }
        else if (typeof(obj) == "number" || typeof(obj) == "string" ||typeof(obj) == "boolean")
        {
            strToReturn = obj;
        }
        else 
        {
            strToReturn +="{";
            var isFirst = true;
            for (var propName in obj)
            {
                if(isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    strToReturn += ', ';    
                }
                strToReturn += indentStr + propName + ": ";
                try
                {
                    strToReturn += dump(strPrefix, indentStr + "  ", obj[propName], curlevel + 1, maxlevels, force);
                }
                catch(err)
                {
                    strToReturn += err;
                }
            }
            strToReturn +="}\n";
        }
    }
    
    return strPrefix + strToReturn;
}

*/

// querystring to POST JavaScript
// copyright 15th October 2007 by Stephen Chapman
// permission to use this Javascript on your web page is granted
// provided that all of the code in this script (including these
// comments) is used without any alteration
function toPost(getString, newTab) 
{
    var parms = getString.split('?'); 
    var newF = document.createElement("form"); 
    newF.action = parms[0]; 
    newF.method = 'POST'; 
    if(newTab)
    {
        newF.target = "_blank";
    }
    var parms = parms[1].split('&'); 
    for (var i=0; i<parms.length; i++) 
    {
        var pos = parms[i].indexOf('='); 
        if (pos > 0) 
        {
            var key = parms[i].substring(0,pos); 
            var val = parms[i].substring(pos+1);  
            /*@cc_on @if (@_jscript)  var newH = document.createElement("<input name='"+key+"'>");  @else */  
            var newH = document.createElement("input"); 
            newH.name = key; /* @end @*/ 
            newH.type = 'hidden'; 
            newH.value = unescape(val); 
            newF.appendChild(newH);
        }
    } 
    document.getElementsByTagName('body')[0].appendChild(newF); 
    newF.submit();
}

// from http://www.xml.com/pub/a/2005/11/09/fixing-ajax-xmlhttprequest-considered-harmful.html?page=2

function getDataFromServer(id, url) 
{    
    // Fetch the element pointed to by the id. If it exists, we destroy it so we can create a new one.
    var oScript = document.getElementById(id);

    // Point at the script tag, if it exists
    var head = document.getElementsByTagName("head").item(0);
     // Destroy the tag, if it exists
    if (oScript) 
    {
        // Destory object
        head.removeChild(oScript);
    }    
    // Create the new script tag
    oScript = document.createElement("script");

    oScript.type = 'text/javascript';
    
    // Setup the src attribute of the script tag
    oScript.src = url;

    if(id)
    {
        // Set the id attribute of the script tag
        oScript.id = id;
    }

    // Create the new script tag which causes the proxy to be called
    head.appendChild(oScript);
}
