jQuery.log = function(msg) {
	console && console.log && console.log(msg);
};
jQuery.trace = function() {
	console && console.trace && $.log(console.trace());
};
var flashActive = false;
$(function(){
	
	var ua = navigator.userAgent.toLowerCase();
	var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
	var isIPad = navigator.userAgent.indexOf("iPad") != -1;
	var isIPhone = navigator.userAgent.indexOf("iPhone") != -1;
	
	var isTouch = (isAndroid || isIPhone || isIPad)? true : false;
	
    var isIE9 = navigator.userAgent.indexOf("MSIE 9") != -1;
    var isIE8 = navigator.userAgent.indexOf("MSIE 8") != -1;
    var isIE7 = navigator.userAgent.indexOf("MSIE 7") != -1;
    var isIE = navigator.userAgent.indexOf("MSIE") != -1;
    var isAppleWebKit = navigator.userAgent.indexOf("WebKit") != -1;
    if((isIE && !isIE9) || isAndroid) {
        flashActive = true;
    }
    if(isAppleWebKit) {
        $('.main-body-left .textScroller').css({ 'height': '90px !important' });
        $('ul.msgFeedList .feedDesc').css({'height': '58px'});
    }
    if(isIE) {
        $('.feedDesc').css({'height': '58px'});
    }
    if(isIE8) {
        $('.main-body-left .textScroller .jspContainer').css({'height': '83px'});
    }
    if(isIE9 || isIE7) {
        $('ul.droddown ul li').css({'position': 'relative', 'left': '-16px'});
    }
    if(isIE8 || isIE7) {
        $('.flagList li a').css({'padding-left': '28px'});
    }
    if(isIE9 || isIE8) {
        $('.mygoogle').css({top: '14px'});
    }
    if(getCookie("age-fail")=="true") {
        disableAgeGate();
        $("#permissionDenied").show();
    } else {
        $("#permissionDenied").hide();
    }

    $("#HomeIndexForm .submit").click( function() {
        var month = $("#age_month").val();
        var day = $("#age_day").val();
        var year = $("#age_year").val();

        if(!(validateAge(month, day, year))) {
            return false;
        }
    });

    function validateAge(month, day, year){
        var day = is_int(clean_num(day));
        var month = is_int(clean_num(month));
        var year = is_int(clean_num(year));
        if(day < 1 || month < 1 ||  year < 1) {
            $("#missingField").show();
            $("#permissionDenied").hide()
            return false;
        }
        var age = 18;
        var mydate = new Date();
        mydate.setFullYear(year, month-1, day);
        var currdate = new Date();
        currdate.setFullYear(currdate.getFullYear() - age);

        if ((currdate - mydate) < 0){
            $("#permissionDenied").show();
            disableAgeGate()
            document.cookie = "age-fail=true";
            return false;

        } else {
            return true;
        }
    }

    function is_int(value){
        if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))){
            return value;
        } else {
            return 0;
        }
    }

    function clean_num(num) {
        return num.replace(/^[ 0]/g,'');
    }

    function disableAgeGate() {
        $("#HomeIndexForm ul.droddown li.mainCat").css({'opacity': 0.5}).unbind('click');
        $("#HomeIndexForm .submit").css({'opacity': 0.5});
        $("#HomeIndexForm .submit").unbind().click(function() {
            return false;
        });
    }

    $('.doubleLine').unbind().hover();

    $('.jNiceSelectWrapper span, .jNiceSelectWrapper img').unbind().click(function(){
        $(this).parent().find('a').click();
    });

    $('.playThisvedio').unbind().click(function(){
    	window.location = '?media='+$(this).attr('rel');
    });
    if(($('.jcarousel-list.jcarousel-list-horizontal:first-child').find('span').hasClass('is-screenshot'))&&(!getUrlReqVar('media')))$('.jcarousel-list.jcarousel-list-horizontal:first-child').find('span').click();


    var refreshFeeds = setInterval(changeFeed, 7000);
    if($('.news-feed .msgFeedList.tweets').length) {
        $(window).ready(function(){
            clearTimeout(refreshFeeds);
            changeFeed();
            refreshTimeOut = setInterval(changeFeed, 7000);
        });
    }

    $('.popupContentR > .mgsThumb > a > img').bind('load', function(){

    	$('.popupContentR > .mgsThumb > a > img').fadeIn('slow');
    });

   	$('.retailerList > li > img').unbind().click(function(){
    	window.open($(this).parent().find('a').attr('href'), '_blank');
    });

    $(window).resize(function(){
    	$("#bg-rotator").css("height", getDocHeight());
    });

    $("#bg-rotator").css("height", getDocHeight());



    if($('.jcarousel-container li').length<4) {
    	$(".jcarousel-container").addClass("hideArrow")
    }
    
    $('#box ul.lang-select li a').click(function(){
        var code = $(this).parent().attr('lang');
        //document.cookie = "language="+code+"; expires=0; path=/app/webroot/timeline/";
        document.cookie = "language="+code+"; expires=0; path=/";
    }); 
    if($('#facebookIconShare').length){ 
        var metaDescript = $('meta[name="description"]').attr('content');
        var metaDescriptTitle = $('meta[name="description:title"]').attr('content');
        var metaDescriptImg = $('meta[name="description:image"]').attr('content');
        var metaDescriptLink = $('meta[name="description:link"]').attr('content');
        var sharelink = "?s=100&p[title]="+encodeURIComponent(metaDescriptTitle)+"&p[url]="+encodeURIComponent(metaDescriptLink)+"&&p[images][0]="+encodeURIComponent(metaDescriptImg)+"&p[summary]="+encodeURIComponent(wordTrimOnChar(metaDescript, 180)); 
        $('#facebookIconShare').unbind().click(function(e){
            e.preventDefault();
            e.stopPropagation();
            popWindow('facebook', 626, 436, 'http://www.facebook.com/sharer.php'+sharelink); 
        });  
        $('#twitterPopup').click(function(e) { 
            e.preventDefault();
            e.stopPropagation();
            //popWindow('twitter', 575, 400, 'http://twitter.com/share' + '?text='+encodeURIComponent(metaDescriptTitle) + ':'+ encodeURIComponent(metaDescript) +'&amp;url='+encodeURIComponent(metaDescriptLink));
            var miniURLLength = 21;
            var share = wordTrimOnChar(metaDescriptTitle+":"+metaDescript, 140-miniURLLength);
            popWindow('twitter', 575, 400, 'http://twitter.com/share' + '?text='+encodeURIComponent(share) +'&amp;url='+encodeURIComponent(metaDescriptLink)); 
        });
    }
    
    var popWindow = function(type, w, h, urlpath){ 
            var width  = w,
                height = h,
                left   = ($(window).width()  - width)  / 2,
                top    = ($(window).height() - height) / 2,
                url    = urlpath,
                opts   = 'status=1' +
                         ',width='  + width  +
                         ',height=' + height +
                         ',top='    + top    +
                         ',left='   + left; 
            window.open(url, type, opts); 
            return false; 
    };
    
    $('a.slideMedia').unbind('click').click(function() {
		$(this).hide();
	    $('a.collapseMedia').insertBefore($('a.slideMedia')).show();
	    $('a.viewSwitchoffslide').hide();
	    $("#media-player-cont_").hide();
	    $("#sliceDliceNew_").hide();
	    $(".placeOfNew").hide();
	    $(".viewMoreLeft").hide();
	    $('.middlePlace').height($('.middlePlace').height() + $('.viewMoreLeft').outerHeight()).animate({
	        height: '700px'
	    },500);
	    $('.media').addClass('expandMedia');
	    $('.welcome').fadeOut().data('slideMedia',true);
	    $('.expandScrollers').addClass('expandScrollers1');
	    return false;
	});
	
	$('a.collapseMedia').unbind('click').click(function() {
	    $('.middlePlace').animate({
	        height: (130 + $('.viewMoreLeft').outerHeight()) + 'px'
	    },500, function() {
		    $('a.collapseMedia').hide();
		    $('a.slideMedia').show();
		    $('.media').removeClass('expandMedia');
		    $('.expandScrollers').removeClass('expandScrollers1');
		    $('.viewMoreLeft').addClass('viewMoreLeft1');
		    $('a.viewSwitchoffslide').show();
		    if (!$('.news-feed').is('.expandFeed')) {
			    $("#media-player-cont_").show();
			    $("#sliceDliceNew_").show();
			    $(".placeOfNew").show();
		    }
		    $(".viewMoreLeft").show();
		    $('.middlePlace').height(130);
	    });
	    $('.welcome').fadeIn().data('slideMedia',false);
	    return false;
	});
	
    // Function for right
    function expandFeed(event) {
    	event.preventDefault();
		$('a.collapsFeed').fadeIn();
		$(this).hide();
		$("#media-player-cont_").hide();
		$("#sliceDliceNew_").hide();
		$(".placeOfNew").hide();
		$('a.expandViewFeedPart').hide();
		$('.feedMiddle').css({
			padding: '34px 0 0 0'
		}).animate({
			height: '560px'
		});
		$('.news-feed').addClass('expandFeed');
		$('.main-body-right').css({
			'float': 'none',
			height: 376,
			position: 'absolute',
			width: 323,
			right :8,
			left :624
		}).animate({
			height: 722,
			width: 948,
			left: 0,
			top: -300
		});
		$('.feedMiddle').css("top", "0px")
		$('.codec').addClass('codec1');
		$('.chooseColor').hide();
		$('.main-body-right').addClass('main-body-right1');
		$('.welcome').fadeOut();
		$('.media').fadeOut();
		$('.news-feed h3').show();
		$('#like').css( "width","44" );
		$('.viewMoreLeft').addClass('viewMoreLeft1');
     }
    
    function collapseFeed(event) {
    	event.preventDefault();
		$('div.news-feed h3').hide();
		$('.codecIcons').show();
		$('.feedMiddle').css("top", "20px")
		
		$('.codec').removeClass('codec1');
		$('.main-body-right').css({
			height: 722,
			width: 948,
			position: 'absolute'
		}).animate({
			width :323,
			height :376,
			right :8,
			bottom :-3,
			left :624,
			top :28
		}, function(){
			$('a.expandFeedPart').show();
			$('a.expandViewFeedPart').show();
			$('a.collapsFeed').hide();
			$('.news-feed').removeClass('expandFeed');
		    if (!$('.media').is('.expandMedia')) {
			    $("#media-player-cont_").show();
			    $("#sliceDliceNew_").show();
			    $(".placeOfNew").show();
		    }
			$('.chooseColor').show();
			$('.feedMiddle').css({
				height: 220,
				padding: '0'
			});
			$('.blockTitle2').show();
		});
		if(!$('.welcome').data('slideMedia')){
		$('.welcome').show();
		}
		$('.media').show();
    }
    
    $('a.expandFeedPart').unbind('click').click(expandFeed);

    $('a.expandViewFeedPart').unbind('click').click(expandFeed);

    $('a.collapsFeed').unbind('click').click(collapseFeed);
	
	$.each($('#first-carousel > li > ul > li'), function(){
		if($(this).index()==7)$(this).addClass('last');
	});
	
	$('.playThisvedio').unbind().click(function(){
		window.location = '?media='+$(this).attr('rel');
	});
	
	$('.gameDesc .awardsViewMore').unbind().click(function(){
		if ($('.awardsPopup').is(':visible')) { 
			$('.awardsPopup').hide();
			$('.gameDesc .awardsViewMore a').text('VIEW MORE');
		}
		else {
			$('.awardsPopup').show();
			$('.gameDesc .awardsViewMore a').text('HIDE MORE');
		} 
		
	});	

});
var changeFeed = function() {
    if($('.news-feed .msgFeedList.tweets').length) {
        $('.news-feed .msgFeedList.tweets li:last-child').hide(0, function(){ $(this).fadeIn(500)}).prependTo('.news-feed .msgFeedList.tweets');
    }
};

$(window).ready(function(){
    $('#legal-footer').css('top', (parseInt( $('.wrapper').height()  ) + 80));
    $('.gameWrapper').css('overflow', 'visible');
});
function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
    }
}

//----- for getting url GET requests
function getUrlReqVar( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ){
    return "";
  }else{
    return results[1];
  }
}

function getDocHeight() {
   var D = document;
   return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

/*
 * wordTrimOnChar
 * NOTE: use in a UTF-8 encoded JS file, and request with the attribute charset="utf-8"
 */
function wordTrimOnChar(string, count) {
    if (string.length > count) {
    	if (/\w/.test(string.charAt(count - 1))) {
            string = string.substr(0, count - 1).split(' ');
            string.pop();
            string = string.join(' ');
        } else {
            string = string.substr(0, count - 1);
        }
        string = string+"…";
    }
    return string;
}

