/**
 * main.js
 * JQuery code for form interactions
 */

// $Id$

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Sets this module's JQuery behavior
$(document).ready(function(){

    $("#fms-form-login").ajaxForm({
        target: "",
        beforeSubmit: validateLoginForm,
        success     : onLoginSuccess
    });

    $("#fms-form-send-pwd").ajaxForm({
        target: "",
        beforeSubmit: validateSendPwdForm,
        success     : onSendPwdSuccess
    });

    $("#fms-form-register").ajaxForm({
        target: "",
        beforeSubmit: validateRegisterForm,
        success     : onRegisterSuccess
    });

    //Execute the slideShow
    slideShow(4000);

});

/* *****************************************************************************
 * Functional used to center the dialog window created by BlockUI.
 */
$.fn.center = function () {

    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");

    return this;
}

/* *****************************************************************************
 * Functional that will display a modal login box that overlays the current page.
 */
function showRegister(){

    $.blockUI({
        message: $("#fms-form-register-wrapper"),
        css: { cursor: 'default', padding: '0', textAlign: 'left', 'border-width': '0px', background: 'none' },
        overlayCSS: { cursor: 'default' }
    });
    $('.blockUI.blockMsg').center();
    $('.blockOverlay').click($.unblockUI);
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will do the basic validation of the form (required fields, confirmations, ...).
//
// formData:
// formData is an array of objects representing the name and value of each field
// that will be sent to the server;  it takes the following form:
//
// [
//     { name:  username, value: valueOfUsernameInput },
//     { name:  password, value: valueOfPasswordInput }
// ]
//
// JqForm:
// jqForm is a jQuery object which wraps the form DOM element
//
// options:
// this is the Options Object passed into ajaxForm/ajaxSubmit
function validateLoginForm(formData, jqForm, options) {

    //get the form object
    var form = jqForm[0];
    var valid = true;

    $(".error").removeClass("error");

    //email required
    if(!form.username.value){
        $("#fms-form-login-username").addClass("error");
        valid = false;
    }

    //pwd required
    if(!form.password.value){
        $("#fms-form-login-password").addClass("error");
        valid = false;
    }

    //everything is good, show the throbber and proceed to the core operation
    if(valid){
        $("#fms-form-login").fadeOut('fast', function(){
            $("#fms-form-login-wrapper").addClass("loading");
        });
    }

    return valid;
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will process the returning value of the submitions to see if the operation
// was successfull or not.
//
// result:
// the responseText or responseXML value (depending on the value of the dataType option).
function onLoginSuccess(result){

    //parse the result so that we know if there was an error or everything went fine
    var str = result.substr(0, 5);

    $("#fms-form-login-wrapper").removeClass("loading");

    if(str == "false"){

        //get the incorrect field
        var idx = result.indexOf("=");

        //check if the resulting error indicates a field. [example: false field_with_error=error_message]
        if(idx != -1){
            var field = result.substr(6, idx-6);
            jAlert(result.substr(idx+1, result.length), 'Login Error');
            $("[name=" + field + "]").addClass("error");
        }else{
            jAlert(result.substr(6, result.length), 'Login Invalid');
        }

        //graphical logic
        $("#fms-form-login").fadeIn('fast');
    }
    else{
        window.location = result;
    }
}


//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will make sure that the username field is not empty and do the graphical logic.
//
// formData:
// formData is an array of objects representing the name and value of each field
// that will be sent to the server;  it takes the following form:
//
// [
//     { name:  username, value: valueOfUsernameInput },
//     { name:  password, value: valueOfPasswordInput }
// ]
//
// JqForm:
// jqForm is a jQuery object which wraps the form DOM element
//
// options:
// this is the Options Object passed into ajaxForm/ajaxSubmit
function validateSendPwdForm(formData, jqForm, options) {

    //get the form object
    var form = jqForm[0];
    var valid = true;

    $(".error").removeClass("error");

    //email required
    if(!form.username.value){
        $("#fms-form-send-pwd-username").addClass("error");
        valid = false;
    }

    //everything is good, show the throbber and proceed to the core operation
    if(valid){
        $("#fms-form-send-pwd").fadeOut('fast', function(){
            $("#fms-form-send-pwd-wrapper").addClass("loading");
        });
    }

    return valid;
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will process the returning value of the submitions to see if the operation
// was successfull or not.
//
// result:
// the responseText or responseXML value (depending on the value of the dataType option).
function onSendPwdSuccess(result){

    //parse the result so that we know if there was an error or everything went fine
    var str = result.substr(0, 5);

    $("#fms-send-pwd-wrapper").removeClass("loading");

    if(str == "false"){

        //get the incorrect field
        var idx = result.indexOf("=");

        //check if the resulting error indicates a field. [example: false field_with_error=error_message]
        if(idx != -1){
            var field = result.substr(6, idx-6);
            jAlert(result.substr(idx+1, result.length), 'Reset Password Error');
            $("[name=" + field + "]").addClass("error");
        }else{
            jAlert(result.substr(6, result.length), 'Reset Password Invalid');
        }

        //graphical logic
        $("#fms-form-send-pwd").fadeIn('fast');
    }
    else{
        jAlert(result, 'Reset Password Successful');
        showLoginForm();
    }
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Simple function used to hide the password retrieval form and show the login form.
function showLoginForm(){

    $("#fms-form-send-pwd-wrapper").fadeOut('fast', function(){
        $("#fms-form-login-wrapper").fadeIn('fast');
    });
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Simple function used to hide the login form and show the password retrieval form.
function showSendPwdForm(){

    $("#fms-form-login-wrapper").fadeOut('fast', function(){
        $("#fms-form-send-pwd-wrapper").fadeIn('fast');
    });
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Slide show function to display the slides
function slideShow(speed) {

    //append a LI item to the UL list for displaying caption
    $('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>');

    //Set the opacity of all images to 0
    $('ul.slideshow li').css({opacity: 0.0});

    //Get the first image and display it (set it to full opacity)
    $('ul.slideshow li:first').css({opacity: 1.0});

    //Get the caption of the first image from REL attribute and display it
    $('#slideshow-caption h3').html($('ul.slideshow li.show').find('img').attr('title'));
    $('#slideshow-caption p').html($('ul.slideshow li.show').find('img').attr('alt'));

    //Display the caption
    $('#slideshow-caption').css({opacity: 0.7, bottom:0});

    //Call the gallery function to run the slideshow
    var timer = setInterval('gallery()',speed);

    //pause the slideshow on mouse over
    $('ul.slideshow').hover(
        function () {
            clearInterval(timer);
        },
        function () {
            timer = setInterval('gallery()',speed);
        }
    );

}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Used by the slideshow function
function gallery() {

    //if no IMGs have the show class, grab the first image
    var current = ($('ul.slideshow li.show')?  $('ul.slideshow li.show') : $('#ul.slideshow li:first'));

    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first'));

    //Get next image caption
    var title = next.find('img').attr('title');
    var desc = next.find('img').attr('alt');

    //Set the fade in effect for the next image, show class has higher z-index
    next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);

    //Hide the caption first, and then set and display the caption
    $('#slideshow-caption').slideToggle(300, function () {
        $('#slideshow-caption h3').html(title);
        $('#slideshow-caption p').html(desc);
        $('#slideshow-caption').slideToggle(500); 
    });

    //Hide the current image
    current.animate({opacity: 0.0}, 1000).removeClass('show');
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will display a HTML alert box containing an iframe with the specified dimensions and source.
function showDemo(w, h, s){

    jAlert("<iframe width='"+w+"' height='"+h+"' frameborder='0' src='"+s+"' scrolling='no'></iframe>", 'Demo');
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will display the terms and conditions on an overlay
function showTerms(){

    $.blockUI({
        message: $('#fms-terms'),
        css: { cursor: 'default', padding: '10px', 'max-height': '500px', overflow: 'auto', 'text-align': 'justify' },
        overlayCSS: { cursor: 'default' }
    });
    $('.blockUI.blockMsg').center();
    $('.blockOverlay').click($.unblockUI);
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will simply do the graphical logic, all validations are done on the server side.
//
// formData:
// formData is an array of objects representing the name and value of each field
// that will be sent to the server;  it takes the following form:
//
// [
//     { name:  username, value: valueOfUsernameInput },
//     { name:  password, value: valueOfPasswordInput }
// ]
//
// JqForm:
// jqForm is a jQuery object which wraps the form DOM element
//
// options:
// this is the Options Object passed into ajaxForm/ajaxSubmit
function validateRegisterForm(formData, jqForm, options) {

    //terms checked?
    if(!$("#fms-form-register-agree").is(":checked"))
        return false;

    $("#fms-form-register").fadeOut('fast', function(){
        $("#fms-form-register-wrapper").addClass("loading");
    });

    return true;
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will process the returning value of the submitions to see if the operation
// was successfull or not.
//
// result:
// the responseText or responseXML value (depending on the value of the dataType option).
function onRegisterSuccess(result){

    //parse the result so that we know if there was an error or everything went fine
    var str = result.substr(0, 5);

    $("#fms-form-register-wrapper").removeClass("loading");

    if(str == "false"){

        $("#fms-form-register-res").html(result.substr(6, result.length));
    }
    else{
        $("#fms-form-register-res").html(result);
    }
    $("#fms-form-register-res").fadeIn('fast');
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will unblock the register form.
function unblockRegisterForm(){

    $("#fms-form-register-res").fadeOut('fast', function(){
        $("#fms-form-register").fadeIn('fast');
    });
}
