/*
 GOBEHEMOTH, All rights reserverd.
 Developed by sedgar: sedgar@gobehemoth.com
*/

var Forms = {};

var WebUserForm = new Class({

	Extends: AjaxForm,

    onFormInitialized: function (options) {
        var form = $(this.options.formId);
        if (form) {
            WebUserForm.instances.push(this);
        }
    },
    
    show: function(senderObj) {
        WebUserForm.hideOpened(this);
        var panel = this.__getFormContainer();
        panel.show();
        
        /*
        new Effect.Parallel([
            new Effect.Opacity(panel, { sync: true, from: 0.3, to: 1 }),
            new Effect.Move(panel, { 
                sync: true, 
                x: -1, y: 20, 
                mode: 'absolute', 
                transition: Effect.Transitions.spring, 
                afterFinishInternal: this.onShowed
            })], 
            {duration: 1.5}
        );*/
        this.onShowed(panel);
        
        panel.parent().toggleClass('active');
    },

    hide: function(senderObj, isSimple) {
        var panel = this.__getFormContainer();
        if (isSimple) {
            /*new Effect.Opacity(panel, 
                Object.extend(
                    { duration: 0.3, from: 1, to: 0.3,
                      afterFinishInternal: function(effect) {
                          effect.element.hide();
                          effect.element.setStyle({top:"-120px"});
                      }
                  }, arguments[1] || { }));
            */
        } else {
            //new Effect.Drop(panel, {x:-1, y:-120, hide:true});
        }
        panel.parent().toggleClass('active');
    },
    
    visible: function() {
        return Element.visible(this.__getFormContainer());
    },
    
    onShowed: function(element) {
        //var form = effect.element.children('form');
        var form = element.children('form')
        if (form.length > 0) {
            try {
                form.children(':input:enabled:first').focus();
            } catch(ex) {}
        }
    },
    
    onBeforeSubmit: function() {
        this.isError = false;
    },
    
    onAfterSubmit: function() {
        if (!this.isError) {
            this.disableForm();
        }
    },
    
    onSuccess: function(responseObj, json) {

        if (responseObj) {
            this.enableForm();            
            this.onResponseReceived(responseObj);
        } else {
            alert("onSuccess: Failed responce handling is not implemented");
        }
    },

    onResponseReceived: function(responseObj) {
        this.__handleResponseMessages(responseObj);        
        if (responseObj.redirect && !responseObj.redirect.blank()) {
            location.href = responseObj.redirect;
        }

        if (responseObj.html) {
            this.__replaceFormContent(responseObj.html);
        }
    },

    onFailed: function(transport, exObj) {
        this.enableForm();
    },
    
    onComplete: function() {
        this.enableForm(); 
    },
    
    __replaceFormContent: function(content) {
        this.removeEvents();
        var ajaxForm = $(this.options.formId);
        ajaxForm.attr('action', '#');
        ajaxForm.html(content);
    },

    __getFormContainer: function() {
        return $(this.options.formId).parent();
    }
});

WebUserForm.forms = {};
WebUserForm.instances = [];

WebUserForm.hideOpened = function(senderObj) {
    for(var i = 0; i < WebUserForm.instances.length; i++) {
    	var isVisible = WebUserForm.instances[i] && senderObj != WebUserForm.instances[i] && WebUserForm.instances[i].is(':visible')
        if (isVisible) {
            WebUserForm.instances[i].hide(null, true);
        }
    }
}

var LoginForm = new Class({

	Extends: WebUserForm,
    	
    onResponseReceived: function(responseObj) {
        this.__handleResponseMessages(responseObj);
        
        if (responseObj.redirect && responseObj.redirect.length > 0) {
            location.href = responseObj.redirect;
        }
    },
    
    onFailed: function(transport, exObj) {
        alert("Login 'onFailed' is not implemented");
        this.isError = true;
    }
});

