/*
 * Web-site developed with PHP 5
 * 
 * Copyright (c) 2011 MagicBrain
 * http://www.magicbrain.pt
 * 
 * Licensed under GPLv3
 * http://www.gnu.org/licenses/
 * 
 * ----------------------------------------------------------------------
 * This file is part of index.php.
 * 
 * index.php is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * index.php is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 * ----------------------------------------------------------------------
 * 
 * Launch  : October 2011
 * Version : 4-stable
 * Released: Tuesday 25th October, 2011 - 19:08
 * 
 */



/**
 * WEB SITE NOTIFIER
 * 
 * This function shows a new notification balloon with the received text,
 * and also unload the balloon by the given time in milliseconds
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
function siteNotifications(title, expires)
{
    // notify the user
    $("#notification").notify
    (
        "create",
        {
            title : title
        },
        {
            expires : expires,
            click   : function (e,instance) { instance.close(); }
        }
    );
}



/**
 * ROUNDS A FLOAT NUMBER
 * @param float num : number
 * @param int dec : decimal places
 * @return float
 *--------------------------------------------------------------------------------------------------------------------------------------------*/
function roundNumber(num, dec)
{
   var result = String(Math.round(num*Math.pow(10,dec))/Math.pow(10,dec));
   if(result.indexOf('.')<0) {result+= '.';}
   while(result.length- result.indexOf('.')<=dec) {result+= '0';}
   return result;
}



/**
 * CALLBACK AFTER LOADING
 * 
 * This function shows all areas of the website one by one, until
 * it reachs the module.
 * For the module presentation, it will search for a URL variable "mod"
 * to see if a module is being forced to be presented first.
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
function showContent()
{
    /** THIS NEEDS TO BE DONE HERE TO PREVENT BAD DISPLAY ON CATALOG STARTUP */
    // we need to set the width of the $pg_photos,
    // which is the sum of its childrens width
    var $pg_photos = $('#pg_photos');
    $pg_photos.children().not(":hidden").each(function() {
        pg_photos_width += $(this).outerWidth(true);
    });
    $pg_photos.css('width', (pg_photos_width)+'px');
    /** END OF CATALOG SETUP PATCH */

    // show Owner Logo
    $("div#hd_logo").animate({
        "top"  : "10px",
        "left" : "10px"
    }, 500, function(){
        // show Footer Bar
        $("div#ft_bar").animate({
            "left"   : "0px",
            "bottom" : "0px"
        }, 500, function(){
            // show Main Menu
            $("div#navigation-block").animate({
                "left" : "0px"
            }, 500, function(){
                // check url variable to confirm if there's no module being forced to load first
                var mod = $.getUrlVar('mod');
                
                // if module contains a value, sets that module as active, else sets the default one
                if (mod!=undefined && $("#mod_"+mod).size()==1) {
                    $("#mod_"+mod).addClass("modActive");
                } else {
                    if ($(".mod_books_news").not(".disabled")) {
                        LoadModules('mod_books_news');
                    }
                    else {
                        LoadModules('mod_books');
                    }
                }
                
                // Show first module
                var oh = $(".modActive").outerHeight(true),
                    ow = $(".modActive").outerWidth(true); // true includes the margin
                $(".modActive")
                    .css({top: -oh+"px", left: ($(window).width()-ow)/2 + "px"})
                    .animate({top: ($(window).height() - oh)/2 + "px"}, 1000, "easeOutBack", function(){
                        // initialize the catalogue
                        catalogueStartUp();
                        // initialize the banner
                        startSlideshowBanner();
                        // initialize the notifications
                        launchNotifications();
                        // Animate Footer Icons
                        $(".lnk_footer").animate({"bottom":"-35px"});
                    });
            });
        });
    });
}



/**
 * Banner Slider
 * 
 * Function to change banner image
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
function startSlideshowBanner()
{
    // SLIDESHOW BANNER
    if ($('.fadeIn img').size() > 0) {
        $("#banner").slideDown();
        $('.fadeIn img:gt(0)').hide();
    }
    
    if ($('.fadeIn img').size() > 1) {
        setInterval(function() {
            changeBanner();
        }, 10000);
    
        $("#bannerNext").bind("click", function(e) {
            changeBanner();
            return false;
        });
        $("#bannerPrev").bind("click", function(e) {
            changeBanner();
            return false;
        });
    }
    else {
        $('.banner').addClass("noCssHover");
    }
}

function changeBanner()
{

    if ($('.fadeIn img.active').next().length == 0) {
        $('.fadeIn img:last-child').removeClass('active').fadeOut("fast");
        $('.fadeIn img:first-child').addClass('active').fadeIn("fast");
    }
    else {
        $('.fadeIn img.active').fadeOut("fast").toggleClass('active').next().addClass('active').fadeIn("fast");
    }
}



/**
 * Popup notifications
 * 
 * Function to launch popup notifications
 * ---------------------------------------------------------------------------------------------------------------------------------------- */

function launchNotifications()
{
    // initiate notifications container
    $("#notification").notify({
        speed: 500,
        expires: false
    });

    
    // get latest news
    $.ajax({
        type    : "POST",
        url     : "components/inc/ajax/get_content_details.php",
        data    : "&table=site_news&id=0",
        success : function(response) {
            
            if(response != "") {
            
                // parse news data
                var data = $.parseJSON(response);
            
                // launch notifiers after website is loaded
                setTimeout( function() {
                    
                    // loads each new
                    for(x = 0; x < data.length; x ++) {
                        
                        // if user hasn't checked the new
                        if(!$.cookie('news_' + data[x]["id"])) {

                            // create new notification with the new
                            $("#notification").notify("create", {
                                title: data[x]["title"]
                            },{
                               // closes the notification
                               click: function(e,instance) {
                                  instance.close();
                                },
                                // creates event to load new
                                beforeopen: function() {
                                                            
                                    var id = data[x]["id"];
                                    
                                    $(this).attr("id","notify_" + id);
                                    
                                    $(this).click(function() {
                                        // verifies if module is present if not loads it
                                        if(!$("#mod_news").hasClass("modActive")) LoadModules('mod_news');
                                        
                                        // calls click on the new to load data
                                        $("#news-titles #row_" + id).trigger("click");
                                    });
                                },
                                close: function() {
                                    var id = $(this).attr("id");
                                    id = id.substr(7);
                                    
                                    // set cookie to check new
                                    var cookieOptions = {expires: 365};
                                    $.cookie('news_' + id, 1, cookieOptions);
                                }
                            });
                        }
    
                    }
                
                }, 1000);
            
            }
        }
    });
}



