$(document).ready(function(){


    var AnimIndex = 0;
    var processing = false;
    var numSlides = ($('.slide').length)-1;
	
    var outTimeout = null;
    $(".subpage-content-main .sidebar-accordion").last().css("margin-bottom","20px");
    $("#mainnav li a.main").hover(function(){
        if($(".site-content").width()>640){

            if(outTimeout){
                clearTimeout(outTimeout);
            }

            $(".subnav").hide();
            show_subsection($(this).attr("id"));
            $("#mainnav li a").removeClass("active");
            $(this).addClass("active");
        }

	var width = $(".promoted img").width();
	//alert(parseInt(width));
	if(parseInt(width)>160){
		//alert('in');
			$("ul.subnav").addClass("subnav_Large");
		$("li.promoted").addClass("imag_space");
	}

    },function(e){
        if($(".site-content").width()>640){
            if(e.pageX<$(this).offset().left){

                $(".subnav").hide();
                $(this).removeClass("active");
            }else if(e.pageY<$(this).offset().top){

                $(".subnav").hide();
                $(this).removeClass("active");
            }else if(e.pageX>$(this).offset().left+$(this).width()){

                $(".subnav").hide();
                $(this).removeClass("active");
            }
        }
    });

    $(".infoicon").click(function(){
        $(".infocontent").stop().slideToggle();
    });
    $(".infocontent .close").click(function(){
        $(this).parent().stop().slideToggle();
    });

    //adjust promoted heighs
    /*
    $(".widepromo").height(($("#s_n_a_sub").children().length-1)*35);
    $("#why_rolls_sub .promoted").css("min-height",((($("#why_rolls_sub ").children().length)/2)*35));
    $("#business_sub .promoted").css("min-height",((($("#business_sub ").children().length)/2)*35));
    $("#global_sub .promoted").css("min-height",((($("#business_sub ").children().length)/2)*35));
    */
    $(".subnav").each(function(){
        var subnav = $(this);
        if($(this).find("li").eq(0).hasClass("promoted")){
            $(this).find("li.promoted").css("min-height",(((subnav.children().length)/2) * 35));
        }

    });


    /***********************************************tabs*************************/

    $("ul.tabs li a").click(function(e){
        e.preventDefault()
        });

    $(".tabs-content").css("width",$(".tab-content-container").width()+"px");

    $(".tab-content-container").each(function(){
        var slider = $(this).find(".tab-content-slider");
        $(this).height(slider.find(".tabs-content").eq(0).height());
    });


    $("ul.tabs li").click(function(){

        var clickedIndex = $(this).index("ul.tabs li");
        var activeElementIndex = $(this).parent().find("li.active").index("ul.tabs li");
        var parentBox = $(this).parent().parent().parent();
        var sliderElement = $(this).parent().parent().parent().find(".tab-content-slider");
        var slideContainer = $(this).parent().parent().parent().find(".tab-content-container");



        if(clickedIndex > activeElementIndex){


            var whereToSlide = slideContainer.width()*(clickedIndex - activeElementIndex);
            $("ul.tabs li").eq(activeElementIndex).removeClass("active");
            $("ul.tabs li").eq(clickedIndex).addClass("active");
            slideContainer.stop().animate({
                height:$(".tabs-content").eq(clickedIndex).height()+"px"
                });
            sliderElement.stop(true,true).animate({
                left:"-="+whereToSlide+"px"
                });

        }else if(clickedIndex < activeElementIndex){
            $("ul.tabs li").eq(activeElementIndex).removeClass("active");
            $("ul.tabs li").eq(clickedIndex).addClass("active");
            var whereToSlide = slideContainer.width()*(activeElementIndex - clickedIndex );
            $("ul.tabs li").eq(activeElementIndex).removeClass("active");
            $("ul.tabs li").eq(clickedIndex).addClass("active");

            slideContainer.stop().animate({
                height:$(".tabs-content").eq(clickedIndex).height()+"px"
                });
            sliderElement.stop(true,true).animate({
                left:"+="+whereToSlide+"px"
                });
        }

    });

    $(".nav_next a").live("click",function(e){

        e.preventDefault();

        var currentActiveElement =  $(this).parent().parent().find("ul.tabs li.active").index();
        var currentNavigator =   $(this).parent().parent().find("ul.tabs li")  ;
        var currentTabs = $(this).parent().parent().find("ul.tabs");
        var firstElelemIndex =  $(this).parent().parent().find("ul.tabs li").first().index("ul.tabs li");
        var lastElelemIndex =  $(this).parent().parent().find("ul.tabs li").last().index("ul.tabs li");
        var tabContentWidth = $(this).parent().parent().width();


        if(currentNavigator.eq(currentActiveElement+1).length > 0){

            var nextElemOffset = currentNavigator.eq(currentActiveElement+1).position().left + currentNavigator.eq(currentActiveElement+1).width();
            if(nextElemOffset> tabContentWidth){
                currentTabs.stop(true,true).animate({
                    left:"-="+currentNavigator.eq(currentActiveElement+1).width()+"px"
                    });
            }
        }else{
            currentTabs.stop(true,true).animate({
                left:"0px"
            });
        }

        if($(this).parent().parent().find("ul.tabs li").length-1 != currentActiveElement){
            currentNavigator.eq(currentActiveElement+1).trigger("click");
        }else{
            currentNavigator.eq(0).trigger("click");
        }

    });

    $(".nav_prev a").live("click",function(e){
        e.preventDefault();
        var currentActiveElement =  $(this).parent().parent().find("ul.tabs li.active").index();
        var currentNavigator =   $(this).parent().parent().find("ul.tabs li");
        var currentTabs = $(this).parent().parent().find("ul.tabs");
        var tabContentWidth = $(this).parent().parent().width();
        var tabContentOffset = $(this).parent().parent().offset().left;
        var nextElemOffset = currentNavigator.eq(currentActiveElement-1).offset().left;

        if(currentActiveElement != 0){
            currentNavigator.eq(currentActiveElement-1).trigger("click");

            if(currentActiveElement-1 == 0){
                currentTabs.stop(true,true).animate({
                    left:"0px"
                });
            }else{
                if(nextElemOffset < tabContentOffset){
                    currentTabs.stop().animate({
                        left:"+="+(currentNavigator.eq(currentActiveElement-1).width()+10)+"px"
                        });

                }
            }

        }else{

            var move = currentNavigator.last().position().left-$(this).parent().parent().width()+currentNavigator.last().width();
            nextElemOffset = currentNavigator.eq(currentActiveElement-1).position().left;
            if(nextElemOffset+currentNavigator.eq(currentActiveElement-1).width() > tabContentWidth){
                currentTabs.stop().animate({
                    left:"-="+(move+30)+"px"
                    });
                console.log("here");
            }
            currentNavigator.eq($(this).parent().parent().find("ul.tabs li").length-1).trigger("click");
        }

    });

    $("form").submit(function(e){

        if($(this).attr("id") == "myrolls-form"){

            var selects = $(this).find("select");
            var canGo = false;
            $.each(selects,function(){
                if($(this).val() != 0){
                    canGo = true;
                }
            });

            if(canGo){
                $(".my-rolls-royce").removeClass("error");
                $(".errormessage").hide();

            }else{
                e.preventDefault();
                $(".my-rolls-royce").addClass("error");
                $(".errormessage").show();
            }
        }

    });


    /***********************tabs end***********************************************/


    $(".subnav").hover(function(){

        if(outTimeout){
            clearTimeout(outTimeout);
        }

    },function(e){

        var sthis = $(this);

        if($(".site-content").width()>640){
            outTimeout = setTimeout(function(){
                sthis.hide();
                $("#mainnav li a").each(function(){
                    $(this).removeClass("active");
                });
            },300);

        }
    });


    if($(".site-content").width()>740){
        imageReplacement();

    }

    $("#mainnav li a.main").click(function(){

        if($(".site-content").width()<=460){
            var id = $(this).attr("id");

            $("#"+id+"_sub").slideToggle();

        }
    });



    $(".career-reset").click(function(){
        $(this).parent().find("option").removeAttr("selected");
        $(this).parent().find("select").find("option:first").attr("selected","selected");
        if($(".site-content").width()>740){
            imageReplacement();
        }
    });


    $(window).resize(function(){
        if($(".site-content").width()>740){
            imageReplacement();
        }else{
            $(".replaceme").show();
            $(".selectreplace").remove();

        }

        if($(".site-content").width()>900){
            $(".subnav:visible").hide();
        }

        resetSliderPositions();
    });

    $(".selectreplace").live("click",function(){

        var index = $(this).index(".selectreplace");

        if($(this).find(".subber").is(":visible")){
            $(this).find(".subber").hide();
        }else{
            $(this).find(".subber").show();
            $(".selectreplace").each(function(){

                if(($(this).index(".selectreplace") != index)&&($(this).find(".subber").is(":visible"))){
                    $(this).find(".subber").hide();
                }
            });
        }

    });

    $(".search-elem input,.text-search-wrapper input").focus(function(){
        $(this).val("");
        if($(this).hasClass("default")){
            $(this).removeClass("default");
        }
    });

    $(".sub").live("click",function(){
        var whichSelect = $(this).parent().parent().attr("id").split("_");
        var whichOption = $(this).attr("id").split("_");

        $(this).parent().parent().find("p:first").text($(this).text());
        switchSelect(whichSelect[1],whichOption[1]);
    });



    if($("#sharer").length>0){
        var sharer = $("#sharer");
        var sharerPosT = $("#sharer").offset().top;
        var sharerPosL = $("#sharer").offset().left;

        $(window).resize(function(){
            sharer = $("#sharer");
            sharerPosT = $("#sharer").offset().top;
            sharerPosL = $("#sharer").offset().left;
            if($(this).scrollTop()>sharerPosT){
                sharer.css("position","fixed");
                sharer.css("left",sharerPosL);
                sharer.css("top","20px");
            }else{
                sharer.css("position","static");
            }
        });

        $(window).scroll(function(){

            if($(this).scrollTop()>sharerPosT){
                sharer.css("position","fixed");
                sharer.css("left",sharerPosL);
                sharer.css("top","20px");
            }else{
                sharer.css("position","static");
            }
        });

    }


    $(".sidebar-trigger").click(function(){
        $(this).parent().find(".sidebar-accordion-content").stop(true,true).slideToggle();


        if($(this).parent().parent().hasClass("subpage-content-main")){

            var others = $(this).parent().parent().find(".sidebar-trigger").not($(this));

            $.each(others,function(){

                if($(this).hasClass("active_trigger")){

                    $(this).removeClass("active_trigger");
                    $(this).removeClass("hovered_active");
                    $(this).parent().find(".sidebar-accordion-content").stop(true,true).slideToggle();
                }
            });


        }


        if($(this).hasClass("active_trigger")){
            $(this).removeClass("active_trigger");
            $(this).removeClass("hovered_active");
            $(this).addClass("hovered_inactive");

        }else{
            $(this).addClass("active_trigger");
            $(this).addClass("hovered_active");
            $(this).removeClass("hovered_inactive");
        }
        var tabbed = $(this).parent().find(".tabbed-content");
        var tabs = tabbed.find(".tabs-content:visible");
        var tabscontainer = tabbed.find(".tab-content-container");
        var activeElem = tabbed.find("ul.tabs li.active").index();
        tabscontainer.height(tabs.eq(activeElem).height());


    });


    $(".sidebar-trigger").hover(function(){
        if($(this).hasClass("active_trigger")){
            $(this).addClass("hovered_active");
        }else{
            $(this).addClass("hovered_inactive");
        }

    },function(){

        $(this).removeClass("hovered_active");
        $(this).removeClass("hovered_inactive");

    });
 /**********************************************************
    ***********************************************************
    ***********************************************************
    ***********************************************************/

    var animTimeout = null;
    
    //for every image add a thumbnail
    $('.slide').each(function(){
        $('.thumbnails ul').append('<li><a href="#" title=""></a></li>');
    });
    
    //hide user interface and reveal on rollover
    $('.scroller_ui').hide();
    $(".big-scroller").hover(
	function () {
	  $('.scroller_ui').stop(true,true).show();
	  //$('.scroller_ui').stop(true,true).fadeIn("fast");
	},
	function () {
	  $('.scroller_ui').stop(true,true).hide();
	  //$('.scroller_ui').stop(true,true).fadeOut("fast");
	}
    );
    
    //on left hover
    $("#nav_prev").hover(
	function () {
	  $(this).addClass("navPrevHover");
	},
	function () {
	  $(this).removeClass("navPrevHover");
	}
    );
    
    //on right hover
    $("#nav_next").hover(
	function () {
	  $(this).addClass("navNextHover");
	},
	function () {
	  $(this).removeClass("navNextHover");
	}
    );
    
    //on left click reduce index by 1
    $('#nav_prev').click(function(event){
        event.preventDefault();
	
	clearInterval(animTimeout);
	
        //loop slides
        if (AnimIndex!= 0)
            {AnimIndex--;}
        else
            {AnimIndex = numSlides;}
         
        if(!processing)
        {
            processing = true;
             
            $('.overlay').fadeIn(400, function(){
                showImage();
            });
        }   
    });
    
    //on right click increase index by 1
    $('#nav_next').click(function(e){
        e.preventDefault();
    
	clearInterval(animTimeout);
	
        //loop slides
        if (AnimIndex != (numSlides))
            {AnimIndex++;}
        else
            {AnimIndex = 0;}
        
	
	$('.showHeading').fadeOut(function(){
	    
	if(!processing)
        {
            processing = true;
    
            $('.overlay').fadeIn(400, function(){
		
                showImage();
		
            });
        }    
	    
	});
        
    });
    
    $(window).load(function() { showImage(); }); 
    
    function showImage(){
         
	var whereToMove = Math.abs($(".big-scroller").width());
	
	//position thumbnails centrally
	//$(".thumbnails").css("left",((whereToMove/2)-(25*($(".thumbnails li").length-1)))+"px");
	//position thumbnails to the right
	$(".thumbnails").css("left",((whereToMove)-(25*($(".thumbnails li").length))-8)+"px")
	
	//remove all css3 animations
	$('.slide').find('.foreground').removeClass('cssAnimateForeground'); 
	$('.slide').find('.background').removeClass('cssAnimateBackground');
	$('.slide').find('.foreground').removeClass('cssAnimateForegroundLeft'); 
	$('.slide').find('.background').removeClass('cssAnimateBackgroundLeft');

        //reset elements to default
	$(".slide").each(function(){
	   
	    if($(this).hasClass("left")){
		$(this).find(".background").stop().css("left","-500px");
	    
	    }else{
		$(this).find(".background").stop().css("left","500px");
		$(this).css("left",whereToMove);
	    }
	   
	    $(this).find(".foreground").stop().css("left","0px");

	});
	
        $('.slide').show();
        $('.overlay').hide();
        
        if(!$.browser.msie){
	    $('.slide').css('opacity', 1);
	}
        
        $('.thumbnails li').removeClass("slideshow_active");
        $('.slide').removeClass("activeImg");
        
        //add active classes
        $('.thumbnails li').eq(AnimIndex).addClass("slideshow_active");
        $('.slide').eq(AnimIndex).addClass("activeImg");
        
        if ($('.slide').eq(AnimIndex).hasClass('left'))
        {
            //animate images
	    if($.browser.webkit){
		
		$('.slide').eq(AnimIndex).find('.foreground').addClass('cssAnimateForegroundLeft');
		$('.slide').eq(AnimIndex).find('.background').addClass('cssAnimateBackgroundLeft');
		$('.showHeading').eq(AnimIndex).fadeIn("slow");
	    }
	    else{
		$('.slide').eq(AnimIndex).find('.background').animate({
		  left: "898px"
		}, {duration:1300});
		
		$('.slide').eq(AnimIndex).find('.foreground').animate({
		  left: "898px"
		}, {duration:900,queue:false});
		
		$('.showHeading').eq(AnimIndex).fadeIn("slow");
            }
	    processing = false;
        }
        else
        {
	    if($.browser.webkit){
		//$('.slide img').load(function() {
		    $('.slide').eq(AnimIndex).find('.foreground').addClass('cssAnimateForeground');
		    $('.slide').eq(AnimIndex).find('.background').addClass('cssAnimateBackground');
		    $('.showHeading').eq(AnimIndex).fadeIn("slow");
	//	});
	    }
	    else{
		
		$('.slide').eq(AnimIndex).find('.background').animate({
		  left: '-898px'
		}, {duration:1300});
		
		$('.slide').eq(AnimIndex).find('.foreground').animate({
		  left: '-898px'
		}, {duration:900,queue:false});
		
		$('.showHeading').eq(AnimIndex).fadeIn("slow");
	    }
            processing = false;
        }
        
	switchAutomate();
    };
    
    //skip to slide using thumbnails
    $('.thumbnails li').click(function(event){
        event.preventDefault();
	
	clearInterval(animTimeout);
	    
        AnimIndex = $(this).index('.thumbnails li');
        
	$('.showHeading').fadeOut(function(){
        if(!processing)
        {
            processing = true;
	    $('.overlay').clearQueue().fadeIn(500, function(){
		showImage();
	    });
        }
	});
    });
    
    function switchAutomate(){
	clearInterval(animTimeout);
	animTimeout = setInterval(function(){
	
	if(AnimIndex < $(".thumbnails li").length-1){
	    AnimIndex++;    
	}else{
	    AnimIndex = 0;
	}
	
	$(".thumbnails li").eq(AnimIndex).trigger("click");	
	
	},10000);
	
    }
    
    /**************************************************************
     **************************************************************
     **************************************************************
     **************************************************************
     **************************************************************/

});

