﻿//    stst 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
    */
    $.stst = $.stst || {};

    /*
    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
    */
    $.stst.init = function(options) {
        var c_self = this;
        var c_ready = false;
        c_self.options = $.extend({}, $.stst.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) {

                });
            },


            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-3451254-12"); // live stss tag
                            pageTracker._initData();
                            //pageTracker._trackPageview();

                            var pageTitle = document.title;
                            // 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', pageTitle + " - " + linkText, 'to / ' + linkURL)
                                });
                            });

                            // Same process as above with some slight varients for getting data from buttons...
                            $('.trackingGAbutton').each(function() {
                                var buttonText = $(this).attr('alt');
                                if (buttonText == null) {
                                    var buttonText = $(this).find('a').text();
                                }
                                var currentLocation = document.location;
                                $(this).click(function() {
                                    pageTracker._trackEvent('Button Click', pageTitle + " - " + buttonText, 'from / ' + currentLocation)
                                });
                            });

                            // Same process as first for links with the class trackingGA
                            $('.trackingGA').each(function() {
                                var linkText = $(this).text();
                                if (linkText == "") {
                                    var linkText = $(this).children('img').attr('alt');
                                };
                                var linkURL = this.href;
                                /*alert("linkText = " + linkText + " >> linkURL = " + linkURL)*/
                                $(this).click(function() {
                                    pageTracker._trackEvent('Selected URL', pageTitle + " - " + linkText, 'to / ' + linkURL)
                                });
                            });

                        }
                    };
                    setTimeout(startGA, 500);
                });
            },

            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;
                        });
                    }
                });
            },

            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"));
        /*** FUNCTION CALL DISABLED BY REQUEST OF EDF ENERGY ***/
        //c_self.functions.googleAnalytics();

        c_ready = true;

    };

    // defaults
    $.stst.init.defaults = {
        //TODO:
        easing: "quad",
        animationSpeed: "1000",
        intervalFrequency: "10000"
    };

    // optional - initialise one or more instances of the class
    $(document).ready(function() {
        new $.stst.init();
    });
})(jQuery);