/**
 * Populate Contents to Right Panel
 * 
 * On click over a list item on the NEWS or AUTHORS modules
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
function populateContent(id, table, target)
{
    $.ajax({
        type    : "POST",
        url     : "components/inc/ajax/get_content_details.php",
        data    : "&table="+ table +"&id="+id,
        success : function(response) {
            if (response == "dbError") {
                // ERROR, do something
            }
            else {
               $("#" + target ).fadeOut('fast', function() {
                    $(this).find(".scroll-content").html(response).text();
                    
                    $("#" + target).fadeIn('fast', function() {
                        // restart scrollbars for the right panel
                        setSlider($("#"+target));
                    });
               });
            }
        }
    });
}



/**
 * Easy Background Image Resizer
 * 
 * Developed by J.P. Given (http://johnpatrickgiven.com)
 * Some modifcations by Hay Kranen < http://www.haykranen.nl >
 * Usuage: anyone so long as credit is left alone
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
(function($) {
    var containerObj, center = false;

    // plugin definition
    $.fn.ezBgResize = function(center) {
        center = center || false;
        // First position object
        containerObj = this;

        containerObj.css("visibility","hidden");

        $(window).load(function() {
            resizeImage();
        });

        $(window).bind("resize",function() {
            resizeImage();
        });

    };

    function resizeImage()
    {
        containerObj.css({
            "position" : "fixed",
            "top"      : "0px",
            "left"     : "0px",
            "z-index"  : "-1",
            "overflow" : "hidden",
            "width"    : getWindowWidth() + "px",
            "height"   : getWindowHeight() + "px"
        });

        // Resize the img object to the proper ratio of the window.
        var iw = containerObj.children('img').width();
        var ih = containerObj.children('img').height();
        
        if ($(window).width() > $(window).height()) {
            if (iw > ih) {
                var fRatio = iw/ih;
                containerObj.children('img').css("width",$(window).width() + "px");
                containerObj.children('img').css("height",Math.round($(window).width() * (1/fRatio)));

                var newIh = Math.round($(window).width() * (1/fRatio));

                if(newIh < $(window).height()) {
                    var fRatio = ih/iw;
                    containerObj.children('img').css("height",$(window).height());
                    containerObj.children('img').css("width",Math.round($(window).height() * (1/fRatio)));
                }
            } else {
                var fRatio = ih/iw;
                containerObj.children('img').css("height",$(window).height());
                containerObj.children('img').css("width",Math.round($(window).height() * (1/fRatio)));
            }
        } else {
            var fRatio = ih/iw;
            containerObj.children('img').css("height",$(window).height());
            containerObj.children('img').css("width",Math.round($(window).height() * (1/fRatio)));
        }

        containerObj.css("visibility","visible");

        // Center BG Image
        if (center) {
            containerObj.children('img').css("position","relative");

            if (containerObj.children('img').width() > containerObj.width()) {
                var wDiff = (containerObj.children('img').width() - containerObj.width()) / 2;
                containerObj.children('img').css("left", "-" + wDiff + "px");
            }
        }
    }

    // Dependable function to get Window Height
    function getWindowHeight()
    {
        var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
            windowHeight = window.innerHeight;
        }
        else {
            if (document.documentElement && document.documentElement.clientHeight) {
                windowHeight = document.documentElement.clientHeight;
            }
            else {
                if (document.body && document.body.clientHeight) {
                    windowHeight = document.body.clientHeight;
                }
            }
        }
        return windowHeight;
    }

    // Dependable function to get Window Width
    function getWindowWidth()
    {
        var windowWidth = 0;
        if (typeof(window.innerWidth) == 'number') {
            windowWidth = window.innerWidth;
        }
        else {
            if (document.documentElement && document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
            }
            else {
                if (document.body && document.body.clientWidth) {
                    windowWidth = document.body.clientWidth;
                }
            }
        }
        return windowWidth;
    }
})(jQuery);



/** JQUERY EXTENSION TO GRAB URL VARIABLES
--------------------------------------------------------------------------------------------------------------------------------------------*/
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});



/** INPUTS CLEAR DEFAULT VALUE
--------------------------------------------------------------------------------------------------------------------------------------------*/
(function($){
    $.fn.clearDefault = function(){
        return this.each(function(){
            var default_value = $(this).val();
            $(this).focus(function(){
                if ($(this).val() == default_value)
                    $(this).val("");
            });
            $(this).blur(function(){
                if ($(this).val() == "")
                    $(this).val(default_value);
            });
        });
    };
})(jQuery);
// usuage example: $('input').clearDefault();





/** INPUTS NUMERIC ONLY (control handler)
--------------------------------------------------------------------------------------------------------------------------------------------*/
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};



/** MAIN MENU
--------------------------------------------------------------------------------------------------------------------------------------------*/
function slide(navigation_id, pad_out, pad_in, time, multiplier)
{
    // creates the target paths
    var list_elements = navigation_id + " li.menu-element",
        link_elements = list_elements + " a:not(.sub-menu-link)";
    
    // initiates the timer used for the menu animation
    var timer = 0;
    
    // creates the slide animation for all list elements 
    $(list_elements).each(function(i)
    {
        // margin left = - ([width of element] + [total vertical padding of element])
        $(this).css("margin-left","-180px");
        // updates timer
        timer = (timer*multiplier + time);
        $(this).animate({ marginLeft: "0" }, timer);
        $(this).animate({ marginLeft: "15px" }, timer);
        $(this).animate({ marginLeft: "0" }, timer);
    });

    // creates the hover-slide effect for all link elements         
    $(link_elements).each(function(i) {
        $(this).hover(function() {
            $(this).stop().animate({
                "padding-left" : pad_out,
                "font-size"    : "16px"
            }, 150, function() {
                
                // clear all sub-menu-elements
                $(navigation_id).find('.sub-menu-element:not(.hiddenLeft)').attr("style", "").addClass("hiddenLeft");

                // check for sub-menu-element
                if ($(this).closest('.menu-element').find('.sub-menu-element').size()==1)
                {
                    var $target  = $(this).closest('.menu-element').find('.sub-menu-element'),
                        distance = $(this).outerWidth(true);
                    $target
                        .css({
                            "left"     : (distance-20) + "px",
                            "padding"  : "30px"
                        })
                        .removeClass("hiddenLeft");
                }
            });
        },      
        function() {
            $(this).stop().animate({
                "padding-left" : pad_in,
                "font-size"    : "12px"
            }, 150);
        });
    });
}



