// non-js filter
if (document.documentElement) { document.documentElement.className += "js"; }

(function ($) {

    $(document).ready(function () {
        //Print button		
        printButton.init(".bookmarks"); 

        //Hide form field value on focus
	    clearInputText.init(); 
        
        //SyncHeight - jQuery plugin	
        $('.panels li a, .twoCols2-1 > div').not('.twoCols .panels li a').syncHeight(); 

        //Expand form container (landing pages)
        expandContainer.init(".js-expand");  

        //Homepage carousel
        $(".carousel").createCarousel(); 

        // Slideshow: homepage special offers
        $('#slides').jhiWidgetCarousel({
            itemsShown: 2,
            itemWidth: 240,
            itemPadding: 0,
            pagerTexts: ['Previous offers', 'Next offers']
        });
    
	    // Slideshow: homepage news
        $('#newsSlides').jhiWidgetCarousel({
            itemsShown: 1,
            itemWidth: 280,
            itemPadding: 0
        });
    
        // Slideshow: homepage customer feedback
        $('#feedbackSlides').jhiWidgetCarousel({
            itemsShown: 1,
            itemWidth: 280,
            itemPadding: 0
        });

        // Cus­tom fadeIn/Out Method
        (function($) {
	        $.fn.customFadeIn = function(speed, callback) {
		        $(this).fadeIn(speed, function() {
			        if(jQuery.browser.msie)
				        $(this).get(0).style.removeAttribute('filter');
			        if(callback != undefined)
				        callback();
		        });
	        };
	        $.fn.customFadeOut = function(speed, callback) {
		        $(this).fadeOut(speed, function() {
			        if(jQuery.browser.msie)
				        $(this).get(0).style.removeAttribute('filter');
			        if(callback != undefined)
				        callback();
		        });
	        };
        })(jQuery); 

    });

    /* ***************************************************************************************
    Print button
    */
    var printButton = {
        printLink: '<li class="print"><a href="#">Print page</a></li>',
        init: function (el) {
            var $el = $(el);
            $('li:first', $el).after(printButton.printLink);
            $('.print a', $el).click(function (e) {
                this.blur();
                if (window.print) window.print();
                e.preventDefault();
            });
        }
    };
    /* @end print button */


    /* ***************************************************************************************
    Take title attribute of the input element and copy that value into the value attribute.
    */
    var clearInputText = {
        init: function () {
            $(':input[title]').each(function () {
                var $this = $(this);
                if ($this.val() === '') {
                    $this.val($this.attr('title'));
                }
                $this.focus(function () {
                    if ($this.val() === $this.attr('title')) {
                        $this.val('');
                    }
                });
                $this.blur(function () {
                    if ($this.val() === '') {
                        $this.val($this.attr('title'));
                    }
                });
            });
        }
    };
    /* @end  */


    /* ***************************************************************************************
     * syncHeight - jQuery plugin to automagically Snyc the heights of columns
     * Made to seemlessly work with the CCS-Framework YAML (yaml.de)
     * @requires jQuery v1.0.3
     *
     * http://blog.ginader.de/dev/syncheight/
     *
     * Copyright (c) 2007-2009 
     * Dirk Ginader (ginader.de)
     * Dirk Jesse (yaml.de)
     * Dual licensed under the MIT and GPL licenses:
     * http://www.opensource.org/licenses/mit-license.php
     * http://www.gnu.org/licenses/gpl.html
     * Version: 1.1
     */

	    $.fn.syncHeight = function(config) {
		    var defaults = {
			    updateOnResize: false	// re-sync element heights after a browser resize event (useful in flexible layouts)
		    };
		    var options = $.extend(defaults, config);		
		    var e = this;
		
		    var max = 0;
		    var browser_id = 0;
		    var property = [
			    // To avoid content overflow in synchronised boxes on font scaling, we 
			    // use 'min-height' property for modern browsers ...
			    ['min-height','0px'],
			    // and 'height' property for Internet Explorer.
			    ['height','1%']
		    ];

		    // check for IE6 ...
		    if($.browser.msie && $.browser.version < 7){
			    browser_id = 1;
		    }
		
		    // get maximum element height ...
		    $(this).each(function() {
			    // fallback to auto height before height check ...
			    $(this).css(property[browser_id][0],property[browser_id][1]);
			    var val=$(this).height();
			    if(val > max){
			       max = val;
			    }
		    });
		
		    // set synchronized element height ...
 		    $(this).each(function() {
  			    $(this).css(property[browser_id][0],max+'px');
		    });
		
		    // optional sync refresh on resize event ...
		    if (options.updateOnResize == true) {
			    $(window).resize(function(){ 
				    $(e).syncHeight();
			    });
		    }
		    return this;
	    };	
        /* @end syncHeight */


        /* ***************************************************************************************
        Expand form container (landing pages)
        */			
        var expandContainer = {
            init: function (el) {
                var $el = $(el);
		        $('.expand-header',$el).addClass('js-enhanced');
		        $('.js-enhanced').click(function()	{
			        $('.inner',$el).slideDown(1000,function()	{
				        $('.expand-header',$el).removeClass('js-enhanced');
			        });			
			        return false;
		        });
            }
        };
        /* @end Expand form container */



        /*
         * --------------------------------------------------------------------
	        jhiWidgetCarousel - a jQuery plugin
	        @author	John Hunter, modified by Marcela Maneos on April 2011
	        created	2010-07-20
	        use: $('#selector').jhiWidgetCarousel({option: 'foo'});
		        for available options see the 'defaults' object below
		        - scrollCallback: a function called after scrolling, with args: (currentIndex, containerDomElem)
         * --------------------------------------------------------------------
         */

        (function ($) {
	
	        var defaults = {
		        paneSelector: 'div.window',
		        itemsContainerSelector: 'ol',
		        itemsSelector: 'li',
		        itemsShown: 2,
		        itemWidth: 220,
		        itemPadding: 0,
		        speed: 500,
		        pagerTexts: ['Previous','Next'],
		        scrollCallback: null
	        };
	
	
	        $.fn.jhiWidgetCarousel = function (options) {
		
		
		        return this.each(function () {
			
			        var opts = $.extend({}, defaults, options),
				        root = $(this),
				        pane = $(opts.paneSelector, root),
				        container = $(opts.itemsContainerSelector, pane),
				        items = $(opts.itemsSelector, container),
				        totalItems = items.length,
				        width = 0,
				        maxWidth = 0, 
				        prev = null,
				        next = null,
				        pager = null,
				        index = 0;			
				
			        width = opts.itemWidth + opts.itemPadding; 
			        maxWidth = width * totalItems;			
			
			        // Create pager
			        prev = makePagerElem('prev', opts.pagerTexts[0]);
			        next = makePagerElem('next', opts.pagerTexts[1]);
			
			        pager = $('<ul class="pager"></ul>').append(prev).append(next);
			
			        if (navigator.userAgent.match(/MSIE 6/)) {
				        // IE6 frameset append string html nonsense
				        pager = $('<div>').append(pager).html();
			        }
			        pane.before(pager);
			        pager = $('ul.pager', root);
			
			
			        $('ul.pager a', root).click(function (e) {
				        e.preventDefault();
				        var newIndex = index;
				
				        newIndex += $(this).parent().hasClass('prev') ? -1 : 1;
				        if (newIndex >= 0 && newIndex <= (totalItems - opts.itemsShown)) {
					        index = newIndex;
					        go();
				        }		         
		            });
			
			        function go() {
				        container.animate({left: -width * index}, opts.speed, doCallback);
	                    setPagerState();
			        }			
			
			        function makePagerElem (type, text) {
				        return $('<li class="' + type + '"><a href="#' + type + '" title="' + text + '">' + text + '</a></li>');
			        }		    
			
			        function setPagerState () {
				        if (index === 0) prev.addClass('off').find('a').removeAttr('href');
				
				        else prev.removeClass('off').find('a').attr('href','#prev');
				
				        if (index === totalItems - opts.itemsShown) next.addClass('off').find('a').removeAttr('href');
				        else next.removeClass('off').find('a').attr('href','#next');
			        }			
			
			        function doCallback () {
				        if (typeof opts.scrollCallback === 'function') {
					        opts.scrollCallback(index, this);
				        }
			        }			
			
			        setPagerState();
		        });
	        };
		
        })(jQuery);
        /* @end */



        /* ***************************************************************************************
        homepage carousel 
        */
        $.fn.createCarousel = function(){
	        return $(this).each(function(){
		
		        var $tabs = $(this);
		        var $tabNav = $tabs.find('.c-nav');
		        var $tabContent = $tabs.find('.c-content');
		        var $tabPanel = $tabContent.find('div.slide');
		        var tabIDprefix = 'tab-';
		        var tabIDsuffix = '-enhanced';
		        var autoRotate = true; //Set tabs auto-ratating
		        var $moreInfoButton = '<a href="#" class="c-more">More information</a>';
		
		
		        //Add class, attributes and ARIA to tab navigation
		        $tabNav
			        .find('li').each(function()	{
				        var tabID = $(this).find('a').attr('href').replace('#','');
				        $(this)
					        .attr({'role':'tab','id':tabIDprefix + tabID, 'role': 'tabslist'})
					        .find('a').attr('tabindex','-1');			
			        })
			        .end()
			        .find('li:first').addClass('selected')
			        .find('a').attr('tabindex',0);	
		
		        //Add class and ARIA to tab panels	
		        $tabPanel.each(function()	{			
			        var tablistID = $(this).attr('id');
			        $(this).attr({'role':'tabpanel','aria-hidden':true, 'id':tablistID + tabIDsuffix, 'aria-labelledby':tabIDprefix + tablistID})
			        /* Add more-info button - if there is secondary content */
			        if( $('div.moreInfo',$(this)).html() != '' )	{
				        $(this).find('div.txt').after($moreInfoButton);
			        }
		        });
		        $tabContent
			        .find('> div:first')
			        .attr('aria-hidden',false)
			        .addClass('slide-selected');		
			
		        //Generic select tab function
		        function selectTab(tab)	{
			        var $this = $(tab);
			        var currentPanelID = ( $this.attr('href').replace('#','')) + tabIDsuffix;
			        //change the tab navigation
			        $tabNav
				        .find('li.selected')
				        .removeClass('selected')
				        .find('a').attr('tabindex',-1);
			        $this	
				        .attr('tabindex',0)
				        .parent('li')
				        .addClass('selected');
			        //change the tablist content
			        $tabContent
				        .find('.slide-selected')
				        .find('div.txt').fadeOut(500,function() {
					        if(jQuery.browser.msie) $(this).get(0).style.removeAttribute('filter');	
				        })				
				        .end()
				        .removeClass('slide-selected')
				        .attr('aria-hidden',true)
			        $('#' + currentPanelID)
				        .find('div.txt').fadeIn(500,function() {
					        if(jQuery.browser.msie) $(this).get(0).style.removeAttribute('filter');
				        })				
				        .end()
				        .addClass('slide-selected')
				        .attr('aria-hidden',false)
		        }
			
		        //Add events
		        $tabNav.find('li a')
			        .click(function()	{
				        selectTab( $(this) );
				        $(this).focus();
				        return false;
			        })
			        .keydown(function(e)	{
				        var currentTab = $(this).parent();
				        //Find keyCode: http://asquare.net/javascript/tests/KeyCode.html
				        var ret = true;
				        switch(e.keyCode)	{
					        //(select the previous tab)
					        case 37: //Left arrow
					        case 38: //Up arrow
						        if(currentTab.prev().size() > 0)	{
							        selectTab( currentTab.prev().find('a') );
							        currentTab.prev().find('a').eq(0).focus();
							        ret = false;
						        } else {
							        selectTab( currentTab.parent().find('a:last') );
							        currentTab.parent().find('a:last').eq(0).focus();
							        ret = false;
						        }
					        break;	
					        //(select the next tab)
					        case 39: //Right arrow
					        case 40: //Down arrow
						        if(currentTab.next().size() > 0)	{
							        selectTab( currentTab.next().find('a') );
							        currentTab.next().find('a').eq(0).focus();
							        ret = false;
						        } else {
							        selectTab( currentTab.parent().find('a:first') );
							        currentTab.parent().find('a:first').eq(0).focus();
							        ret = false;
						        }
					        break;
					        case 36: //Home key, select the first tab
						        selectTab( currentTab.parent().find('a:first') );
						        currentTab.parent().find('a:first').eq(0).focus();
						        ret = false;
					        break;
					        case 35: //End key, select the last tab
						        selectTab( currentTab.parent().find('a:last') );
						        currentTab.parent().find('a:last').eq(0).focus();
						        ret = false;
					        break;
				        }
				        return ret;
			        });
			
		        //If focus is on an element in a tab panel:
		        //Control + Up Arrow/Left Arrow: Set focus on the tab button for the currently displayed tab
		        $tabPanel.keydown(function(e)	{
			        if( e.ctrlKey && (e.keyCode == 37 || e.keyCode == 38) )	{
				        $tabNav.find('li.selected a').focus();
			        }
		        });
		
		
		        /* Slide up/down the secondary content after clicking on the "more info" link */
		        var linkMore = $('a.c-more');
		        linkMore.toggle(function()	{
			        if(autoRotate)	{
				        clearInterval(rotateTabs);				
			        }
		
			        $('.slide-selected .moreInfo').animate({'bottom':0},800, function() {
				        $('.slide-selected .c-more')
				        .css('backgroundPosition','0 -730px')
				        .text('Back to products');
			        })			
		        }, function()	{ 
			        $('.slide-selected .moreInfo').animate({'bottom':-360},800,function()	{
				        $('.slide-selected .c-more')
				        .css('backgroundPosition','0 -630px')
				        .text('More information');
			        });			
			        return false;
		        });
			
		        //Optional rotation
		        if(autoRotate)	{
			        var rotateTabs = setInterval(function()	{
				        var currentTab = $tabNav.find('li.selected');
				        if(currentTab.next().find('a').length)	{
					        selectTab( currentTab.next().find('a') );
				        } else {
					        selectTab($tabNav.find('li:first a'));
				        }
			        }, 6000)
		        };
		        //Clear rotating after mouseover the tabs area
		        if(autoRotate)	{
			        $tabNav.find('a').bind('mouseover click keydown focus',function()	{
				        clearInterval(rotateTabs);
			        })					
		        }
		
	        });
        }
        /* @end homepage carousel  */





})(jQuery)
	


