/*************************************************************************************************
 *  http.js                                                                                      *
 *  Copyright 2009 Skill Technology, LLC                                                         *
 *                                                                                               *
 *  Author:  Matt Haak                                                                           *
 *  Website: http://www.skilltechnology.com                                                      *
 *************************************************************************************************/

var HTTP;

if (HTTP && (typeof HTTP != "object" || HTTP.NAME))
    throw new Error("Namespace 'HTTP' already exists");

// Create our namespace, and specify some meta-information
HTTP = {};

HTTP.controller = '/a/c';

// This is a list of XMLHttpRequest creation factory functions to try
HTTP._factories = [
    function() { return new XMLHttpRequest(); },
    function() { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); },
    function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
    function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
    function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];

// When we find a factory that works, store it here
HTTP._factory = null;

// Create and return a new XMLHttpRequest object.
// 
// The first time we're called, try the list of factory functions until
// we find one that returns a nonnull value and does not throw an
// exception.  Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {

	if (HTTP._factory != null) return HTTP._factory();

    for(var i = 0; i < HTTP._factories.length; i++) {
        try {
            var factory = HTTP._factories[i];
            var request = factory();
            if (request != null) {
                HTTP._factory = factory;
                return request;
            }
        }
        catch(e) {
            continue;
        }
    }

    // If we get here, none of the factory candidates succeeded,
    // so throw an exception now and for all future calls.
    HTTP._factory = function() {
        throw new Error("XMLHttpRequest not supported");
    }
    HTTP._factory(); // Throw an error
}


HTTP.encodeFormData = function(data) {

	data.timestamp = (new Date()).valueOf();	

    var pairs = [];
    var regexp = /%20/g; // A regular expression to match an encoded space

	try { // IE sometimes craps out on the following for some reason, when first loading the external site
	    for(var name in data) {
	        var value = data[name].toString();
	        // Create a name/value pair, but encode name and value first
	        // The global function encodeURIComponent does almost what we want,
	        // but it encodes spaces as %20 instead of as "+". We have to
	        // fix that with String.replace()
	        var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
	            encodeURIComponent(value).replace(regexp,"+");
	        pairs.push(pair);
	    }
    } catch (e) {}

    // Concatenate all the name/value pairs, separating them with &
    return pairs.join('&');
};

HTTP.WITH_PROGRESS = false;
HTTP.WITHOUT_PROGRESS = true;
HTTP.WITH_CALLBACK = false;
HTTP.WITHOUT_CALLBACK = true;

HTTP.btn_onclick_fn_regex = new RegExp("^.*btn_onclick_fn_([0-9X]+)\(\).*$");

HTTP.quickGet = function(parameters, passthru) {
	this.get(parameters, this.WITH_PROGRESS, this.WITH_CALLBACK, passthru);
}

/* HTTP.getJSession = function () {
	if (window.session != undefined && session.id != undefined)
		return session.id;

	var match = location.href.match(/^[^#]+#([A-F0-9]+)$/);
	if (match) {
		var hashPart = match[1];
		return hashPart;
	}
	
	return null;
} */

HTTP.lowLevelGet = function(controller_path, parameters, txt_handler_fn_name) {
	var target = controller_path;
	var params = HTTP.encodeFormData(parameters);
	var post_data = params;

	// target += ';jsessionid=' + HTTP.getJSession();

	var request = HTTP.newRequest();
	request.open('POST', target);
	request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
	
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", post_data.length);
	request.setRequestHeader("Connection", "close");

	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			if (request.status == 200 && request.responseText.length) {
				lowLevelResponseTextHandler[txt_handler_fn_name](request.responseText);
			} else { alert('request.status:' + request.status + ' request.responseText:' + request.responseText); }
		}
	}
	
	request.send(post_data);
}

HTTP.get = function(parameters, without_progress, without_callback, passthru) {
	
	var btn_progress_id = null;
	var hide_btn_progress_fn = null;
	
	var btn_frame_id = null;
	
	try {
		if (top.showBtnProgress) {
			
			if (self.frameElement)
				btn_frame_id = self.frameElement.id;
			
			// toConsole('call with progress');
		
			var caller = HTTP.get;
			var caller_count = 0;
			var callers_str = '';
			
			while (caller.caller) {
				caller=caller.caller;
		
				// all calls from button clicks will originate with something like this (approx 66 chars):
				
				// function anonymous()
				// {
				// top.btn_onclick_fn_125441050309X2866363()
				// }
		
				// so, we'll only consider callers with (approx) the right length.
				
				if (caller.toString().length < 90) {
					var caller_str = caller.toString().replace(/\n/g,'\uffff');
					
					var m = caller_str.match(HTTP.btn_onclick_fn_regex);
		
					if (m != null) {
						// toConsole('call from button');
						btn_progress_id = m[1]
						top.showBtnProgress(m[1], btn_frame_id);
					}
				}
				
				callers_str += caller + '\n\n';
				
				caller_count++;
				if (caller_count > 1000) // prevent infinite loop just in case
					break;
			}
			
			// alert(callers_str);
		}
	} catch (e) {}
	
	if (!without_progress && window.startProgress)
		startProgress();
	
	var target = HTTP.controller;
	var params = HTTP.encodeFormData(parameters);
	var post_data = params;

	// target += ';jsessionid=' + HTTP.getJSession();
	 
	var request = HTTP.newRequest();
	request.open('POST', target);
	request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
		
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", post_data.length);
	request.setRequestHeader("Connection", "close");

	if (!without_callback) {
		// request.passthru = (passthru ? passthru : null);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				if (request.status == 200 && request.responseText) { 
					if (window.stopProgress)
						stopProgress();
					var r = null;
					eval(request.responseText);
					r.passthru = passthru;
					if (r.condition != 'ERROR_GENERAL') {
						if (actionResponseHandler[r.action])
							actionResponseHandler[r.action](r);
						else
							httpErrorHandler(r.msg + ' (Error on action <' + r.action + '>)');
						
					} else
						handleResponseGenerically(r);
				} else
					httpErrorHandler('XHR Exception: request.status:' + request.status + ' request.responseText:' + request.responseText);
				
				if (btn_progress_id)
					setTimeout('top.hideBtnProgress(\'' + btn_progress_id + '\'' + (btn_frame_id ? ',\'' + btn_frame_id + '\'' : '') + ')',250);
			}
		}
	} else {
		request.onreadystatechange = function() {
			if (request.readyState == 4 && btn_progress_id) {
				setTimeout('top.hideBtnProgress(\'' + btn_progress_id + '\'' + (btn_frame_id ? ',\'' + btn_frame_id + '\'' : '') + ')',250);
			}			
		}
	}
	
	request.send(post_data);
}

function httpErrorHandler(errorMsg) {
	if (window.GG && GG.Nav && GG.Nav.showFloatingError)
		GG.Nav.showFloatingError(errorMsg);
	else
		throw(errorMsg);	
}

if (window.slp)
	slp(5);