$(document).ready(function () {

    initVideoPlayer();
    initHero();
    initRideGuide();
    initCrossSite();
    initGasCalculator();
	initTracking();
});


/*
Function: initGlobal
   
Initializes global elements
   
Parameters:
none
   
*/
var initGlobal = function () {
}

/*
Function: Trip
   
Define Trip class
   
Parameters:
none
   
*/


var Trip = function () {
    this.milesTraveled = 0;
    this.milage = 0;
    this.gasPrice = 0.0;
    this.parkingCost = 0;
    this.dailyTripFare = 0;

    this.CurrencyFormatted = function (amount) {
        var i = parseFloat(amount);
        if (isNaN(i)) { i = 0.00; }
        var minus = '';
        if (i < 0) { minus = '-'; }
        i = Math.abs(i);
        i = parseInt((i + .005) * 100);
        i = i / 100;
        s = new String(i);
        if (s.indexOf('.') < 0) { s += '.00'; }
        if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
        s = minus + s;
        return s;
    }

    this.getTripFare = function (transitSystem) {
        transitSystem = transitSystem.toLowerCase();
        switch (transitSystem) {
            case 'milwaukee':
                return '3.50';
                break;
            case 'ozaukee':
                return '4.70';
                break;
            case 'racine':
                return '3.00';
                break;
            case 'washington':
                return '5.50';
                break;
            case 'waukesha':
                return '3.50';
                break;
            default: return '';

        }
    }

    this.getCosts = function (timeframe) {
        timeframe - timeframe.toLowerCase();
        var results = new Array(3);

        var fixedPerMile = .0537;

        if (isNaN(this.parkingCost)) { this.parkingCost = 0; }

        var drivingCostPerMile = parseFloat((this.gasPrice / this.milage) + fixedPerMile);
        var drivingCostPerDay = parseFloat((drivingCostPerMile * this.milesTraveled)) + parseFloat(this.parkingCost);

        if (timeframe == 'daily') {
            results[0] = this.CurrencyFormatted(drivingCostPerDay);
            results[1] = this.CurrencyFormatted(this.dailyTripFare);
        }
        else if (timeframe == 'weekly') {
            results[0] = this.CurrencyFormatted(drivingCostPerDay * 5);
            results[1] = this.CurrencyFormatted(this.dailyTripFare * 5);
        }
        else if (timeframe == 'annually') {
            results[0] = this.CurrencyFormatted(drivingCostPerDay * 5 * 52);
            results[1] = this.CurrencyFormatted(this.dailyTripFare * 5 * 52);
        }
        else {
            results[0] = this.CurrencyFormatted(0);
            results[1] = this.CurrencyFormatted(0);
        }

        results[2] = this.CurrencyFormatted(parseFloat(results[0] - results[1]));

        if (results[2] < 0) { results[2] = 0; }

        return results;
    }

}

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    }
}

