function decodeJSON(stringData) {
    try {
        return Ext.util.JSON.decode(stringData);
    }
    catch (err) {
        yt_alert('ERROR', 'Could not decode ' + stringData + '\n\n The error was: ' + err.description);
    }
}
function hide(id) {
    var elem = document.getElementById(id);
    if (elem) elem.style.display = "none";
}

function show(id) {
    var elem = document.getElementById(id);
    if (elem) elem.style.display = "";
}
function update(id, html) {
    var elem = document.getElementById(id);
    if (elem) elem.innerHTML = html;
}
function _login() {
    var btn = document.getElementById("btn_login");
    var progress = document.getElementById("login_progress");
    var form = document.getElementById("form_login");
    if (form) form.submit();
}
function login() {
    var win = Ext.getCmp("popup_login_window");
    if (typeof (win) == "undefined" || !win.isVisible()) {
        hide("btn_login");
        show("login_progress");
        setTimeout("_login();", 500);
    }
}
function _login_popup() {
    Ext.Ajax.request({
        url: yt_WebRootPath + "/public/home/login.rails",
        params: { username: document.getElementById("login-username").value, password: document.getElementById("login-password").value, ajax: 1 },
        method: "POST",
        success: function(result, request) {
            var loginResult = decodeJSON(result.responseText);
            if (loginResult.Result) {
                var elem = document.getElementById("auction_id");
                document.location.href = (elem && elem.value && elem.value.length ? yt_WebRootPath + "/secure/auction/search?id=" + elem.value + "&searchAll=1" : loginResult.Message);
                return;
            }
            show("popup_login_button");
            var progress = Ext.getCmp("popup_login_progress");
            progress.hide();
            progress.reset();
            Ext.getCmp("popup_login_top_label").hide();
            update("popup_login_error_message", loginResult.Message);
            Ext.getCmp("popup_login_error").show();
        },
        failure: function(result, request) {
            var loginResult = decodeJSON(result.responseText);
            Ext.getCmp("popup_login_top_label").hide();
            update("popup_login_error_message", loginResult.Message);
            Ext.getCmp("popup_login_error").show();
        }
    });
}
function login_popup() {
    Ext.EventObject.stopPropagation();
    if (!Ext.getCmp("popup_login_form").getForm().isValid()) return;
    hide("popup_login_button");
    var progress = Ext.getCmp("popup_login_progress");
    progress.show();
    progress.wait({ increment: 100, interval: 20 });
    setTimeout("_login_popup();", 2000);
}
function show_login_popup(id) {
    var win = Ext.getCmp("popup_login_window");
    if (typeof(win) == "undefined") {
        var popup = document.createElement("DIV");
        document.body.appendChild(popup);
        popup.id = "login-popup";
        popup.className = "x-hidden";
        popup.innerHTML = "<div class='x-window-header'>Inloggning</div>";
        win = new Ext.Window({
            autoHeight: true,
            applyTo: 'login-popup',
            closeAction: 'hide',
            id: 'popup_login_window',
            items: new Ext.form.FormPanel({
                bodyStyle: 'padding:15px',
                defaults: { width: 250, msgTarget: 'side' },
                html: '<div id="popup_login_button" style="text-align:right"><input type="button" class="buttonStyle" value="Logga in" onclick="login_popup();"/></div>',
                id: 'popup_login_form',
                items: [
                    new Ext.form.Label({ hidden: true, html: '<div style="float:left"><img src="' + yt_StaticWebPath + '/Content/images/icn_failure.png" onload="fixPNG(this);"/></div><div id="popup_login_error_message" style="font-weight:bold;margin-left:40px;height:32px"/>', id: 'popup_login_error' }),
                    new Ext.form.Label({html:'<div>Du m&#229;ste logga in f&#246;r att bevaka eller l&#228;gga/hantera bud</div><br/>&nbsp;', id:'popup_login_top_label', style:'font-weight:bold;'}),
                    new Ext.form.TextField({ allowBlank: false, fieldLabel: 'E-postadress', id: 'login-username', listeners: { 'specialkey': { fn: function() { if (Ext.EventObject.getKey() == Ext.EventObject.ENTER) login_popup(); } } }, name: 'login-username' }),
                    new Ext.form.TextField({ allowBlank: false, fieldLabel: 'L&#246;senord', id: 'login-password', listeners: { 'specialkey': { fn: function() { if (Ext.EventObject.getKey() == Ext.EventObject.ENTER) login_popup(); } } }, inputType: 'password', name: 'login-password' }),
                    new Ext.form.Label({ html: '<br/><div>Har du gl&#246;mt l&#246;senordet? <b><a href="' + yt_WebRootPath + '/public/home/forgotpassword.rails">Klicka h&#228;r&raquo;</a></b></div><div>Vill du vara med i budgivningen? <b><a href="' + yt_WebRootPath + '/public/home/apply.rails">Registrera dig h&#228;r&raquo;</a></b></div><br/>', style: 'font-weight:bold;' }),
                    new Ext.ProgressBar({ autoWidth: true, hidden: true, id: 'popup_login_progress' }),
                    new Ext.form.Hidden({ id: 'auction_id', name: 'auction_id', value: id })
                ],
                labelWidth: 75,
                labelPad: 10,
                layoutConfig: { labelSeparator: '' }
            }),
            layout: 'form',
            plain: true,
            resizable: false,
            width: 425
        });
        win.on('show', function() { Ext.getCmp("login-username").focus(true, 300); });
    }
    var topLabel = Ext.getCmp("popup_login_top_label");
    if (typeof (id) != "undefined" && id > 0) {
        topLabel.show();
        Ext.getCmp("auction_id").setValue(id);
    } else {
        topLabel.hide();
        Ext.getCmp("auction_id").setValue("");
    }
    show("popup_login_button");
    var progress = Ext.getCmp("popup_login_progress");
    progress.hide();
    progress.reset();
    win.show();
}

function redirectLogin(id) {
    var url = replaceQueryString(window.location.href, 'popupLogin', '1');
    url = replaceQueryString(url, 'auction_id', id);
    if (url.indexOf("/secure/auction/search") > 0)
        url = replaceQueryString(url, 'id', id);
    var replace = 'http://';
    if (yt_SslEnabled)
        replace = 'https://';
    window.location.href = url.replace('http://', replace);
}