﻿//functions in alphabetical order

function cufonCalls() {
    //add a span for tabs
    $('.navigation-top td a').each(function() {
        if ($(this).html() == "GAS PROMOTIONS") $(this).html('PROMOTIONS');
        if ($(this).html() == "GAS STATION LOCATIONS") $(this).html('LOCATIONS');
        if ($(this).html() == "GAS CREDIT CARDS") $(this).html('CREDIT CARDS');
    });
    $('.tabs li a').each(function() {
        $(this).find('span').clone().appendTo(this);
        $(this).find('span:nth-child(2)').addClass('hovered');
    });
    Cufon.replace(['.navigation-top-utils a'], {
        fontFamily: 'GothamCondensed',
        hover: {
            textShadow: '0px 0px #555555'
        }
    });
    Cufon.replace(['.logo, .boiler h1, .close,  .replace-normal'], {
        fontFamily: 'Gotham',
        hover: true
    });
    Cufon.replace(['.logo, .navigation-bottom a .title, #slides .cta'], {
        fontFamily: 'Gotham'
    });
    Cufon.replace(['.navigation-top, .navigation-tiny a, h4, .boiler h2, .navigation-top-utils .submit, #finder_tabs a span, .replace-condensed'], {
        fontFamily: 'GothamCondensed',
        hover: true
    });
    Cufon.replace(['#weather_tabs a span, .replace-black'], {
        fontFamily: 'GothamBlack',
        hover: true
    });
    Cufon.replace(['h3'], {
        fontFamily: 'Filmotype LaSalle',
        hover: true
    });
    /*advertising*/
    Cufon.replace(['.small-title'], {
        fontFamily: 'GothamCondensed',
        textShadow: '1px 1px 3px #555555'
    });
    Cufon.replace(['.category'], {
        fontFamily: 'Gotham',
        textShadow: '1px 1px 3px #555555'
    });
    Cufon.replace(['#basketPongRulesContainer h2, #basketPongRulesContainer a.back '], {
        fontFamily: 'Gotham',
        hover: true
    });
    $('.navigation-bottom a').each(function(index) {
        $(this).hover(
			function() {
			    Cufon.replace(['.navigation-bottom a:nth-child(' + (index + 1) + ') .title'], { fontFamily: 'Gotham', color: '#ffffff' });
			},
			function() {
			    Cufon.replace(['.navigation-bottom a:nth-child(' + (index + 1) + ') .title'], { fontFamily: 'Gotham', color: '#dfdfe1' });
			}
		);
    });
}

function documentBack() {
    var referrerURL = document.referrer;
    var referrerDomain = referrerURL.split("/")[2];
    var documentDomain = document.domain;
    $("#back_button.close").click(function() {
        if (referrerDomain == documentDomain) {
            history.go(-1);
        }
        else {
            window.location = "http://" + documentDomain;
        }
    });
}

function hideLocationTabErrors() {
    var $content = $('#finder');
    var $errors = $content.find('ul.errors');
    $errors.empty().hide();
    $content.animate({ height: "290px" }, 200, function() { });
}

function horizontalSlide(element, inner) {
    $(element).each(function(index) {
        var outer_width = $(this).width();
        var inner_width = $(this).find(inner + ":nth-child(1)").outerWidth(true);
        var total = $(this).find(inner).length;
        var mover = $(element).find(".slidemotion");

        if (total * inner_width > outer_width) {
            mover.css({ 'position': 'absolute', 'left': 0 });
            mover.css({ 'width': inner_width * total + 'px' });
            var slideAnimation = setInterval("horizontalSlideMe('" + element + "', '" + inner + "')", 75);
        }
        else {
            //center
            var marginOffset = parseFloat($(this).find(inner + ":first").css("marginLeft"));
            $(this).find(inner + ":first").css({ 'margin-left': ((outer_width - (inner_width * total)) / 2 + marginOffset) + "px" });
        }
    });
}
function horizontalSlideMe(element, inner) {
    $(element).each(function() {
        var padded_shift = 100;
        var speed_adjust = 7;
        if (mouse_y > $(element).offset().top + $(element).height()) {
            speed_adjust += (mouse_y - $(element).offset().top - $(element).height()) / 8;
        }
        else if (mouse_y < $(element).offset().top) {
            speed_adjust += ($(element).offset().top - mouse_y) / 8;
        }

        //copied from above, because it's easier than passing with a setTimeout
        if (speed_adjust < 30) {
            var inner_width = $(this).find(inner + ":nth-child(1)").outerWidth(true);
            var total = $(this).find(inner).length;
            var mover = $(element).find(".slidemotion");
            var outer_padding = parseFloat($(this).css("paddingLeft"));
            var range = (inner_width * total) - $(this).width();
            var adjusted_shift = (mouse_x - $(element).offset().left - padded_shift) / ($(this).width() - (padded_shift * 1.5));
            if (adjusted_shift <= 0) { adjusted_shift = 0; }
            else if (adjusted_shift >= 1) { adjusted_shift = 1; }
            var targ_x = -(adjusted_shift * range) + outer_padding;
            var slide_x = parseFloat(mover.css('left'));
            slide_x -= (slide_x - targ_x) / speed_adjust;
            slide_x = slide_x + "px";
            mover.css({ 'left': slide_x });
        }
        //$('.blackout').html(speed_adjust + ' ');
    });
}

