//    Blueroom init
//    Ensures ga and cm scripts are only run after they have been loaded. Prevents js errors.

(function($) {

	//console.log()
	/* 
	Scope
	This initialises the namespace if it has not been initialised elsewhere
	*/
	$.blueroom = $.blueroom || {};

	/*
	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
	*/
	$.blueroom.init = function(options) {
		var c_self = this;
		var c_ready = false;
		c_self.options = $.extend({}, $.blueroom.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) {

				});
			},

			/*
			coreMetrics: function() {
			Tracking: Core Metrics
			$.getScript("http://www.o2.co.uk/assets/O2HybridNav/Static-files/coremetrics/eluminate.js", function() {
			$.getScript("http://www.o2.co.uk/assets/O2HybridNav/Static-files/coremetrics/cmdatatagutils.js", function() {
			if (typeof (window['cmSetProduction']) != "undefined") {
			cmSetProduction();
			cmCreatePageviewTag("blueroom | O2", "O2 blueroom", null);
			}
			});
			});
			},
			*/

			googleAnalytics: function() {
				//Tracking: Google Analytics
				$.getScript("http://www.google-analytics.com/ga.js", function() {
					var pageTracker;
					function startGA() {
						if (typeof (window['_gat']) != "undefined") {
							pageTracker = _gat._getTracker("UA-4274186-5"); // new script for blueroom
							pageTracker._initData();
							pageTracker._trackPageview();

							// Create some events
							// -- Doesnt seem to work, think google updated their code?
							// Buttons
							//var buttonTracker = pageTracker._createEventTracker("Button");
							// External Links
							//var externalLinksTracker = pageTracker._createEventTracker("External_Links");
							// Selected Links (that have been given a set class)
							//var selectedTracker = pageTracker._createEventTracker("Selected_Links");

							// Copied from below and figured it would be good to keep a duplicate up here for logical management of tracking ;¬)
							// Any external link....
							$("a[rel=\"External\"],a[@href^=http]:not([rel=\"External\"])").each(function() {

								// Grab the text from the external link
								var linkText = $(this).text();
								// If the link doesnt have any text
								if (linkText == "") {
									// We can assume if it doesnt have text its an image...
									// (This could be argued as slightly short sighted, but i feel in this case its safe to assume)
									// Anyway... grab the alt text of the nested image
									var linkText = $(this).children('img').attr('alt');
								};
								// Grab the URL so we can log this as well...
								var linkURL = this.href;

								//console.log(linkText + ' - ' + this.href)

								// Add the click event handler to call the GA function...
								$(this).click(function() {
									pageTracker._trackEvent('External URL', linkText, 'to / ' + linkURL)

									//alert(linkText + ' - ' + this.href);
								});
							});

							// Same process as above with some slight varients for getting data from buttons...
							$('.button').each(function() {
								var buttonText = $(this).find('input').attr('value');
								if (buttonText == null) {
									var buttonText = $(this).find('a').text();
								}
								var currentLocation = document.location;
								$(this).click(function() {
									pageTracker._trackEvent('Button Click', buttonText, 'from / ' + currentLocation)
								});
							});

							// Same process as first for links with the class trackGA
							$('.trackGA').each(function() {
								var linkText = $(this).text();
								if (linkText == "") {
									var linkText = $(this).children('img').attr('alt');
								};
								var linkURL = this.href;
								$(this).click(function() {
									pageTracker._trackEvent('Selected URL', linkText, 'to / ' + linkURL)
								});
							});

						}
					};
					setTimeout(startGA, 500);
				});
			},
			configureBookmarks: function() {

				var bookmarkContent = $("#bookmark-content");
				var onThisComputer = new $("<li><a href=\"#\">On this computer</a></li>");
				//bookmarkContent.css('opacity', 0);

				onThisComputer.addClass("first");
				bookmarkContent.find("ul li:first").removeClass("first");
				bookmarkContent.find("ul").prepend(onThisComputer);
				onThisComputer.find("a").click(function() {
					c_self.functions.bookmark();
					return false;
				});

				var shadow = $("<div></div>");
				shadow.addClass("shadow");
				bookmarkContent.prepend(shadow);

				var bookmarks = $("<div></div>");
				bookmarks.addClass("bookmarks");
				bookmarkContent.find("ul").wrap(bookmarks);

				bookmarkContent.css({ bottom: $("#inner-footer").outerHeight() + 24 });

				var bookmarksLinkContainer = $("<div id=\"bookmarks\"></div>");
				bookmarksLinkContainer.addClass("links-container");
				var bookmarksLink = $("<a href=\"#\">Bookmark</a>");
				bookmarksLink.addClass("links-link");
				bookmarksLinkContainer.append(bookmarksLink);

				$("#additional-links").append(bookmarksLinkContainer);
				bookmarkContent.animate({ height: "hide" }, 0, function() {
					//bookmarkContent.css('opacity', 1);
				});
				bookmarksLink.click(function() {

					// TOGGLE BG IMAGE                    
					// If it doesnt have the class of expanded
					// Change background image to the up state
					// $("#inner-footer #additional-links #bookmarks.links-container a.links-link").css("background","url(../Assets/Generic/Images/Icons/arrow_top-blue.gif) no-repeat scroll right center");                       
					// Add class of expanded
					// $(this).addClass("expanded");
					// Else If it does have the class of expanded
					// Change background image back
					// $("#inner-footer #additional-links #bookmarks.links-container a.links-link").css("background","url(../Assets/Generic/Images/Icons/arrow_right-blue.gif) no-repeat scroll right center");                                               
					// Remove class of expanded
					// $(this).removeClass("expanded");
					// End if

					var position = bookmarksLink.position();
					/*9 padding on content and 3 margin on outer-content*/
					bookmarkContent.css({ bottom: $("#inner-footer").outerHeight() + 9 + 3 + 15 });
					//var top = position.top;
					var left = position.left - 16;
					bookmarkContent.css({ left: left });
					bookmarkContent.animate(
						{
							height: "toggle"/*, opacity: "toggle"*/
						},
						500,
						function() {
							// toggle background
							//alert("change BG")
						}
					); return false;
				});
			},
			bookmark: function() {
				if ($.browser.msie) {
					window.external.AddFavorite(location.href, document.title);
				}
				else if ($.browser.mozilla) {
					window.sidebar.addPanel(document.title, location.href, '');
				}
				else if ($.browser.safari) {
					window.sidebar.addPanel(document.title, location.href, '');
				}
				else if ($.browser.opera) {
					window.sidebar.addPanel(document.title, location.href, '');
				}
				else {
					window.external.AddFavorite(location.href, document.title);
				}
			},
			//jl 16/12/2008
			//open all pdf links in a new window, change title attribute of link to reflect this
			findPDFLinks: function() {
				$("a").filter(function() {
					return this.href.match(RegExp(".pdf|.PDF+\"")) != null
				}).each(function() {
					if ($(this).attr("title") != null) {
						$(this).attr("title", $(this).attr("title") + " (PDF, opens in a new window)");
					}
					else {
						$(this).attr("title", "PDF, opens in a new window");
					};
					$(this).click(function() {
						window.open($(this).attr("href"));
						return false;
					});
				});

			},
			configureExternalLinks: function() {
				// Loop through all links that are absolute or with rel="External"
				// don't process ones that go to O2 More pages
				$("a[rel=\"External\"],a[@href^=http]:not([rel=\"External\"])").filter("a:not([@href^=http://www.o2more.co.uk])").each(function() {

					// 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;
							if ($(anchor).attr("title") != "") {
								$(anchor).attr("title", $(anchor).attr("title") + " (opens in a new window)").attr("target", "_blank");
							}
							else {
								$(anchor).attr("title", "Opens in a new window").attr("target", "_blank");
							}
							//$(this).click(function() {
							//window.open($(anchor).attr("href"));
							//return false;
							//});
						}
					}
				});
			},
			ieMarginFloatFix: function() {
				// This function is here to fix the IE bug that ignores margin-bottom/top
				// when setting overflow hidden to clear floats
				var ieClear = $("<div></div>");
				ieClear.addClass('ieOverflowFix');

				$('body').find('*').each(function() { // loop through every element
					if ($(this).siblings().length > 0) { // check to see if it has a sibling
						if ($(this).css('float') != 'none') { // check to see if siblings are floating
							var parent = $(this).parent(); // set parent 
							if (!parent.children("div").hasClass("ieOverflowFix")) { // check to see if the fix has already been applied
								ieClear.clone().appendTo(parent)
							}
						}
					}
				});
			},
			setupRoundedCorners: function() {
				if ($.browser.msie) {

					$('.eventsList').corner("5px");
					$('.outer-content').corner("5px");
					$('.inner-content').corner("5px");
					$('.rounded').corner("5px");

				}

			},
			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]);
				}
			},
			debuglog: function(logtext) {
				/*try {
				if (console && console.log) {
				console.log(logtext);
				}
				}
				catch (err) {
				//alert(err);
				}*/
			}
		};

		$("body").addClass("js");
		c_self.functions.initialise($("body"));
		c_self.functions.googleAnalytics();
		//        c_self.functions.coreMetrics();
		c_self.functions.configureBookmarks();
		c_self.functions.configureExternalLinks();
		c_self.functions.findPDFLinks();
		//      c_self.functions.ieMarginFloatFix();
		//c_self.functions.setupRoundedCorners();
		c_ready = true;

	};

	// defaults
	$.blueroom.init.defaults = {
		//TODO:
		easing: "quad",
		animationSpeed: "1000",
		intervalFrequency: "10000"
	};

	// optional - initialise one or more instances of the class
	$(document).ready(function() {
		new $.blueroom.init();
	});
})(jQuery);
