$(document).ready(function() {
    initGlobal();
});

/*
   Function: initGlobal
   
   Initializes global elements
   
   Parameters:
        none
   
*/

var initGlobal = function() {

    initTracking();
    
    // Split ULs in .second-level-content
    $(".second-level-content ul").each(function() {
        if ($(this).children("li").length > 1) {
            var second = $(this).clone();
            var first = $(this).clone();
            first.children(":even").remove();
            second.children(":odd").remove();
            $(this).after(first).after(second);
            $(this).remove();
        }
    });

    // build out captions based on alt tags
    // TODO: if alt text contains [caption] remove [caption] and fire jcaption

    $('#content img.caption').jcaption();

    // add .last to small content excerpt last container
    $('#content .subfeature:last').addClass("last");
}

/*
   Function: initHero

   Initializes home page Hero module.

   Parameters:

      autoplay - Boolean value for autoplay
      delay - Number of milliseconds to waut before moving to the next slide

*/

var initHero = function(autoplay, delay){
	var currentSlide = 1;
	var totalSlides = 3;
	
	// bind click action for controls
	$("#hero-controls a").click(function(e) {
	e.preventDefault();
	//clearInterval(animLoop);
		var slideNumber = $(this).attr("id").replace("control-","");
		if(slideNumber != currentSlide){
			$("#hero-slide-" + slideNumber).fadeIn("slow");
			$("#hero-slide-" + currentSlide).fadeOut("slow");
			$("#hero-controls li").removeClass("current");
			$(this).parent().addClass("current");
			currentSlide = slideNumber;
		}
	});
	
	// animate before hovered
	if(autoplay === true){
		animLoop = window.setInterval(
						function(){
									var nextSlide = parseInt(currentSlide)+1;
									if(nextSlide>totalSlides){nextSlide = 1;}
									$("#hero-controls #control-" + nextSlide).click();
								  },
						delay
					);
		
		// stop animation on hover
		$("#homepage-hero").hover(function(){
			clearInterval(animLoop);	
		});
	}
}


/*
   Function: initHistory

   Initializes History module.

   Parameters:

		none
*/

var initHistory = function() {
    var currentSlide = 1;
    var slideWidth = 787;
    var totalSlides = 6;
    var nudge = 12;
    var speed = 1000;

    // bind click actions for year controls
    $("#history-controls a").click(function(e) {
        e.preventDefault();
        currentSlide = $(this).attr("id").replace("control-", "");
        var newOffset = parseInt((currentSlide * slideWidth) - slideWidth);
        var wrapperOffset = $(this).parent().parent().offset().left;
        var buttonOffset = $(this).offset().left - ($(this).parent().width());
        if (buttonOffset < parseInt(19 + wrapperOffset)) {
            buttonOffset = 19;
        } else {
            buttonOffset = parseInt(buttonOffset + nudge - wrapperOffset);
        }
        $("#history-timeline").animate({
            left: "-" + newOffset + "px"
        }, speed, 'easeOutCubic');

        if (navigator.appName == 'Microsoft Internet Explorer') {
            $("#history-controls ul").animate({
                backgroundPositionX: buttonOffset + "px"
            }, speed, 'easeOutCubic');
        }
        else {
            $("#history-controls ul").animate({
                backgroundPosition: buttonOffset + "px 17px"
            }, speed, 'easeOutCubic');
        }

        if (currentSlide >= totalSlides) {
            $("#arrow-control-right").hide();
        } else {
            $("#arrow-control-right").show();
        }

        if (currentSlide <= 1) {
            $("#arrow-control-left").hide();
        } else {
            $("#arrow-control-left").show();
        }
    });

    //bind click actions for arrow controls
    $("#arrow-control-left").click(function(e) {
        e.preventDefault();
        if (currentSlide > 1) {
            var prevSlide = currentSlide - 1;
            $("#control-" + prevSlide).click();

        }
    });

    $("#arrow-control-right").click(function(e) {
        e.preventDefault();
        if (currentSlide < totalSlides) {
            var nextSlide = parseInt(currentSlide) + 1;
            $("#control-" + nextSlide).click();

        }
    });
    $("#arrow-control-right a").focus(function() {
        $(this).addClass("focus");
    });
    $("#arrow-control-right a").blur(function() {
        $(this).removeClass("focus");
    });

}



/*
   Function: initVideoPlayer

   Initializes Video Player.

   Parameters:

		controlOffset - Integer value for the bottom offset position of the video control bar
*/