function getCurrentScroll() {
    var current = $('html').scrollTop();
    if ($('body').scrollTop() > current) current = $('body').scrollTop();
    return current
}

function navigationTop() {
    var registerDropped = false;
    $('.navigation-top-utils a .icon').css({ 'transform': 'scale(0.75)' });
    $('.navigation-top-utils a.find-p66').hover(function() {
        $(this).find('.icon').stop().animate({ scale: 1 }, 200);
    },
	function() {
	    $(this).find('.icon').stop().animate({ scale: 0.75 }, 200);
	});
    $('.navigation-top td').css({ 'width': (100 / $('.navigation-top td').length) + '%' }); //sets top nav to uniform widths
    //track
    $('.navigation-top td a').click(function() {
        _gaq.push(['_trackEvent', 'TopNavigation', $(this).attr("href").replace(".aspx", "")]);
    });
    $('a.find-p66').click(function() {
        _gaq.push(['_trackEvent', 'TopNavigation', 'findstation']);
    });
    $('.navigation-bottom a').click(function() {
        _gaq.push(['_trackEvent', 'BottomNavigation', $(this).attr("href").replace(".aspx", "")]);
    });
}

function offerTracking() {
    //track
    $('.promotions .card a').click(function(e) {
        //_gaq.push(['_trackEvent', 'Promotions', $(this).attr("class")]);
        trackclick(this, 'Promotions', $(this).attr("class"));
        e.preventDefault();
    });
    $('.creditcard .card a').click(function(e) {
        _gaq.push(['_trackEvent', 'CreditCards', $(this).attr("class")]);
    });
}

