// Fix US style date formatting for Chrome
$.validator.methods["date"] = function (value, element) { return true; } 

$.fn.checkEmail = function () {
    var o = $(this[0]); // the html element
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

    var email = $(o).val()

    return filter.test(email);
}

jQuery(document).ready(function () {
	// accordion script
	jQuery('.accordion .head').click(function () {
		if (jQuery(this).hasClass("active")) {
			jQuery(this).removeClass("active");
		} else {
			jQuery(this).addClass("active");
		}
		jQuery(this).next().slideToggle('slow');
		return false;
	}).next().hide();
	// open the first accordion
	jQuery('.accordion .head:first').click();
});


jQuery(document).ready(function () {

    // GA

    // GA - Ticket Page -> Ticket Module - Annual Pass

    jQuery(".page").delegate(".ticket-button", "click", jQuery.proxy(function (event) {
        var button = jQuery(event.currentTarget);
        var category = "Button - Purchase Intention";
        var actions = button.parent().find(".ticket-name").text();
        var label = window.location.href;
        var href = button.find("a").attr("href");

        //_trackEvent("Purchase Intention", Name of Ticket Type, Name of Button CTA, URL of the page)
        _gaq.push(["_trackEvent", category, actions, label]);
        _gaq.push(function () {
            var pageTracker = _gat._getTrackerByName(); // Gets the default tracker.
            var linkerUrl = pageTracker._getLinkerUrl(href);
            window.location.href = linkerUrl;
        });
        //_gaq.push(['_link', href, false]);

        //_gaq.push(function() { window.location.href = href; });

        return false;
    }, this));


    // GA Generic CTA Tile Tracking
    jQuery(".page").delegate(".cta.tile a", "click", jQuery.proxy(function (event) {
        var ctaButton = jQuery(event.currentTarget);
        var ctaContainer = ctaButton.parents(".cta");
        var category = "Promo Click - Purchase Intention";
        var actions = ctaContainer.attr("data-action");
        var label = window.location.href;
        var href = ctaButton.attr("href");

        _gaq.push(["_trackEvent", category, actions, label]);
        _gaq.push(function () { window.location.href = href; });

        return false;

    }, this));


    // GA - A Feature
    jQuery("#feature").delegate(".cta a", "click", jQuery.proxy(function (event) {
        var featureButton = jQuery(event.currentTarget);
        var item = featureButton.parents(".item");

        var category = "Promo Click - A Feature";
        var actions = item.find(".cta .title").text();
        var label = window.location.href;
        var href = featureButton.attr("href");

        _gaq.push(["_trackEvent", category, actions, label]);
        _gaq.push(function () { window.location.href = href; });

        return false

    }, this));

    // GA - Social Media
    jQuery("#social-media a").click(function () {
        var href = jQuery(this).attr("href");

        var category = "Social Site Click Through";
        var actions = "";

        if (href.indexOf("facebook.com") > 0) {
            actions = "FB";
        } else if (href.indexOf("twitter.com") > 0) {
            actions = "TWTR";
        }
        
        var label = window.location.href;

        _gaq.push(["_trackEvent", category, actions, label]);
        _gaq.push(function () { window.location.href = href; });

        return false;
    });

});


/* Author: Jeremy Manoto

*/

/**
* Loads a file from a Url.
* @param {String} url Template to load
*/
var LoadTemplate = function (url) {
	var template = jQuery.ajax({
		url: url,
		cache: true,
		success: function () {
		},
		async: false
	}).responseText;

	return template;
}



