﻿/// <reference path="/Kooboojs/jquery-1.4.1.js"/>
/// <reference path="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAXqdlwIyFc38TnDZCpFrVGRRFAgPNFoPgMWltjHrJgGvbEhsHiBQJeXw_AnUx3PhO-kHCoTRIwMbAow"/>

jQuery.fn.extend({
    disableSelection: function() {
        this.each(function() {
            this.onselectstart = function() { return false; };
            this.unselectable = "on";
            jQuery(this).css('-moz-user-select', 'none');
        });
    }
});

jQuery.getParameterByName = function(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
};

var Idonix = {};

Idonix.Initialise_Menu = function() {

    var menuItems = $(".menu-item");
    var subMenuUls = $(".sub-menu");
    var selectedMenuItemId = $("ul.main-menu > li.selected").attr("id");
    var selectedSubMenuItemId = $("ul.sub-menu > li.selected").attr("id");
    var allSubMenus = $(".sub-menu");
    var allSubMenusChildren = $(allSubMenus.children());
    var introTextDivs = $(".intro-text");

    var animationSpeed = 250;
    var infoTextHoldTime = 300;
    var subMenuHoldTime = 700;

    var showDefaultPageInfo = false;
    var hideSubmenu = {};
    var activeSubMenus = {};

    var hoverCount = 0;

    var defaultPageName = "";
    var activeInfoText = "";
    var activeMenuItem = "";

    // An item should always be selected
    if (selectedMenuItemId != undefined) {
        activeInfoText = defaultPageName = selectedMenuItemId.substring(9, selectedMenuItemId.length);
    }

    // Can set the active sub menu if we stated on one
    if (selectedSubMenuItemId != undefined) {
        activeSubMenus[defaultPageName] = true;
    }

    // Function used to show the info text for a pages menu item
    var showPageInfo = function(pageName) {

        // No longer want to go back to the current pages description.
        showDefaultPageInfo = false;

        // Only show this page if we arent already on it
        if (pageName != activeInfoText) {

            // Does this page have a description?
            var descriptionDiv = $("#introText_" + pageName);
            if (descriptionDiv.length > 0) {

                // Fade out all other intro text divs
                introTextDivs.hide();

                // Fade in the description for this page
                descriptionDiv.fadeIn(animationSpeed);

                // This is now our active page
                activeInfoText = pageName;
            }
        }

    };

    // Sets the info text back to the default (usually the home page)
    var resetPageInfo = function() {

        // We want to show the current pages info text..
        showDefaultPageInfo = true;

        // So we check this is still the case after infoTextHoldTime expires  
        setTimeout(function() {
            if (showDefaultPageInfo && activeInfoText != defaultPageName) {
                // Do it
                showPageInfo(defaultPageName);
            }
        }, infoTextHoldTime);
    };

    // Function used to knock off all active sub menus.
    var hideActiveSubMenus = function() {
        for (var name in activeSubMenus) {
            if (activeSubMenus[name] == true) {
                var activeSubMenu = $("#menuItem_" + name + " .sub-menu");
                var activeSubMenuChildren = activeSubMenu.children();

                activeSubMenu.css("display", "none");
                activeSubMenu.css("left", "-60px");
                activeSubMenuChildren.animate({ opacity: "0" }, 10);

                activeSubMenus[name] = false;
            }
        }
    }

    // Sets the sub menu back to the default
    var resetSubMenu = function() {

        // Only need to reset if the current page is an item in a sub menu.
        if (selectedSubMenuItemId != undefined) {

            var defaultSubMenu = $("#menuItem_" + defaultPageName + " ul.sub-menu");
            var defaultSubMenuChildren = $(defaultSubMenu.children());

            // Hide other active sub menus
            hideActiveSubMenus();

            // Fade in this sub menu
            defaultSubMenu.css("display", "block");
            defaultSubMenu.css("left", "0px");
            defaultSubMenuChildren.animate({ opacity: "1" }, animationSpeed);
            activeSubMenus[defaultPageName] = true;

        }
    }

    // Function called when the mouse enters a menu item
    var onEnter = function(element) {

        hoverCount++;

        var item = (element.length > 0) ? $(element) : $(this);
        var itemId = item.attr("id");

        var pageName = itemId.substring(9, itemId.length);
        var subMenu = item.children(".sub-menu");
        var subMenuChildren = $(subMenu.children());
        var pageInfoDiv = $("#introText_" + pageName);

        // When re-hovering over a sub menu item,
        // the owning menu-item will also raise a hover event.
        // This is a hack to stop this second event from resetting the info text.
        if (!(item.hasClass("hasSubMenu") && hoverCount > 1)) {
            // Show this pages info text
            showPageInfo(pageName);
        }

        // Show the sub menu for this page
        if (subMenu.length > 0 && pageName != defaultPageName) {

            // We no longer want to hide this submenu
            hideSubmenu[pageName] = false;

            // In case we are currently animating
            subMenu.stop();
            subMenuChildren.stop();

            // Do nothing if we are already showing this sub menu
            if (activeSubMenus[pageName] != true) {

                // Hide other active sub menus
                hideActiveSubMenus();

                // Fade in this sub menu
                subMenu.css("display", "block");
                subMenu.css("left", "-60px");
                subMenu.animate({ left: "0px" }, animationSpeed);
                subMenuChildren.animate({ opacity: "1" }, animationSpeed);
                
                // Now this is the active sub menu
                activeSubMenus[pageName] = true;

            }
            else {
                // Ensure all is visible and good.
                subMenu.css("display", "block");
                subMenu.css("left", "0px");
                subMenuChildren.css("opacity", "1");
            }

        }

    };

    // Function called when the mouse leaves a menu item
    var onLeave = function(element) {

        hoverCount--;

        var item = (element.length > 0) ? $(element) : $(this);
        var pageName = this.id.substring(9, this.id.length);

        // Only handle mouse out for pages other than the default
        if (pageName != defaultPageName) {

            var subMenu = item.children(".sub-menu");
            var subMenuChildren = subMenu.children();

            // Hide the sub menu
            if (subMenu.length > 0) {

                // We want to hide the submenu..
                hideSubmenu[pageName] = true;

                // Start bringing in the default menu
                resetSubMenu();

                // So we check this is still the case after subMenuHoldTime expires  
                setTimeout(function() {
                    if (hideSubmenu[pageName]) {

                        // Hard to go back once we start animating,
                        // so this is no longer considered active
                        activeSubMenus[pageName] = false;

                        // Positions are animated with the ul
                        subMenu.animate(
                                { left: "60px" },
                                animationSpeed,
                                "linear",
                                function() {
                                    if (hideSubmenu[pageName]) {
                                        subMenu.css("left", "-60px");
                                        subMenu.css("display", "none");
                                        hideSubmenu[pageName] = false;
                                    }
                                });

                        // Opacity animated on the child elements (to fix ie bug)
                        subMenuChildren.animate(
                                { opacity: "0" },
                                animationSpeed,
                                "linear");

                    }
                }, subMenuHoldTime);
            }

        }

        // Reset the info text to the current pages description.
        resetPageInfo();

    };

    // Setup each sub menu
    subMenuUls.each(function(i) {
        var subMenuUl = $(subMenuUls[i]);
        if (!subMenuUl.hasClass("selected")) {
            var subMenuItems = subMenuUl.children();
            subMenuItems.css("opacity", "0");
            subMenuUl.css("left", "-60px");
        }
    });

    // Attatch events
    menuItems.hover(onEnter, onLeave);
    menuItems.click(onEnter);

}

