// This is a generic function to get XML HTTP Request object
function appmain_getXmlHttp() {
    var xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function appmain_callAjax(url, method, sendparams, callbackfunc) {
    var responsetype = (typeof(arguments[4]) == 'undefined') ? "JSON" :  arguments[4];
    var gacode = (typeof(arguments[5]) == 'undefined') ?"undef" :  arguments[5];
    var checkLogin = (typeof(arguments[6]) == 'undefined') ? true : arguments[6];
    var redirectToRegister = (typeof(arguments[7]) == 'undefined') ? false : arguments[7];

    var xmlHttp = appmain_getXmlHttp();

    xmlHttp.open(method, encodeURI(url), true);
    if(method == "POST") {
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState == 4) {
            var response = xmlHttp.responseText;
            if(responsetype == "JSON") {
                var json = eval("(" + response + ")");
                var redirected = appmain_redirectIfRequired(json, gacode, checkLogin, redirectToRegister);
                if(redirected == false) {
                    eval(callbackfunc +"(json);");
                }
            }
            else if (responsetype == "RAW") {
                eval(callbackfunc + "(response);");
            }
        }
    };    
    xmlHttp.send(sendparams);
}

function appmain_tabclicked(tabId) {
    document.getElementById("gt-rightpanel").innerHTML = "";
    var url = _LGP_BASE_URL + "index.php?op=tab&active=" + tabId;
    appmain_callAjax(url, "GET", /* params */ null, "appmain_ontabclickedcomplete", "JSON", "flow/tabclick", false /*checkLogin */);
}

function appmain_ontabclickedcomplete(json) {
    document.getElementById("navcontainer").innerHTML = json.html;
}
 
function appmain_refreshHeader() {
    var url = _LGP_BASE_URL + "index.php?op=header";
    appmain_callAjax(url, "GET", null /*params*/, "appmain_refreshHeaderComplete", "JSON", "flow/refreshheader", false /*checkLogin*/);
}

function appmain_refreshHeaderComplete(json) {
    document.getElementById('gt-header').innerHTML = json.html;
}

function appmain_updateCoins() {
    var coins = (typeof(arguments[0]) == 'undefined') ? null :  arguments[0];
    if(coins == null) {
        var url = _LGP_BASE_URL + "index.php?op=coins";
        appmain_callAjax(url, "GET", null /*params*/, "appmain_updateCoinsComplete", "JSON", null /* gacode */, false /*checkLogin*/);
    }
    else {
        document.getElementById("personalGreenBucksCounter").innerHTML = coins;
    }
}

function appmain_updateCoinsComplete(json) {
    document.getElementById('personalGreenBucksCounter').innerHTML = json.html;
}

function appmain_aboutPageClicked() {
    document.getElementById("gt-rightpanel").innerHTML = "";
    appmain_callAjax(url, "GET", null /*params*/, "appmain_aboutPageClickedComplete", "JSON", "flow/aboutclick", false /*checkLogin*/);
}

function appmain_aboutPageClickedComplete(json) {
    document.getElementById('gt-body').innerHTML = json.html;
} 

function appmain_showMessage(msg) {
    var um = document.getElementById('userMessageDiv');
    um.innerHTML = msg;
    um.style["visibility"] = "visible";
    setTimeout("appmain_hideMessage();", 5000);
}

function appmain_hideMessage() {
    var um = document.getElementById('userMessageDiv');
    um.style["visibility"] = "hidden";
}

function getDialogBody(title, msg) {
    return html;
}

function appmain_showDialog() {
    var message = (typeof(arguments[0]) == 'undefined') ? "" :  arguments[0];
    var title = (typeof(arguments[1]) == 'undefined') ? "Dialog" :  arguments[1];
    var button1Text = (typeof(arguments[2]) == 'undefined') ? null :  arguments[2];
    var button1Action = (typeof(arguments[3]) == 'undefined') ? null :  arguments[3];
    var button2Text = (typeof(arguments[4]) == 'undefined') ? null :  arguments[5];
    var button2Action = (typeof(arguments[5]) == 'undefined') ? null :  arguments[5];
    var button3Text = (typeof(arguments[6]) == 'undefined') ? null :  arguments[6];
    var button3Action = (typeof(arguments[7]) == 'undefined') ? null :  arguments[7];

    var html = "";
    html += '<table bgcolor="#ffffff" border="1" frame="border" rules="none">';
    html += ' <tr bgcolor="#3b5998" align="left" style=" color: #ffffff; font-size: 14px; font-family: lucida grande,tahoma,verdana,arial,sans-serif;">';
    html += '   <td align="left" width="95%" colspan="2">';
    html += '    <label style="text-color:white">' + title + '</lable>';
    html += '   </td>';
    html += '   <td align="right" width="5%" colspan="1">';
    html += '    <div style="align:right"><input type="button" class="dialogbutton" onclick="javascript:void(0);appmain_hideDialog();" value="X"></input></div>';
    html += '   </td>';
    html += ' </tr>';
    html += ' <tr bgcolor="#FCFCFC" align="center" class="rootTDSecondCol">';
    html += '   <td colspan="3">';
    html += message;
    html += '   </td>';
    html += ' </tr>';
    if(button1Text != null) {
        html += ' <tr bgcolor="#EDEDED" align="center">';
        html += '   <td width="33%">';
        if(button3Text != null) {
            html += '    <input type="button" class="fbbutton" onclick="javascript:void(0); ' + button3Action + ';" value="' + button3Text + '"></input>';
        }
        html += '   </td>';
        html += '   <td width="33%">';
        if(button2Text != null) {
            html += '    <input type="button" class="fbbutton" onclick="javascript:void(0); ' + button2Action + ';" value="' + button2Text + '"></input>';
        }
        html += '   </td>';
        html += '   <td width="33%">';
        if(button1Text != null) {
            html += '    <input type="button" class="fbbutton" onclick="javascript:void(0); ' + button1Action + ';" value="' + button1Text + '"></input>';
        }
        html += '   </td>';
        html += ' </tr>';
    }
    html += '</table>';


    var ud = document.getElementById('dialogDiv');
    var rd = document.getElementById('rootDiv');
    ud.innerHTML = html;
    ud.style["visibility"] = "visible";
    rd.style["opacity"] = "0.30"; 
    rd.style["filter"] = 'alpha(opacity='+ (30*1) + ')';
    //rd.zoom="1";
//    ud.style["opacity"] = "1.00"; 
}

