// JavaScript Document

$(function () {

	var width = $(".zobrazlogin").width();
	$(".login-form").css("width",width+ 30 + "px");
	
	$(".zobrazlogin").toggle(function() {
		$('.login').slideDown("slow");
		$(this).addClass("active");
		return false;
	}, function() {
		$('.login').slideUp("slow");
		$(this).removeClass("active");
		return false;
	});

// ------------------------------
//   Load options
// ------------------------------

// get list from server

    yftSelect = {"highlightedElement":$("select#learn").parents("tr")
                                                       .get(0)};

// onload

    getActualSelectOptions("select#learn",_config.register.learn.getOptionsUrl,yftSelect);

// frequency
    setInterval(function () {
      getActualSelectOptions("select#learn",_config.register.learn.getOptionsUrl,yftSelect);
    }, _config.register.learn.refreshData);

// ------------------------------
//   Captcha
// ------------------------------

  function refreshCaptcha(e) {
     var $dom = $(this);
	   if(!$(this).hasClass("fadedYGT")) {
        var newSessionPath,newImagePath,formId;
        formId = $(this).parents("form").attr("id");

        if(formId=="login") {
            newSessionPath = _config.login.captcha.newSession;
            newImagePath   = _config.login.captcha.newImage;
        } else if(formId=="register") {
            newSessionPath = _config.register.captcha.newSession;
            newImagePath   = _config.register.captcha.newImage;    
        }

          var ajaxManagerCaptcha = $.manageAjax.create('cacheQueue', { 
              queue: 'clear',
              preventDoubbleRequests : true,
              maxRequests : 1
          }); 

          ajaxManagerCaptcha.add({
            url: newSessionPath,
            cache: false,
            type: "GET",
            success: function(){      

              ajaxManagerCaptcha.add({
                url: newImagePath,
                cache: false,
                type: "GET",
                success: function(html){      
                  $("#"+formId+" .captchaimage img").remove();
                  $("#"+formId+" .captchaimage").prepend(html).yellowFadeTechnique({
                    callback: function () {
                      $dom.one('click',refreshCaptcha);
                    }
                  });        
                }
              });
        
            }
          });       
      }
  }

	$(".refreshimg").bind('click',function () { return false; })
                  .one('click',refreshCaptcha);
                  
  function isFormValid(data,config) {
    $parent = $(config.noticeSelector).parent()
                                        .parent();

    $("#window ").children(".window").hide();
    $context = $('#'+formId+'FormDialog');
    $context.show();
    $("ul",$context).empty();
    
    if(data.url == 1 || data.url == 2) {
      $actulForm = $("#"+formId);
      if($actulForm=="login") $actulForm.clearForm();
      $(".refreshimg",$actulForm).trigger("click");
      if(data.url == 1) {        
        $(config.errorSelector).html("<"+config.wrapper+"><"+config.errorElement+" class=\""+config.errorClass+"\">"+config.failure.invalidCaptcha+"</"+config.errorElement+"></"+config.wrapper+">").fadeIn(config.fadeInSpeed);
      } else if(data.url == 2) {
        $(config.errorSelector).html("<"+config.wrapper+"<"+config.errorElement+"  class=\""+config.errorClass+"\">"+config.failure.invalidFailureMsg+"</"+config.errorElement+"></"+config.wrapper+">").fadeIn(config.fadeInSpeed);
      } else {
        throw new Error("Ivalid return type , selector : "+config.errorSelector);
      }
    } else { // refresh
      url = data.url;
      $(config.noticeSelector).html("<"+config.wrapper+">"+jQuery.format(config.successful.validMessage, config.successful.countDownSec, data.url, data.url)+"</"+config.wrapper+">");
      $(config.noticeSelector).fadeIn("fast",function () {
        
        setInterval(function () {
          actualTime = parseInt($(".remainingSecToRedirect",$parent).text());            
          actualTime--;
          $(".remainingSecToRedirect",$parent).html(actualTime);
          if(actualTime==0) {
            window.location = url;//"index.php";//url;
            return;
          }                                    
        }, 1000);
        
      });
    }
    
    $("h4 strong",$context).text(eval("_localStr."+formId+".headline"));
    showOverlay(false);
  }
  
// ------------------------------
//   Login form
// ------------------------------
// ------------------------------
//      validate
// ------------------------------
    
    loginValidateObject = {
  		rules: {
  			username: {
  				required: true,
  				minlength: 3,
  				username: true
  			},
  			password: {
  				required: true,
  				minlength: 5
  			},
  			captcha: {
  				required: true,
  				remote: _config.login.captcha.checkUrl
  			}

  		},
  		messages: {
  			username: {
  				required: _localStr.loginForm.usernameReq,
  				minlength: _localStr.registrationForm.usernameLength,
  				username: _localStr.registrationForm.usernameBadFormat
  			},
  			password: {
  				required: _localStr.loginForm.passwordReq,
  				rangelength: _localStr.registrationForm.passwordLength
  			},
  			captcha: {
          required: _localStr.registrationForm.capchaReq,
          remote: _localStr.registrationForm.capchaNotEqual
        }
  		},
      submitHandler : sendLoginData,
      errorLabelContainer: "#loginErrors"
    }
    
    jQuery.extend(loginValidateObject, customValidateObject);
    $("#login").validate(loginValidateObject);

// ------------------------------
//      ajax form
// ------------------------------

    loginAjaxFormObject = {
  		url: _config.login.sendInfoPath,
  		success: function (data) {
        _configValid = {
          noticeSelector  : "#loginNotices",
          errorSelector   : "#loginErrors",
          errorClass      : customValidateObject.errorClass,
          errorElement    : customValidateObject.errorElement,
          wrapper         : customValidateObject.wrapper,          
          fadeInSpeed     : customValidateObject.errorFadeInSpeed,
          failure         : {
            invalidCaptcha      : _localStr.registrationForm.capchaNotEqual,
            invalidFailureMsg   : _localStr.loginForm.wrongLoginDate
          },
          successful    : {
            validMessage : _localStr.login.successful,
            countDownSec : _config.login.timer
          }
        }
        isFormValid(data,_configValid);        
      }
		}
		jQuery.extend(loginAjaxFormObject, customAjaxFormObject);
		
    function sendLoginData(form) {
    	$(form).ajaxSubmit(loginAjaxFormObject);
    }

// ------------------------------
//   Registration form
// ------------------------------
// ------------------------------
//      validate
// ------------------------------

    registrationValidateObject = {
  		rules: {
  		  firstname: {
          required: true,
          minlength: 2
        },
  		  surname: {
          required: true,
          minlength: 2
        },
        bornDay : {
          required: true,
          range: [1, 31]
        },
        bornMonth : {
          required: true,
          range: [1, 12]
        },
        bornYear : {
          required: true,
          range: [1900, actualYear]
        },
  			usernameReg: {
  				required: true,
  				minlength: 3,
  				username: true,
  				remote: _config.register.username.checkUniqueUrl
  			},
  			passwordReg: {
  				required: true,
  				minlength: 5
  			},
  			passwordConfirm: {
  				required: true,
  				minlength: 5,
  				equalTo: "#passwordReg"
  			},  			
  			street: {
  				required: true,
  				minlength: 2
  			},
  			city: {
  				required: true,
  				minlength: 2        
        },
        postalCode: {
  				required: true,
  				minlength: 5  
        },
        email: {
          required: true,
          email: true
        },
        telefon: {
          required: true,
          minlength: 9
        },
        terms: { required: true },
  			captchaReg: {
  				required: true,
  				remote: _config.register.captcha.checkUrl
  			}
  		},
  		messages: {
  		  firstname: {
          required: _localStr.registrationForm.firstNameReq,
          minlength: _localStr.registrationForm.firstNameLength
        },
  		  surname: {
          required: _localStr.registrationForm.lastNameReq,
          minlength: _localStr.registrationForm.lastNameLength
        },
        bornDay : {
          required: _localStr.registrationForm.bornDayReq,
          range: _localStr.registrationForm.bornDayRange
        },
        bornMonth : {
          required: _localStr.registrationForm.bornMonthReq,
          range: _localStr.registrationForm.bornMonthRange
        },
        bornYear : {
          required: _localStr.registrationForm.bornYearReq,
          range:  _localStr.registrationForm.bornYearRange
        },
  			usernameReg: {
  				required: _localStr.loginForm.usernameReq,
  				minlength: _localStr.registrationForm.usernameLength,
  				username: _localStr.registrationForm.usernameFormat,
  				remote: _localStr.registrationForm.usernameIsUsed
  			},
  			passwordReg: {
  				required: _localStr.loginForm.passwordReq,
  				minlength: _localStr.registrationForm.passwordLength
  			},
  			passwordConfirm: {
  				required: _localStr.registrationForm.passwordConfrimReg,
  				minlength: _localStr.registrationForm.passwordLength,
  				equalTo: _localStr.registrationForm.passwordsNotEqual
  			},  			
  			street: {
  				required: _localStr.registrationForm.streetReq,
  				minlength: _localStr.registrationForm.streetLength
  			},
  			city: {
  				required: _localStr.registrationForm.cityReq,
  				minlength: _localStr.registrationForm.cityLength        
        },
        postalCode: {
  				required: _localStr.registrationForm.postalCodeReq,
  				minlength: _localStr.registrationForm.postalCodeLength  
        },
        email: {
          required: _localStr.registrationForm.emailReq,
          email: _localStr.registrationForm.emailFormat
        },
        telefon: {
          required: _localStr.registrationForm.phoneReq,
          minlength: _localStr.registrationForm.phoneLength
        },
        terms: _localStr.registrationForm.termsServices,
  			captchaReg: {
          required: _localStr.registrationForm.capchaReq,
          remote: _localStr.registrationForm.capchaNotEqual
        }
  		},
      submitHandler : sendRegisterData,
      errorLabelContainer: "#registerErrors"
    };
    
    jQuery.extend(registrationValidateObject, customValidateObject);
    $("#register").validate(registrationValidateObject);

// ------------------------------
//      ajax form
// ------------------------------

    registerAjaxFormObject = {
  		url: _config.register.sendInfoPath,
  		success: function (data) {
  		
        _configValid = {
          noticeSelector  : "#registerNotices",
          errorSelector   : "#registerErrors",
          errorClass      : customValidateObject.errorClass,
          errorElement    : customValidateObject.errorElement,
          wrapper         : customValidateObject.wrapper,          
          fadeInSpeed     : customValidateObject.errorFadeInSpeed,
          failure         : {
            invalidCaptcha      : _localStr.registrationForm.capchaNotEqual,
            invalidFailureMsg   : _localStr.register.failure
          },
          successful    : {
            validMessage : _localStr.register.successful,
            countDownSec : _config.register.timer
          }
        }
        isFormValid(data,_configValid);
  		}
		};
		
		jQuery.extend(registerAjaxFormObject, customAjaxFormObject);
		
    function sendRegisterData(form) {
    	$(form).ajaxSubmit(registerAjaxFormObject);
    }

// ------------------------------
//   Captcha after bind validations
// ------------------------------

$("#login input:image, #register input:image").click(function() {
  formId = $(this).parents("form").attr("id");
  if(!$("#"+formId).valid()) {    
    $("#window ").children(".window").hide();
    $context = $('#'+formId+'FormDialog');
    $context.show();
    $("h4 strong",$context).text(eval("_localStr."+formId+".headline"));
    showOverlay(true);
  }
});

});