$(document).ready(function() {
    slide("#menu-navigation", 25, 15, 150, .8);
    
    /* OPEN BOX */
    $(".openModalBox").live('click', function(event){
        event.preventDefault();

        var box = $(this).attr("rel");
        
        $("#"+box).css({
            "margin-top" : "-" + ($("#"+box).outerHeight(true)/2) + "px"
        });
        
        $("#lightbox, #"+box).fadeIn(300);
        
        // load book details
        if ($(this).hasClass('item-viewDetails')) {
            var $ele = $(this);
                id   = $ele.closest("a").find('span.item-id').html();
        
            populate_book_details(id);
        }
        
        // load book details from authors
        if ($(this).hasClass('author-viewDetails')) {
            var book_id = $(this).find('a').attr('rel');
            populate_book_details(book_id);
        }
    });
    
    /* CLOSE BOX */
    $("#lightbox, .lightbox-close").live("click", function(event)
    {
        event.preventDefault();

        // If this is closing a DataSheet, we hide the zoom element
        if ($(this).parents("#productdatasheetbox-panel")) {
            $(".zoomtracker").css({"z-index":"-9999"});
        }
        
        if ($(".lightbox-panel:visible").size() == 1) {
            $("#lightbox").fadeOut(300);
        }
        
        $(".lightbox-panel").css({"margin-top" : "0px"}).fadeOut(300);
    });

    // window buttons functions
    $(".bd .opts a.close").bind("click", function() {
        LoadModules('mod_books');
    });
});



/**
 * MODULE SHOW / HIDE
 * 
 * Set of functions to control modules show / hide effect,
 * and check specific events for each module
--------------------------------------------------------------------------------------------------------------------------------------------*/
// Check Module Specific Events
function checkModules(modShow)
{
    module = modShow;

    if (modShow.indexOf("books") !== -1) {
        $("#body-background").animate({
            "opacity": 0.6
        }, 200, function() {
            // Shrink the menu to the bottom left corner of screen
            $("div#navigation-block").removeClass().addClass("tiny");
        });

        // Reset all books in the list to visible
        $("#pg_photos li").show();

        // Show only books marked as "news"
        if (modShow.indexOf("news") !== -1) {
            // hide all but marked as news
            $("#pg_photos li:not(.is_new)").hide();
            module = 'mod_books';
        }

        // Show only books marked as "highlights"
        if (modShow.indexOf("highlights") !== -1) {
            // hide all but marked as news
            $("#pg_photos li:not(.is_highlight)").hide();
            module = 'mod_books';
        }

        // Restart the catalogue
        initSlider();
        configGallery();
        $(window).hashchange();

    }
    else {
        $("#body-background").animate({"opacity":1}, 200);
        // Grow the menu to the center left side of screen
        $("div#navigation-block").removeClass().addClass("big");
    }

    return module;
}



/**
 * GOOGLE MAPS GLOBAL SCOPE VARIABLE FOR API v3.0 INTERACTION
 * ------------------------------------------------------------------------------------ */
var global = {};
global.initMap = function(){
    $.post("components/inc/ajax/get_googleMaps.php", { "id": 1 }, function(data)
    {
        $("#gmaps").gMap(
        {
            controls: {
                panControl         : true,
                zoomControl        : true,
                mapTypeControl     : false,
                scaleControl       : false,
                streetViewControl  : false,
                overviewMapControl : false
            },
            scrollwheel: data.scrollwheel,
            maptype: 'ROADMAP',
            markers: [
                {
                    latitude: data.latitude,
                    longitude: data.longitude,
                    html: data.html,
                    icon: {
                        image: "http://www.google.com/mapfiles/marker.png",
                        shadow: "http://www.google.com/mapfiles/shadow50.png",
                        iconsize: [20, 34],
                        shadowsize: [37, 34],
                        iconanchor: [9, 34],
                        shadowanchor: [19, 34]
                    }
                }
            ],
            zoom: 16
        });
        $("#gmaps").removeClass('ajaxFirstLoad');
    }, "json");
}



// Show or Hide Modules
function LoadModules(modShow)
{
    var modHide = $(".modActive").attr("id");

    // Array with effects for random selection
    var arrName = new Array();
    arrName[0]='def';
    arrName[1]='jswing';
    arrName[2]='easeInQuad';
    arrName[3]='easeOutQuad';
    arrName[4]='easeInOutQuad';
    arrName[5]='easeInCubic';
    arrName[6]='easeOutCubic';
    arrName[7]='easeInOutCubic';
    arrName[8]='easeInQuart';
    arrName[9]='easeOutQuart';
    arrName[10]='easeInOutQuart';
    arrName[11]='easeInSine';
    arrName[12]='easeOutSine';
    arrName[13]='easeInOutSine';
    arrName[14]='easeInExpo';
    arrName[15]='easeOutExpo';
    arrName[16]='easeInOutExpo';
    arrName[17]='easeInQuint';
    arrName[18]='easeOutQuint';
    arrName[19]='easeInOutQuint';
    arrName[20]='easeInCirc';
    arrName[21]='easeOutCirc';
    arrName[22]='easeInOutCirc';
    arrName[23]='easeInElastic';
    arrName[24]='easeOutElastic';
    arrName[25]='easeInOutElastic';
    arrName[26]='easeInBack';
    arrName[27]='easeOutBack';
    arrName[28]='easeInOutBack';
    arrName[29]='easeInBounce';
    arrName[30]='easeOutBounce';
    arrName[31]='easeInOutBounce';

    // hide current module
    var oh = $("#"+modHide).outerHeight(true),
        ow = $("#"+modHide).outerWidth(true); // true includes the margin
    $("#"+modHide)
        .animate({top: -oh+"px", left: ($(window).width()-ow)/2 + "px"})
        .removeClass("modActive");

    modShow = checkModules(modShow);


    // MODULE :: CONTACTS FORM or CONTACTS
    if (modShow.indexOf("contactsForm") !== -1)
    {
        $("#CF_onlineForm .captchaRefresh").siblings("img").attr("src","components/inc/captcha.php?r=" + Math.random());
    }
    else if (modShow.indexOf("contacts") !== -1)
    {
        if ($('#gmaps.ajaxFirstLoad').size()==1)
        {
            $.getScript('http://maps.google.com/maps/api/js?sensor=true&callback=global.initMap', function(data1, textStatus){});
        }
    }
    
    var oh = $("#"+modShow).outerHeight(true),
        ow = $("#"+modShow).outerWidth(true); // true includes the margin
    $("#"+modShow)
        .css({top: -oh+"px", left: ($(window).width()-ow)/2 + "px"})
        .animate({top: ($(window).height() - oh)/2 + "px"}, 1000, arrName[27])
        .addClass("modActive");

    // flags the body tag with the current active module, for features control
    $("body").addClass($(".modActive").attr("id"));
}





