/* ---------------------------------- */
/* register global vars */
var $window;
var $body;
var $mainNav;
var $subNavAll;
var $subNavOverlay;
var $mobile;
var $unsupported;
var $windowHeight;
var $windowWidth;
var $resizeBackup;

/* ---------------------------------- */
/* document ready */
jQuery( function ($) {

    /* define value of global vars */
    $window = $(window);
    $body = $('body');
    $mainNav = $('#JM_objMainNav');
    $subNavAll = $('.JM_objSubNavi');
    $subNavOverlay = $('#JM_objSubNaviOverlay');
    $mobile = ($body.hasClass('webkit-mobile') || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
    $unsupported = $body.hasClass('unsupported-browser');
    $windowHeight = (typeof window.innerHeight == 'undefined')? document.documentElement.clientHeight : window.innerHeight;
    $windowWidth = (typeof window.innerWidth == 'undefined')? document.documentElement.clientWidth : window.innerWidth;
	
	if ($mobile) {
		$body.addClass('isMobile');
	}

    // instantiate here ->

    $.initNavigation();
    $.initAccordionLinks();
    $.initOverlabels();
    $.initFormElements();
    $.initStoreSubnavigation();
    setTimeout(function(){
      $.initFooter();
    }, 500);

    $("form[name='ordercatalog']").validateForm();

});
(function($) {
    /* ---------------------------------- */
    /* SHELL */
    $.fn.SHELL = function(el) {
        this.each( function() {
            var $self = $(this);
        })
    };
    /* ---------------------------------- */
    /* Navigation */
    $.initNavigation = function() {
        var navFadeSpeed = 500;
        var navFadeDelay = 250;
        var navOverlayOpacity = 0.95;

        var fadeInTimeout;

        var subNavItemCenter ;
        var posTop;
        var posBottom;
        var posLeft;
        var posRight;
        var navActive = false;

        $('#JM_objSubNavi_4').css({display: 'block', visibility: 'hidden'});
        $('#JM_objSubNavi_4 #JM_objSubNaviStoresSearch .JM_objSubNaviCenter').optimizeStoreSearchField();
        $('#JM_objSubNavi_4').css({display: 'none', visibility: 'visible'});
		
		// deaktivate shop navigation-link
		$mainNav.find('a').eq(4).removeClass('hasSub').addClass('has-hover').bind('mouseover',function(){
			$.hideSubNavigation();
		});
		

        // Show Sub Navigation
        $mainNav.find('a.hasSub').mouseover( function() {
            $self = $(this);
            
            fadeInTimeout = setTimeout( function() {
                $subNavOverlay.stop(true, true).css({
                    display: 'block'
                }).animate({
                    opacity: navOverlayOpacity
                }, navFadeSpeed);

                // stop animation of teaser
                $('[data-slider="true"] .JM_objProgressbar div').stop().clearQueue()
            	navActive = true;
                var displaySub = $('#JM_objSubNavi'+$self.data('subnavi'));
                //if(displaySub.css('display') == 'none') {
                    $mainNav.find('a.hasSub').removeClass('active');
                    $self.addClass('active');
                    $subNavAll.removeClass('activeSub');
                    displaySub.addClass('activeSub');
                    $subNavAll.fadeOut(navFadeSpeed);
                    displaySub.fadeIn(navFadeSpeed);

                    subNavItemCenter = $subNavAll.parent().find('.activeSub .JM_objSubNaviCenter');
                    posTop = $mainNav.offset().top;
                    posBottom = $subNavOverlay.height() - $('#home-socialbar').height();
                    posLeft = subNavItemCenter.offset().left;
                    posRight = subNavItemCenter.offset().left + subNavItemCenter.width();
                //}
            },navFadeDelay);
        });
        $mainNav.find('a.hasSub').mouseout( function() {
            clearTimeout(fadeInTimeout);
        });
        // Hide Sub Navigation
        $body.mousemove( function(event) {
            if($subNavOverlay.css('display') != 'none') {
                if(event.pageY < posTop || event.pageY > posBottom || event.pageX < posLeft || event.pageX > posRight) {
                  $.hideSubNavigation();
                }
            }
        });
        $mainNav.find('a:first').bind('mouseover', function(){
            if($subNavOverlay.css('display') != 'none') {
              $.hideSubNavigation();
            }
        });

        $.hideSubNavigation = function(){
           $mainNav.find('a.active').removeClass('active');
                    $subNavAll.removeClass('activeSub');
                    $subNavAll.fadeOut(navFadeSpeed);
                    $subNavOverlay.fadeOut(navFadeSpeed,function(){
                    if (navActive && $('[data-slider-active="true"]').length > 0) {
                        var percent = Math.floor(100/($(window).width()/$('[data-slider-active="true"] .JM_objProgressbar div').width()))
                        $('[data-slider-active="true"]').setStoryStage({first:true,progress:percent});
                      }
                      navActive = false;
                   });
        }

        // show submit button in search and stores flyout
        $('#JM_objSubNaviStoresSearchInput').focusin( function() {
            $('#JM_objSubNaviStoresSearchSubmit').css({
                visibility: 'visible'
            });
        });
        $('#JM_objSubNaviSearchInput').focusin( function() {
            $('#JM_objSubNaviSearchSubmit').css({
                visibility: 'visible'
            });
        });

        // use tags for search
        $('.JM_objSubNaviSearchTags a').bind('click', function() {
            var sword = $(this).text();
            $('#JM_objSubNaviSearch label').css({textIndent: '-1000px'});
            $('#JM_objSubNaviSearchSubmit').css({visibility: 'visible'});
            $('#JM_objSubNaviSearchInput').val(sword);
            $('#JM_objSubNaviSearch form').submit();
            return false;
        });

        // make last link (more) not clickable
        if ($mobile) {
        	$mainNav.find('a.hasSub').click( function() {
        		if ($(this).hasClass('active')){
        		  $.hideSubNavigation();	
        		}
          		return false;	
        	});
        	        	
        }
        else {
        	$mainNav.find('a.hasSub:last').click( function() {
          		return false;	
        	});
        }
    };
    /* ---------------------------------- */
    /* Footer */
    $.initFooter = function() {
        var footer = $(".JM_objfooter");
        var windowW = $("#JM_siteHome").length > 0 ? $(window).width() : 960;
        var divW = 0;
        $("div.JM_fitIn").children().each(function() {
            divW += $(this).outerWidth();
        });
        $("div.JM_fitIn").width(divW);

        $(".JM_fitIn").each( function(index) {
            var $that = $(this);
            var startW = $that.width();
            var startFS = parseInt($that.css("font-size"));
            $that.css({
              "letter-spacing": "-23px",
              "margin-left": "-23px"
            });
            var calcFS = startFS / startW * windowW + 24;
            var calcCss = {
              "font-size":(~~calcFS),
              "line-height":(~~(calcFS/100*80))+"px",
              "z-index":(index+100)
            };
            if($("html").hasClass("ie7"))
              var calcCss = {
                "font-size":(~~calcFS),
                "margin-top":-(~~(calcFS/100*80))+"px"
              };
            $that.css(calcCss).children().css(calcCss);
        });
        $("div.JM_fitIn").width("auto");
        if(!footer.hasClass("active"))
          footer.height(footer.height() + 20).hide().css("visibility", "visible").fadeIn();
        footer.addClass("active");
        footer.find("a").each(function(index){
          var $link = $(this);
          var $hitArea = $("<a>", {
            "class":"hitArea",
            "href":$link.attr("href"),
            "target":$link.attr("target"),
            text:$link.text()
          }).width($link.width()).height($link.height()).css({
            "left":$link.position().left,
            "top":$link.position().top,
            "font-size":$link.css("font-size"),
            "line-height":$link.css("font-size"),
            "opacity":0,
            "overflow":"hidden",
            "white-space": "nowrap"
          });
          if($("html").hasClass("ie7") || $("html").hasClass("ie8"))
            $hitArea.css("top", $link.position().top - 100);
          $link.after($hitArea);
          $hitArea.hover(function(){
            $link.addClass("hover");
          }, function(){
            $link.removeClass("hover");
          });
          if($link.hasClass("JM_fitIn"))
            $link.css({
              "left":$link.position().left,
              "top":$link.position().top
            });
        });
        $("div.JM_fitIn").css({
          "top":$("div.JM_fitIn").position().top,
          "margin-left":0,
          "left":$("div.JM_fitIn").position().left,
          "width":"100%"
        }).find(".hitArea").css("top", 0);
        $("div.JM_fitIn a").css("margin-top", 0);
        $("a.JM_fitIn, div.JM_fitIn").css("position", "absolute");
    };
    $.resetFooter = function() {
        $(".JM_fitIn, .JM_fitIn a, .JM_fitIn span").each( function(index) {
            var $that = $(this);
            $that.attr("style", "");
        });
        $(".hitArea").remove();
    };
    /* ---------------------------------- */
    /* Accordion Links */
    $.initAccordionLinks = function() {
        $("#JM_objAccordion .JM_objAccordionLink a").click( function(e) {
            e.preventDefault();
            var $that = $(this);
            var accSection = $that.closest("section");
            var allSec = $("#JM_objAccordion > section");

            if(!accSection.hasClass("active") && !$(".JM_objAccordionContent").is(":animated")) {
                accSection.find(".JM_objAccordionContent").slideToggle( function() {
                    accSection.addClass("active");
                });
                allSec.filter(".active").find(".JM_objAccordionContent").slideToggle( function() {
                    allSec.filter(".active").not(accSection).toggleClass("active");
                });
            }
        });
    };
    /* ---------------------------------- */
    /* Overlabels */
    $.initOverlabels = function() {
        $("label.JM_overlabel").overlabel();
    };
    /* ---------------------------------- */
    /* styled Form Elements */
    $.initFormElements = function() {
        $(".JM_styledSelect").each(function(){
          var $that = $(this);
          var labelOption = $that.find("option").first();
          var label = $("<label>", {
            "class":($that.hasClass("JM_errorInvalid")) ? "JM_styledSelectText JM_errorInvalid" : "JM_styledSelectText",
            "for":$that.attr("id"),
            text: labelOption.text()
          });
		  
          if(!$that.is(':visible')){
            label.hide();
          }
		  
          $that.before(label);
          $that.change(function(){
            label.html($(this).find("option:selected").text());
            if($(this).find("option:selected").val()!=='') {
              label.removeClass('JM_errorInvalid');
            }
          });
        });
    };
    /* ---------------------------------- */
    /* store subnavigation */
    $.initStoreSubnavigation = function() {
    	$('.JM_objSubNaviStoreSelect').each(function(){
    		var $self = $(this);
    		var $links =  $self.find('a');
    		var $form = $('#JM_objSubNaviStoresSearch form');
    		var $input = $form.find('input[type="text"]');

    		$links.bind('click',function(e){
    		  var $val = $(this).hasClass('JM_objSubNaviAllLink')?$(this).parents('div.JM_objSubNaviCol').find('h2').text():$(this).text();
    		  $input.focus().val($val);
    		  $form.submit();
    		  e.preventDefault();
    		});
    	})
    };

    /* ---------------------------------- */
    /* optimize size of stores search field */
    $.fn.optimizeStoreSearchField = function(){
      $list         = $(this).find('ul');
      $listItems    = $list.find('li');
      $inputfield   = $listItems.find('input[type="text"]').first();

      var space  = $list.width();
      $listItems.each(function(){
        space = space - $(this).outerWidth();
      });
      space = space-10;
      var inputSize = $inputfield.width();
      $inputfield.width(inputSize + space);
    };
    /* ---------------------------------- */
    /* validate forms */
    $.fn.validateForm = function() {
        return this.each( function(i) {
      	    
            var $self = $(this);
            var $selectState = $('select[name="state"]');
                     
            jQuery.validator.addMethod("defaultInvalid", function (value, element) {
                return value != element.defaultValue;
            }, "");
            jQuery.validator.messages.required = "";

            $("select[name='country']").change( function () {
            	if ($(this).val() === "USA") {
                //if ($(this).val() === "Vereinigte Staaten von Amerika" || $(this).val() === "United States of America" || $(this).val() === "États-Unis" || $(this).val() === "Stati Uniti d'America" || $(this).val() === "Estados Unidos") {
                    if($.browser.msie && $.browser.version <= 7) {
                    	$selectState.parent().find('.JM_styledSelectText').css({'display':'inline-block'});
                    }
                    else {
                    	$selectState.parent().find('.JM_styledSelectText').show();
                    }
                    $selectState.show();
                    $selectState.addClass('required');
                }
                else {
                    $selectState.parent().find('.JM_styledSelectText').hide();
                    $selectState.hide();
                    $selectState.removeClass('required');
                }
            });
            
            $self.validate({
                invalidHandler: function (e, validator) {
                    var errors = validator.numberOfInvalids();
                    if (errors) {
                       $(".JM_errorText").show(); 
                    }
                },
                errorPlacement: function (error, element) {
                    if (element[0].nodeName === 'SELECT') {
                        element.parent().find('label').addClass('JM_errorInvalid');
                    }
                },
                errorClass: "JM_error"
            });

        })
    };    
})(jQuery);

