/** 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();



/** HANDLER FOR CLASS "OpenNewWindow"
--------------------------------------------------------------------------------------------------------------------------------------------*/
$(function() {
    $('a.OpenNewWindow').click(function(){
        window.open($(this).attr('href'));
        return false;
    });
});



/** MENU :: HEADER
 * ---------------------------------------------------------------------------------------------------------------------------------------- */

// css class | img path | padding right for "li" with sub menu
var arrowimages = {
        down  : ['downarrowclass', 'components/img/icons/arrow_down.png', 30],
        right : ['rightarrowclass', 'components/img/icons/arrow_right.png']
    }

var jqueryslidemenu = {

    // duration of slide in/out animation, in milliseconds
    animateduration: {over: 250, out: 250},

    buildmenu:function(menuid, arrowsvar) {
        jQuery(document).ready(function($) {
            var $mainmenu=$("#"+menuid+">ul")
            var $headers=$mainmenu.find("ul").parent()
            $headers.each(function(i){
                var $curobj=$(this)
                var $subul=$(this).find('ul:eq(0)')
                this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
                this.istopheader=$curobj.parents("ul").length==1? true : false
                $subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
                $curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
                    '<img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
                    +'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
                    + '" style="border:0;">'
                )
                $curobj.hover(
                    function(e){
                        var $targetul=$(this).children("ul:eq(0)")
                        this._offsets={left:$(this).offset().left, top:$(this).offset().top}
                        var menuleft=this.istopheader? 0 : this._dimensions.w
                        menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
                        if ($targetul.queue().length<=1) //if 1 or less queued animations
                            $targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).slideDown(jqueryslidemenu.animateduration.over)
                    },
                    function(e){
                        var $targetul=$(this).children("ul:eq(0)")
                        $targetul.slideUp(jqueryslidemenu.animateduration.out)
                    }
                ) //end hover
            }) //end $headers.each()
            $mainmenu.find("ul").css({display:'none', visibility:'visible'})
        }) //end document.ready
    }
}

//build menu with ID="hd_menu" on page:
jqueryslidemenu.buildmenu("hd_menu", arrowimages)



/** VERTICAL MENU :: Catalogues area vertical menu (accordion)
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
/*
HTML structure to use:

Notes:
1: each menu MUST have an ID set. It doesn't matter what this ID is as long as it's there.
2: each menu MUST have a class 'menu' set. If the menu doesn't have this, the JS won't make it dynamic

Optional extra classnames:
noaccordion : no accordion functionality
collapsible : menu works like an accordion but can be fully collapsed
expandfirst : first menu item expanded at page load

<ul id="menu1" class="menu [optional class] [optional class]">
<li><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
...
</ul>
<li><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
...
</ul>
...
</ul>
*/

function startVerticalMenu() {
    $('ul.menu ul').hide();
    $.each($('ul.menu'), function(){
        $('#' + this.id + '.expandfirst ul:first').show();
    });
    $('ul.menu li a').click(
        function() {
            var checkElement = $(this).next();
            var parent = this.parentNode.parentNode.id;

            if($('#' + parent).hasClass('noaccordion')) {
                $(this).next().slideToggle('normal');
                return false;
            }
            if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                if($('#' + parent).hasClass('collapsible')) {
                    $('#' + parent + ' ul:visible').slideUp('normal');
                }
                return false;
            }
            if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                $('#' + parent + ' ul:visible').slideUp('normal');
                checkElement.slideDown('normal');
                $('ul.menu li a').removeClass("active");
                $(this).addClass("active");
                return false;
            }
        }
    );
}
$(function() {
    startVerticalMenu();
});



/** Buttons for Product Related Items
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
function _init_more_products(carousel) {
    $('.related-nav .next').bind('click', function() {
        carousel.next();
        return false;
    });

    $('.related-nav .prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};



/** ONLOAD :: Initialize Scripts
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
$(function() {
    // initialize banner
    $('#banner, #highlights').cycle({
        fx: 'fade',
        speed: 1500,
        timeout: 5000,
        randomizeEffects: false,
        easing: 'easeOutCubic',
        cleartypeNoBg: true
    });

    // initialize modal (fancybox)
    $("a.zoom").fancybox({
        'padding': 1,
        'overlayOpacity': 0.7,
        'zoomSpeedIn': 500,
        'zoomSpeedOut': 500
    });

    // initialize login modal (fancybox)
    $("a.login").fancybox({
        'padding': 1,
        'showCloseButton': false,
        'frameWidth': 400,
        'frameHeight': 200,
        'hideOnContentClick': false
    });

    // initialize register modal (fancybox)
    $("a.register").fancybox({
        'padding': 1,
        'showCloseButton': false,
        'frameWidth': 600,
        'frameHeight': 350,
        'hideOnContentClick': false
    });

    // fancybox login form submit
    $("#login-form").live("submit", function() {
        var data = $("#email").val();
        alert(data);
        $("a.login").fancybox(data).trigger('click');
        return false;
    });

    // activate catalogue sub-navigation option
    var mod = $.getUrlVar('mod');
    if ((mod=="catalogue") && (mod!=null) && (typeof(mod)!="undefined") && (mod.length>=1)) {
        var fam = $.getUrlVar('f');
        if ((fam!="") && (fam!=null) && (typeof(fam)!="undefined") && (fam.length>=1)) {
            $('#catalogueVM li a.menuFAM_' + fam).addClass("active");
            $('#catalogueVM li a.menuFAM_' + fam).next("ul").show(250);
        }
        var sfam = $.getUrlVar('sf');
        if ((sfam!="") && (sfam!=null) && (typeof(sfam)!="undefined") && (sfam.length>=1)) {
            $('#catalogueVM li ul li a.menuSFAM_' + sfam).addClass("active");
        }
    }

    // initialize Products Slider
    $(".related-products-holder ul").jcarousel({
        scroll: 2,
        auto: 5,
        wrap: 'both',
        initCallback: _init_more_products,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

});