$(function() {


    /**
     * FOOTER ICON LINKS
     */
    $('.lnk_icon')
        .mouseover(function(){
            $(this).animate({"bottom":"+=35px"});
        })
        .mouseout(function(){
            $(this).animate({"bottom":"-=35px"});
        });


    /**
     * FOOTER HIDDEN PANELS
     */
    $("div#ft_bar > ul > li > a").bind("click", function() {
        if ($(this).attr("href").indexOf("#") !== -1) {
            $(this).siblings(".hiddenPanel").toggle(100);
            return false;
        }
    });
    $(".hiddenPanel a.close").bind("click", function() {
        $(this).closest(".hiddenPanel").toggle(100);
        return false;        
    });


    /**
     * BIND CLICK EVENT TO NEWS HEADERS
     */
    $("li.populateContent").bind("click", function(e) {
        // set active status
        $(this).addClass("active").siblings("li").removeClass("active");

        // Get ID and TABLE
        var rowID = $(this).attr('id').substring(4);
        var table = $(this).parents("ul").attr('class').split(' ')[0];
        var target = $(this).closest(".wrap").find(".target").attr("id");

        // Go Ajax
        populateContent(rowID, table, target);
        return false;
    });



    /**
     * URL CONTROLED MODULES
     */

    // get url variables
    var mod = $.getUrlVar('mod'),
        id  = $.getUrlVar('id');


    // check if link to news is present    
    if(mod == 'news' && id > 0) {
        $("#news-titles #row_" + id).trigger("click");
    }
    else {
        /* TRIGGER CLICK EVENT ON FIRST NEWS HEADER */
        $("#news-titles li:first").trigger("click");    
    }


    /* TRIGGER CLICK EVENT ON FIRST AUTHOR NAME */
    $("#authors-titles li:first").trigger("click");


    // check if link to product dataSheet is present
    if (mod == 'books' && id > 0) {
        $("li#book_" + id).find('.item-viewDetails').trigger("click");
    }

});

/*
 * 
 * 
 * 
 * location.hash = $(this).attr("name");
 * 
 * 
 * 
 * 
 * 
 */

/** ---------------------------------------------------------------------------------------------------------------------------------------
 * WEBSITE MODULE :: Newsletter Subscription Form
 * 
 * Start of functions to control the newsletter
 * subscription form, its messages, user interaction,
 * etc.
 * Also functions to post and collect data from this
 * form.
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
// Clear User Messages
function NS_clearUsrMsgs()
{
    $('#footerNewsletter .user_msg').addClass("hidden").find("p").addClass("hidden");
}

// Show User Messages
function NS_showUserMessage(errorClass)
{
    // hide all error messages
    NS_clearUsrMsgs();

    // show correct error message by supplied element
    $('#footerNewsletter .user_msg')
        .css({"display":"block"})
        .removeClass("hidden")
        .hide()
        .fadeIn(1000)
        .find("."+errorClass)
        .removeClass("hidden")
        .end();
}

/** Reset Form */
function NS_formReset(limit)
{
    if (limit=="captcha") {
        $("#NS_captcha").val($("#NS_captcha").next("span").html());
        $(".captchaRefresh").trigger("click");        
    }
    else {
        $("#NS_name").val($("#NS_name").next("span").html());
        $("#NS_email").val($("#NS_email").next("span").html());
        $("#NS_captcha").val($("#NS_captcha").next("span").html());
        $(".captchaRefresh").trigger("click");

        $('#footerNewsletter input[class*="tick"]').removeClass(function(i, c) {
          return c.match(/active\d+/g).join(" ");
        });

        // hide all error messages
        NS_clearUsrMsgs();
    }
}

/** Post Form Data */
function NS_postFormData()
{
    // collect user inputed data
    var name = $("#NS_name").val();
    var email = $("#NS_email").val();
    var formID = $("#NS_formID").val();
    var captcha = $("#NS_captcha").val();

    // URL DATA STRING FOR AJAX POST
    var dataString = '&formID=' + formID + '&name=' + name + '&email=' + email + '&captcha=' + captcha;
    // alert(dataString); return false;
    $.ajax({
        type    : "POST",
        url     : "components/inc/ajax_posts.php",
        data    : dataString,
        success : function(response) {
            $("body").removeClass("cursorWait");
            if (response=="ok") {
                // all OK
                NS_showUserMessage("NS_submitOK");
                NS_formReset("");
            }
            else if (response=="dbError") {
                // database error
                NS_showUserMessage("NS_DBerror");
            }
            else if (response=="captchaFail") {
                // email error
                NS_showUserMessage("NS_captchaFail");
                NS_formReset("captcha");
            }
            else {
                // system error [ unknown ]
                NS_showUserMessage("NS_systemError");
            }
        },
        error: function(response) {
            // system error [ post error ]
            NS_showUserMessage("NS_systemError");
        }
    });
}

/** Startup all related functions */
$(function() {
    
    // Reset form on statup
    NS_formReset("");

    // clear default input value
    $('#NS_name, #NS_email, #NS_captcha').clearDefault();

    // Inputs Validation
    $('#footerNewsletter input[type=text]').bind("blur", function() {
        // get current value from input
        var value = $(this).val();

        // if the current value is empty or equal to the default one, sets error to the input and show error message
        if ((value == "") || (value == $(this).next(".default").html())) {
            $(this).removeClass("tickGreen").addClass("tickRed");
            // in case of captcha field, error message is different
            if ($(this).attr("id")=="NS_captcha") {
                NS_showUserMessage("NS_captcha");
            } else {
                NS_showUserMessage("NS_mandatory");
            }
        }
        else if ($(this).attr("id")=="NS_email") {
            // in case of email field, additional verification is required for proper email address
            var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
            if (reg.test(value) == false) {
                $(this).removeClass("tickGreen").addClass("tickRed");
                NS_showUserMessage("NS_email");
            } else {
                $(this).removeClass("tickRed").addClass("tickGreen");
                // hide all error messages
                NS_clearUsrMsgs();
            }
        }
        else {
            // no errors found, set input to valid
            $(this).removeClass("tickRed").addClass("tickGreen");
            // hide all error messages
            NS_clearUsrMsgs();
        }
    });

    // Form submit
    $('#NS_onlineForm').submit(function() {
        $("body").addClass("cursorWait");
        // Invalid Inputs Present, or Valid Inputs count diferent from form total mandatory inputs
        if ($("#footerNewsletter .tickRed").size()>=1 || $("#footerNewsletter .tickGreen").size()!=3) {
            // mark all inputs without the success class, with the error class (since all are mandatory)
            $("#footerNewsletter input[type=text]").each(function() {
                $(this).not(".tickGreen").addClass("tickRed");
            });
            NS_showUserMessage("NS_mandatory");
            $("body").removeClass("cursorWait");
            return false;
        }
        // All Good
        if ($("#footerNewsletter .tickGreen").size()==3) {
            NS_postFormData();
            return false;
        }
        $("body").removeClass("cursorWait");
        return false;
    });
    
    $(".banner a.close").bind("click", function() {
        $(this).closest("#banner").slideUp( function() {
            $("#openBanner").slideDown();
        });
    });
    
    $("#openBanner").click( function() {
        $(this).slideUp();
        $("#banner").slideDown();
    });
});



