﻿/***

O2 Priority V5 MVC
2010 www.aislondon.com

***/

(function ($) {

	/* 
	Scope
	This initialises the namespace if it has not been initialised elsewhere
	*/
	$.priority = $.priority || {};

	/*
	Global fields
	Any global objects that you need access to are defined here
	*/
	var g_ready = false;
	var g_self = this;

	/* 
	API methods
	If the class has any API methods then put them here
	(methods that can be called directly on objects e.g. $("body").customMethod();
	*/
	$.fn.preferences = function () {
		return this.each(function () {
			//alert("API method called on " + this);
		});
	};

	/* Class */
	$.priority.init = function (options) {
		var c_self = this;
		var c_ready = false;
		c_self.options = $.extend({}, $.priority.init.defaults, options);

		/*
		Instance methods
		*/
		c_self.functions = {
			interval: function () {
				/*
				Insert tasks to be repeated at set intervals
				*/
				c_self.functions.debuglog("interval event");
				setTimeout(c_self.functions.interval, c_self.options.intervalFrequency);
			},
			initialise: function (context) {
				context.each(function (index) {

				});
			},

			//open all pdf links in a new window, change title attribute of link to reflect this -keep this -MT
			setPDFLinks: function () {
				$("a").filter(function () {
					return this.href.match(RegExp(".pdf|.PDF+\"")) != null
				}).each(function () {
					if ($(this).attr("title") == null) {
						$(this).attr("title", "PDF, opens in a new window");
					};
					$(this).attr("target", "_blank");
				});

			},
			//this might conflict with new tooltips functionality -MT
			configureExternalLinks: function () {
				// Loop through all links that are absolute or with rel="External"
				// don't process ones that go to O2 More pages
				debug("setting external links");
				$("a[rel=\"External\"],a[href^=http]:not([rel=\"External\"])")
				//.filter("a:not([href^=http://www.o2more.co.uk])") - REMOVED AT PM REQUEST AB - JAN 11
                    .filter("a:not([href^=http://staging.aislondon.com])")
                    .filter("a:not([href^=http://www.o2priority.co.uk])")
                    .filter("a:not([href^=http://localhost])")
                    .filter("a:not([rel=Internal])")
                    .each(function () {

                    	//add external for GA -MT
                    	$(this).attr("rel", "External");

                    	// If the URL is definitely external OR its container is "event-bookmark"
                    	if (this.href.indexOf(location.hostname) == -1 || $(this).parent().parent().attr("id") == "event-bookmark") {

                    		if ($(this).attr("class") != "videolink") {
                    			var anchor = $(this);
                    			var titleText = anchor.attr("title") + "";

                    			if (titleText != "" && titleText.indexOf("(opens in a new window)") == -1) {
                    				$(anchor).attr("title", titleText + " (opens in a new window)").attr("target", "_blank");
                    			}
                    			else {
                    				$(anchor).attr("title", "Opens in a new window").attr("target", "_blank");
                    			}

                    		}
                    	}
                    });
			},

			setupSignIn: function () {
				var signInOverlay = $("#signInOverlay");
				var signInBox = $("#divSignInBox");
				var signInMenu = $("#divSignInRegister, #businessOffers");
				var eventSignInLinks = $(".lnkSignIn_Event");

				var nonO2message = $('#divAjaxSignInNoto2');
				if (nonO2message.length == 0) {
					signInBox.find('.userDetails').show();
				} else {
					signInBox.find('.userDetails').hide();
				};

				//only needs it in IE8, no idea what it'll be in IE9 -MT
				if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "8") {
					//alert("in IE8");
					signInBox.find(".form-row .inputContainer").keydown(function (event) {
						//alert(window.event.keyCode);

						if (window.event.keyCode == 13) {
							//prevent default .net from firing
							event.returnValue = false;
							event.cancel = true;

							signInBox.find("input#butSignIn").click();
							return false;
						}
					});
				}

				if (signInMenu.hasClass('signedIn')) {
					dialogClose();
				} else {

	    $("#lnkSignIn, .buttonSignIn").live('click', function () {
						var pageWidth = $(document).width();
						var pageHeight = $(document).height();

						var viewportHeight = $(window).height();

						signInOverlay.css({
							"opacity": 0.8,
							"width": '100%', //width and height are for IE6
							"height": pageHeight
						});

						//signInBox.css({
							//"top": viewportHeight / 2 - signInBox.height() / 2
			            //});

			            var myHeight = signInBox.height();

			            var screenPos = $(window).scrollTop();
			            var boxPos = (viewportHeight / 2) - (myHeight / 2) + screenPos;

			            signInBox.css({
			                "top": boxPos
			            });


						if (signInBox.css("display") == "none") {
							signInOverlay.fadeIn(200);
							signInBox.fadeIn(200);
						}
						else {
							dialogClose();
						}

                        $('#divSignInBox .userDetails').show();
						return false;
					});

					$("#divSignInBox .closeBtn").live('click', function () {
						dialogClose();
						return false;
					});
				};

				eventSignInLinks.live('click', function () {
					var pageNr = $(".pagination-numbers:first").find(".pageNumber").text();
					var signInVal = $("#SignInUrl").val() + "/" + pageNr;
					$("#SignInUrl").val(signInVal);
					signInMenu.find("#lnkSignIn").click();
					return false;
				});

				function dialogClose() {
					signInOverlay.fadeOut(200);
					signInBox.fadeOut(200);
					signInBox.find('.feedback-message').hide();
					signInBox.find('input.input-validation-error').removeClass('input-validation-error');

					var nonO2message = $('#divAjaxSignInNoto2');
					if (nonO2message.length > 0 && nonO2message.is(':visible')) {
						nonO2message.hide();
						signInBox.find('.userDetails').show();
					};
				};

			},

			checkboxSetup: function () {
				var checkBoxContainer = $('.preferences-list').not(".singleCategory");
				if (checkBoxContainer.length > 0) {
					debug('got checkboxes');
					checkBoxContainer.each(function () {

						var checkAllBox = $(this).find("li input.catchAll");
						var childrenBoxes = $("li input", this).not(".catchAll");

						checkAllBox.click(function () {
							debug('click all');
							if ($(this).attr('checked') == true) {
								childrenBoxes.each(function () {
									$(this).attr('checked', true);

								})
							} else {
								childrenBoxes.each(function () {

									$(this).attr('checked', false);
								})
							}
						});

						childrenBoxes.click(function () {
							var allChecked = true;

							childrenBoxes.each(function () {
								if ($(this).attr('checked') == false) {
									allChecked = false;
								}
							});

							if ($(this).attr('checked') == false) {
								debug("this child was checked");
								checkAllBox.attr('checked', false);
							}
							else if ($(this).attr('checked') == true && allChecked == true) {
								debug("this child was unchecked");
								checkAllBox.attr('checked', true);
							}
						});
					});
				}
			},

			setupFAQs: function () {

				var faqsContainer = $("#faq-container");
				if (faqsContainer.length > 0) {
					var faqsItemsHeaders = faqsContainer.find(".faqs-section ul li h3 a");
					var faqsItemsContent = faqsContainer.find(".faqs-section ul li .content");

					faqsItemsHeaders.toggle(function () {

						$(this).addClass("open");
						faqsItemsContent.eq(faqsItemsHeaders.index($(this))).slideDown(400);
						// GA tracking 
						$(this)._trackGAlink("Expansions-FAQs");

					}, function () {
						$(this).removeClass("open");
						faqsItemsContent.eq(faqsItemsHeaders.index($(this))).slideUp(400);

					});
				};

			},

			setupGA: function () {
				_gaq = [];
				_gaq.push(['_setAccount', 'UA-4274186-5']);
				_gaq.push(['_trackPageview']);

				(function () {
					var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
					//ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/u/ga_debug.js';  //turn on for debugging if required
					ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
				})();

				// track all external links
				$("a[rel=\"External\"]").click(function () {
					$(this)._trackGAurl("External URL");
				});

				// track all external links
				$("a.trackGAInternal").click(function () {
					$(this)._trackGAurl("Internal URL");
				});

				// track PDF downloads
				$("span.pdf a").click(function () {
					// for Perks pdfs
					var pdfText = $.trim($(this).attr("title").split("(PDF")[0]);

					_gaq.push(['_trackEvent', 'Downloads', 'PDF', pdfText]);
					debug("GA call >> category: Downloads, action: PDF, label: " + pdfText);
				});

				// track Gig Finder downloads
				$(".gig-finder a").click(function () {
					_gaq.push(['_trackEvent', 'Downloads', 'Gig Finder']);
					debug("GA call >> category: Downloads, action: Gig Finder");
				});

				// track promo-panel clicks
				$(".promo-panel").not(".gig-finder").find("a").click(function () {
					$(this)._trackGAlink("Promo Panels");
				});

				// HTML search events
				$(".priority-tooltip.JS-tooltip, .favourites-tooltip.JS-tooltip").click(function () {
					$(this)._trackGAlink("Show");
				});

				// track event FB and twitter clicks
				$(".event-info-box a.fb-share-btn").live('click', function () {
					$(this)._trackGAsocial("Facebook-Share");
				})

				$(".event-info-box a.twitter-share-button").live('click', function () {
					$(this)._trackGAsocial("Twitter");
				})

				// Same process as above with some slight varients for getting data from buttons...
				$(':submit').each(function () {
					var buttonText = $(this).attr('value');
					if (buttonText == null) {
						return;
					}
					var currentLocation = document.location;
					if (buttonText != 'Send') {
						$(this).click(function () {
							_gaq.push(['_trackEvent', currentLocation, buttonText]);
						});
					}

				});

				// Same process as above with some slight varients for getting data from buttons...
				$(':button').each(function () {
					var buttonText = $(this).attr('value');
					if (buttonText == null) {
						return;
					}
					var currentLocation = document.location;
					$(this).click(function () {
						_gaq.push(['_trackEvent', currentLocation, buttonText]);
					});

				});

				// Same process as above with some slight varients for getting data from buttons...
				$('#get-priority-moments').click(function () {
					$(this).click(function () {
						_gaq.push(['_trackEvent', 'Moments', 'Get Priority Moments now']);
						debug("GA call >> category: Moments, action: Get Priority Moments now");
					});
				});
			},

			fixPng: function () {
				if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
					DD_belatedPNG.fix('.pngFix');
				}
			},

			preload: function () {
				c_self.functions.debuglog("preload");
				c_self.functions.preloadImages(/*insert array of images here*/);
			},
			preloadImages: function () {
				for (var i = 0; i < arguments.length; i++) {
					$("<img>").attr("src", arguments[i]);
				}
			}

		};

		//c_self.functions.initialise($("body"));
		c_self.functions.checkboxSetup();
		c_self.functions.setupSignIn();
		c_self.functions.setupFAQs();

		c_self.functions.configureExternalLinks();
		c_self.functions.setPDFLinks();
		c_self.functions.setupGA();

		//IE6 only
		c_self.functions.fixPng();

		c_ready = true;

	};

	// defaults
	$.priority.init.defaults = {
		//TODO:
		animationSpeed: "1000",
		intervalFrequency: "10000"
	};

	// optional - initialise one or more instances of the class
	$(document).ready(function () {
		$.br_init = new $.priority.init();

	});

})(jQuery);