function onAfter(curr, next, opts) {
    var index = opts.currSlide;
    $('#prev')[index == 0 ? 'hide' : 'show']();
    $('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
}
function ourGasDemo() {
    if ($('.ourgas').length > 0) {
        $('.video-disc').hide();
        $("#demo").css({ 'opacity': 0, 'left': '-999em' });
        $("#demo a").each(function() {
            $(this).click(function(e) {
                e.preventDefault();
            });
        });
        var fireComplete = false;
        $("#intro").click(function(e) {
            e.preventDefault();
            //track
            _gaq.push(['_trackEvent', 'OurGasDemo', 'Start']);

            $("#demo-1, #demo-2, #demo-3").css({ 'opacity': 0 });
            $("#intro").fadeOut(200);
            $("#demo p").css({ 'opacity': 0 });
            $("#demo").delay(100).css({ 'left': 0 }).animate({ "opacity": 1 }, 500);

            ourGasEnginepart('#engine_part_top', '#shadowpart_top', 0, 0);
            ourGasEnginepart('#engine_part_mid', '#shadowpart_mid', 0, 0);
            ourGasEnginepart('#engine_part_btm', '#shadowpart_btm', 0, 0);

            if (iOS) $(".video-mask").append('<img src="images/ourgas/video_play_btn.png" />');

            $("#demo-1, #demo-2, #demo-3").delay(1500).animate({ "opacity": 1 }, 500, "easeOutQuad", function() {
                //complete, add clicks and fire video 1
                if (fireComplete == false) {
                    fireComplete = true;
                    ourGasShowVideo("#video_demo_1");
                    $("#demo a").each(function() {
                        $(this).click(function(e) {
                            e.preventDefault();
                            ourGasShowVideo($(this).attr('href'));
                        });
                    });
                }
            });
        });
    }
}
function ourGasEnginepart(element, shadow, x_final, y_final) {
    if (!jQuery.support.opacity) {
        //set BG pngs to inline 'filter' images
        var bg_url1 = $(shadow).css("background-image").replace("url(", "").replace(")", "");
        $(shadow).css({ "filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + bg_url1 + ",sizingMethod='scale')", "background-image": "none" });
        var bg_url2 = $(element + " .normalpart").css("background-image").replace("url(", "").replace(")", "");
        $(element + " .normalpart").css({ "filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + bg_url2 + ",sizingMethod='scale')", "background-image": "none" });
    }
    $(element).find(".normalpart").css({ 'opacity': 0 }).delay(1600).css({ 'opacity': 1 });
    $(shadow).css({ 'opacity': 0 }).animate({ "opacity": 1 }, 800).delay(800).animate({ "opacity": 0 }, 1000);
    $(element).animate({ left: x_final, top: y_final }, 1500, "easeInOutQuart", function() {
        $(element + " .shadowpart").fadeOut(200);
    });
}
function ourGasShowVideo(element) {
    //track
    _gaq.push(['_trackEvent', 'OurGasDemo', element.substr(1)]);
    $("#demo p").animate({ 'opacity': 0 }, 300);
    $('.video-disc').hide();
    $(".video-background").empty();
    $(element).fadeIn(600, "easeOutQuad", function() {
        var video_dir = "../video/";
        var video_url = video_dir + $(element).find("p").attr('class');
        var video_url_flv = video_url + '.flv';
        var video_tag_dir = "media/video/";
        var video_tag_url = video_tag_dir + $(element).find("p").attr('class');
        var fp_version = swfobject.getFlashPlayerVersion();

        $("#demo p").html($(element).find("p").html());
        $(element).find(".video-background").empty();
        $(element).find(".video-background").append('<div id="video_holder"></div>');
        if (fp_version["major"] >= 9) {
            swfobject.embedSWF("media/swf/ourgas_smallvideo.swf", "video_holder", "164", "164", "10.0.0", false, { videoURL: video_url_flv }, { wmode: "transparent" }, null);
        }
        else {
            $('#video_holder').append(
				'<video preload="auto" width="164" height="164" autoplay="autoplay">' +
				'<source src="' + video_tag_url + '.ogv" type="video/ogg" />' +
				'<source src="' + video_tag_url + '.mp4" type="video/mp4" />' +
				'</video>'
			);

        }
        $("#demo p").animate({ 'opacity': 1 }, 500, function() {
        });
    });

    if (iOS) {
        $('.video-mask').click(function(e) {
            e.preventDefault();
            var theVideo = $('#video_holder').find('video');
            $(this).find("img").hide();
            theVideo.bind("ended", function(e) {
                $(".video-mask img").show();
            });
            theVideo.load();
            theVideo.play();
        });
    }
}

function slidesStart() {
    $('.welcome #slides').slides({
        preload: true,
        preloadImage: 'img/loading.gif',
        firstPlay: 16000,
        play: 7000,
        pause: 3000,
        hoverPause: true,
        slideEasing: "easeInOutQuart",
        slideSpeed: 800
    });
    $(".promotions .pagination li").each(function(index) {
        //if (index == 0) $(this).css({'display':'none'});
        $(this).addClass("icon-" + index);
    });
    $(".pagination").each(function() {
        $(this).css({ "margin-left": "-" + (($(this).width() / 2) - 15) + "px" });
    });
    //track
    $("#slides .slide a").click(function(evt) {

        //if link is the personal card link on the marquee
        if ($(this).hasClass("personalCardMarquee")) {
            trackclick(this, 'HomeMarquee', 'personal-card');
            evt.preventDefault();
        } else {

            //_gaq.push(['_trackEvent', 'HomeMarquee', $(this).parent().parent().attr("class").replace("slide", "")]);

            //to delay transition to other page
            trackclick(this, 'HomeMarquee', $(this).parent().parent().attr("class").replace("slide", ""));
            evt.preventDefault();
        }
    });
}

//Initialize calls

var mouse_x;
var mouse_y;
var slide_paused = false;
var video_up = false;
var iOS = false;
if (navigator.userAgent.match(/like Mac OS X/i)) {
    iOS = true;
}
$(document).ready(function() {
    $(document).mousemove(function(e) {
        mouse_x = e.pageX;
        mouse_y = e.pageY;
    });
    cufonCalls();
    documentBack();
    navigationTop();
    initRegister();
    ourGasDemo();
    slidesStart();
    horizontalSlide("#slideblock", ".icon");
    var tabs = $('#finder, #finder-weather').tabs({ select: hideLocationTabErrors });
    offerTracking();
});