var SignupForm = new Class({

	Extends: WebUserForm,
    
    onResponseReceived: function(responseObj) { 

            if(responseObj.errors.length>0)
            {
                if(responseObj.errors[0].key=='email')
                {
                    document.getElementById("formRegister").style.display = 'none';
                    document.getElementById("registerSuccess").style.display = 'none';
                    document.getElementById("errorUsername").style.display = 'none';
                    document.getElementById("errorEmailText").innerHTML = responseObj.errors[0].message.toUpperCase();
                    document.getElementById("errorEmail").style.display = 'block';
                    document.getElementById("errorPassword").style.display = 'none';
                }
                if(responseObj.errors[0].key=='username')
                {
                    document.getElementById("formRegister").style.display = 'none';
                    document.getElementById("registerSuccess").style.display = 'none';
                    document.getElementById("errorUsernameText").innerHTML = responseObj.errors[0].message.toUpperCase();
                    document.getElementById("errorUsername").style.display = 'block';
                    document.getElementById("errorEmail").style.display = 'none';
                    document.getElementById("errorPassword").style.display = 'none';
                }
                if(responseObj.errors[0].key=='password')
                {
                    document.getElementById("formRegister").style.display = 'none';
                    document.getElementById("registerSuccess").style.display = 'none';
                    document.getElementById("errorUsername").style.display = 'none';
                    document.getElementById("errorEmail").style.display = 'none';
                    document.getElementById("errorPasswordText").innerHTML = responseObj.errors[0].message.toUpperCase();
                    document.getElementById("errorPassword").style.display = 'block';
                }

            }
            else
            {
                document.getElementById("formRegister").style.display = 'none';
                document.getElementById("registerSuccess").style.display = 'block';
                document.getElementById("errorUsername").style.display = 'none';
                document.getElementById("errorEmail").style.display = 'none';
           }

        this.__handleResponseMessages(responseObj);
      
/*
        if (responseObj.html) {
            this.__replaceFormContent(responseObj.html);
        }
*/
    }
});

var ForgotForm = new Class({

	Extends: WebUserForm,
    
    onResponseReceived: function(responseObj) {
        this.__handleResponseMessages(responseObj);
        
        if (responseObj.html) {
            this.__replaceFormContent(responseObj.html);
        }
    }
});

