//------------------------------------
// Implementation of:
//  - Snip namepace
//  - Snip.LoginControl class
//  - Snip.RegisterControl class
//
// BSD License: http://www.opensource.org/licenses/bsd-license.php
//Copyright (c) 2007, Kyle Beyer (http://daptivate.com)
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
//Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 
//Neither the name of the organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------
 
//
// Namespace
var Snip = (function() {
    //
    // private namespace members
    var _debug = 1;
    //
    // status control
    var _status = null;
    //
    // username
    var _username = '';
    //
    // authentication status
    var _auth = false;
    //
    // persist cookie flag
    var _persistCookie = false;

    //
    // private namespace functions

    //
    // helper function to clear a control's value and give back focus
    function ClearControl(ctrl, giveFocus) {
        ctrl.value = '';
        if (giveFocus) { ctrl.focus(); }
    }

    //
    // username validation
    function CheckUsername(u) {
        var filter = /^[0-9a-zA-Z_\.\-\s]+$/;
        return filter.test(u);
    }

    //
    // e-mail validation
    function CheckMail(e) {
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return filter.test(e);
    }

    //
    // common timeout method
    function OnTimeout(result) {
        SetStatus("Sorry, the request was taking too long.  Please try again.", "bad");
    }

    //
    // common error method
    function OnError(result) {
        var resultMessage = result.get_message();
        var errorMessage = "Exception: " + resultMessage;
        errorMessage = errorMessage + "\n-----------------------------------\n";
        errorMessage = errorMessage + " StackTrace: + ";
        errorMessage = errorMessage + result.get_stackTrace();

        if (_debug == 1) {
            alert(errorMessage);
        }
        SetStatus("Error: " + resultMessage + ".", "bad");
    }

    //
    // called when status needs displayed
    function SetStatus(m, t) {
        _status.style.display = "block";
        _status.innerHTML = m;

        if (t == "bad") {
            _status.className = 'form-status bad';
        } else if (t == "good") {
            _status.className = 'form-status good';
        } else {
            _status.className = 'form-status ok';
        }
    }
    //
    // called when status needs cleared
    function ClearStatus() {
        _status.innerHTML = '';
        _status.style.display = "none";
    }
    return {
        //
        // LoginControl javascript object
        //
        LoginControl: function(eID, pID, sID, cID, aID, uID, fID, lID, mID) { // last 3 are sections ForgotDetails and section LoginData and Email field of ForgotDetails

            //
            // declare request objects (private)
            var _saltRequest = null;
            var _loginRequest = null;
            //
            // declare form sections
            var _fID = fID;
            var _lID = lID;
            //
            // declare form control names/ids
            var _eID = eID;
            var _pID = pID;
            var _sID = sID;
            var _cID = cID;
            var _aID = aID;
            var _uID = uID;
            var _mID = mID;
            var AutomaticEmail = "";
            //
            // declare document control vars (public)
            var _e = null;
            var _p = null;
            var _c = null;
            //
            // set status control
            _status = null;
            //
            // open status
            var _open = false;
            var _isToRedirect = true;
            //
            // login callbacks
            var _loginCallback = null;
            var _logoutCallback = null;

            // --------------------------------------------
            // PUBLIC LoginControl Functions            
            // --------------------------------------------

            //
            // used to initialize authentication status from 
            // optional hidden field (aID) populated by server  
            // and username field (uID) pupulated by server
            this.init_fields = function() {
                // get server auth status
                var aF = document.getElementById(_aID);
                if (aF != null) {
                    var val = aF.value;
                    if (val != null && val.length > 0) {
                        _auth = val == 'True' ? true : false;
                    }
                }
                // get server username
                var uF = document.getElementById(_uID);
                if (uF != null) {
                    var val = uF.value;
                    if (val != null && val.length > 0) {
                        _username = val;
                    } else {
                        _auth = false;
                    }
                }
            }

            //
            // used to get authenication status
            this.get_auth = function() {
                return _auth;
            };
            //
            // used to get authenicated username
            this.get_username = function() {
                return _username;
            };
            //
            // used to set login callback function
            this.set_loginCallback = function(value) {
                _loginCallback = value;
            };
            //
            // used to set logout callback function
            this.set_logoutCallback = function(value) {
                _logoutCallback = value;
            };
            //
            // used to get open status
            this.IsOpen = function() {
                return _open;
            };
            // used to get know if needs redirection
            this.IsToRedirect = function() {
                return _isToRedirect;
            };
            //
            // Send email with details of domegos account
            // 
            this.ForgotDetails = function() {
                // email validation
                var _m = $get(_mID);
                var m = _m.value;
                if (m == null || m == '') {
                    SetStatus("Email required", "bad");
                    ClearControl(_m, true);
                    return;
                }
                if (!CheckMail(m)) {
                    SetStatus("Email invalid.", "bad");
                    _m.focus();
                    return;
                }
                SetStatus("Verifying email...", "ok");
                SendDetails(m);
            };
            this.AutomaticResend = function() {
                ReSendConfirmationEmail(AutomaticEmail, _p.value);
            }
            //
            // called when login button is pressed
            // if 'remember me' is checked then true should be passed in.
            this.LoginUser = function(remember) {
                // email validation
                var e = _e.value;
                if (e == null || e == '') {
                    SetStatus("Username required", "bad");
                    ClearControl(_e, true);
                    return;
                }
                /* if( !CheckMail(e) ){
                SetStatus("Invalid Email.", "bad");
                _e.focus();        
                return;
                }*/

                // password validation
                var p1 = _p.value;
                if (p1 == null || p1 == '') {
                    SetStatus("Password required", "bad");
                    ClearControl(_p, true);
                    return;
                }
                // save persist flag
                _persistCookie = remember;

                SetStatus("Verifying information...", "ok");
                VerifyUserName(_e.value);
            };

            //
            // called when logout button is pressed
            this.LogoutUser = function() {
                if (_auth) {
                    Domegos.Web.AppCode.Membership.AuthenticationService.Logout(
                                            OnLogoutComplete,
                                            OnTimeout,
                                            OnError);
                }
            };

            //
            // opens the control
            this.Open = function() {
                // show form
                _c = document.getElementById(_cID);
                _c.style.display = "";

                // get references to controls
                _e = document.getElementById(_eID);
                _p = document.getElementById(_pID);
                _status = document.getElementById(_sID);
                // clear fields & set focus
                ClearControl(_p, false);
                ClearControl(_e, true);

                // if it's less than IE7 then it shows iframe
                if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
                    var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
                    if (ieversion <= 6) {
                        var layer = _c;
                        var iframe = document.getElementById('iframetop');
                        iframe.style.display = '';
                        iframe.style.width = 280;
                        iframe.style.height = 265;
                        iframe.style.position = 'absolute';
                    }
                }
                _open = true;
            };

            //
            // closes the control
            this.Close = function() {
                if (_open) {
                    // clear fields
                    ClearControl(_p, false);
                    ClearControl(_e, true);
                    ClearStatus();
                    var iframe = document.getElementById('iframetop');
                    iframe.style.display = 'none';
                    // hide
                    _c.style.display = "none";
                }
                _open = false;
            };
            //
            // show error message
            this.ShowErrorMessage = function(_errorMessage) {
                SetStatus(_errorMessage, "bad");
            };
            //
            // performs event for a key press
            this.KeyPressed = function(e, target) {
                var evt = window.event ? window.event : e;
                var k = evt.which ? evt.which : evt.keyCode;
                if (evt && k == 13 && !(evt.srcElement && (evt.srcElement.tagName.toLowerCase() == "textarea"))) {
                    var defaultButton = document.getElementById(target);
                    if (defaultButton) {
                        if (typeof (defaultButton.click) != "undefined")
                            defaultButton.click();
                        else if (typeof (defaultButton.onclick) != "undefined")
                            defaultButton.onclick();
                        else
                            return true;
                        evt.cancelBubble = true;
                        if (evt.stopPropagation) { evt.stopPropagation(); }
                        return false;
                    }
                }
                return true;
            };
            // Show ForgotDetails control
            this.ShowForgotDetails = function() {
                $get(_fID).style.display = "";
                $get(_lID).style.display = "none";
            };
            // Hide ForgotDetails control
            this.HideForgotDetails = function() {
                $get(_fID).style.display = "none";
                $get(_lID).style.display = "";
            };
            // --------------------------------------------
            // PRIVATE LoginControl Functions            
            // --------------------------------------------

            //
            // verifies username against membership store
            function VerifyUserName(u) {
                _saltRequest = new Domegos.Web.AppCode.Membership.SaltRequest();
                _saltRequest.username = u;

                Domegos.Web.AppCode.Membership.AuthenticationService.VerifyUserLogin(_saltRequest,
                                                            OnVerifyComplete,
                                                            OnTimeout,
                                                            OnError);
            }
            //
            // verifies on database that Email exists and send the email if it does
            function ReSendConfirmationEmail(m, p) {
                Domegos.Web.AppCode.Membership.AuthenticationService.ReSendConfirmationEmail(m, p,
                                                        OnSendDetailsComplete,
                                                        OnTimeout,
                                                        OnError);
            }
            //
            // verifies on database that Email exists and send the email if it does
            function SendDetails(m) {
                Domegos.Web.AppCode.Membership.AuthenticationService.SendDetails(m,
                                                        OnSendDetailsComplete,
                                                        OnTimeout,
                                                        OnError);
            }
            //
            // called when username verification completes
            function OnSendDetailsComplete(result) {
                if (result.success && result.email_sent) {
                    SetStatus(result.message, "good");
                } else {
                    SetStatus(result.message, "bad");
                }
            }
            //
            // called when username verification completes
            function OnVerifyComplete(result) {
                if (result.success) {
                    CompleteLogin(result.salt, result.challenge);
                } else {
                    SetStatus("Sorry, " + _e.value + " is not a registered username.  Would you like to <a href=\'/SignUp\' >Sign up</a>?", "bad");
                    ClearControl(_e, true);
                }
            }

            //
            // called after email is verified
            function CompleteLogin(s, c) {
                SetStatus("Checking Password...", "ok");

                _loginRequest = new Domegos.Web.AppCode.Membership.LoginRequest();
                _loginRequest.username = _e.value;
                var pwd_hmac = b64_hmac_sha1(s, _p.value);
                _loginRequest.passwordHMAC = b64_hmac_sha1(c, pwd_hmac).toString();
                _loginRequest.createCookie = _persistCookie;
                _loginRequest.hash = window.location.hash;
                _loginRequest.passwordClear = _p.value;
                Domegos.Web.AppCode.Membership.AuthenticationService.Login(_loginRequest,
                                                OnLoginComplete,
                                                OnTimeout,
                                                OnError);
            }

            //
            // called when authentication check completes
            function OnLoginComplete(result) {
                if (result.status == 2) {// PropertyOwner and manual redirection needed
                    _auth = true;
                    _username = result.username;
                    document.location.href = _domegosRoot + "/PropertyOwner/";
                    _isToRedirect = true;
                }
                else if (result.status == 3) {// PropertyOwner and automatic redirection needed
                    _auth = true;
                    _username = result.username;
                    _isToRedirect = true;
                    if ($get("LoginInfo_LoggedIn") != null) {
                        $get("LoginInfo_LoggedIn").style.display = "";
                        $get("LoginInfo_UserName").innerHTML = _username;
                        $get("LoginInfo_NotLoggedIn").style.display = "none";
                    }
                    if (window.UpdateLogin_DoPostBack)
                        UpdateLogin_DoPostBack();

                    if (_loginCallback != null && typeof (_loginCallback) == 'function') {
                        _loginCallback();
                    }
                }
                else if (result.status == 1) {// block the redirection
                    _auth = true;
                    _username = result.username;
                    _isToRedirect = false;
                    if ($get("LoginInfo_LoggedIn") != null) {
                        $get("LoginInfo_LoggedIn").style.display = "";
                        $get("LoginInfo_UserName").innerHTML = _username;
                        $get("LoginInfo_NotLoggedIn").style.display = "none";
                    }
                    if (window.UpdateLogin_DoPostBack)
                        UpdateLogin_DoPostBack();

                    if (_loginCallback != null && typeof (_loginCallback) == 'function') {
                        _loginCallback();
                    }
                }
                else if (result.status == 6) {
                    _isToRedirect = false;
                    _auth = false;
                    AutomaticEmail = result.email;
                    SetStatus("You have not activated your account please check your email. If you didn\'t receive the activation email <a href=\"#\" onclick=\"_loginControl.AutomaticResend()\">resend it now</a>.", "bad");
                }
                else if (result.status == 7) { // Password is too short and its lenght must be increased
                    _isToRedirect = false;
                    _auth = false;
                    window.location.href = '/SetLongerPassword';
                }
                else {
                    _isToRedirect = false;
                    _auth = false;
                    SetStatus("Invalid password. Please try again.", "bad");
                    ClearControl(_p, true);
                }
            }

            //
            // called when logout request completes
            function OnLogoutComplete(result) {
                _auth = false;
                _username = '';
                if ($get("LoginInfo_LoggedIn") != null) {
                    $get("LoginInfo_LoggedIn").style.display = "none";
                    $get("LoginInfo_UserName").innerHTML = "";
                    $get("LoginInfo_NotLoggedIn").style.display = "";
                }
                if (window.UpdateLogin_DoPostBack)
                    UpdateLogin_DoPostBack();

                if (_logoutCallback != null && typeof (_logoutCallback) == 'function') {
                    _logoutCallback();
                } else {

                }
            }

        } // end LoginControl
        // marcojs INSERT HERE THE JS FOUND IN SNIPCONTROLREGISTER.JS TO RESTORE THE REGISTRATION FUNCTION



} // end return

    })();                                                      // end Snip

// notify atlas script has loaded
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