/** WEBSITE MODULE :: Orders Form
--------------------------------------------------------------------------------------------------------------------------------------------*/
function OF_clearUsrMsgs()
{
    $('#mod_orderForm .user_msg').addClass("hidden").find("p").addClass("hidden");
}

function OF_showErrorMessage(errorClass)
{
    // hide all error messages
    OF_clearUsrMsgs();

    // show correct error message by supplied element
    $('#OF_orderForm .user_msg')
        .css({"display":"block"})
        .removeClass("hidden")
        .hide()
        .fadeIn(1000)
        .find("."+errorClass)
        .removeClass("hidden")
        .end();
}

function OF_formReset()
{
    $("#OF_name").val($("#OF_name").next("span").html());
    $("#OF_email").val($("#OF_email").next("span").html());
    $("#OF_contact").val($("#OF_contact").next("span").html());
    $("#OF_nif").val($("#OF_nif").next("span").html());
    $("#OF_zipcode").val($("#OF_zipcode").next("span").html());
    $("#OF_zipcodename").val($("#OF_zipcodename").next("span").html());
    $("#OF_address").val($("#OF_address").next("span").html());
    $("#OF_captcha").val($("#OF_captcha").next("span").html());
    $(".captchaRefresh").trigger("click");

    $('#OF_orderForm input[class*="tick"]').removeClass(function(i, c) {
      return c.match(/active\d+/g).join(" ");
    });

    // hide all error messages
    OF_clearUsrMsgs();

}




$(function() {
    // Inputs Validation
    $('#mod_orderForm input[type=text], #mod_orderForm textarea').bind("blur", function() {
        // get current value from input
        var value = $(this).val();

        // if the current value is empty or equal to the default one, sets error to the input and show error message
        if ((value == "") || (value == $(this).next(".default").html())) {
            $(this).removeClass("tickGreen").addClass("tickRed");
            // in case of captcha field, error message is different
            if ($(this).attr("id")=="OF_captcha") {

            } else {

            }
        }
        else if ($(this).attr("id")=="OF_email") {
            // in case of email field, additional verification is required for proper email address
            var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
            if (reg.test(value) == false) {
                $(this).removeClass("tickGreen").addClass("tickRed");

            } else {
                $(this).removeClass("tickRed").addClass("tickGreen");

            }
        }
        else {
            // no errors found, set input to valid
            $(this).removeClass("tickRed").addClass("tickGreen");

        }
    });

});


/** FEATURES
--------------------------------------------------------------------------------------------------------------------------------------------*/
$(function() {

    // Background Resize
    $("#body-background").ezBgResize();

    // Drag Module Window
    $('div.bd').each(function() {
        var $e = $(this);
            $handle = $e.find('.drag');
        $($e).draggable({
            handle      : $handle,
            containment : 'document'
        });        
    });

    // Minimize Module
    $('div.bd').each(function() {
        var $e = $(this).find('.mini');
        $e.bind('click', function() {
            $e
            .closest('.bd')
            .css({"overflow" : "hidden"})
            .animate({
                "width"    : "45px",
                "height"   : "15px"
            }, "slow", function() {
                $e.addClass("maxi").removeClass("mini");
            });
        });
    });

    // Maximize Module
    $('div.bd .maxi').live("click", function() {
        $(this).closest('.bd').css({
            "overflow" : "visible",
            "width"    : "auto",
            "height"   : "auto"
        });
        LoadModules('mod_ebooks');
    });

    /** Cart Resume
     *  Open the cart header panel with the order items 
     */
    $('#hd_usr_order').click(function(event) {

        // prevent link default behavior
        event.preventDefault();

        // hidden user message for empty cart
        $('#cart, #cartEmpty').hide();

        // show the cart or the user message by the items count
        if ($(this).find('#totalInCart').html()==0) {
            $('#cartEmpty').show();
        }
        else {
            $('#cart').show();
        }

        // toggle the panel
        $(this)
            .toggleClass('active')
            .next('div')
            .fadeToggle('fast', function() {
                setSlider($('#cart-table-wrap'));
            });
    });

    /** Cart Resume
     *  Close the cart header panel
     */
    $('#hd_cart a.hd_cart_close').bind('click', function(event) {
        event.preventDefault();
        $(this).closest('div').prev('a').trigger('click');
    });


    /**
     * Search Box
     */
    $('#hd_usr_search').click(function(event) {
        event.preventDefault();
        $(this).toggleClass('active').next('div').fadeToggle('fast');
    });
    $('a.hd_search_close').bind('click', function(event) {
        event.preventDefault();
        $(this).closest('div').prev('a').trigger('click');
    });


    /** Logout
     *  Ajax post for current session destroy and
     *  user logout log
     */
    $('#hd_usr_logout').bind('click', function(event) {
        event.preventDefault();

        var formID     = 8,
            dataString = "formID="+formID;

        $.ajax({
            type: "POST",
            url: "components/inc/ajax_posts.php",
            data: dataString,
            beforeSend: function() {
                // this is where we append a loading image
                // $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
            },
            success: function(response) {
                if (response == "SessionError") {
                    // notify the user
                    siteNotifications($('#LANG_USR_MSG .LANG_USR_MSG_LOGOUT_FAIL').html(), 8000);
                }

                if (response == "ok") {
                    // reset forms
                    $('.usrStatusAffected').each(function() {
                        var defaultValue = $(this).next('.inputDefault').html();
                        $(this).attr("value", defaultValue);
                    });

                    // notify the user
                    siteNotifications($('#LANG_USR_MSG .LANG_USR_MSG_LOGOUT_OK').html(), 8000);

                    // change header options
                    $(".hd_usr_login_logout").toggleClass('hidden');

                }
            },
            error: function() {
                // notify the user
                siteNotifications($('#LANG_USR_MSG .LANG_USR_MSG_LOGOUT_FAIL').html(), 8000);
            }
        });

    });

    // initialize custom scroll bars
    // usuage to restart after ajax content: setSlider(selector);
    $('.scroll-pane').each(function() {
        setSlider($(this));
    });
});