/*var GunControl = new Class({

	Extends: AjaxForm,

    initialize: function (options) {
    	this.parent(options);
        this.initForm(options);
        this.timer = new Timer();
        this.timer.onTick = jQuery.proxy(this.onAimTimeTick, this)
        this.disable();
    },
    
    enable: function() {
        try {
            this.enableForm();
            $(this.options.aimTimePanelId).show();
            this.timer.start();
        
            var moreBtn = $(this.options.moreTimeButtonId);
            if (moreBtn.is(':disabled') == false) {
                moreBtn.show();
                moreBtn.attr('disabled', 'disabled');
            }
        } catch (ex) {
            this.showAlert(ex.message);
        }
    },
    
    disable: function() {
        try {
            this.disableForm();
            $(this.options.aimTimePanelId).hide();
            this.timer.stop();
        } catch (ex) {
            this.showAlert(ex.message);
        }
    },
    
    isEnabled: function() {
        return (this.timer && this.timer.isStarted);
    },
    
    setOwnerId: function(userId) {
        this.userId = userId;
    },
    
    sendRequest: function(sender, dX, dY) {
        try {
            if (this.lastMoveButtonId == sender.id || !this.timer.isStarted) {
                return false;
            }
            this.mode = 'aiming';
            this.lastMoveButtonId = sender.id;
            if (dX == 0 && dY == 0) {
                this.options.submitParams[this.options.actionName] = 'reset';            
            } else {
                this.options.submitParams['dx'] = dX;
                this.options.submitParams['dy'] = dY;
                this.options.submitParams[this.options.actionName] = 'move';
            }
            this.onSubmit();
        } catch (ex) {
            this.showAlert(ex.message);
        }
        
        return false;
    },
    
    sendShot: function(sender) {
        try {
            if (this.lastMoveButtonId == sender.id || !this.timer.isStarted) {
                return false;
            }
            this.lastMoveButtonId = sender.id;
            
            if (Application.userInfo.shots > 0) {
                this.mode = 'shot';
                this.options.submitParams['shot'] = true;
                this.options.submitParams[this.options.actionName] = this.mode;
                Application.userInfo.decrementShots();
                this.onSubmit();
            } else {
                this.onAimTimeOver();
            }
        } catch (ex) {
            this.showAlert(ex.message);
        }
    
        return false;
    },
    
    takeMoreTime: function() {
        var moreBtn = $(this.options.moreTimeButtonId);
        if (moreBtn.is(':disabled')) {
            return false;
        }
        
        this.mode = 'takeMoreTime'
        this.options.submitParams[this.options.actionName] = this.mode;
        moreBtn.attr('disabled', 'disabled');
        moreBtn.hide();
        this.onSubmit();
        
        return false;
    },
    
    getAimTime: function() {
        var element = $(this.options.aimTimeId);
        if (element.length > 0) {
            var secondsLeft = parseInt(element.text());
        }
        return secondsLeft;
    },
    
    setAimTime: function(time) {
        var element = $(this.options.aimTimeId);
        if (element.length > 0) {
            element.html(time);
        }
    },
    
    onAfterSubmit: function(ajaxForm, options) {
        switch(this.mode) {
            case 'shot':
                this.lastMoveButtonId = null;
                break;
            case 'takeMoreTime':
                break;
            case 'aiming':
                this.lastMoveButtonId = null;
                break;
        }
    },
    
    onSuccess: function(responseObj) {
        switch(this.mode) {
            case 'shot':
                this.onSuccessShot(responseObj);
                break;
            case 'takeMoreTime':
                this.onSuccessMoreTime(responseObj);
                break;
            case 'aiming':
                this.onSuccessAiming(responseObj);
                break;
        }
        
        if (!responseObj.success) {
            this.__handleResponseMessages(responseObj);
        }
    },
    
    onSuccessShot: function(responseObj) {
        if (responseObj.shots) {
            Application.userInfo.setShotsCount(responseObj.shots);
            
            if (Application.userInfo.shots > 0) {
                // show more time buton only once
                var moreBtn = $(this.options.moreTimeButtonId);
                if (moreBtn.is(':visible')) {
                    moreBtn.removeAttr('disabled');
                }
            }
        }
    },
    
    onSuccessMoreTime: function(responseObj) {
        if(responseObj.addedSeconds) {
            var seconds = parseInt(responseObj.addedSeconds);
            var secondsLeft = this.getAimTime();
            secondsLeft += seconds;
            this.setAimTime(secondsLeft);
            
            // after more time got, hide the button
            $(this.options.moreTimeButtonId).hide();
        }
    },
    
    onSuccessAiming: function(responseObj) {
        if (responseObj.shots) {
            Application.userInfo.setShotsCount(responseObj.shots);
        }
    },
    
    onFailed: function(transport, exObj) {
       
    },
    
    onComplete: function(transport) { 
        if(Application.userInfo.shots > 0) {
            if (!this.isEnabled()) {
                this.enable();
            }
        } else {
            // disable aim control, remove from queue
            // if no more available shots
            this.onAimTimeOver();
        }
    },

    onAimTimeTick: function(timer) {
        var element = $(this.options.aimTimeId);
        if (element) {
            var secondsLeft = parseInt(element.innerHTML);
            
            if (secondsLeft > 0) {
                secondsLeft--;
                element.html(secondsLeft);
            } else {
                this.onAimTimeOver();
            }
        } else {
            throw('Element with ID ' + this.options.aimTimeId + ' is not found.');
        }
    },
    
    onAimTimeOver: function() {
        this.disable();
        Application.takeControlService.enableButton();
        Application.usersQueue.removeItemByUserId(this.userId);
        
    }
});*/