function appmain_hideDialog() {
    var ud = document.getElementById('dialogDiv');
    var rd = document.getElementById('rootDiv');
    ud.innerHTML = "";
    ud.style["visibility"] = "hidden";
    rd.style["opacity"] = "1.00"; 
    rd.style.filter = 'alpha(opacity=100)';
}

function appmain_redirectToHome() {
    var url = _LGP_BASE_URL + "index.php";
    appmain_callAjax(url, "GET", null /*params*/, "appmain_redirectToHomeCallback", "RAW");
}

function appmain_redirectToHomeCallback(raw) {
    document.write(raw);
    document.close();
}

function appmain_checkMaint(json) {
    //alert ("in check maint");
    if(json.isInMaint == true) {
        document.write(json.html);
        document.close();
        return true;
    }
    return false;
}

//function appmain_redirectIfRequired(json, gacode, checkLogin, redirectToRegister) {
function appmain_redirectIfRequired() {
    
    var json = arguments[0];
    var gacode = (typeof(arguments[1]) == 'undefined') ?"undef" :  arguments[1];
    var checkLogin = (typeof(arguments[2]) == 'undefined') ? true : arguments[2];
    var redirectToRegister = (typeof(arguments[3]) == 'undefined') ? false : arguments[3];
    //alert (gacode + "  " + checkLogin);

    var redirected = appmain_checkMaint(json);
    if(redirected == false) {
        // register with google tracker (only if not in maint mode
        var pageTracker = _gat._getTracker('UA-1032481-4');
        pageTracker._trackPageview(gacode);
        // check for login
        if(checkLogin == true) {
            if (json.isLoggedIn == false) {
                //alert("isLoggedIn is false " + json.invitee + " : " + json.inviteSetId);
                if(json.registerWithGift == true) {
                    //alert("calling registerwithgift " + json.invitee + " : " + json.inviteSetId);
                    authenticate_registerWithGift(json.invitee, json.inviteSetId);
                }
                else {
                    if(redirectToRegister == false) {
                        authenticate_loginClicked();
                    }
                    else {
                        authenticate_registerClicked();
                    }
                }
                redirected = true;
            }
        }
    }
    return redirected;
}
//-------

//GENERIC FUNCTIONS SHOULD BE MOVED SOMEWHERE
//-------

function serializeForm(ele) {

	var str = '';
	for (var i=0; i < ele.length; i++)
	{
		var eid = ele.elements[i].id;
		var ename = ele.elements[i].name;
		var eval =  ele.elements[i].value;
		var type =  ele.elements[i].type;
        var checked = ele.elements[i].checked;
		
		//alert ("eid = " + eid + " ename = " + ename + " eval = " + eval); 
		//if(eid != null && eid.substring(0,4) == 'lgp-') {
        if(type != null && type == 'checkbox' && checked == false) {
            // alert("checked is false for "+eid);
            continue;
        }
		else if(eid != null) {
			if(i > 0) {
				str += ':';
			}
			str += eid + '=' + eval;
		}
		//else if (ename != null && ename.substring(0,4) == 'lgp-') {
		else if (ename != null) {
			if(i > 0) {
				str += ':';
			}
			str += ename + '=' + eval;
		}
	}
	
	return urlencode(str);
}

function urlencode(str) {
//	str = escape(str);
//	str = str.replace('+', '%2B');
//	str = str.replace('%20', '+');
//	str = str.replace('*', '%2A');
//	str = str.replace('/', '%2F');
//	str = str.replace('@', '%40');
//  return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
    return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}

    
function toggle(ele) {
    //alert('in toggle ' + ele.checked + " " + ele.value);
    if(ele.checked == true) {
        ele.value = "on";
    }
    else {
        //alert('turning off');
        ele.value = "off";
    }
}
    

(function () {                                                                 
    var swapper =                                                               
        function (a,L,e) {                                                     
            var r = Math.floor(Math.random()*L);                               
            var x = a[e];                                                       
            a[e] = a[r];                                                       
            a[r] = x;                                                           
        };                                                                     
    Array.prototype.shuffle =                                                   
        function () {                                                           
            var i,L;                                                           
            i = L = this.length;                                               
            while (i--) swapper(this,L,i);                                     
        };                                                                     
})();