/** CUSTOM SCROLLBARS
--------------------------------------------------------------------------------------------------------------------------------------------*/
function setSlider($scrollpane)
{
    var difference   = 0,
        proportion   = 0,
        handleHeight = 0;
    
    //change the main div to overflow-hidden as we can use the slider now
    $scrollpane.css('overflow','hidden');

    /**
     * if it's not already there, wrap an extra
     * div around the scrollpane so we can use the mousewheel later
     */
    if ($scrollpane.parent('.scroll-container').length==0) {
        $scrollpane.wrap('<\div class="scroll-container"> /');
    }

    /**
     * compare the height of the scroll content
     * to the scroll pane to see if we need a scrollbar
     */
    difference = $scrollpane.find('.scroll-content').height()-$scrollpane.height();//eg it's 200px longer 

    /**
     * if the scrollbar is needed, set it up...
     */
    if(difference>0)
    {
        proportion = difference / $scrollpane.find('.scroll-content').height();//eg 200px/500px

        handleHeight = Math.round((1-proportion)*$scrollpane.height());//set the proportional height - round it to make sure everything adds up correctly later on
        handleHeight -= handleHeight%2; 

        //if the slider has already been set up and this function is called again, we may need to set the position of the slider handle
        var contentposition = $scrollpane.find('.scroll-content').position();    
        var sliderInitial = 100*(1-Math.abs(contentposition.top)/difference);
        //$scrollpane.next().find(".slider-vertical").slider("value", newSliderValue);//and set the new value of the slider


        /**
         * if the slider-wrap doesn't exist, insert it and set the initial value
         */
        if ($scrollpane.next('.slider-wrap').length==0)
        {
            //append the necessary divs so they're only there if needed
            $scrollpane.after('<\div class="slider-wrap"><\div class="slider-vertical"><\/div><\/div>');

            //set the height of the slider bar to that of the scroll pane
            $scrollpane.next('.slider-wrap').height($scrollpane.height());

            sliderInitial = 100;
        }
       
        /**
        * set up the slider 
        */
        $scrollpane.next().find('.slider-vertical').slider({
            orientation: 'vertical',
            min: 0,
            max: 100,
            value: sliderInitial,
            slide: function(event, ui) {
                var topValue = -((100-ui.value)*difference/100);
                /* move the top up (negative value) by the percentage
                 * the slider has been moved times the difference in height
                 */
                $scrollpane.find('.scroll-content').css({top:topValue});
            },
            change: function(event, ui) {
                var topValue = -((100-ui.value)*difference/100);
                /* move the top up (negative value) by the percentage
                 * the slider has been moved times the difference in height
                 */
                $scrollpane.find('.scroll-content').css({top:topValue});
            }   
        });

       //set the handle height and bottom margin so the middle of the handle is in line with the slider
       $scrollpane.next().find(".ui-slider-handle").css({height:handleHeight,'margin-bottom':-0.5*handleHeight});
       var origSliderHeight = $scrollpane.height();//read the original slider height
       var sliderHeight = origSliderHeight - handleHeight ;//the height through which the handle can move needs to be the original height minus the handle height
       var sliderMargin =  (origSliderHeight - sliderHeight)*0.5;//so the slider needs to have both top and bottom margins equal to half the difference
       $scrollpane.next().find(".ui-slider").css({height:sliderHeight,'margin-top':sliderMargin});//set the slider height and margins
       $scrollpane.next().find(".ui-slider-range").css({top:-sliderMargin});//position the slider-range div at the top of the slider container

    }//end if

     /**
      * code for clicks on the scrollbar outside the slider
      * stop any clicks on the slider propagating through to the code below
      */
    $(".ui-slider").click(function(event){
        event.stopPropagation();
    });
   
    $(".slider-wrap").click(function(event){//clicks on the wrap outside the slider range
        var offsetTop = $(this).offset().top;//read the offset of the scroll pane
        var clickValue = (event.pageY-offsetTop)*100/$(this).height();//find the click point, subtract the offset, and calculate percentage of the slider clicked
        $(this).find(".slider-vertical").slider("value", 100-clickValue);//set the new value of the slider
    }); 

     
    /**
     * additional code for mousewheel
     */
    $scrollpane.parent().mousewheel(function(event, delta){
        var speed = 1;
        var sliderVal = $(this).find(".slider-vertical").slider("value");
        
        sliderVal += (delta*speed);
 
        $(this).find(".slider-vertical").slider("value", sliderVal);
        
        event.preventDefault();
    });
}



/** emptyFavorites()
 *  ----------------
 * 
 * On click, empty the user favorites by cleaning up the cookie
 * that olds the favorites data
 */
function emptyFavorites()
{
    if ($.cookie('favorites_ids')) {
        var ids = $.cookie('favorites_ids').split(';');
    }

    for (var x = 0; x < ids.length; x++) {
        $.cookie('favorites_' + ids[x], null, {expires:-1});
    }

    $.cookie('favorites_ids', null, {expires:-1});

    $("#favSum").html('0.00');
    $("#favorites table > tbody").html('');
    $(".favWrap .noFavs").show();
    $(".favWrap .yesFavs").hide();
    $('#favorites').removeClass("full");

    // Close the favorites panel
    $('#favorites .close').trigger('click');
}



/** convertToOrder()
 *  ----------------
 * 
 * On click, converts the favorites list into an order
 * list.
 * If the cart already has items, tey are preserved
 */
function convertToOrder()
{
    if ($.cookie('favorites_ids')) {

        var ids = $.cookie('favorites_ids').split(';'),
            x   = 0;
        
        for(x = 0; x < ids.length; x++) {
            if ($.cookie('favorites_' + ids[x])) {
                data = $.cookie('favorites_' + ids[x]).split(';');
                addToCookie("cart", ids[x], data[0], data[2]);
                $('input.favoriteItemID[value="'+ids[x]+'"]').closest('tr').find('.delFavorite').trigger("click");
            }
        }
        
        $("#cart .no_itens").hide();
        $("#cart .yes_itens").show();

        // close favorites panel
        $('"favorites a.close').trigger("click");
    }
}