/*
Function: initGasCalculator
   
Initializes Gas Calculator
   
Parameters:
none
   
*/
var initGasCalculator = function () {


    var step = 1;
    var thisTrip = new Trip();

    // initialize display
    $('.gas-panel').hide();
    $('.reset').hide();
    $('.error-message').hide();
    $('#calculate-costs').show();

    $('.continue').click(function (e) {
        e.preventDefault();
        if (step == 1) {
            //validate
            $('.gas-panel .error').removeClass('error');
            $('.error-message').hide();
            if (isNaN($('#miles-traveled').val()) || $('#miles-traveled').val().trim() == '') { $('#miles-traveled').addClass('error'); }
            if (isNaN($('#mileage').val()) || $('#mileage').val().trim() == '') { $('#mileage').addClass('error'); }
            if (isNaN($('#gas-price').val()) || $('#gas-price').val().trim() == '') { $('#gas-price').addClass('error'); }
            if (isNaN($('#parking-cost').val()) || $('#parking-cost').val().trim() == '') { $('#parking-cost').val('0.00'); }

            if ($('.error').length > 0) { $('.error-message').show(); }
            else {
                //calculate
                thisTrip.milesTraveled = parseFloat($('#miles-traveled').val());
                thisTrip.milage = parseFloat($('#mileage').val());
                thisTrip.gasPrice = parseFloat($('#gas-price').val());
                thisTrip.parkingCost = parseFloat($('#parking-cost').val());
                
                //update
                $('.gas-panel').hide();
                $('#compare-to-bus').show();
                $('#compare-nav').addClass('current');
                $('#calc-costs-nav').removeClass('current');
                $('#calc-costs-nav').addClass('complete');
                $('.reset').show();
                
                step = 2;
            }
        } else if (step == 2) {
            //validate
            $('.gas-panel .error').removeClass('error');
            $('.error-message').hide();
            if (isNaN($('#daily-trip-fare').val()) || $('#daily-trip-fare').val().trim() == '' || parseFloat($('#daily-trip-fare').val()) <= 0) { $('#daily-trip-fare').addClass('error'); }
            if ($('.error').length > 0) { $('.error-message').show(); }
            else {
                //calculate
                thisTrip.dailyTripFare = parseFloat($('#daily-trip-fare').val());

                //update
                $('.gas-panel').hide();
                $('#view-savings').show();
                $('#compare-nav').removeClass('current');
                $('#compare-nav').addClass('complete');
                $('#savings-nav').addClass('current');

                var daily = thisTrip.getCosts('daily');
                var weekly = thisTrip.getCosts('weekly');
                var annually = thisTrip.getCosts('annually');

                $('.first td:eq(0)').html('$' + daily[0]);
                $('.first td:eq(1)').html('$' + daily[1]);
                $('.first td:eq(2)').html('$' + daily[2]);

                $('.middle td:eq(0)').html('$' + weekly[0]);
                $('.middle td:eq(1)').html('$' + weekly[1]);
                $('.middle td:eq(2)').html('$' + weekly[2]);

                $('.last td:eq(0)').html('$' + annually[0]);
                $('.last td:eq(1)').html('$' + annually[1]);
                $('.last td:eq(2)').html('$' + annually[2]);

                $('.annual-savings').html('$' + annually[2]);

                $('#share-results').show();
                $('#want-to-save-more').show();
                $('#legal').show();
                $('.continue').hide();

                
                step = 3;
            }
        } else if (step == 3) {
            $('.gas-panel .error').removeClass('error');
            $('.error-message').hide();
            
            step = 3;
        }
    });

    $('#select-system').change(function () {
        $('#daily-trip-fare').val(thisTrip.getTripFare($(this).val()));
    });

    $('.reset').click(function (e) {
        e.preventDefault();

        $('.gas-panel').hide();
        $('#calculate-costs').show();
        $('#gas-calc-progress li').removeClass('complete');
        $('#gas-calc-progress li').removeClass('current');
        $('#calc-costs-nav').addClass('current');
        $('.reset').hide();
        $('#share-results').hide();
        $('#want-to-save-more').hide();
        $('#legal').hide();
        $('.continue').show();
        $('.error-message').hide();
        step = 1;
    });

    $('#calc-costs-nav a').click(function (e) {
        e.preventDefault();

        $('.gas-panel').hide();
        $('#calculate-costs').show();
        $('#gas-calc-progress li').removeClass('current');
        $('#gas-calc-progress li').removeClass('complete');
        $(this).parent().addClass('current');
        $('.reset').hide();
        $('#share-results').hide();
        $('#want-to-save-more').hide();
        $('#legal').hide();
        $('.continue').show();
        step = 1;
    });

    $('#compare-nav a').click(function (e) {
        e.preventDefault();
        if (step > 2) {

            $('.gas-panel').hide();
            $('#compare-to-bus').show();
            $('#gas-calc-progress li').removeClass('current');
            $('#gas-calc-progress li').removeClass('complete');
            $('#calc-costs-nav').addClass('complete');
            $(this).parent().addClass('current')
            $('#share-results').hide();
            $('#want-to-save-more').hide();
            $('#legal').hide();
            $('.continue').show();
            step = 2;
        }
    });
    $('#savings-nav a').click(function (e) {
        e.preventDefault();
    });




}


