// (c) 2008 klickTel AG. All rights reserved.

var loginDialogClass = Class.create({
    
    prototypeVersion:0,
    id:'loginDialogContainer',
    signupId:'signupDialogContainer',
    signupConfId:'signupConfirmationContainer',
    bugMeId:'bugMeDialogContainer',
    domEl:null,
    signupDomEl:null,
    signupConfDomEl:null,
    bugMeDomEl:null,
    loggedIn:false,
    
    urlPath:'',
    urlPathDefault:'/content/global/ajax/',
    urlPathAlt:'/global/ajax/',
    fileLoginStatus:'loginStatus.php',
    fileLogout:'logout.php',
    fileLogin:'login.php',
    fileCheckEmail:'checkEmail.php',
    fileSignup:'signup.php',
    fileAddressbook:'addressbook.php',
    fileSuggestSwitch:'suggestSwitch.php',
    fileSignupConfirmationDialog:'signupConfirmation.php',
    fileBugMeDialog:'bugMeDialog.php',
    fileSignupDialog:'signupDialog.php',
    fileLoginDialog:'loginDialog.php',
    
    isMSIE6:false,
    isMSIE:false,
    iframeEl:null,
    isMaps:false,

    reloadCounter:0,
    
    initialize:function() {
        
        if(typeof Prototype != 'undefined' && Prototype != null) {
            this.prototypeVersion = parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]);

            // Only works with Prototype.js >= 1.6
            if(this.prototypeVersion >= 1.6) {
                
                // Is MAPS?
                this.isMaps = (typeof mapUtils != 'undefined' && mapUtils != null);

                if($('eventBug') == null) {
                    var ebg = new Element('div', { id:'eventBug' });
                    $(document.body).appendChild(ebg);
                    ebg.setStyle({ display:'none'});
                }

                // Detect IE < 7
                if(navigator.userAgent.indexOf("Opera")==-1){
                        if (navigator.appVersion.indexOf("MSIE")!=-1){
                                var temp=navigator.appVersion.split("MSIE");
                                var version=parseFloat(temp[1]);
                                this.isMSIE = true;
                                this.isMSIE6=(version < 7);
                        }
                }
	        
                // MYDE, KTBB etc. have no content dir
                if(location.href.match(/^http\:\/\/(my|myde|blackberry|toolbar|klicklink|update)\./) || location.pathname.match(/^\/(kartensuche|lebenslagen|routenplaner|maps)/)) {
                    this.urlPath = this.urlPathAlt;
                } else {
                    this.urlPath = this.urlPathDefault;
                }
                
                // Fetch the login status from the server
                this.updateLoginStatus();
                
                if($('loginPane') == null) {
                    var pane = new Element('div', { id:'loginPane' });
                    $(document.body).appendChild(pane);
                    pane.setStyle({
                        display:'none',
                        backgroundColor:'white',
                        opacity:0.5,
                        position:'absolute',
                        top:0,
                        left:0,
                        zIndex:99999999
                    });
                    
                    // IF IE < 7 add an iframe to overlay SELECT boxes
                    if(this.isMSIE6) {
                        var iframe = new Element('iframe', { id:'loginPane_iframe' });
                        $(document.body).appendChild(iframe);
                        iframe.setStyle({
                            display:'none',
                            opacity:0.2,
                            position:'absolute',
                            top:0,
                            left:0,
                            zIndex:99999998
                        });
                        this.iframeEl = iframe;
                    }

                }
                
                // Attach event handlers to specific classes!
                var evEls = $$('.loginDialog_login', '.loginDialog_logout');
                if(evEls.length > 0) {
                    evEls.each(function(el) {
                        el.observe('click', this.handleClick.bindAsEventListener(this));
                    }.bind(this));
                }
                
                var evEls = $$('.loginDialog_signup');
                if(evEls.length > 0) {
                    evEls.each(function(el) {
                        el.observe('click', this.handleSignup.bindAsEventListener(this));
                    }.bind(this));
                }
                
                // Form fields with this class and a rel attribute with the default value
                var autoCheckFields = $$('form input.clickcheck');
                if(autoCheckFields.length > 0) {
                     autoCheckFields.each(function(fld) {
                        fld.observe('focus', this.clickCheck.bindAsEventListener(this));
                        fld.observe('blur', this.clickCheck.bindAsEventListener(this));

                        fld.setStyle({ color:'#000' });
                        var rel = fld.getAttribute('rel');
                        var val = $F(fld).strip();
                        if(rel == val || val == '') {
                            fld.value = rel;
                            $(fld).setStyle({ color:'#0D4580' });
                        }


                    }.bind(this));
                }
                
                // Update the login/logout status automatically every 60 seconds
                new PeriodicalExecuter(function(pe) {
                    this.updateLoginStatus();
                }.bindAsEventListener(this), 60*20);
                
                // Suggest Checkbox
                if($('suggestSwitch') != null) {
                    var cb = $('suggestSwitch').down('span.checkbox');
                    if(cb != null) {
                        cb.setStyle({
                            cursor:'pointer'
                        });
                        cb.observe('click', this.suggestSwitch.bindAsEventListener(this));
                        $('suggestSwitch').show();
                    }

                    var cookieResult = this.getCookie('klickSuggest');

                    // If the user has a cookie that contains 1 or the user does not have a cookie
                    // at all the checkbox is active otherwise inactive
                    if(cookieResult == 1 || cookieResult == null) {
                        $('suggestSwitch').down('span.checkbox').addClassName('checked');
                        if(cookieResult == null) {
                            // Try to set cookie because not available
                            new Ajax.Request(this.urlPath+this.fileSuggestSwitch, {
                                parameters:
                                {
                                    status:1,
                                    sid:this.getParam('sid')
                                }
                            });
                        }
                    }
                }


            } else {
                console.warn('loginDialog: prototype.js is too old ('+this.prototypeVersion+') - required is at least 1.6!');
            }
        } else {
            console.warn('loginDialog: prototype.js not loaded!');
        }
    },
    
    
    suggestSwitch:function(e)
    {
        var el = Event.element(e);
        var checked = el.hasClassName('checked');
        var v = 0;
        if(checked) {
            el.removeClassName('checked');
            v = 0;
        } else {
            el.addClassName('checked');
            v = 1;
        }
        new Ajax.Request(this.urlPath+this.fileSuggestSwitch, {
            parameters:
            {
                status:v,
                sid:this.getParam('sid')
            }
        });
    },
    
    
    clickCheck:function(e)
    {
        var el = Event.element(e);
        var eventType = e.type.toLowerCase();

        if(el.hasClassName('clickcheck')) {        
            $(el).setStyle({ color:'#000' });
            var rel = el.getAttribute('rel');
            var val = $F(el).strip();
            
            if(eventType == 'blur') {
                if(rel == val || val == '') {
                    el.value = rel;
                    $(el).setStyle({ color:'#0D4580' });
                }
            } else {
                if(rel == val) {
                    el.value = '';
                }
            }
        }
    },
    
    
    getParam:function(name)
    {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return results[1];
    },
    
    
    init:function()
    {
        //console.log('loginDialog INIT');
        if($('nav_main') != null) {
            if($('mainLoginStatus') == null) {
                var div = new Element('div', { id:'mainLoginStatus' });
                var a   = new Element('a', { href:'#' });
                $('nav_main').appendChild(div);
                div.appendChild(a);
                a.observe('click', this.handleClick.bindAsEventListener(this));
            } else {
                var a = $('mainLoginStatus').down('a');
            }
           // console.log('STATUS:'+this.loggedIn);
            if(this.loggedIn) {
                a.update('Abmelden');
                a.removeClassName('login');
                a.addClassName('logout');
            } else {
                a.update('Anmelden');
                a.removeClassName('logout');
                a.addClassName('login');
            }
            //this.updateAddressbookLinks();
            a.blur();
        }

    },
    
    
    updateAddressbookLinks:function(forceReRead)
    {
        if(forceReRead == null) forceReRead = false;
        if(forceReRead == true) forceReRead = 1; else forceReRead = 0;
        
        //console.log('updateAddressbookLinks');
        // Get all the links
        var links = $$('.addressbookRemove', '.addressbookAdd');
        if(links.length == 0) return;

        new Ajax.Request(this.urlPath+this.fileAddressbook, {
            parameters:
            {
                action:'getall',
                sid:this.getParam('sid'),
                force:forceReRead
            },

            onSuccess:function(req)
            {              
                var entries = '';
                try
                {
                    entries = req.responseText.evalJSON();
                } catch (e) {
                    console.error(e);
                }

                // Extract the GIDs out of the links
                links.each(function(link) {
                    if(typeof link.href != 'undefined') {
                        var lnk = link.getAttribute('href');
                        var gid1 = lnk.match(/gid=([0-9A-Za-z\.]+)/);
                        if(gid1) {
                            var gid = gid1[1];
                            //console.log('onpage='+gid);
                            if(this.inArray(gid, entries)) {
                                // Is IN The user's addressbook
                                 //console.log('is in!');
/*
                                if(link.hasClassName('adrbookadd') || link.hasClassName('adrbookremove')) {
                                    link.removeClassName('adrbookadd');
                                    link.addClassName('adrbookremove');
                                }*/
                                 if(!link.hasClassName('addressbookRemove')) {
                                    link.removeClassName('addressbookAdd');
                                    link.addClassName('addressbookRemove');
                                }
                            } else {
                                //console.log('is NOT in');
/*
                                if(link.hasClassName('adrbookadd') || link.hasClassName('adrbookremove')) {
                                    link.removeClassName('adrbookremove');
                                    link.addClassName('adrbookadd');
                                }
*/
                                if(!link.hasClassName('addressbookAdd')) {
                                    link.removeClassName('addressbookRemove');
                                    link.addClassName('addressbookAdd');
                                }
                            }
                        }
                    }
                }.bind(this));

            }.bind(this)
        });
    },
    

    inArray:function(needle, haystack)
    {
        if(haystack.indexOf(needle) != -1) {
            return true;
        } else {
            return false;
        }
    },
    

    closeAllDialogs:function(exception)
    {
        if(exception == null) exception = '';
        if(exception != 'login') this.hide(true);
        if(exception != 'bugme') this.hideBugMeDialog(true);
        if(exception != 'signup') this.hideSignupDialog(true);
        if(exception != 'signupconfirmation') this.hideSignupConfirmationDialog(true);
    },
    
    
    handleSignup:function(e)
    {
        console.log('handleSignup');
        if(e != null) {
            var el = Event.element(e);
            Event.stop(e);
        }
        this.closeAllDialogs('signup');
        this.showSignupDialog();
    },
    
    
    handleClick:function(e)
    {
        //console.log('handleClick');
        //console.log(e);
        // Is MAPS?
        this.isMaps = (typeof mapUtils != 'undefined' && mapUtils != null);

        Event.element(e).blur();
        Event.stop(e);
        if(this.loggedIn) {
            // Logout
            //console.log('logout');
            new Ajax.Request(this.urlPath+this.fileLogout, {
                parameters:
                {
                    sid:this.getParam('sid')
                },

                onSuccess:function()
                {
                    //this.updateLoginStatus();
	            //this.fireEvent('logout');	
                   // this.onLogout();
                    this.updateLoginStatus();
                }.bind(this)
            });
        } else {
            // Login
            if(!this.isMaps) {
   //             this.onLogin();
            //if (typeof mapUtils != 'undefined' && mapUtils != null) {
             //       mapUtils.fetchNotification('Login');				
           // } else {
             //       this.updateAddressbookLinks();
                    this.show();
            } else {
                //console.warn('Fetching great stuff...');
                mapUtils.fetchNotification('Login');				
            }

            this.updateLoginStatus();
        }
    },
    

    onLogin:function()
    {
        if(this.isMaps) {
        //if (typeof mapUtils != 'undefined' && mapUtils != null) {
            // mapUtils.fetchNotification('Login');				
        } else {
            this.updateAddressbookLinks(true);
			/*
			if (typeof recommendationDialog == "undefined") {
				var e = document.createElement("script");
		   		e.type="text/javascript";
		   		e.src = "/global/scripts/recommendationDialog.js";
				e.onload = function () {
					recommendationDialog = new recommendationDialogClass();
				}
				document.getElementsByTagName("head")[0].appendChild(e);
				
			} else if (recommendationDialog == null) {
				recommendationDialog = new recommendationDialogClass();
			}
			*/
        }
        this.fireEvent('login');
        ktMenu.update('login');
		
		
		
		
     	//   ktMenu.init();
       // this.updateLoginStatus();
    },
    
    
    forceLogout:function()
    {
        new Ajax.Request(this.urlPath+this.fileLogout, {
            parameters:
            {
                sid:this.getParam('sid')
            },

            onSuccess:function()
            {
                //this.updateLoginStatus();
                //this.fireEvent('logout');	
                // this.onLogout();
                this.updateLoginStatus();
            }.bind(this)
        });
    },
    

    onLogout:function(noMenuExec)
    {
        // console.log('loginDialog.js: onLogout 0');
        this.updateAddressbookLinks(true);
        this.fireEvent('logout');
        // console.log('loginDialog.js: onLogout 1');
       //if(ktMenu.loginStatus == true && !noMenuExec) {
        if(!noMenuExec) {
            ktMenu.handleLogout(null, true);
            // console.log('loginDialog.js: onLogout 2');
        }
        // console.log('loginDialog.js: onLogout 3');
     //   ktMenu.init();
       // this.updateLoginStatus();
	   if (typeof recommendationDialog != "undefined" && recommendationDialog != null) {
	   	recommendationDialog.removeRecommendationLinks();
		recommendationDialog = null;
	   }
	   
    },
    
    
    showPane:function()
    {
        Element.clonePosition($('loginPane'), $(document.body));
        if(this.iframeEl != null) {
            Element.clonePosition($(this.iframeEl), $(document.body));
            
            // Because in IE6 both the iframe and the DIV are overlayed we need
            // to set the transparencies each to the half values

            $(this.iframeEl).setStyle({
                opacity:0.2 //Math.round(parseFloat($(this.iframeEl).getStyle('opacity')/2),1)
            });

/*
            $('loginPane').setStyle({
                opacity:Math.round(parseFloat($('loginPane').getStyle('opacity')/2),1)
            });
*/
            $(this.iframeEl).show();
        }
        $('loginPane').show();
    },
    
    
    hidePane:function() {
        if($('loginPane') != null) $('loginPane').hide();
        if(this.iframeEl != null) {
            $(this.iframeEl).hide();
        }
    },
    
    
    styleDialog:function(domEl)
    {
        domEl.setStyle({
            display:'none',
            zIndex:999999999,
            position:'absolute',
            top:0,
            left:0
            //width:'300px',
            //border:'1px solid black',
            //backgroundColor:'white'
        });
    },
    
    
    load:function(onCompleteCallback)
    {
        this.domEl = new Element('div', { id:this.id });
        $(document.body).appendChild(this.domEl);
        this.styleDialog(this.domEl);

        new Ajax.Updater(this.domEl, this.urlPath+this.fileLoginDialog, {
            onComplete:function() {
                // Add button events
                var cancelBt = $(this.domEl).select('img.cancel_button')[0];
                var loginBt  = $(this.domEl).select('img.login_button')[0];
                if (cancelBt != null) {
                    cancelBt.observe('click', function() { this.hide(false); }.bindAsEventListener(this));
                }
                if (loginBt != null) {
                    loginBt.observe('click', this.handleLogin.bindAsEventListener(this));
                }

                var signupLink = $(this.domEl).down('.loginDialog_signup');
                if(signupLink != null) {
                    signupLink.observe('click', this.handleSignup.bindAsEventListener(this));
                }
                
                // Custom event fired whenever a form was submitted by pressing ENTER
                // in a form field!
                $(this.domEl).observe('klickTel:submitForm', function() {
                    this.handleLogin();
                }.bindAsEventListener(this));

                onCompleteCallback();
            }.bind(this)
        });
    },


    loadSignupDialog:function(onCompleteCallback)
    {
        this.signupDomEl = new Element('div', { id:this.signupId });
        $(document.body).appendChild(this.signupDomEl);
        this.styleDialog(this.signupDomEl);

        new Ajax.Updater(this.signupDomEl, this.urlPath+this.fileSignupDialog, {
            onComplete:function() {
                // Custom event fired whenever a form was submitted by pressing ENTER
                // in a form field!
                $(this.signupDomEl).observe('klickTel:submitForm', function() {
                    this.handleSignupButton();
                }.bindAsEventListener(this));
                onCompleteCallback();
            }.bind(this)
        });
    },
    
    
    loadBugMeDialog:function(onCompleteCallback)
    {
        this.bugMeDomEl = new Element('div', { id:this.bugMeId });
        $(document.body).appendChild(this.bugMeDomEl);
        this.styleDialog(this.bugMeDomEl);
        
        new Ajax.Updater(this.bugMeDomEl, this.urlPath+this.fileBugMeDialog, {
            onComplete:function() {
                onCompleteCallback();
            }.bind(this)
        });
    },
    
    
    loadSignupConfirmationDialog:function(onCompleteCallback)
    {
        this.signupConfDomEl = new Element('div', { id:this.signupConfId });
        $(document.body).appendChild(this.signupConfDomEl);
        this.styleDialog(this.signupConfDomEl);
        
        new Ajax.Updater(this.signupConfDomEl, this.urlPath+this.fileSignupConfirmationDialog, {
            onComplete:function() {
                onCompleteCallback();
            }.bind(this)
        });
    },

        
    show:function(centerElement)
    {
        this.closeAllDialogs('login');
        if($(this.domEl) == null) {
            this.load(function() { this.showDialog(centerElement, true); }.bindAsEventListener(this));
        } else {
            this.showDialog(centerElement);
        }
    },
    
    
    showSignupDialog:function(centerElement)
    {
        this.closeAllDialogs('signup');
        if($(this.signupDomEl) == null) {
            this.loadSignupDialog(function() { this.showSignupDialogEx(centerElement, true); }.bindAsEventListener(this));
        } else {
            this.showSignupDialogEx(centerElement);
        }
    },
    
    
    showBugMeDialog:function(centerElement)
    {
        this.closeAllDialogs('bugme');
        if($(this.bugMeDomEl) == null) {
            this.loadBugMeDialog(function() { this.showBugMeDialogEx(centerElement, true); }.bindAsEventListener(this));
        } else {
            this.showBugMeDialogEx(centerElement);
        }
    },
    
    
    showSignupConfirmationDialog:function(centerElement)
    {
        this.closeAllDialogs('signupconfirmation');
        if($(this.signupConfDomEl) == null) {
            this.loadSignupConfirmationDialog(function() { this.showSignupConfirmationDialogEx(centerElement, true); }.bindAsEventListener(this));
        } else {
            this.showSignupConfirmationDialogEx(centerElement);
        }
    },


    showBugMeDialogEx:function(centerElement, justLoaded)
    {
        if(this.bugMeDomEl == null) {
            console.error('showBugMeDialogEx: bugMeDomEl is NULL!');
            return;
        }

        this.initDialog(this.bugMeDomEl, centerElement, true);
        
        // Event listeners
        if(justLoaded == true) {
            var loginBt  = $(this.bugMeDomEl).down('a.login_button');
            var cancelBt = $(this.bugMeDomEl).down('img.cancel_button');
            var signupBt = $(this.bugMeDomEl).down('img.signup_button');
            
            cancelBt.setStyle({
                cursor:'pointer'
            });
            
            signupBt.setStyle({
                cursor:'pointer'
            });
            
            cancelBt.observe('click', function(e) { this.hideBugMeDialog(false); }.bindAsEventListener(this));
            loginBt.observe('click', function(e) {  this.show(null); }.bindAsEventListener(this));
            signupBt.observe('click', function(e) { this.showSignupDialog(null); }.bindAsEventListener(this));
        }
    },

    
    
    showSignupDialogEx:function(centerElement, justLoaded)
    {
        if(this.signupDomEl == null) {
            console.error('showSignupDialogEx: signupDomEl is NULL!');
            return;
        }
        
        this.initDialog(this.signupDomEl, centerElement, true);
        
        // Event listeners
        if(justLoaded == true) {
            var frm = $('signupDialog').down('form');
            var cancelBt = $(this.signupDomEl).down('img.cancel_button');
            var signupBt = $(this.signupDomEl).down('img.login_button');
            
            cancelBt.setStyle({
                cursor:'pointer'
            });
            
            signupBt.setStyle({
                cursor:'pointer'
            });
            
            cancelBt.observe('click', function() { this.hideSignupDialog(); }.bindAsEventListener(this));
            signupBt.observe('click', this.handleSignupButton.bindAsEventListener(this));
        }
    },
    
    
    showSignupConfirmationDialogEx:function(centerElement, justLoaded)
    {
        if(this.signupConfDomEl == null) {
            console.error('showSignupConfirmationDialogEx: signupConfDomEl is NULL!');
            return;
        }
        this.initDialog(this.signupConfDomEl, centerElement, true);
        // Event listeners
        if(justLoaded == true) {
            var closeBt = $(this.signupConfDomEl).down('img.close_button');
            
            closeBt.setStyle({
                cursor:'pointer'
            });
            
            closeBt.observe('click', function() { this.hideSignupConfirmationDialog(); }.bindAsEventListener(this));
        }
    },
    
    
    // TODO: Must be way better - use MAPS version!
    checkEmail:function(eml)
    {
        return eml.match(/.+@.+/);
    },
    
    
    handleSignupButton:function(e)
    {
        if(e != null) {
            var el = Event.element(e);
            Event.stop(e);
        }

        var termsCB  = $('signupForm_userLicence').checked;
        var userName = $F('signupForm_email').strip();
        var password1= $F('signupForm_password_one').strip();
        var password2= $F('signupForm_password_two').strip();
        
        // Check for errors
        var errorDomEls = $('signupDialog').select('div.error');
        errorDomEls.each(function(el) {
            el.hide();
        });

        if(userName != '' && password1 != '' && password2 != '') {
            if(password1 != password2) {
                this.showErrorBlock(errorDomEls, 'password_mismatch');
            } else if(!this.checkEmail(userName)) {
                this.showErrorBlock(errorDomEls, 'email_invalid');
            } else if(!termsCB) {
                this.showErrorBlock(errorDomEls, 'user_licence');
            } else {
                // Check e-mail
                // email_existing
                $(this.signupDomEl).down('img.ajaxindicator').show();
                $(this.signupDomEl).down('form').disable();
                new Ajax.Request(this.urlPath+this.fileCheckEmail, {
                    parameters:
                    {
                        e:userName,
                        sid:this.getParam('sid')
                    },

                    onComplete:function(req)
                    {
                        var result = req.responseText.strip();
                        if(result == 1) {
                            // Already exists
                            $(this.signupDomEl).down('img.ajaxindicator').hide();
                            $(this.signupDomEl).down('form').enable();
                            this.showErrorBlock(errorDomEls, 'email_existing');
                        } else {
                            // New, ok, signup now!
                            var md5 = new md5Class();
                            var encpass = md5.MD5(password1);
                            new Ajax.Request(this.urlPath+this.fileSignup, {
                                parameters:
                                {
                                    u:userName,
                                    p:encpass
                                },

                                onComplete:function(req)
                                {
                                    // TODO!!
                                    this.showSignupConfirmationDialog();
                                    this.fireEvent('signup');
                                }.bind(this)
                            });
                            
                            $(this.signupDomEl).down('img.ajaxindicator').hide();
                            $(this.signupDomEl).down('form').enable();
                        }
                    }.bind(this)
                });
            }
        } else if(userName == '') {
            this.showErrorBlock(errorDomEls, 'email_missing');
        } else if(password1 == '') {
            this.showErrorBlock(errorDomEls, 'password_missing');
        } else if(password2 == '') {
            this.showErrorBlock(errorDomEls, 'password2_missing');
        } else {
            this.showErrorBlock(errorDomEls, 'input_missing');
        }

        // valid_confirm

    },
    
    
    handleLogin:function()
    {
        // Read field values
        var frm        = $(this.domEl).down('form');
        var userName   = $F('loginForm_email').strip();
        var password   = $F('loginForm_password_one').strip();
        var persistent = (frm.select('input[name=permanentCheck]')[0] == true);
        
        // Check for errors
        var errorDomEls = $('loginDialog').select('div.error');
        errorDomEls.each(function(el) {
            el.hide();
        });

        if(userName != '' && password != '') {
            if(!this.checkEmail) {
                this.showErrorBlock(errorDomEls, 'email_invalid');
            } else {
                // AJAX Check!
                var md5 = new md5Class();
                var encpass = md5.MD5(password);
                frm.disable();
                frm.down('img.ajaxindicator').show();
                new Ajax.Request(this.urlPath+this.fileLogin, {
                    parameters:
                    {
                        l:userName,
                        p:encpass,
                        c:persistent
                    },
                    
                    onSuccess:function(req)
                    {
                        var frm        = $(this.domEl).down('form');
                        frm.enable();
                        frm.down('img.ajaxindicator').hide();
                        var result = req.responseText.strip();
                        if(result == 'success') {
                             this.hide();
                             var frm = $(this.domEl).down('form');

                             $('loginForm_email').value='';
                             $('loginForm_password_one').value='';
                             frm.select('input[name=permanentCheck]')[0].checked = true;
                            
                            this.updateLoginStatus();
                            
                        } else if (result == 'invalid_login') {
                            this.showErrorBlock(errorDomEls, 'invalid_login');
                        } else if (result == 'user_hold') {
                            this.showErrorBlock(errorDomEls, 'user_hold');
                        } else if (result == 'user_pending') {
                            this.showErrorBlock(errorDomEls, 'user_pending');
                        } else if (result == 'user_delete') {
                            this.showErrorBlock(errorDomEls, 'user_delete');
                        }
                    }.bind(this)
                });
            }
        } else if (userName == '') {
            // E-mail missing but password given
            this.showErrorBlock(errorDomEls, 'email_missing');
        } else if (password == '') {
            // E-mail given but password missing
            this.showErrorBlock(errorDomEls, 'password_missing');
        } else {
            // ERROR: At least one field is empty
            this.showErrorBlock(errorDomEls, 'input_missing');
        }
    },
    
    
    showErrorBlock:function(errorDomEls, block)
    {
        errorDomEls.each(function(el) {
            if(el.hasClassName(block)) {
                el.show();
            }
        });
    },
    
    
    hideErrorBlock:function(errorDomEls, block)
    {
        errorDomEls.each(function(el) {
            if(el.hasClassName(block)) {
                el.hide();
            }
        });
    },
    
    
    hide:function(keepPane)
    {
    	if(keepPane == null) keepPane = false;
    	if($(this.domEl) != null) {
            this.fade(this.domEl, function() {
                if(!keepPane) this.hidePane();
            }.bindAsEventListener(this));
        }
    },
    
    
    hideSignupDialog:function(keepPane)
    {
        if($(this.signupDomEl)) {
            this.fade(this.signupDomEl, function() {
                if(!keepPane) this.hidePane();
            }.bindAsEventListener(this));
        }
    },
    
    
    hideBugMeDialog:function(keepPane)
    {
        if(keepPane == null) keepPane = false;
        // console.log(this.bugMeDomEl);
        if($(this.bugMeDomEl) != null) {
            this.fade(this.bugMeDomEl, function() {
                if(!keepPane) this.hidePane();
                // this.hidePane();
            }.bindAsEventListener(this));
        }
    },

    
    hideSignupConfirmationDialog:function(keepPane)
    {
        if(keepPane == null) keepPane = false;
        if($(this.signupConfDomEl) != null) {
            this.fade(this.signupConfDomEl, function() {
                if(!keepPane) this.hidePane();
                // this.hidePane();
            }.bindAsEventListener(this));
        }
    },

    
    centerDialog:function(dialogDomEl, centerElement, showAtHeader)
    {
        if(showAtHeader == null) showAtHeader = false;
        if(dialogDomEl == null) {
            console.error('centerDialog called with a null element');
            return;
        }
        
        if(centerElement == null) {
            centerElement = $('main');
            if(centerElement == null) centerElement = $(document.body);
        }
        var parentPos  = $(centerElement).cumulativeOffset();
        var parentDims = $(centerElement).getDimensions();
        var selfDims   = $(dialogDomEl).getDimensions();
        var diffX      = Math.round((parentDims.width - selfDims.width)/2);
        var diffY      = Math.round((parentDims.height - selfDims.height)/2);
        
        if(diffY < 0) diffY = 50;
        diffY = 100;
        
        
        if(showAtHeader) {
            diffY = 50+this.scrollOffset()[1];
/*
            // diffY = ;
            var scrollOffset = 0;
            if(typeof window.pageYOffset != 'undefined') {
                // Firefox
                scrollOffset = window.pageYOffset;
            } else if (typeof document.body.scrollTop != 'undefined') {
                scrollOffset = document.body.scrollTop;
            }
      */
        }
  
        
        

        $(dialogDomEl).setStyle({
            left:diffX+'px',
            top:diffY+'px'
        });
    },
    
    
    scrollOffset: function() {
        var x, y;
        if (self.pageYOffset) {
            // all except Explorer
            x = self.pageXOffset;
            y = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            // Explorer 6 Strict
            x = document.documentElement.scrollLeft;
            y = document.documentElement.scrollTop;
        } else if (document.body) {
            // all other Explorers
            x = document.body.scrollLeft;
            y = document.body.scrollTop;
        }
        if (!x) x = 0;
        if (!y) y = 0;
        arrayScrollOffset = new Array(x,y);
        return arrayScrollOffset;
    },
    
    
    appear:function(domEl, callback)
    {
        if(typeof Effect != 'undefined') {
            new Effect.Appear($(domEl), { duration:0.2, afterFinish:callback });
        } else {
            $(domEl).show();
            callback();
        }
    },


    fade:function(domEl, callback)
    {
        if(typeof Effect != 'undefined') {
            new Effect.Fade($(domEl), { duration:0.2, afterFinish:callback});
        } else {
            $(domEl).hide();
            callback();
        }
    },
    
    
    showDialog:function(centerElement, justLoaded)
    {
        if(this.domEl == null) {
            console.error('showDialog: domEl is NULL!');
            return;
        }
        this.initDialog(this.domEl, centerElement, true);
    },
    
    
    initDialog:function(domEl, centerElement, showAtHeader)
    {
        if(domEl == null) {
            console.error('initDialog called with a NULL element!');
            return;
        }
        this.showPane();
        this.centerDialog(domEl, centerElement, showAtHeader);
        if(!showAtHeader) $(domEl).scrollTo();
        this.appear(domEl, function() {
            var subForm = $(domEl).down('form');
            if(subForm != null) {
                
                // Always focus the first form element if there is a form
                subForm.focusFirstElement();

                // ... and add an ENTER event listener if there is no submit button
                if(!subForm.down('input[type=submit]')) {
                    var textFields = subForm.select('input[type=text]', 'input[type=password]');
                    if(textFields.length > 0) {
                        textFields.each(function(fld) {
                            fld.observe('keyup', function(e) {
                                if(e.keyCode == Event.KEY_RETURN) {
                                    $(domEl).fire('klickTel:submitForm');
                                    //Event.element(e).up('form').submit();
                                }
                            });
                        });
                    }
                }
            }
        });
        
    },
    
    
    updateLoginStatus:function()
    {
        // Is MAPS?
        this.isMaps = (typeof mapUtils != 'undefined' && mapUtils != null); 
        
        this.reloadCounter++;
        new Ajax.Request(this.urlPath+this.fileLoginStatus, {
            
            parameters:
            {
                sid:this.getParam('sid'),
                count:this.reloadCounter
            },

            onSuccess:function(req)
            {
                if(req.responseText == '1') {
                    if(this.loggedIn == false) {
                        this.onLogin();
                    }
                    this.loggedIn = true;
                    
                } else {
                    if(this.loggedIn == true) {
                        this.onLogout();
                    }
                    this.loggedIn = false;
                }
                this.fireEvent('updateLoginStatus');
         //       this.updateLoginStatus();
    /*
                if (typeof mapUtils != 'undefined' && mapUtils != null) {
                     mapUtils.logOut();				
                } else {
                    this.updateAddressbookLinks();
                }
*/
                this.init();
            }.bind(this)
        });
    },
    
    
    addressbookAction:function(action, gid, el, onCompleteCallback)
    {
        // console.log('addressbookAction: action='+action+', gid='+gid);
        var url = this.urlPath+this.fileAddressbook;
        var detailView = el.hasClassName('vcard');
        
        if(action == 'add' && !detailView) { // Only adding can take longer as geocoding happens!
            //var indicator = new Element('img', { src:this.urlPath+'images/indicator-small.gif', alt:'AJAX' });
            //el.appendChild(indicator);
            el.addClassName('ajaxindicator');
            //indicator.setStyle({ marginLeft:'2px' });
            //el.setStyle({ textDecoration:'none' });
        }


        // If the user is not logged in prompt him to login or signup
        if(!this.loggedIn && action == 'add') {
            // Call the appropriate MAPS dialog
            if(this.isMaps) {
                //alert('NOT IN MAPS: Call the "Bug me, I\'m not logged in!" dialog');
                // Maps does not allow this kind of dialog - it's not used there at all!
            } else {
                // Not in MAPS
                this.showBugMeDialog();
            }
        }
        
        new Ajax.Request(url, {
            parameters:
            {
                action:action,
                gid:gid,
                sid:this.getParam('sid')
            },

            onComplete:function(req)
            {
                var result = req.responseText.strip();
                //if(indicator != null) indicator.remove();
                //el.setStyle({ textDecoration:'underline' });
                el.removeClassName('ajaxindicator');
                this.fireEvent('addressbook-'+action);
                onCompleteCallback(result, el, action);
            }.bind(this)
        });
    },
    
    
    getCookie:function(name){
        var i=0;
        var suche = name+"=";
        while (i<document.cookie.length){
            if (document.cookie.substring(i, i+suche.length)==suche){
                var ende = document.cookie.indexOf(";", i+suche.length);
                ende = (ende>-1) ? ende : document.cookie.length;
                var cook = document.cookie.substring(i+suche.length, ende);
                return unescape(cook);
            }
            i++;
        }
        return null;
    },

    
    fireEvent:function(name) {
        $('eventBug').fire('klickTel:'+name);
    },
    

    listenEvent:function(name, callback) {
        $('eventBug').observe('klickTel:'+name, callback);
    }
    
});

var loginDialog;
Event.observe(window, 'load', function() {
    loginDialog = new loginDialogClass();
   // loginDialog.show();
});