/**
 * FAVORITES FUNCTIONS
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
$(function() {


    /**
     * initialize favorites list from existent cookie
     */
    if ($.cookie('favorites_ids')) {
        var FavIds = $.cookie('favorites_ids').split(';'),
            FavSum = 0,
            x      = 0;
        
        for(x = 0; x < FavIds.length; x++) {
            if ($.cookie('favorites_' + FavIds[x])) {
                data = $.cookie('favorites_' + FavIds[x]).split(';');
                $("#favorites table tbody:last")
                    .append('<tr><td class="remove"><img src="components/img/icons/cross-small.png" class="delFavorite"></td><td><input type="hidden" name="favID_' + FavIds[x] + '" value="' + FavIds[x] + '" class="favoriteItemID"><span>' + data[0] + '</span></td><td class="price"><span class="favorite_item_value">' + data[2] + '</span> &euro;</td></tr>');
                FavSum += parseFloat(data[2]);
            }
        }

        $("#favSum").html(roundNumber(FavSum,2));
        
        $(".favWrap .noFavs").hide();
        $(".favWrap .yesFavs").show();
        $('#favorites').addClass("full");
    }
    else {
        $("#favSum").html('0.00');
        $(".favWrap .noFavs").show();
        $(".favWrap .yesFavs").hide();
        $('#favorites').removeClass("full");
    }


    /**
     * delete item from favorites
     */
    $(".delFavorite").live("click", function() {

        var id = $(this).parent("td").next("td").find("input").val();

        // remove clicked line from header cart
        $('#favorites').find('.favoriteItemID[value="'+id+'"]').closest("tr").remove();

        // delete cookie
        $.cookie('favorites_' + id, null, {expires:-1});
        
        var ids    = $.cookie('favorites_ids').split(';'),
            newIds = new Array(),
            n      = 0;

        $.cookie('favorites_ids', null, {expires:-1});

        for(var x = 0; x < ids.length; x++) {
            if (ids[x] != id) {
                newIds[n] = ids[x];
                n++;
            }
        }
        
        if (newIds.length > 0) {
            $.cookie('favorites_ids',newIds.join(';'),{expires: 365});
        }
        else {
            $.cookie('favorites_ids', null, {expires:-1});
        }


        // round and show sum
        var total = 0,
            val   = 0,
            sum   = 0;

        // update header cart sum
        $("#favorites tbody tr span.favorite_item_value").each(function(){
            
            val = $(this).html();
            
            total += parseFloat(val);
        });
        
        total = roundNumber(total,2);

        $("#favSum").html( total );

        if (total == 0) {
            $(".favWrap .noFavs").show();
            $(".favWrap .yesFavs").hide();
            $("#favorites").removeClass("full");
        }
    });

});



/**
 * CART FUNCTIONS
 * ---------------------------------------------------------------------------------------------------------------------------------------- */

$(function() {

     //init cart products from cookie
      $("#cart table > tbody").html('');
      
      if($.cookie('cart_ids')) {
        ids = $.cookie('cart_ids').split(';');
        var sum = 0;
        
        for(var x = 0; x < ids.length; x++) {
            if ($.cookie('cart_' + ids[x])) {
                data = $.cookie('cart_' + ids[x]).split(';');
                $("#cart table tbody:last").append('<tr><td class="remove"><img src="components/img/icons/cross-small.png" class="delCart"></td><td><input type="hidden" name="id_' + ids[x] + '" value="' + ids[x] + '" class="cartItemID"><span>' + data[0] + '</span></td><td class="price"><span class="cart_item_value">' + data[2] + '</span> &euro;</td></tr>');
                sum += parseFloat(data[2]);
            }
        }
        
        $("#totalInCart").css({"color":"green"}).html(x);
        $("#sum").html(roundNumber(sum,2));
        
        $("#cart .no_itens").hide();
        $("#cart .yes_itens").show();
      }
      else {
        $("#totalInCart").css({"color":"red"}).html(0)
        $("#sum").html('0.00');
        $("#cart .yes_itens").hide();
        $("#cart .no_itens").show();
      }


    // delete item from order and cart
    $(".delCart").live("click", function() {
        var id = $(this).parent("td").next("td").find("input").val();

        // remove clicked line from header cart
        $('#cart-table').find('.cartItemID[value="'+id+'"]').closest("tr").remove();

        // remove clicked line from order confirmation
        $('#orderconfirm-panel').find('.cartItemID[value="'+id+'"]').closest("tr").remove();

        // delete cookie
        $.cookie('cart_' + id, null, {expires:-1});
        
        var ids    = $.cookie('cart_ids').split(';'),
            newIds = new Array(),
            n      = 0;

        $.cookie('cart_ids', null, {expires:-1});

        for(var x = 0; x < ids.length; x++) {
            if (ids[x] != id) {
                newIds[n] = ids[x];
                n++;
            }
        }
        
        if (newIds.length > 0) {
            $.cookie('cart_ids',newIds.join(';'),{expires: 365});
        }
        else {
            $.cookie('cart_ids', null, {expires:-1});
        }


        // round and show sum
        var total = 0,
            val   = 0,
            sum   = 0;

        // update header cart sum
        $("#cart tbody tr span.cart_item_value").each( function() {
            
            val = $(this).html();
            
            total += parseFloat(val);
        });
        
        total = roundNumber(total,2);

        $("#sum").html( total );
        
        $("#totalInCart").css({"color":"green"}).html(parseInt($("#totalInCart").html())-1);
        
        if (total == 0) {
            $("#cart .no_itens").show();
            $("#cart .yes_itens").hide();
        }
        
        // update order sum
        $("#orderconfirm-panel .val span").each(function() {
            sum+= parseFloat($(this).html());
        });

        $("#total_order").html(roundNumber(sum,2));

    });
});


/** CART :: ADD NEW ITEM
 *  This will check to see if the selected item exists, and if not:
 *  1. Creates a Cookie for it
 *  2. Add it to the cart panel
 *  3. Update the cart with the new total value
 *  4. Update the cart button with the new total items
 *  5. Update global cart cookie with product id's for the cart construction
 * ---------------------------------------------------------------------------------------------------- */
function addToCookie(type, id, name, price)
{
    /** Close resume panel */
    if (type=="favorites") {
        if ($('#favorites .hiddenPanel').is(":visible")) {
            $('#favorites').find('.close').trigger('click');
        }
    }

    if (type=="cart") {
        if ($('#hd_cart').is(":visible")) {
            $('#hd_cart').find('.hd_cart_close').trigger('click');
        }
    }

    // New cart item array
    var cartNewItem = new Array(
        name.replace(';','&#59;'),
        1,
        roundNumber(parseFloat(price),2)
    );

    // New cart item cookie string
    var cookieString = cartNewItem.join(';');
    
    
    // Cookie options
    var cookieOptions = {expires: 365};
    
    if ($.cookie(type + '_' + id)) {
        // If item cookie already exists, nothing happends
    }
    else {

        // CREATE COOKIE
        $.cookie(type + '_' + id, cookieString, cookieOptions);

        /** Add new item to proper panel */
        if (type=="cart") {        
            // ADD NEW ROW TO THE CART PANEL
            $("#cart-table tbody").append('<tr><td class="remove"><img src="components/img/icons/cross-small.png" class="delCart"></td><td><input type="hidden" name="id_'+ id +'" value="'+ id +'" class="cartItemID"><span>' + cartNewItem[0] + '</span></td><td class="price"><span class="cart_item_value">' + cartNewItem[2] + '</span> &euro;</td></tr>');
    
            // incremente total articles (header button)
            $("#totalInCart").css({"color":"green"}).html(parseInt($("#totalInCart").html())+1);
        }

        if (type=="favorites") {        
            // ADD NEW ROW TO THE CART PANEL
            $("#favorites table tbody").append('<tr><td class="remove"><img src="components/img/icons/cross-small.png" class="delFavorite"></td><td><input type="hidden" name="id_'+ id +'" value="'+ id +'" class="favoriteItemID"><span>' + cartNewItem[0] + '</span></td><td class="price"><span class="favorite_item_value">' + cartNewItem[2] + '</span> &euro;</td></tr>');
            $("#favorites .noFavs").hide();
            $("#favorites .yesFavs").show();
        }


        /** Update or Create a cookie */
        if ($.cookie(type+'_ids')) {
            $.cookie(type+'_ids', $.cookie(type+'_ids') + ';' + id);
        }
        else {
            $.cookie(type+'_ids', id , cookieOptions);
        }
    }

    /** Process Items Sum */
    if (type=="cart") {
        // round and show sum
        var total = 0;
        $(".cart_item_value").each(function(){
            var val = $(this).html();
            total += parseFloat(val);
        });
        
        total = roundNumber(total,2);
        
        $("#sum").html(total);
        $("#cart .no_itens").hide();
        $("#cart .yes_itens").show();
    }
}



