if (jQuery) (function(jQuery) {
    jQuery.extend(jQuery.ark, { login: function() { } });
    jQuery.extend(jQuery.ark.login, {
        checkInterval: null,
        SetCheckInterval: function() {
            if (!this.checkInterval) {
                this.checkInterval = setInterval('jQuery.ark.login.CheckLoggedIn();', 500);
            }
        },
        ClearCheckInterval: function() {
            if (this.checkInterval) {
                clearInterval(this.checkInterval);
                this.checkInterval = null;
            }
        },
        init: function() {
            this.SetCheckInterval();
        },
        ClearDefaultText: function(control, defaultValue, optionalPasswordControl) {
            if (control) {
                if (control.value == defaultValue) {
                    if (optionalPasswordControl) {
                        optionalPasswordControl = document.getElementById(optionalPasswordControl);
                        control.style.display = 'none';
                        optionalPasswordControl.style.display = 'block';
                        optionalPasswordControl.focus();
                    }
                    else {
                        if (control.value != 'Email Address') return;
                        control.value = '';
                    }
                }
            }
        },
        RestoreDefaultText: function(control, defaultValue, optionalDefaultPasswordControlId) {
            if (control && control.value == '') {
                this.RestoreDefaultText_Force(control, defaultValue, optionalDefaultPasswordControlId)
            }
        },
        RestoreDefaultText_Force: function(control, defaultValue, optionalDefaultPasswordControlId) {
            if (control) {
                if (optionalDefaultPasswordControlId) {
                    optionalDefaultPasswordControl = document.getElementById(optionalDefaultPasswordControlId);
                    control.style.display = 'none';
                    optionalDefaultPasswordControl.style.display = 'block';
                }
                else {
                    control.value = defaultValue;
                }
            }
        },

        AuthCookieName: '', //'.AUTH'
        IsLoggedIn: function() {
            var clientCookieValue = jQuery.cookie(jQuery.ark.login.AuthCookieName);
            return null != clientCookieValue && '' != clientCookieValue;
        },
        LoginAction: function(openPopupLogin) {
            this.action = null;
            this.cancelAction = null;
            this.Reset = function() { this.action = null; this.cancelAction = null; }
            this.Set = function(action, cancelAction) { this.action = action; this.cancelAction = cancelAction; }
            this.OpenPopupLogin = openPopupLogin;
            this.Do = function(isDoneImmediately) {
                if (this.action) {
                    if (typeof (this.action) == 'function') { this.action(isDoneImmediately); }
                    else if (typeof (this.action == 'string')) { new Function('action', this.action)(); }
                    else { alert('Actions of type "' + typeof (this.action) + '" are not supported!'); }
                }
                this.Reset();
            }
            this.LoginThenDo = function(action, cancelAction) { // returns isDoneImmediately
                if (IsLoggedIn()) {
                    this.Set(action, cancelAction);
                    this.Do(true);
                    return true;
                }
                else {
                    this.Set(action, cancelAction);
                    this.OpenPopupLogin(cancelAction);
                    return false;
                }
            }
        },
        LoginServiceCallProcessor: function(messageEventBonus, serviceUrlEventBonus, serviceUrl, loginParamName, passwordParamName, passwordRememberParamName, successResponseValue) {
            this.serviceUrl = serviceUrl;
            this.loginParamName = loginParamName;
            this.passwordParamName = passwordParamName;
            this.passwordRememberParamName = passwordRememberParamName;
            this.successResponseValue = successResponseValue;
            this.Process = function(loginValue, passwordValue, passwordRememberValue, finallyCall, failCall, disabledCall, successCall) {
                jQuery.ark.login.ClearCheckInterval();
                var params = {};
                params[this.loginParamName] = loginValue;
                params[this.passwordParamName] = passwordValue;
                params[this.passwordRememberParamName] = passwordRememberValue;
                jQuery.get(serviceUrl, params,
					function(data) {
					    //alert("Data Loaded: " + data + '|' + successResponseValue);
					    var result = (data == successResponseValue);

					    if (result) {
							if (messageEventBonus != '')
							{
								jQuery.post(serviceUrlEventBonus, 
											{"ajaxkey": Math.random()
											},
											function(data){
												if (trim(data) == '+'){
														 //var messageEventBonus = "EVENT 1000";
														 ShowDialogPopup('', messageEventBonus);
												}
												jQuery.ark.login.ProcessLoginResult(result, data, finallyCall, failCall, disabledCall, successCall);
											});	
							}
							else
							{
								jQuery.ark.login.ProcessLoginResult(result, data, finallyCall, failCall, disabledCall, successCall);										
							}
					        //alert('CM login end');
					        cmCreateConversionEventTag("Login", "2", "Microsite:Games", "0");
					    }
					    else {
					        jQuery.ark.login.ProcessLoginResult(result, data, finallyCall, failCall, disabledCall, successCall);
					    }
					    //jQuery.ark.login.ProcessLoginResult(result, data, finallyCall, failCall, disabledCall, successCall);
					}
				);
            };
        },

        ProcessLoginResult: function(result, resultCode, finallyCall, failCall, disabledCall, successCall) {
            //assert(checkInterval == null);
            if (result) {
                //assert(authCookie != null);
                jQuery('.listen_login').trigger('login');
                loginAction.Do();
                if (successCall) { successCall() };
            }
            else {
                //assert(authCookie == null);
                jQuery('.listen_logout').trigger('logout');

                if (disabledCall && resultCode == "+-") { disabledCall() };
                if (failCall && resultCode == "-") { failCall() };
            }
            this.SetPreviousStatus(IsLoggedIn());
            this.SetCheckInterval();
            if (finallyCall) { finallyCall() };
        },

        previousStatus: undefined,
        SetPreviousStatus: function(status) { this.previousStatus = status; },
        CheckLoggedIn: function() {
            var currentStatus = IsLoggedIn();

            if (typeof this.previousStatus != 'undefined') {
                if (this.previousStatus != currentStatus) {
                    this.ProcessLoginResult(currentStatus);
                }
            } else {
                jQuery('.listen_init').trigger('init');
            }
            this.previousStatus = currentStatus;
        },
        dummy: 0
    });
})(jQuery);
jQuery(function() { jQuery.ark.login.init(); });

