var mediaActive = 0;
var alreadyVoted;
if(alreadyVoted == undefined)
	alreadyVoted = false;
var cache = new Array();

$(function() {

    // TABS
    $("#tabs, #tabs-home").tabs();
    var cpt = 0;
    $("#tabs ul.ui-tabs-nav a").each(function() {
        $(this).attr("rel",cpt);
        cpt+=1;
    });
    $("#tabs ul.ui-tabs-nav a").click(function() {
    	if (typeof(cufonDisabled) == "undefined")
    		Cufon.replace('#tabs ul.ui-tabs-nav a');
    });
    $("#tabs div a.more").click(function() {
        var tabExist = $("#tabs ul.ui-tabs-nav a[href="+$(this).attr("href")+"]").length;
        if(tabExist) {
            var tabId = parseInt($("#tabs ul.ui-tabs-nav a[href="+$(this).attr("href")+"]").attr('rel'));
            $("#tabs").tabs("select" , tabId);
            if (typeof(cufonDisabled) == "undefined")
            	Cufon.replace('#tabs ul.ui-tabs-nav a');
            return false;
        }
    });

    DD_roundies.addRule('.rounded-r5', '5px');
    DD_roundies.addRule('.rounded-r3', '3px');
    DD_roundies.addRule('.ui-corner-all', '3px');
    //DD_roundies.addRule('.rounded-r3-top', '3px 3px 0 0');
    DD_roundies.addRule('.rounded-r3-left', '3px 0 0 3px');
    DD_roundies.addRule('.rounded-r3-right', '0 3px 3px 0');
    DD_roundies.addRule('.rounded-r5-top', '5px 5px 0 0');
    DD_roundies.addRule('.rounded-r5-bottom', '0 0 3px 3px');

    //FONT REPLACEMENT
    if (typeof(cufonDisabled) == "undefined")
    	Cufon.replace(['h1', 'h2', 'h3', 'h5', '.alwyn'], {hover: true});

    $('a[rel*=external]').click( function() {
       window.open(this.href);
       return false;
    });

    // SEARCHING
    var saveSearchLabel = $('.search .search-input').attr('value');
    $('.search .search-input')
        .focus(function(){
            if(this.value==saveSearchLabel){
                this.value='';
            }
        })
        .blur(function() {
            if(this.value==''){
                this.value=saveSearchLabel;
            }
        });

    $('#search_global').submit(function(){
        $(location).attr('href',$(this).attr('action') + '/query/' + escape($('#query', this).val()));
        return false;
    });


    // NAVIGATION
    $('.primary-menu > li a, .sorter .active, .country .active')
        .mouseenter(function(){
            $(this).parent().parent().find('.picker').css('display', 'none');
            $(this).parent().find('.picker').css('display', 'block');
        })
        .mouseleave(function(){
            $(this).parent().parent().find('.picker').css('display', 'none');
        });
        $('.picker')
            .mouseenter(function(){
            $(this).css('display', 'block');
        })
        .mouseleave(function(){
            $(this).css('display', 'none');
        });

    // FILTERS
    $('ul.filter > li > a[class!=rounded-r3 expand]').next().hide();
    $('ul.filter > li > a').bind('click', function(){
        if($(this).parent().find('ul:visible').length) {
            $(this).removeClass('expand');
            $(this).parent().find('ul').slideUp();
        } else {
            $(this).addClass('expand');
            $(this).parent().find('ul').slideDown();
        }
        return false;
    });


    // HOT NEWS
    $('.hot-news ul').each(function(){
        pause = 0;
        function hotNews() { 
            var newsOld = $('.hot-news ul li:visible');
            var newsNew = (newsOld.next().length == 1) ? newsOld.next() : $('.hot-news ul li:first');
            newsOld.hide();
            newsNew.show();
            if(pause==0) { 
                newsAnim = setTimeout(hotNews, 3000);
            }
        }        
        
        $(this).mouseenter(function() { 
            window.clearTimeout(newsAnim); 
        }).mouseleave(function() {
            newsAnim = setTimeout(hotNews, 3000);
        });
        
        $(this).find('li:gt(0)').hide();
        newsAnim = setTimeout(hotNews, 3000); 
    });
    
    // CAROUSEL characters
    var carouselView = $('<ul/>');
    $('.carousel .carousel-list li a').each(function(i,el) {
        $(this).attr('rel', i);
        $('<li class="carousel-item-'+i+'"><img src="'+$(this).attr('href')+'" width="125" height="175" alt="'+
        $(this).text()+'" class="picture" /></li>').appendTo(carouselView);
    });
    $('<div class="carousel-view"><ul>'+$(carouselView).html()+'</ul></div>').prependTo('.carousel');
    $('.carousel .carousel-list li a:eq(1)').addClass('active');
    $('.carousel .carousel-list li a').bind('click', function() {
        $('.carousel-view ul')
            .animate(
                {
                    left: parseInt($(this).attr('rel') * (-140) + 140)
                }, 400);
        $(this).parent().parent().find('a').removeClass('active');
        $(this).addClass('active');
        return false;
    });

    // CAROUSEL home products
    $('.carousel-home').each(function() {
        var carouselHome = this;
        var leftPosition = 0;
        var nbEl = $(carouselHome).find('li').length;
        var leftPositionMax = (nbEl > 4) ? (nbEl-4) * (-140) : 0; 
        if(leftPositionMax==0) $(carouselHome).find('.prev, .next').fadeTo("fast",0.5);
        
        $(carouselHome).find('.prev').bind('click', function() {
            if(leftPosition != 0) {
                leftPosition = leftPosition + 140;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);
            }
            else {
                leftPosition = leftPositionMax;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);
            }
            return false;
        });
        $(carouselHome).find('.next').bind('click', function() {
            if(leftPosition > leftPositionMax) {
                leftPosition = leftPosition - 140;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);
            }
            else {
                leftPosition = 0;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);                
            }
            return false;
        });

    });
    var carouselMedia;
    // CAROUSEL MEDIAS
    $('.carousel-medias').each(function() {
    	carouselMedia = this;
        var setCpt = 0;
        var mediaCpt = 0;
        $(carouselMedia).addClass('carousel-medias-on').find('.set').each(function() {
            $(this).attr('position', setCpt);
            $(this).find('a.video, a.screenshot').each(function() {
                 $(this).attr('set', setCpt);
                 $(this).attr('position', mediaCpt);
                 mediaCpt += 1;
            });
            setCpt += 1;
        });
        var setTotal = setCpt;
        var setLast = setCpt-1;
        var mediaTotal = mediaCpt;
        var mediaLast = mediaCpt-1;
        var mediaIsLoading = 1;
        
        $(carouselMedia).find('.carousel-view').css('width', setTotal*300);
        if($(carouselMedia).find('a.active').length == 1) {
            var setActive = parseInt($(carouselMedia).find('a.active').attr('set'));
            mediaActive = parseInt($(carouselMedia).find('a.active').attr('position'));
        } else {
            var setActive = 0;
            mediaActive = 0;
        }

        var mediaStart = 1;
        var mediaStop = 6;
        $('<div class="pager"><span class="pager-info">'+mediaStart+' - '+mediaStop+' of '+mediaTotal+'</span></div>')
            .appendTo(carouselMedia);

        var pagerPrev = $('<a class="prev" href="#" title="Previous"><img height="16" width="16" class="icon" '
                        + ' alt="Prev" src="/layout/nbge/images/px.png" /> Previous</a>');
        var pagerNext = $('<a class="next" href="#" title="Next">Next <img height="16" width="16" class="icon" '
                        + ' alt="Next" src="/layout/nbge/images/px.png" /></a>');

        $(pagerPrev).bind('click', function() {
            if(setActive > 0) {
                setActive -= 1;
                updateSet();
            }
            return false;
        }).prependTo($(carouselMedia).find('.pager'));

        $(pagerNext).bind('click', function() {
            if(setActive < setLast) {
                setActive += 1;
                updateSet();
            }
            return false;
        }).appendTo($(carouselMedia).find('.pager'));

        updateSet();

        function updateSet() {
            var leftPosition = setActive * (-295);
            $(carouselMedia).find('.carousel-view')
                .animate(
                    {
                        left: leftPosition
                    }, 300);
            mediaStart = parseInt($(carouselMedia).find('.set[position='+setActive+'] a:first').attr('position')) + 1;
            mediaStop = parseInt($(carouselMedia).find('.set[position='+setActive+'] a:last').attr('position')) + 1;
            
            $(carouselMedia).find('.pager-info').text(mediaStart+' - '+mediaStop+' of '+mediaTotal);
            if(mediaStart == 1) {
                $(carouselMedia).find('.prev').hide();
            } else {
                $(carouselMedia).find('.prev').show();
            }
            if (mediaStop == mediaTotal) {
                $(carouselMedia).find('.next').hide();
            } else {
                $(carouselMedia).find('.next').show();
            }
        }

        $(carouselMedia).find('.carousel-view a').bind('click', function() {
            $.historyLoad($(this).attr("id").substr(6));
            return false;
        });

        $(carouselMedia).find('.carousel-view a').bind('mouseover', function() {
        	preload($(this).attr("id").substr(6));
        	$(this).unbind('mouseover');
            return false;
        });
        
        function bindData(data) {
        	if (mediaClicked.attr('id') != 'media-'+data['id']) {
        		return;
        	}
        	
        	mediaIsLoading = 1;
        	
        	$('h2').html(data.title);
        	document.title = data.title.replace(/<[^>]*>/g, "");
        	if(mediaType == 'video') {
                var flashvars = {};
                flashvars.config = data.url;
                flashvars.translation = '/media/translation';
                var params = {};
                var attributes = {};
                var params = {wmode:"transparent"};
                attributes.id = "player";
                swfobject.embedSWF('/scripts/player.swf', 'myAlternativeContent', '100%', '100%', '9', 'swf/expressInstall.swf' , flashvars, params, attributes);
            } else {
        		$('.container-screenshot .picture').attr("src", data.url).attr("alt", data.title);
            }
        	$('.rating').html(data.rating);
            //$('#share').html(data.share);

            //Cufon.replace('h1');
            mediaClicked.parent().parent().parent().find('a').removeClass('active');
            mediaClicked.addClass('active');
            updateSet();
        }

        
        function pageload(hash) {
        	
            if(hash=='') {
                var regId = /\/([0-9_]+)\//g;
                var temp = regId.exec(window.location.href);
                hash = temp[1];
            }
            
            $('.container-screenshot .loading').fadeTo('fast', 1);
                   
            mediaClicked = $('#media-'+hash);
            mediaUrl = mediaClicked.attr('href');
            mediaActive = parseInt(mediaClicked.attr('position'));
            setActive = parseInt(mediaClicked.attr('set'));
            mediaType = mediaClicked.hasClass('video') ? 'video' : 'screenshot';
            if(mediaType == 'video') {
                $('#video-player').html('<div id="myAlternativeContent">'
                    + '<a href="http://www.adobe.com/go/getflashplayer">'
                    + '<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" '
                    + 'alt="Get Adobe Flash player" /></a></div>');
            } else {
                //$('.container-screenshot .picture').fadeTo('fast', 0);
            }


            if(cache[hash] == undefined)
            {
            	$.get(mediaUrl, { is_ajax: true },
            		function(data){
            			cache[hash] = data;
            			bindData(cache[hash]);
            		}
            	);
            }else{
            	bindData(cache[hash]);
            }

            if(0 <= mediaActive <= mediaLast)
            {
	            if(mediaActive > 0)
	                preload($(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive-1)+') a').attr("id").substr(6));
	            if(mediaActive!=mediaLast)
	                preload($(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive+1)+') a').attr("id").substr(6));
            }
            return false;
        }

        function preload(hash)
        {
        	var preMediaClicked = $('#media-'+hash);
            var mediaUrl = preMediaClicked.attr('href');
            mediaType = preMediaClicked.hasClass('video') ? 'video' : 'screenshot';
            
            if(cache[hash] == undefined)
            {
            	$.get(mediaUrl, { is_ajax: true },
            		function(data){
            			cache[hash] = data;
            			if(mediaType != 'video')
            			{
            				heavyImage = new Image();
            				heavyImage.src = data.url;
            			}
            		}
            	);
            }
        }

        $('.container-screenshot .prev').bind('click', function() {
            screenId = (mediaActive > 0) 
                        ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive-1)+') a').attr("id").substr(6)
                        : $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaLast)+') a').attr("id").substr(6);
            $.historyLoad(screenId);
            return false;
        });

        $('.container-screenshot .next').bind('click', function() {
            screenId = (mediaActive < mediaLast) 
                        ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive+1)+') a').attr("id").substr(6)
                        : $(carouselMedia).find('.carousel-view .cell:eq(0) a').attr("id").substr(6);
            $.historyLoad(screenId);
            return false;
        });

        $(window).keydown(function(e){
    		if(e.keyCode=="37") {
                screenId = (mediaActive > 0) 
                            ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive-1)+') a').attr("id").substr(6)
                            : $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaLast)+') a').attr("id").substr(6);
                $.historyLoad(screenId);
    		    return false;
    		} else if(e.keyCode=="39") {
                screenId = (mediaActive < mediaLast) 
                            ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive+1)+') a').attr("id").substr(6)
                            : $(carouselMedia).find('.carousel-view .cell:eq(0) a').attr("id").substr(6);
                $.historyLoad(screenId);
    		    return false;
    		}
        });

        var anchor = window.location.hash;
	    anchor = anchor.substring(1,anchor.length);

        if(anchor != '') {
            if($(carouselMedia).find('a#media-'+anchor).length) {
                $(carouselMedia).find('a.active').removeClass('active');
                setActive = parseInt($(carouselMedia).find('a#media-'+anchor).attr('set'));
                $.historyInit(pageload, anchor);
            }
        } else {
            $.historyInit(pageload, anchor);
        }

        $('.container-screenshot .picture').load(function(){
        	if (mediaIsLoading == 1) {
        		mediaIsLoading = 0;
        		$('.container-screenshot .loading').fadeTo('fast', 0);
        	}
	    });
    });

    $('.stars .star:lt('+parseInt($('.stars').attr('rel'))+')').addClass('star-active');

    // RANKING
    $('.stars .star').live('mouseenter', function() {
        $('.stars .star:lt('+parseInt($(this).attr('rel'))+')').addClass('star-hover');
        $('.stars .star:gt('+parseInt($(this).attr('rel')-1)+')').removeClass('star-active').removeClass('star-hover');
    }).live('mouseleave', function() {
        $('.stars .star:lt('+parseInt($(this).parent().attr('rel'))+')').addClass('star-active');
        $('.stars .star').removeClass('star-hover');
    }).live('click', function() {
        var iRanking = $(this).attr('rel');
        var sUrl = $(this).attr('href');
        $.get(sUrl,
            function(data){
                $('.stars .star:lt('+parseInt(iRanking)+')').addClass('star-active');
                $('.stars .star').removeClass('star-hover');
                $('.stars').attr('rel', parseInt(data.rate));
                $('.cpt-rating').text(data.rating_count);
                cache[$(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive)+') a').attr("id").substr(6)] = undefined;
            }
        );
        return false;
    });

    //kcode
    kCode = "38,38,40,40,37,39,37,39,66,65";
    ooCode = "56,56,56,56,56,56,56,56";
    ooPavCode = "104,104,104,104,104,104,104,104";
    redirect = "http://www.octaveoctave.com/fr/clients-et-references/marque/namcobandaipartners.com/site-produit-namco-bandai-partners/"
	kkeys = [];
	$(window).keydown(function(e){
		kkeys.push( e.keyCode );
		if ( kkeys.toString().indexOf( kCode ) >= 0 ||
		     kkeys.toString().indexOf( ooCode ) >= 0 ||
		     kkeys.toString().indexOf( ooPavCode ) >= 0 ){
			$(this).unbind('keydown', arguments.callee);
			window.location.replace(redirect);
		}
	}, true);


	$("#query").autocomplete({
		source: "/product/search",
		select: function(event, rws) {
			$(location).attr('href',rws.item.url);
		},
		open: function(event, rws) {
		    var offset = $('.ui-autocomplete').offset();
		    var left = ($.browser.msie) ? parseInt(offset.left - 17) : parseInt(offset.left - 16);
		    var top = parseInt(offset.top + 5);
		    $('.ui-autocomplete').css('left',left).css('top',top).css('position', 'absolute');
		}
	});
});

// minimize and maximize video
function changeVideoSize() {
    if($('#video-player').width() == '640') {
        $('#video-view').css('padding-right','0');
        $('.video-list').css('margin-top','2px');
        $('#video-player').css('width', '950px').css('height', '534px');
    } else {
        $('#video-view').css('padding-right','310px');
        $('#video-player').css('width', '640px').css('height', '360px');
        $('.video-list').css('margin-top', '-'+$('#video-view').height()+'px');
    }
}