/*
   Function: initHero
   
   Plugin used for home page hero and ride guide
   http://www.slidesjs.com/ for full config options
   
   Parameters:
        none
   
*/
var initHero = function() {
    if ($("#hero").length > 0) {
        $('#hero .slides_container img').css('display', 'block');
        $("#hero").slides({
            generateNextPrev: true,
            preload: true,
            preloadImage: '/_images/ajax-loader-sm.gif',
            play: 5000,
            pause: 2500,
            hoverPause: true,
            pagination: false,
            generatePagination: false,
            slideSpeed: 900,
            animationStart: function(current) {
                $('#hero .caption').animate({
                    "opacity": 0
                }, 1);
            },
            animationComplete: function(current) {
                $('#hero .caption').animate({
                    "opacity": 1
                }, 100);
            }
        });
    }
}


/*
   Function: initRideGuide
   
   Plugin used for home page hero and ride guide
   http://www.slidesjs.com/ for full config options
   
   Parameters:
        none
   
*/
var initRideGuide = function() {
    if ($("#ride-guide").length > 0) {
        $("#ride-guide").slides({
            generateNextPrev: true,
            preload: true,
            preloadImage: '/_images/ajax-loader-sm.gif',
            hoverPause: true,
            slideSpeed: 500
        });
    }
}


/*
Function: initVideoPlayer

    Initializes Video Player.

Parameters:
    
    none
*/
var initVideoPlayer = function() {
    if ($('a.player').length > 0) {
        $f('a.player', { src: '/_flash/flowplayer.commercial-3.2.6.swf', wmode: 'opaque' }, {
            key: '#$b10db3a3f97a97f0227',
            clip: {
                autoBuffering: true,
                accelerated: true,
                bufferLength: 2,
                scaling: "fit",
                eventCategory: 'Commercials',
                // onFinish: function () {
                //    this.getPlugin("play").css({opacity: 100});
                // },
                // onBegin: function() {
                //     this.stop();
                // } 
                onBegin: function() {
                    $(".playlist a.now-playing").removeClass("now-playing");
                    var nowPlaying = $f().getClip().completeUrl;
                    $("a[href='" + nowPlaying + "']").addClass("now-playing");
                }
            },
            canvas: {
                background: '#000000',
                backgroundGradient: 'none'
            },
            plugins: {
                controls: {
                    url: '/_flash/flowplayer.controls-3.2.4.swf',
                    all: false,
                    play: true,
                    mute: true,
                    fullscreen: true,
                    scrubber: true,
                    time: true,
                    volume: true
                },
                sharing: {
                    url: '/_flash/flowplayer.sharing-3.2.0.swf'
                },
                gatracker: {
                    url: '/_flash/flowplayer.analytics-3.2.2.swf',
                    debug: false,
                    events: {
                        all: true
                    },
                    //trackingMode: 'Bridge',
                    accountId: 'UA-195174-26'
                }
            }
        });

        // update player video from anchors within the playlist UL
        var player = $f();
        $("ul.playlist a[href*='.flv']").click(function(event) {
            event.preventDefault();
            var video = $(this).attr('href');
            player.play(video);
        });
        
        // set available video count
        var videoCount = $('ul.playlist li').length;
        $('span.video-count').html(videoCount + " videos available");
        
        // set width for playlist
        var playlistWidth = 0;
        $('ul.playlist li').each(function() {
            playlistWidth += $(this).outerWidth(true);
        });
        $('ul.playlist').css('width', playlistWidth);
    }
}


/*
Function: initTracking

    Initializes additional Google Analytics.

*/
var initTracking = function() {
    //external links
    $("a[href^='http:']").not("[href*='yourotherwheels.com']").click(function(e) {
        _gaq.push(["_trackEvent", "ExternalLink", "Link", $(this).attr('href')]);
    });

    //PDFs
    $("a[href*='.pdf']").click(function(e) {
        _gaq.push(["_trackEvent", "PDF", "Download", $(this).attr('href')]);
    });
}

var initCrossSite = function() {
    $('#cross-site').change(function(data) {
        document.location = $(this).val();
    });
}