//TODO: refactoring
function ForgotPassword(textEmailId, validatorDivId, serviceCallMode)
{
	this.textEmailId = textEmailId;
	this.validatorDivId = validatorDivId;
	this.serviceCallMode = serviceCallMode;

	this.textEmail = document.getElementById(textEmailId);
	this.validatorDiv = document.getElementById(validatorDivId);

	this.ProcessSubmitClick = function()
	{
		if (this.Validate(this.textEmail))
		{
			DoServiceCall(jQuery.ark.loginBox.SignIn.id, this.serviceCallMode, this.textEmail.value);
		}
	};

	this.ProcessJSSubmitClick = function(url, closeScript, msgControl) {
	    if (this.Validate(this.textEmail)) {
	        jQuery.post(url, {
	            'email': this.textEmail.value,
	            'key': Math.random()
	        },
			function(data) {
			    this.SetInvalidStatus = function(text) {
			        //msgControl.style.display = 'block';
			        //msgControl.innerHTML = text;
			        ShowDialogPopup(text);
			    };

			    if (parseInt(data) == 1) {
			        ShowDialogPopup('Forgot Password', 'Your Password has been sent to your email address.');
			        jQuery('#ShowDialogPopup_Caption').addClass("popupForgot_pass");
			        eval(closeScript);
			    }
			    if (parseInt(data) == -1) {
			        //ShowDialogPopup('Forgot Password', 'Please enter a valid email address.');
			        //this.SetInvalidStatus('Invalid email address');

			        ShowDialogPopup("Please enter a valid email address.");
			    }
			    if (parseInt(data) == -2) {
			        ShowDialogPopup('Forgot Password', 'Send password failed. <br /> Please Try Again Later.');
			        eval(closeScript);
			    }
			    if (parseInt(data) == -3) {
			        //this.SetInvalidStatus('Email address not found');
			        //ShowDialogPopup('Forgot Password', 'Email address not found.');

			        //ShowDialogPopup("Email address not found.");
			    }
			});
	    }
	};


	this.Validate = function() {

		if (this.textEmail && this.textEmail.value && IsEmail(this.textEmail.value)) {
			return true;
		}else {
		    ShowDialogPopup('Login', "Please enter valid email address");
			return false;
		}
	};
	this.SetInvalidStatus = function(text) {
		this.textEmail.className = 'home_Forgot_email_error coll';
		this.validatorDiv.style.display = 'block';
		this.validatorDiv.innerHTML = text;
	};
}