function show_subsection(id){
    if($("#"+id+"_sub").length >0){
        $("#"+id+"_sub").css("min-width",$("#"+id).width());
        $("#"+id+"_sub").show();
    }
}

function imageReplacement(){

    var iSelect= $("select.replaceme");
    var zIndex = 999;
    $(".selectreplace").remove();
    if(iSelect.length>0){
        $.each(iSelect,function(index,elem){
            var parent = $(this).parent(); //selectbox container

            var menu = $(this).find("option:selected").text(); //option that is selected

            if($(this).hasClass("wide_sel")){
                parent.append('<div class="selectreplace wide_sel" id="select_'+index+'"><p>'+menu+'</p></div>');//append image replacement box
            }else{
                parent.append('<div class="selectreplace" id="select_'+index+'"><p>'+menu+'</p></div>');//append image replacement box
            }

            parent.find("#select_"+index).append("<div class='subber'></div>");//insert dropdown box



            parent.find("#select_"+index).css("z-index",zIndex);
            zIndex--;

                $(this).find("option").each(function(i,e){
                var cls="";
                if("country"==$(this).attr("class")){
                    cls="class='country'";
                }
                $("#select_"+index).find(".subber").append('<div class="sub whitereplace" id="option_'+i+'"><p '+ cls+'>'+$(this).text()+"</p></div>");
            });           


            $(this).hide();
        });

    }

}

function resetSliderPositions(){
    //get the tab elements
    var tabs = $(".tabbed-content");
    //check which one is active and grab content container width
    var contentWidth = $(".tabbed-content").width();


    $(".tabs-content").width($(".tab-content-container:visible").width());
    $(".tab-content-container").each(function(){
        var slider = $(this).find(".tab-content-slider");
        $(this).height(slider.find(".tabs-content:visible").eq(0).height());
    });

    $.each(tabs,function(){

        var navs = $(this).find("ul.tabs li");


        $.each(navs,function(i,v){

            //if active is found reposition the content according to the container width
            //and active index number width*index should give accurate position

            if($(this).hasClass("active")){
                //find the slider element
                var slider = $(this).parent().parent().parent().find(".tab-content-slider");
                slider.css("left","-"+(contentWidth*i)+"px");
            }


        });

    });


}


function switchSelect(select_index,option_index){
    var selectbox = $("select").eq(select_index);
    selectbox.find("option").removeAttr("selected"); //remove all selected values there might be
    selectbox.find("option").eq(option_index).attr("selected","selected");
}