var initVideoPlayer = function(controlOffset) {
    
    // setup video player 
    $f(".video-player", { src: '/cmn/flash/flowplayer.commercial-3.2.5.swf', wmode: 'opaque' }, {

        key: '#$45b5d9fd14d89f04734',
    	play: { // use custom play button
    		url: '/App_Themes/Main/images/video-control-play.png',
    		width: 99,
    		height: 99  
    	},
        plugins: {
            controls: {
                "timeColor": "#ffffff", "borderRadius": "0px", "bufferGradient": "none", "slowForward": true, "backgroundColor": "rgba(102, 102, 102, 1)", "volumeSliderGradient": "none", "slowBackward": false, "timeBorderRadius": 0, "time": true, "progressGradient": "none", "height": 28.65, "tooltips": { "marginBottom": 5, "volume": true, "scrubber": true, "buttons": false }, "fastBackward": false, "opacity": 1, "border": "0px", "volumeSliderColor": "#ffffff", "bufferColor": "#000000", "buttonColor": "#ffffff", "mute": true, "autoHide": { "enabled": true, "hideDelay": 2000, "hideStyle": "fade", "mouseOutDelay": 500, "hideDuration": 400, "fullscreenOnly": false }, "backgroundGradient": "none", "width": "100pct", "display": "block", "buttonOverColor": "rgba(108, 88, 6, 1)", "url": "/cmn/flash/flowplayer.controls-3.2.3.swf", "fullscreen": true, "timeBgColor": "#000000", "scrubberBarHeightRatio": 0.4, "bottom": 0, "stop": false, "sliderColor": "#9e9e9e", "zIndex": 1, "scrubberHeightRatio": 0.7, "tooltipTextColor": "rgba(108, 88, 6, 1)", "sliderGradient": "none", "timeBgHeightRatio": 0.99, "volumeSliderHeightRatio": 0.4, "name": "controls", "volumeBarHeightRatio": 0.2, "left": "50pct", "tooltipColor": "#C9C9C9", "playlist": false, "durationColor": "rgba(108, 88, 6, 1)", "play": true, "fastForward": true, "progressColor": "#ffffff", "timeBorder": "1px solid rgba(0, 0, 0, 0.3)", "volumeBorderRadius": 0, "scrubberBorderRadius": 0, "volume": false, "scrubber": true, "builtIn": false, "bottom": controlOffset
            }, // controls
            gatracker: { // http://flowplayer.org/plugins/flash/analytics.html - For full config...
                url: "/cmn/flash/flowplayer.analytics-3.2.1.swf",
                labels: {
                    start: "Start",
                    play: "Play",
                    pause: "Pause",
                    resume: "Resume",
                    seek: "Seek",
                    stop: "Stop",
                    finish: "Finish",
                    mute: "Mute",
                    unmute: "Unmute",
                    fullscreen: "Full Screen",
                    fullscreenexit: "Full Screen Exit"
                },
                debug: false,
                trackingMode: "Bridge",
                googleId: "UA-195174-31"
            } //google analytics
        } // plugins
    }).each(function() {
        this.ipad(); //initialize ipad plugin that allows video to play in place.
    });

} // End initVideoPlayer


/*
Function: initTracking

Initializes additional Google Analytics.

*/
var initTracking = function() {
    //external links
    $("a[href^='http:']").not("[href*='mooreoil.com']").click(function(e) {
        _gaq.push(["_trackEvent", "External_Links", "Click", $(this).attr('id') + "_" + $(this).attr('href')]);
    });

    //downloads
    $("a[href*=.pdf]").click(function(e) {
        _gaq.push(["_trackEvent", "Downloads", "Click", $(this).attr('id') + "_" + $(this).attr('href')]);
    });

    //mailto links

    $("a[href^='mailto:']").click(function(e) {
        _gaq.push(["_trackEvent", "Mailto_Links", "Click", $(this).attr('id') + "_" + $(this).attr('href')]);
    });

    //homepage hero
    $('#homepage-hero a').click(function(e) {
        _gaq.push(["_trackEvent", "Homepage Hero", "Click", $(this).attr('id') + "_" + $(this).attr('href')]);
    });

    //brands feature 
    $('.brands-preview').click(function(e) {
        _gaq.push(["_trackEvent", "Brands Feature", "Click", $(this).attr('id') + "_" + $(this).attr('href')]);
    });

}   // End initTracking