var FeatureSlider = base2.Base.extend({
	constructor: function (options) {
		this.SetOptions(options);
		this.LoadTemplates();
		this.SetEvents();
		this.SetItems();
		this.Cleanup();
	},

	Defaults: {
		TimerInterval: 5000,
		TransitionSpeed: 2000,
		ContainerSlider: ".slider",
		ContainerThumbnails: ".thumbnails",
		DefaultItems: null,
		StartIndex: 0,
		ThumbnailItemWidth: 70,
		TitleOffsetX: 0,
		TitleOffsetY: 0,

		TemplateFeatureItem: "/templates/template_feature_item.html",
		TemplateFeatureCTA: "/templates/template_feature_cta.html"
	},

	Container: null,

	Timer: null,

	ThumbnailScrolling: null, // used for scrolling the thumbnails

	CurrentIndex: null,

	Templates: {},

	IsStarted: false, // determines if the feature slider has been started.

	// List of items
	Items: new base2.Array2(),

	// INITIALISATION
	SetOptions: function (options) {

		this.Options = jQuery.extend({}, this.Defaults, options);
		this.Container = jQuery(this.Options.ContainerSlider);
		this.CurrentIndex = this.Options.StartIndex;

	},

	LoadTemplates: function () {
		this.Templates.FeatureItem = LoadTemplate(this.Options.TemplateFeatureItem);
		this.Templates.FeatureCTA = LoadTemplate(this.Options.TemplateFeatureCTA);
	},

	/* Loads any default supplied items into the array */
	SetItems: function () {
		if (this.Options.DefaultItems) {
			base2.Array2.forEach(this.Options.DefaultItems, jQuery.proxy(function (featureItem) {
				this.AddItem(featureItem);
			}, this));
		}
	},

	// EVENTS
	SetEvents: function () {

		var scroller = this.Container.find(this.Options.ContainerThumbnails); //jQuery("#feature .slider .thumbnails");
		var hiddenY = scroller.height();
		var showY = 0;

		// Set the container hover for thumbnails
		//        this.Container.mouseenter(function (event) {

		//            scroller.stop(true, false).animate({ top: showY });

		//        }).mouseleave(function (event) {

		//            scroller.stop(true, false).animate({ top: -hiddenY });

		//        });


		// Thumbnail Trigger
		this.Container.find(this.Options.ContainerThumbnails).delegate(".thumbnail", "click", jQuery.proxy(function (event) {
			var target = jQuery(event.currentTarget);

			// get the index of the current item
			var targetIndex = target.index();

			this.TransitionTo(targetIndex);

			// stop and start the timer. resets half way timed transitions
			this.Stop();
			this.Start();

		}, this));


		// Thumbnail Scroller
		this.Container.find(this.Options.ContainerThumbnails).delegate(".arrow", "mousedown", jQuery.proxy(function (event) {
			var arrow = jQuery(event.currentTarget);
			var scrollEndX = arrow.parent().find(".items .scroller").width() - arrow.parent().find(".items").width();
			var direction = arrow.hasClass("left") ? "left" : "right";
			var targetX = (direction == "left") ? 0 : scrollEndX;
			console.log("[Feature Thumbnail]: Scrolling to: " + targetX);
			var scroller = arrow.parent().find(".items");
			scroller.animate({ scrollLeft: targetX });

		}, this)).delegate(".arrow", "mouseup", jQuery.proxy(function (event) {
			var arrow = jQuery(event.currentTarget);
			var direction = arrow.hasClass("left") ? "left" : "right";
			console.log("[Feature Thumbnail]: Stop");
			var scroller = arrow.parent().find(".items");
			scroller.stop();

		}, this));
	},

	// ITEMS
	/* Add a FeatureItem to the list to show */
	AddItem: function (featureItem) {

		this.AddItemToDOM(featureItem);
		this.Items.push(featureItem);

		// Determine if the default should show straight away
		if (this.Items.length == 1) {
			featureItem.Element.show().css({ opacity: 1 });
		}

		// Resize thumbnail scroller to fit.
		var thumbnailScroller = this.Container.find(this.Options.ContainerThumbnails).find(".scroller");
		var scrollerWidth = this.Items.length * this.Options.ThumbnailItemWidth;
		if (scrollerWidth < 280) scrollerWidth = 280;
		thumbnailScroller.width(scrollerWidth);


		this.Cleanup();
	},
	/* Creates the item node to add to the DOM */
	AddItemToDOM_OLD: function (featureItem) {

		// MAIN IMAGE
		var itemContainer = jQuery("<div>");
		itemContainer.attr({ 'class': "item" });
		itemContainer.attr({ 'style': "background-image: url(" + featureItem.Options.image + ")" });

		var itemContent = jQuery("<div>");
		itemContent.attr({ 'class': "content" });
		itemContainer.append(itemContent);

		var itemCTA = jQuery("<div>");
		itemCTA.attr({ 'class': 'cta' });
		itemContent.append(itemCTA);
		itemCTA.css({ position: 'relative', left: featureItem.Options.titleOffsetX, top: featureItem.Options.titleOffsetY });

		var itemCTAText = jQuery(featureItem.Options.title);
		itemCTA.append(itemCTAText);

		// var itemCTAImage = jQuery("<img>");
		// itemCTAImage.attr({ 'src': featureItem.Options.titleImage });
		// itemCTA.append(itemCTAImage);

		var itemCTALink = jQuery("<a>");
		itemCTALink.attr({ 'class': 'button', 'href': featureItem.Options.CTALink });

		itemCTALink.append(jQuery("<span>" + featureItem.Options.CTAText + "</span>"))
		itemCTA.append(itemCTALink);

		// Default to hidden
		itemContainer.css({ opacity: 0 }).hide();

		featureItem.Element = itemContainer;

		this.Container.append(itemContainer);


		// THUMBNAIL IMAGE
		var thumbnail = jQuery("<div>");
		thumbnail.attr({ 'class': 'thumbnail' });
		var thumbnailImage = jQuery("<img>");
		thumbnailImage.attr({ 'src': featureItem.Options.thumbnailImage });
		thumbnail.append(thumbnailImage);


		// ACTIVE STATE
		//        var active = jQuery("<div>");
		//        active.attr({ 'class': 'indicator' });
		//        thumbnail.append(active);
		if (this.Items.length >= 1)
			thumbnailImage.fadeTo(0, 0.5);


		var ContainerThumbnailScroller = this.Container.find(this.Options.ContainerThumbnails).find(".scroller");
		ContainerThumbnailScroller.append(thumbnail);

	},

	AddItemToDOM: function (featureItem) {

		var template = jQuery(this.Templates.FeatureItem);

		var item = template.find(".item").css({ backgroundImage: 'url(' + featureItem.Options.image + ')' });

		if (featureItem.Options.title != "") {
			template.find(".title").append(featureItem.Options.title);
			template.find(".cta").css({ position: 'relative', left: featureItem.Options.titleOffsetX, top: featureItem.Options.titleOffsetY });
		} else {
			template.find(".title").remove();
		}

		if (featureItem.Options.CTAText != "") {
			template.find(".button").attr({ href: featureItem.Options.CTALink }).find("span").append(featureItem.Options.CTAText);
			template.find(".cta").css({ display: "block" });
		} else {
			template.find(".button").remove();
		}


		var itemContainer = item;

		featureItem.Element = itemContainer;

		// Hide by default
		featureItem.Element.css({ opacity: 0 }).hide();

		this.Container.append(featureItem.Element);


		// THUMBNAIL IMAGE
		var thumbnail = jQuery("<div>");
		thumbnail.attr({ 'class': 'thumbnail' });
		var thumbnailImage = jQuery("<img>");
		thumbnailImage.attr({ 'src': featureItem.Options.thumbnailImage });
		thumbnail.append(thumbnailImage);




		// ACTIVE STATE
		//        var active = jQuery("<div>");
		//        active.attr({ 'class': 'indicator' });
		//        thumbnail.append(active);
		if (this.Items.length >= 1)
			thumbnailImage.fadeTo(0, 0.5);


		var ContainerThumbnailScroller = this.Container.find(this.Options.ContainerThumbnails).find(".scroller");
		ContainerThumbnailScroller.append(thumbnail);

	},

	// Remove unnecessary markup if not needed eg: CTA text and Nav slider
	Cleanup: function () {
		console.log("[FeatureSlider] - # Items: " + this.Items.length);


		// Remove Thumbnail Navigator if only 1 item in list
		if (this.Items.length <= 1) {
			this.Container.find(this.Options.ContainerThumbnails).css({ display: "none" });
			this.Stop(); // Don't animate
		}
		else {
			this.Container.find(this.Options.ContainerThumbnails).css({ display: "block" });
			if (!this.IsStarted)
				this.Start();

		}

	},

	// TRANSITIONS ANIMATING
	/* Start the iterations over the Feature Items */
	Start: function () {
		this.Timer = setInterval(jQuery.proxy(this.DelegateTransition, this), this.Options.TimerInterval)
		this.IsStarted = true;
	},
	/* Stop the iterations/animation */
	Stop: function () {
		clearInterval(this.Timer);
		this.IsStarted = false;
	},

	/* Transition/Iteration function called by the Timer
	* Handles feature item transitions. 
	*/

	DelegateTransition: function () {

		var currentItem;
		if (!this.CurrentIndex && this.CurrentIndex == null) {
			// We are just STARTING
			currentItem = this.Items[this.Options.StartIndex];
			currentItem.Element.show().stop(true, false).animate({ opacity: 1 }, this.Options.TransitionSpeed);
			this.CurrentIndex = this.Options.StartIndex;
			console.log("[FeatureSlider]: Starting at " + this.CurrentIndex);
		} else {
			var nextIndex = this.CurrentIndex + 1;
			if (nextIndex == this.Items.length) nextIndex = 0; // Loopback around the array

			this.TransitionTo(nextIndex);

		}
	},

	/* Transition the slider to the specified index */
	TransitionTo: function (targetIndex) {
		if (targetIndex == this.Items.length) targetIndex = 0; // Loopback around the array
		var targetItem = this.Items[targetIndex];

		console.log("[FeatureSlider]: Transitioning from " + this.CurrentIndex + " to " + targetIndex);

		// Hide the current showing item
		if (this.CurrentIndex != null) {
			currentItem = this.Items[this.CurrentIndex];
			currentItem.Element.show().stop(true, false).animate({ opacity: 0 }, this.Options.TransitionSpeed, "swing", function () { jQuery(this).hide(); });
		}
		targetItem.Element.show().stop(true, false).animate({ opacity: 1 }, this.Options.TransitionSpeed)

		// Highlight the appropriate thumbnail
		var targetThumbnail = this.Container.find(this.Options.ContainerThumbnails).find(".thumbnail").removeClass("active").eq(targetIndex);
		targetThumbnail.addClass("active");
		//var targetThumbnail = this.Container.find(this.Options.ContainerThumbnails).find(".thumbnail").eq(targetIndex);
		// Fade out the previous thumbnail
		this.Container.find(this.Options.ContainerThumbnails).find(".thumbnail img").fadeTo(this.Options.TransitionSpeed, 0.3).eq(this.CurrentIndex);

		targetThumbnail.find("img").fadeTo(this.Options.TransitionSpeed, 1.0);


		// Sroll to current position
		var scrollContainer = this.Container.find(this.Options.ContainerThumbnails).find(".items");
		var scrollLeft = scrollContainer.scrollLeft();
		var scrollWidth = scrollContainer.width();
		var thumbnailPosX = targetThumbnail.position().left;

		var scrollToPosX = scrollLeft;

		if (thumbnailPosX + targetThumbnail.outerWidth() > scrollLeft + scrollWidth) {
			// SCROLL

			var remainingWidth = scrollContainer.children(".scroller").width() - (scrollLeft + scrollWidth);
			if (remainingWidth < scrollWidth) {
				scrollToPosX = scrollContainer.children(".scroller").width() - scrollWidth;
			}


		} else if (thumbnailPosX < scrollLeft) {
			var scrollToPosX = thumbnailPosX;
		}

		scrollContainer.animate({ scrollLeft: scrollToPosX }, 1000);



		console.log("[FeatureSlider]: Current ScrollLeft: " + scrollContainer.scrollLeft() + " || thumbnail x pos: " + thumbnailPosX);

		this.CurrentIndex = targetIndex;
	}


})


var FeatureItem = base2.Base.extend({
	constructor: function (options) {
		this.SetOptions(options);
	},

	Defaults: {},

	// DATA
	title: "",
	titleImage: "",
	image: "",
	thumbnailImage: "",
	CTAText: "",
	CTALink: "",
	titleOffsetX: "",
	titleOffsetY: "",

	// DOM
	Element: null,

	// INITIALISATION
	SetOptions: function (options) {

		this.Options = jQuery.extend({}, this.Defaults, options);

	}
})