Idonix.Initialise_LoginBox = function () {

    var loginLink = $("#loginLink");
    var loginTemplate = $("#loginTemplate");
    var loginForm = $("#loginTemplate form");
    var loginFormHtml = loginTemplate.html();
    var returnUrl = $.getParameterByName("returnurl");

    loginTemplate.html("");

    var showLoginBox = function () {
        $.fancybox(
            loginFormHtml,
            {
                'transitionIn': 'fade',
                'transitionOut': 'fade',
                'speedIn': 600,
                'speedOut': 200,
                'overlayShow': true,
                'titlePosition': 'inside',
                'onComplete': Idonix.FancyBox_Resize
            });
        $("#name").focus();
    };

    loginLink.click(function () {
        showLoginBox();
    });

    if (returnUrl.length > 0) {
        showLoginBox();
    }

}

Idonix.Initialise_FancyBox = function() {
    $("a.magnify").fancybox({
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'speedIn': 600,
        'speedOut': 200,
        'overlayShow': true,
        'scrolling': 'no',
        'titlePosition': 'outside',
        'onComplete': Idonix.FancyBox_Resize
    });

    $("a.inline-explainer").fancybox({
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 600,
        'speedOut': 200,
        'overlayShow': true,
        'titlePosition': 'inside',
        'onComplete': Idonix.FancyBox_Resize
    });

    $("a.youTube").fancybox({
        'transitionIn': 'elastic',
        'padding': 0,
        'autoScale': false,
        'transitionOut': 'fade',
        'width': 320,
        'height': 180,
        'type': 'swf'
    });

    $("a.jwPlayer").fancybox({
         'autoscale' : false,
         'transitionIn' : 'fade',
         'transitionOut': 'fade',
         'padding': 0,
         'autoDimensions': true,
//         'title': this.title,
//         'href': this.href,
         'onComplete': Idonix.JWPlayer_Init,
         'onClosed': Idonix.JWPlayer_Destroy
     });
 }

 Idonix.JWPlayer_Init = function (containerHRef) {

     var containerId = containerHRef.toString().split("#")[1];
     var container = $("#" + containerId);
     var fileName = container.attr("title");
     var grabbedHeight = false;
     var grabbedWidth = false;
     var height = 180;
     var width = 320;

     var styleInfo = container.attr("style");

     if (typeof (styleInfo) != "undefined") {

         var styles = styleInfo.split(";");
         var len = styles.length;

         for (var i = 0; i < len; i++) {
             var grabHeight = false;
             var grabWidth = false;
             var style = $.trim(styles[i].toString());
             if (style.substr(0, 6).toLowerCase() == "height") {
                 grabHeight = true;
             }
             if (style.substr(0, 5).toLowerCase() == "width") {
                 grabWidth = true;
             }

             if (grabHeight || grabWidth) {
                 var value = parseInt($.trim(style.split(":")[1]));

                 if (grabHeight == true) {
                     height = value;
                     grabbedHeight = true;
                 }
                 if (grabWidth == true) {
                     width = value;
                     grabbedWidth = true;
                 }

             }

         }
     }

     if (grabbedHeight == true && grabbedWidth == false) {
         // Default to 16x9
         width = parseInt((height * 16) / 9)
     }

     if (grabbedWidth == true && grabbedHeight == false) {
        // Default to 16x9
         height = parseInt((width * 9) / 16)
     }

     // Position the close button (can't sensibly do with css as fancybox
     // doesn't emit enough html...
     $("#fancybox-close").css("left", ((width / 2) - 12) + "px");

     jwplayer(containerId).setup({
         autostart: true,
         controlbar: "none",
         file: fileName,
         height: height - 14,
         width: width, // - 16,
         stretching: "uniform",
         players: [
            { type: "html5" },
            { type: "flash", src: "/jwplayer/player.swf" }
        ]
     });
 }

 Idonix.JWPlayer_Destroy = function (containerHRef) {

     var containerId = containerHRef.toString().split("#")[1];

     jwplayer(containerId).remove();

 }

 Idonix.FancyBox_Resize = function () {
     var corner1 = $("#fancy-bg-nw");
     var corner2 = $("#fancy-bg-ne");
     var left = corner1.position().left + corner1.width();
     var width = corner2.position().left - left;
     var centre = left + (width / 2);
     var closeButton = $("#fancybox-close");
     // Position the close button (can't sensibly do with css as fancybox
     // doesn't emit enough html...
     closeButton.css("left", centre - (closeButton.width() / 2) + "px");

 }

 Idonix.PlayHomePageMovie = function (containerId, movieName, staticImage) {
     jwplayer(containerId).setup({
         autostart: true,
         controlbar: "none",
         file: movieName,
         height: 180,
         width: 320,
         repeat: "none",
         volume: 80,
         image: staticImage,
         stretching: "none",
         players: [
            { type: "html5" },
            { type: "flash", src: "/jwplayer/player.swf" }
        ]
     });
 }

