$(function(){
	"use strict";
    var $gameContent = $('#games-content'),
        $header =  $('#header'),
        $topnav = $('#topnav'),
        $subnav = $('#subnav');

    //check if not a touch enabled device, then bind hover event for tabs.
    //this prevents an issue on touch devices where the touch event on the link is interpreted
    //as a hover event, causing undesired user experience.
    if (!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch)) {
        $('ul.nav-tabs li#games-tab a', $topnav).on('mouseover', function() {
            var $this = $(this);
            if ($header.prop('hoverTimeout-topnav')) {
                $header.prop('hoverTimeout-topnav', clearTimeout($header.prop('hoverTimeout-topnav')));
            }

            $header.prop('hoverIntent-topnav', setTimeout(function() {showDropDownMenu($this);}, 250));
        });

        $header.on('mouseout', function(e) {

            if ($header.prop('hoverIntent-topnav')) {
                $header.prop('hoverIntent-topnav', clearTimeout($header.prop('hoverIntent-topnav')));
            }

            $header.prop('hoverTimeout-topnav', setTimeout(function() {
                var target = e.toElement || e.relatedTarget,
                    $target = $(target);
                if (!$header.has($target).length || //not in the header
                    ($topnav.has($target).length && !$('li', $topnav).has($target).length) || //or in the nav bar and not on one of the tabs
                    $('.inside', $header).first().has($target).length // or in the area between the browser top and the nav
                ) {hideDropDownMenu();}
            }, 250));
        });

        //bind events for subnav
        $subnav.on('mouseover', '.language span, .community span, .family span', function() {
            var $this = $(this);

            if ($header.prop('hoverTimeout-subnav')) {
                $header.prop('hoverTimeout-subnav', clearTimeout($header.prop('hoverTimeout-subnav')));
            }

            $header.prop('hoverIntent-subnav', setTimeout(function() {showSubSubnav($this);}, 250));
        });

        $header.on('mouseout', function(e) {
            if ($header.prop('hoverIntent-subnav')) {
                $header.prop('hoverIntent-subnav', clearTimeout($header.prop('hoverIntent-subnav')));
            }

            $header.prop('hoverTimeout-subnav', setTimeout(function() {
                var target = e.toElement || e.relatedTarget,
                    $target = $(target);
                if (!$header.has($target).length ||
                    $topnav.has($target).length ||
                    ($subnav.has($target).length && !$('li', $subnav).has($target).length)) {hideSubSubnav();}
            }, 250));
        });
    } else {
        $subnav.on('touchstart', '.language span, .community span, .family span', function () {
            var $this = $(this);
            var prevStateOpen = $this.data('open') || false;
            if (prevStateOpen) {hideSubSubnav();} else {showSubSubnav($this);}

            $this.data('open', !prevStateOpen);
        });
    }
    
    function showSubSubnav($this)
    {
        $subnav.addClass('open');
        $('.active', $subnav).removeClass('active');
        $this = $this.addClass('active').parent();
        
        var open = '';
        if($this.hasClass('language')){
            open = 'languages';
        } else if($this.hasClass('community')){
            open = 'communities';
        } else if($this.hasClass('family')){
            open = 'families';
        }
        
        var $subsubnav = $('#sub-subnav');
      
        $subsubnav.removeClass().addClass(open);
    }
    
    function hideSubSubnav(){
        $subnav.removeClass('open');
        $('.active', $subnav).removeClass('active');
        $('#sub-subnav').removeClass();
    }

    //show/hide search text
    $('#search').focus(function() {$(this).val(null);})
    .blur(function() {
        if( $(this).val() === '' ){$(this).val('Search');}
    });

    //limits number of games shown
    function gamesFeaturedLimit(games_limit){
        //limit featured games displayed
        //var games_cnt    = $('ul.games-list li').size();
        var count = 0;
        $('ul.games-list li').each(function() {
           if( count >= games_limit ) {$(this).hide();}
           count++;
        });
    }

    function hideDropDownMenu() {        
        $gameContent.stop().slideUp(function(){
            $(this).css('height', '');
        });
        $('.open', $topnav).removeClass('open');
        $('.arrow', $topnav).removeClass('arrow');
    }

    function showDropDownMenu($this) {       
        $('.open', $topnav).removeClass('open');
        $('.arrow', $topnav).removeClass('arrow');
        $($this).addClass('open');
        $($this).removeClass('arrow');
        $($this).addClass('arrow');

        if($gameContent.css('display') == 'none' || $gameContent.height() < 308){
            $gameContent.css('height', '').slideDown();
        }
	  
	  $('.games-list').carouFredSel({
		auto : false,
		width : 400,
		height: 240,
		align : "center",
		responsive : true,
		items : {
		    visible:5,
		    height:180
		}, 
		prev : { 
		    key : "left"
		}
	  });  
    }
    
    (function buildMenu() {
        var $container = $('#games-content');     
      $.ajax({
        async: true,
        url : window.twokApiUrl + '/games/get-featured',
        type: 'get',
        cache: true,
        dataType: 'jsonp',
        error : function(jqXHR,textStatus,errorThrown){
            //console.log('something broke ' + errorThrown);
        },
        success: function(data) {
            for(var i in data){
              data[i].imageUrl = window.twokApiUrl + '/images/' + data[i].BoxArtImageID;
            }
			$.each(data, function(ckey,cdata) {
				cdata.Slug = "https://www.2k.com"+cdata.Slug
			});
            var templateData = {
                games: data,
                viewAll: window.twoK.localization["View All"],
                featuredGames: window.twoK.localization["Featured Games"]
            };
            var template = Handlebars.templates.gamesFeatured(templateData);
            $container.append(template);
		
		$('.games-list').carouFredSel({
		    auto : false,
		    width : 400,
		    height: 240,
		    align : "center",
		    responsive : true,
		    items : {
			  visible:5,
			  height:180
		    }, 
		    prev : { 
			  key : "left"
		    }
		});

		$('div.games-menu').find('.headernext').click(function() {
		    //Commenting these 2 lines to allow analytics to fire - update globalAnalytics.js if these need to be uncommented
		    //event.preventDefault();
		    //event.stopPropagation();
		    $(".games-list").trigger("next", 5);
		});

		$('div.games-menu').find('.headerprev').click(function() {
		    $(".games-list").trigger("prev", 5);
		});

		var counter = 0;
		$('div.games-menu').find('img').each(function() {counter++;});

		if(counter <= 5) {
		    $('div.games-menu').find('.headerprev').hide();
		    $('div.games-menu').find('.headernext').hide();
		} else {
		    $('div.games-menu').find('.headerprev').show();
		    $('div.games-menu').find('.headernext').show();
		}

		$('.game-title').each(function(){
		    var $this = $(this);
		    var text = $this.html();
		    var maxHeight = 20;
		    $this.css('height', 'auto');

		    while($this.height() > maxHeight){
			   text = text.replace(/ [^ ]*$/, '...');
			   $this.html(text);
		    }
		    $this.css('overflow', 'visible');
		}); 
        }
      });
    })();
    
    (function transformGameTitle(){
     
      var $title = $('.gamePageTitle h1');
      if($title.length == 1){
        var words = $title.html().split(' ');
        var title = '';
        for(var i in words){
            title += '<div class="pageTitle">' + words[i] + ' </div>';
        }
        $title.html(title);
      }
    })();

});