var prefix = "";
var allowSubmit = false;
var form;

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery(document).ready(function() {
	if(window.location.href.indexOf("logout.php") != -1) {
		jQuery.cookie("WHMCSUID", null); //, {path:"/"}
		jQuery.cookie("WHMCSPW", null); //, {path:"/"}]
		jQuery.cookie("WHMCSUID", null, {path:"/"});
		jQuery.cookie("WHMCSPW", null, {path:"/"});
		jQuery.cookie("WHMCSUID", null, {path:"/portal"});
		jQuery.cookie("WHMCSPW", null, {path:"/portal"});
	}
	//jQuery("body").append("<textarea id='textBuffer' style='width=100%;height=400px;'>"+document.cookie+"</textarea>");
	var loginBtn = jQuery("input[name='Login']");
	loginBtn.click(function() {
		try {
			if(allowSubmit) { return true; }
			form  = jQuery(this).parents("form");
			var kids  = form.children("input,select,textarea,button");
			var eleme = {};
			kids.each(function () {
				eleme[jQuery(this).attr('name')] = jQuery(this).val();
			});
//			var cookies = document.cookie.split(";");
//			for (i in cookies) {
//				var cook = cookies[i].split("=");
//				eleme[cook[0].replace(/^\s+|\s+$/g,"")] = cook[1].replace(/^\s+|\s+$/g,"");
//			}
			var forma = form.attr("action");
			
			if(forma.indexOf("/") != -1) {
				prefix = forma.substring(0, forma.lastIndexOf("/")+1); 
			}
			
			form.prepend("<div style='float:right;margin:0 0 0 -10px;padding:4px 15px 0px 0px;'><img src='"+prefix+"images/spinner.gif' /></div>");
			
			eleme['rememberme'] = 'on';
			
			//alert(eleme);
			jQuery.ajax({
				type:		'POST',
				url:		forma, 
				data:		eleme,
				context:	document,
				dataType:	'html',
				success:	function(data, textStatus) {
					//jQuery("#textBuffer").val(data);
					if(data.indexOf("Access Denied") != -1) {
						//alert("Access Denied!");
						allowSubmit = true;
						form.submit();
					} else {

						data = data.replace(/src\="/g, "src=\""+prefix+"");
						data = data.replace(/href\="/g, "href=\""+prefix+"");
						data = data.replace(new RegExp(prefix+"\/http", "gi"), "http");
						//alert("Access Granted!");
						var html = jQuery("div[class='body']:first-child", data).html();
						//jQuery("#textBuffer").val(html);
						
						var start = data.indexOf("whmcsuid=")+9;
						var end = data.indexOf(";", start);
						var whmcsuid = data.substring(start, end);
						start = data.indexOf("whmcspw=")+8;
						end = data.indexOf(";", start);
						var whmcspw = data.substring(start, end);
						start = data.indexOf("phpsess=")+8;
						end = data.indexOf(";", start);
						var sess = data.substring(start, end);
						
						//jQuery.cookie("PHPSESSID", sess, {path:prefix});
						jQuery.cookie("WHMCSUID", whmcsuid, {path:"/"+prefix});
						jQuery.cookie("WHMCSPW", whmcspw, {path:"/"+prefix}); //"/"+
						
						jQuery("div[class='body']:first-child").html(html);
					}
				},
				complete:	function(xhr, textStatus) {
					//jQuery("#textBuffer").val(dump(xhr));
				}
			});
			//alert("POSTing to "+forma+" "+dump(eleme));
		}
		catch(e){
			//console.write(e.description);
		}
		finally{
			return false;
		}
	});
});

function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }
    return out;
}
