//    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();
                        }
                    };
                    setTimeout(startGA, 500);
                });
            },
            ieMarginFloatFix: function() {
				// This function fixes the IE bug that ignores margin-bottom/top when setting overflow hidden to clear floats
				var ieClear = $("<div></div>");
				ieClear.addClass('ieOverflowFix');
				
				if ($.browser.msie) {
					$('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);
								};
							};
						};
					});
				};
            },
            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);
                }
            },
            configureExternalLinks: function() {
                // Loop through all links that are absolute or with rel="External"
                $("a[rel=\"External\"],a[@href^=http]:not([rel=\"External\"])").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") {
                        var anchor = this;
                        if ($(anchor).attr("title") != "") {
                            $(anchor).attr("title", $(anchor).attr("title") + " (opens in a new window)");
                        }
                        else {
                            $(anchor).attr("title",  "Opens in a new window");
                        }
                        $(this).click(function() {
                            window.open($(anchor).attr("href"));
                            return false;
                        });
                    }
                });
            },
            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.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);