Idonix.Initialise_GoogleMap = function() {

    if (typeof GBrowserIsCompatible != 'undefined') {
        if (GBrowserIsCompatible()) {

            var map = new GMap2(document.getElementById("map_canvas"));

            if (map != null) {
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());

                map.setCenter(new GLatLng(52.59724, -2.558114), 14);

                var point = new GLatLng(52.59724, -2.558114);
                var marker = new GMarker(point);

                var html = '<p style="color:black;"><em>Idonix</em><br />7 Sheinton Street<br />Much Wenlock<br />Shropshire<br />TF13 6HT</p>';

                GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(html);
                });

                map.addOverlay(marker);
                map.openInfoWindow(map.getCenter(), html);
            }
        }
    }
}

var EDay = {};

EDay.InitialiseWidget = function(widgetType, width, elementId) {

    var showFlash = true;
    var altImgURL = "";
    var siteName = "";
    var meterType = "";
    var height = width * 0.3792;
    var title = "E-Day";
    var bgColour = "#FFFFFF"
    var titleURL = "http://www.e-day.org.uk";
    var scaleMode = "showAll";
    var link = "http://www.e-day.org.uk";

    switch (widgetType) {
        case "OfficeDial":
            siteName = "family";
            meterType = "Dial";
            bgColour = "#000000";
            title = "Idonix Office"
            showFlash = true;
            break;
        case "NationalDial":
            siteName = "national";
            meterType = "Dial";
            bgColour = "#00BEF2";
            title = "National electricity usage"
            showFlash = true;
            break;
        case "NationalCost":
            siteName = "national";
            meterType = "CostMeter";
            bgColour = "#00BEF2";
            title = "National electricity Bill"
            showFlash = true;
            break;
        case "NationalDemandCurve":
            siteName = "national";
            meterType = "Graph";
            bgColour = "#00BEF2";
            title = ""
            showFlash = true;
            break;
        case "NationalC02":
            siteName = "national";
            meterType = "EmmisionsMeter";
            bgColour = "#00BEF2";
            title = "National electricity C02 Emissions"
            showFlash = true;
            break;
        case "Summary":
            siteName = "national,island,school,family historic";
            meterType = "Summary";
            showFlash = (new Date() >= Date.parse("Oct 6, 2009"));
            altImgURL = "http://www.e-day.org.uk/Portals/0/Images/staticSummaryImage_1.png";
            break;
        case "ScillyOMeter":
            siteName = "island";
            meterType = "CircleMeter";
            bgColour = "#00709E";
            showFlash = true;
            break;
        case "IslandDemandCurve":
            siteName = "island";
            meterType = "Graph";
            bgColour = "#00709E";
            showFlash = true;
            break;
        default:
            siteName = "national,island,school,family";
            meterType = "Summary";
            showFlash = (new Date() >= Date.parse("Oct 6, 2009"));
            altImgURL = "http://www.e-day.org.uk/Portals/0/Images/staticSummaryImage_1.png";
            break;
    }

    var html = "";

    if (showFlash) {
        html = "<div style='background-color:" + bgColour + "; width:" + width + "px; height:" + height + "px;'><embed src='http://www.e-day.org.uk/Portals/0/widgets/Widgets_8.swf' class='flash' scaleMode='" + scaleMode + "' FlashVars='_MeterType=" + meterType + "&_SiteName=" + siteName + "&_Title=" + title + "&_TitleURL=" + titleURL + "&_Link=" + link + "&_WebServiceHost=http://www.e-day.org.uk/dataservice/' quality='high' wmode='transparent' bgcolor='" + bgColour + "' width='" + width + "' height='" + height + "' name='Widgets' align='top' allowScriptAccess='sameDomain' allowFullScreen='false' type='application/x-shockwave-flash' pluginspage='http://www.adobe.com/go/getflashplayer' /></div>";
    }
    else {
        html = "<a href='" + link + "' target='_blank'><img width='" + width + "' height='" + height + "' border='0' alt='" + title + "' src='" + altImgURL + "'></img></a>";
    }

    if (elementId != undefined) {
        var element = document.getElementById(elementId);
        if (element != undefined) {
            element.innerHTML = html;
        }
    }

    return html;
}


$(document).ready(function () {

    Idonix.Initialise_Menu();
    Idonix.Initialise_LoginBox();
    Idonix.Initialise_FancyBox();
    Idonix.Initialise_GoogleMap();

});