/** emptyCart()
 *  -----------
 * 
 *  On click, empty the user cart by cleaning up the cookie
 *  that olds the cart data
 */
function emptyCart()
{
    if ($.cookie('cart_ids')) {
        var ids = $.cookie('cart_ids').split(';');
    }
    
    $("#totalInCart").css({"color":"red"}).html(0);
    $("#sum").html('0.00');
    $("#cart table > tbody").html('');
    
        
    for (var x = 0; x < ids.length; x++) {
        $.cookie('cart_' + ids[x], null, {expires:-1});
    }
            
    $.cookie('cart_ids', null, {expires:-1});
    $("#cart .no_itens").show();
    $("#cart .yes_itens").hide();

    // Close the orders resume panel
    $('#hd_cart').find('.hd_cart_close').trigger('click');
}



/** fillOrderDetails()
 *  ------------------
 * 
 *  On click, calls the first step of the
 *  finish order form and fills it with
 *  the cookie contents that olds the
 *  cart data
 */
function fillOrderDetails()
{
    // initialize variables
    var sum   = 0,
        total = 0,
        x     = 0,
        ids   = [];

    if ($.cookie('cart_ids')) {
        ids = $.cookie('cart_ids').split(';');
        
        if (ids.length > 0) {
            $("#orderItens tbody").html('');
            
            for (x = 0; x < ids.length; x++)
            {
                if ($.cookie('cart_' + ids[x]))
                {
                    data = $.cookie('cart_' + ids[x]).split(';');
                    $("#orderItens tbody:last").append(
                        '<tr>' +
                        '<td class="del"><img src="components/img/icons/cross-small.png" class="delCart" width="16" height="16" alt="X"></td>' +
                        '<td class="txt"><input type="hidden" name="order_id" value="' + ids[x] + '" class="cartItemID"><input type="hidden" name="order_name" value="' + data[0] + '"><span>' + data[0] + '</span></td>' +
                        '<td class="qtd"><input type="text" name="order_qtd" value="' + data[1] + '" size="3" class="input-txt s" maxlength="3"></td>' +
                        '<td class="val"><input type="hidden" name="order_price" value="' + data[2] + '"><span>' + data[2] + '</span> &euro;</td>' +
                        '</tr>'
                    );
                    sum += parseFloat(data[2]);
                }
            }
            
            total = roundNumber(sum, 2);
            $("#total_order").html(total);
            
            $("#orderconfirm-panel").css({
                "margin-top" : "-" + ($("#orderconfirm-panel").outerHeight(true)/2) + "px"
            });
        
            $("#lightbox, #orderconfirm-panel").fadeIn(300, function() {
                setSlider($("#orderItens"));
                $("input[name=order_qtd]").numeric();
            });
        }

        // Close the orders resume panel
        $('#hd_cart').find('.hd_cart_close').trigger('click');
    }
}



/**
 * ORDER CONFIRMATION PANEL
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
$(function() {

    // confirms order and shows details popup
    $("#confirmOrder").click( function() {
                    
        $(".lightbox-panel").hide(0, function() {
            
            $(".lightbox-panel").css({"margin-top" : "0px"});
                
            $("#orderdetails-panel").css({
                "margin-top" : "-" + ($("#orderdetails-panel").outerHeight(true)/2) + "px"
            });
            
            $("#orderdetails-panel").show(0, function() {
                 $("#OF_orderForm .captchaRefresh").siblings("img").attr("src","components/inc/captcha.php?r=" + Math.random());
            });
        });
    });

    // user changes the item quantity
    $('#orderconfirm-panel input[name="order_qtd"]').live("keyup", function() {

        // initialize variables
        var units  = $(this).val(),
            price  = $(this).closest("tr").find("input[name=order_price]").val(),
            cost   = units * price,
            result = roundNumber(cost,2),
            sum    = 0;

        // set the new line price
        $(this).closest("tr").find(".val span").html(result);

        // recalculate the cart sum
        $(".val span").each( function() {
            sum+= parseFloat($(this).html());
        });

        // set the cart sum
        $("#total_order").html(roundNumber(sum,2));
    });

});


$(function() {

    /**
     * Show books only with promotions
     */
    $('#banner .fadeIn').bind("click", function() {

        // initialize variables
        var totalBooks = $("#pg_photos li").size(),
            x          = 0;

        // load all books
        LoadModules('mod_books');

        // hide what is not promotion
        $("#pg_photos li").each( function() {
            if (!$(this).hasClass("is_promotion"))
            {
                $(this).hide();
            }
            x++;

            if (x == totalBooks) {
                initSlider();
                configGallery();
                $(window).hashchange();
            }
        });
    });

    /**
     * Show books only from a certain colection
     */
    $('.sub-menu-link').bind("click", function(event)
    {
        event.preventDefault();
        // initialize variables
        var colection = $(this).attr("class").split(' ')[1];

        // load all books
        LoadModules('mod_books');

        // hide what is not from this colection
        $('#pg_photos li:not(.'+colection+')').hide();

        // restart the books slider
        initSlider();
        configGallery();
        $(window).hashchange();

        $('.sub-menu-element:not(.hiddenLeft)').attr("style", "").addClass("hiddenLeft");
    });

    /**
     * COLECTIONS MENU :: control for mouse leave event
     */
    $('.sub-menu-element').bind("mouseleave", function() {
        $(this).attr("style", "").addClass('hiddenLeft');
    });

    $('#banner p').hover(
        function() {
            $(this).animate({"background-color":"#ddd"});
        },
        function() {
            $(this).animate({"background-color":"#fff"});
        }
    );

});

