
/// <reference path="jquery-1.3.2-vsdoc.js" />


// depends on prototype.js
// our namspace:


if (Ix == undefined) var Ix = {};

/*--------------------------------------------------------------------------*/
// Flash Utils

Ix.Flash = {};

Ix.Flash.Enabled = true;

Ix.Flash.BuildFlashHTML = function(meterType, siteName, bgColour, width, height, title, titleURL, scaleMode, vars) {

    if (width == undefined) width = 625;
    if (height == undefined) height = 237;
    if (title == undefined) title = "";
    if (titleURL == undefined) titleURL = "";
    if (scaleMode == undefined) scaleMode = "noScale";
    if (vars == undefined) vars = "";
    else vars = "&" + vars;

    var html = "<div style='background-color:" + bgColour + "; width:" + width + "; height:" + height + ";'><embed src='" + Ix.ApplicationPath + "/Portals/0/widgets/Widgets_7.swf' class='flash' scaleMode='" + scaleMode + "' FlashVars='_MeterType=" + meterType + "&_SiteName=" + siteName + "&_Title=" + title + "&_TitleURL=" + titleURL + "&_WebServiceHost=" + Ix.SiteRootURL + "/dataservice/" + vars + "' 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>";
    return html;
}

/*--------------------------------------------------------------------------*/
//Meter related Data and Styles

Ix.Styles = {};

Ix.Styles.National = {};
Ix.Styles.National.Colour = "#00BEF2";

Ix.Styles.Island = {};
Ix.Styles.Island.Colour = "#00709E";

Ix.Styles.School = {};
Ix.Styles.School.Colour = "#ED1B24";

Ix.Styles.Family = {};
Ix.Styles.Family.Colour = "#8CC63E";

Ix.Styles.GetStyle = function(styleName) {
    switch (styleName.toLowerCase()) {
        case "national": case "national rolling":
            return Ix.Styles.National;
            break;
        case "island": case "island historic":
            return Ix.Styles.Island;
            break;
        case "school": case "school historic":
            return Ix.Styles.School;
            break;
        case "family": case "family historic":
            return Ix.Styles.Family;
            break;
    }
}

/*--------------------------------------------------------------------------*/
//Page Load

Ix.Page = {};

Ix.Page.OnPageLoad = function()
{
//    //Hide login/logout button if not logged in 
//    var loginBtn = jQuery('#dnn_dnnLOGIN_cmdLogin');
//    if((loginBtn.length > 0) && (loginBtn.text() == 'Login'))
//    {
//        loginBtn.css('display', 'none');
//    }
}

/*--------------------------------------------------------------------------*/
// collection of utitlity functions
Ix.Utils = {};

Ix.Utils.mr2 = function(num) {
    // 2 decimal places
    return Math.round(num * 100) / 100
};

Ix.Utils.mr1 = function(num) {
    // 1 decimal places
    return Math.round(num * 10) / 10
};

Ix.Utils.GetEmbedDivFromTargetId = function(targetId) {
    var target = jQuery("#" + targetId);
    target.text("");
    var parent = jQuery(target.parents(".container"));
    var content = jQuery("div.embedDiv", parent);
    return content;
}

Ix.Utils.InsertYouTubeToParent = function(targetId, youTubeId) {
    var content = Ix.Utils.GetEmbedDivFromTargetId(targetId);
    content.html("<object width='320' height='196'><param name='wmode' value='transparent'><param name='movie' value='http://www.youtube.com/v/" + youTubeId + "&hl=en&fs=1&rel=0'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed class='video' wmode='transparent' src='http://www.youtube.com/v/" + youTubeId + "&hl=en&fs=1&rel=0' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='320' height='196'></embed></object>");
};

Ix.Utils.Trim = function(str, chars) {
	return Ix.Utils.LTrim(Ix.Utils.RTrim(str, chars), chars);
}
 
Ix.Utils.LTrim = function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
Ix.Utils.RTrim = function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/*--------------------------------------------------------------------------*/
// Mouse handling

Ix.Utils.OnMouseOver = function(element)
{
    element = jQuery(element);
    if (!element.hasClass("mouseHover"))
    {
        element.addClass("mouseHover");
    }
}

Ix.Utils.OnMouseOut = function(element)
{
    element = jQuery(element);
    if (element.hasClass("mouseHover"))
    {
        element.removeClass("mouseHover");
    }
}

Ix.Utils.InitIFramePage = function() {
    //Set the head backcolour to white
    jQuery("#pageContent").css("background-color", "white");
}

/*--------------------------------------------------------------------------*/
// Container functions

Ix.Containers = {};

Ix.Containers.Cache = {};

Ix.Containers.AnimatingDiv = null;
Ix.Containers.OldHeight = 0;

Ix.Containers.RestoreVisibility = function()
{
    //Get the cookie first
    var cookie = document.cookie;

    //Check for containers that should always start minimized
    var minimizedContainers = jQuery('div.startsMinimized');

    if (minimizedContainers.length > 1)
    {
        for (var exp in minimizedContainers)
        {
            exp = jQuery(exp);
            exp.removeClass('startsMinimized');
            Ix.Containers.Hide(exp, 0);
        }
    }
    else if (minimizedContainers.length > 0)
    {
        minimizedContainers.removeClass('startsMinimized');
        Ix.Containers.Hide(minimizedContainers, 0);
    }

    //console.log("Load: cookie = " + document.cookie);

    //Restore previous visibility for all containers from cookie
    if (cookie.length > 0)
    {
        var cookies = cookie.split(';');
        for (var i = 0; i < cookies.length; i++)
        {
            var cookieInfo = cookies[i].split('=');
            if ((cookieInfo.length > 1) && (Ix.Utils.Trim(cookieInfo[0]) === 'EdayVisibility'))
            {
                var params = cookieInfo[1].split('|');
                for (var j = 0; j < params.length; j++)
                {
                    //Get the stored visibility 
                    var visibilityInfo = params[j].split('.');
                    var containerId = visibilityInfo[0];
                    var visibility = visibilityInfo[1];
                    if (containerId.length)
                    {
                        var element = jQuery('#' + containerId);
                        if (element.length)
                        {
                            var container = element.parents('table.container')[0];
                            var expanderButton = jQuery('div.expander', container);
                            if (visibility === 'hidden' && expanderButton.length)
                            {
                                //Hide if necessary
                                Ix.Containers.Hide(expanderButton, 0);
                            }
                        }
                    }
                }
            }
        }
    }
}

Ix.Containers.WriteContainerVisibilityToCookie = function()
{

	var date = new Date();
	date.setTime(date.getTime()+(100*24*60*60*1000));
	var expires = "expires="+date.toGMTString() + "; ";
	var visibilityString = "";
    for (var containerId in Ix.Containers.Cache) 
	{
	    visibilityString += containerId + ".";
	    if(Ix.Containers.Cache[containerId]['isVisible'])
	    {
            visibilityString += "visible|";
        }
        else
        {
            visibilityString += "hidden|";
        }
	}
	var cookieString = "EdayVisibility=" + visibilityString + "; " + expires + "path=/";
	document.cookie = cookieString;
}

Ix.Containers.Show = function(expanderButton, animSpeed) {

    var expanderButton = jQuery(expanderButton);
    var container = expanderButton.parents('table.container');
    var containerHead = container.find('td.containerHead');
    var contentDiv = jQuery(container.find('div.content')[0]);
    var contentCell = jQuery(container.find('td.contentCell')[0]);
    var lineBreak = container.find('td.lineBreak');
    var flashObjects = container.find('.flash');

    var cachedProps = Ix.Containers.Cache[contentDiv[0].id];

    expanderButton.removeClass('expanderMinimized');
    expanderButton.addClass('expanderMaximized');

    lineBreak.css('height', '2px');
    containerHead.css('padding-bottom', '4px');
    contentDiv.css('padding-top', '0px');
    contentDiv.css('padding-bottom', '0px');

    if (jQuery.browser.msie) {
        lineBreak.parent().css('display', 'block');
    }

    var doAnim = true;
    var oldHeight = 0;

    if (cachedProps != undefined) {
        oldHeight = cachedProps['height'];
        //console.log("oldheight: " + oldHeight);
        cachedProps['isVisible'] = true;
    }
    else {
        contentDiv.height("100%");
        //console.log("calcd height: " + contentCell.height());
        oldHeight = contentDiv.height();
        if (jQuery.browser.msie) {
            doAnim = false;
        }
        else {
            contentDiv.height("1px");
        }
    }

    if (animSpeed == undefined) {
        animSpeed = 1;
    }

    if (doAnim) {
        contentDiv.animate({ height: oldHeight, opacity: 1 }, (oldHeight * 1.5) * animSpeed, function() {
            if (jQuery.browser.mozilla) //firefox reloads flash objects when they are resized.
            {
                var flashObjects = container.find('.flash');
                flashObjects.show();
            }
        });
    }

    Ix.Containers.WriteContainerVisibilityToCookie();
}


Ix.Containers.Hide = function(expanderButton, animSpeed)
{
    var expanderButton = jQuery(expanderButton);  
    var container = expanderButton.parents('table.container');
    var containerHead = container.find('td.containerHead');
    var contentDiv = jQuery(container.find('div.content')[0]);
    var contentCell = jQuery(container.find('td.contentCell')[0]);
    var embedDiv = jQuery(container.find('div.embedDiv')[0]);
    var lineBreak = container.find('td.lineBreak');

    var currentHeight = contentCell.height();
    
    if(jQuery.browser.mozilla) //firefox reloads flash objects when they are resized.
    {
        var flashObjects = container.find('.flash');
        flashObjects.hide();
    }
    
    if(animSpeed == undefined)
    {
        animSpeed = 1;
    }
    
    Ix.Containers.AnimatingDiv = contentDiv;
    
    expanderButton.removeClass('expanderMaximized');
    expanderButton.addClass('expanderMinimized');
    
    contentDiv.css('padding-top', '6px');
    contentDiv.css('padding-bottom', '0px');
    containerHead.css('padding-bottom', '0px');
    lineBreak.css('height', '0px');   
    
    //cache the height
    if(!Ix.Containers.Cache[contentDiv[0].id])
    {
        Ix.Containers.Cache[contentDiv[0].id] = [];
        Ix.Containers.Cache[contentDiv[0].id]['height'] = currentHeight;
    }

    //embedDiv.animate({ height: '1px', opacity: 0 }, (currentHeight * 1.5) * animSpeed);
    contentDiv.animate({height: '1px', opacity: 0}, (currentHeight * 1.5) * animSpeed, function() { contentDiv.hide(); });

    if(jQuery.browser.msie)
    {
        lineBreak.parent().css('display', 'none');  
    }

    Ix.Containers.Cache[contentDiv[0].id]['isVisible'] = false;
    Ix.Containers.WriteContainerVisibilityToCookie();
}


Ix.Containers.ToggleVisibility = function(element)
{

    var expanderButton = jQuery(element);

    if (expanderButton.hasClass('expanderLink'))
    {
        expanderButton = expanderButton.parents('td.containerHead').find('div.expander');
    }

    expanderButton = jQuery(expanderButton[0]);

    if (expanderButton.hasClass('expanderMaximized'))
    {
        Ix.Containers.Hide(expanderButton);
    }
    else
    {
        Ix.Containers.Show(expanderButton);
    }
}

Ix.Containers.HideAnimCompleted = function(element) 
{
    if(Ix.Containers.AnimatingDiv != null)
    {
        Ix.Containers.AnimatingDiv.hide();
    }
}

/*--------------------------------------------------------------------------*/
// New version of prototype's periodicalTimer, reworked for
//  a) stopping timer whilst executing rather than just ignoring ticks
//  b) clearing timer after ticks - prevents memory leaks?
//  c) attempts to be self-adjusting timer to keep more accurate
//  d) running once immediatley, before first elapsed time
// and now for jQuery......
Ix.PeriodicalExecuter = function(callback, frequency, noWait, maxticks, stopped) {

    var tim = {};

    tim.callback = callback;
    tim.frequency = frequency;
    tim.currentlyExecuting = false;
    tim.expectedNextStart = 0;
    tim.executes = 0;
    tim.totaldrift = 0;
    tim.averagedrift = 0;
    tim.stopped = stopped === undefined ? false : stopped;
    tim.maxticks = maxticks === undefined ? 0 : maxticks;
    tim.timer = 0;

    tim.onTimerEvent = function() {
        if (tim.timer != 0) {
            clearTimeout(tim.timer);
            tim.timer = 0;
        }
        if (!tim.stopped) {
            if (!tim.currentlyExecuting) {
                try {
                    tim.currentlyExecuting = true;
                    tim.execute();
                }
                catch (ex) {
                }
                finally {
                    tim.currentlyExecuting = false;
                }
            }
            if (!tim.stopped && (tim.maxticks == 0 || (tim.maxticks > 0 && tim.executes < tim.maxticks))) {
                tim.start();
            }
        }
    };

    tim.start = function() {
        var intervalMs = this.frequency;
        var nowMs = Number(new Date);
        if (this.expectedNextStart != 0) {
            intervalMs = this.expectedNextStart - nowMs;
        };
        intervalMs = Math.max(10, (intervalMs - this.averagedrift));
        this.timer = setTimeout(this.onTimerEvent, intervalMs);
    };

    tim.execute = function() {
        var startMs = Number(new Date); // milliseconds
        this.executes++;
        if (this.expectedNextStart > 0) {
            var mydrift = this.expectedNextStart - startMs;
            if (!mydrift == 0 && this.executes > 1) {
                this.totaldrift += mydrift;
                this.averagedrift = Math.floor(this.totaldrift / this.executes);
            }
        };

        this.callback(this);

        var now = Number(new Date);
        if (this.expectedNextStart === 0) {
            this.expectedNextStart = startMs + (this.frequency);
        } else {
            this.expectedNextStart = this.expectedNextStart + (this.frequency);
        };
    };

    tim.stop = function() {
        this.stopped = true;
        if (this.timer == 0) return;
        clearTimeout(this.timer);
        this.timer = 0;
        this.lastStart = 0;
    };



    if (!tim.stopped) {

        //running once immediateley, without waiting first elapsed time
        if (noWait) tim.execute();

        // and go with the timer...
        tim.start();
    };
    return tim;

};

/*--------------------------------------------------------------------------*/
// A Global timer that will call all attatched functions

Ix.ContinuousTimer = {};

Ix.ContinuousTimer.FPS = 15;
Ix.ContinuousTimer.FrameLength = 0; //Set on creation

Ix.ContinuousTimer.Timer = null;

Ix.ContinuousTimer.Callbacks = [];

Ix.ContinuousTimer.Add = function(callback)
{
    Ix.ContinuousTimer.Callbacks.push(callback);
    if(!Ix.ContinuousTimer.Timer)
    {
        Ix.ContinuousTimer.FrameLength = 1000 / Ix.ContinuousTimer.FPS;
        Ix.ContinuousTimer.Timer = new Ix.PeriodicalExecuter(Ix.ContinuousTimer.Tick, Ix.ContinuousTimer.FrameLength, true, 0, false);
    }
}

Ix.ContinuousTimer.Tick = function()
{
    for (var i = 0; i < Ix.ContinuousTimer.Callbacks.length; i++)
    {
        Ix.ContinuousTimer.Callbacks[i]();
    }
}


/*--------------------------------------------------------------------------*/
// Ajax Data

Ix.Utils.Ajax = {};

Ix.Utils.Ajax.GetReading = function(type, siteName, callback)
{
    jQuery.ajax({
        type: "POST",
        global: "false",
        url: Ix.ApplicationPath + "/dataservice/GetReadings.asmx/" + type,
        data: "{siteName:'" + siteName + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) 
        { 
            callback(msg.d); 
        }               
    });
};

Ix.Utils.appendStyleSheet = function(url) {

    var headID = document.getElementsByTagName("head")[0];
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = url; //e.g. '/widgets/css/minutedial.css';
    cssNode.media = 'screen';
    headID.appendChild(cssNode);

};

Ix.Utils.fetchJSONData = function(tagID, scriptURL) {

    // tagID should be unique for different types of calls
    // as we'll replace the scripttaag by name
    var scriptTagID = tagID;
    var head = document.getElementsByTagName('head').item(0)
    var scriptTag = document.getElementById(scriptTagID);
    if (scriptTag) {
        head.removeChild(scriptTag);
    }
    script = document.createElement('script');

    var cacheFrigger = Number(new Date());

    script.src = scriptURL + '?' + cacheFrigger;
    script.type = 'text/javascript';
    script.id = scriptTagID;
    head.appendChild(script)

    // the called .js will then call the required function with its data

};

///////////////////////////////////////////////////////////////////////////////////////
//Widget Initialization
///////////////////////////////////////////////////////////////////////////////////////

Ix.InitializeMeter = function(meterType, siteName, title, targetId, delayLoad) {

    var style = Ix.Styles.GetStyle(siteName.split(",")[0]);
    var embedDiv = Ix.Utils.GetEmbedDivFromTargetId(targetId);

	if (delayLoad == undefined)
	{
		delayLoad = 0;
	}
	
    if (embedDiv.length && style != undefined) {

        var shortSiteName = siteName.split(" ")[0];
        var width = 625;
        var height = 237;
        var backColour = style.Colour;
        var scaleMode = "noScale";

        if (meterType == "BarGraph") {
            height = 330;
            backColour = "#FFFFFF";
        }

        embedDiv.html(Ix.Flash.BuildFlashHTML(meterType, siteName, backColour, width, height, title, Ix.SiteRootURL + "/" + shortSiteName + ".aspx", scaleMode, "_Style=" + shortSiteName + "&_DelayLoad=" + delayLoad.toString()));
    }
}

Ix.InitializeCountdown = function(targetId, edayDateString, width, height) {

    var embedDiv = Ix.Utils.GetEmbedDivFromTargetId(targetId);

    if (embedDiv.length) {

        edayDateString = edayDateString.replace(/-/g, "%2F").replace(/:/g, "%3A").replace(/ /g, "+");

        //var width = 295;
        //var height = 80;

        embedDiv.html(Ix.Flash.BuildFlashHTML("Countdown", "", "#FFFFFF", width, height, "", "", "showAll", "_EDayDate=" + edayDateString));
    }
}

Ix.InitAll = function() {
    Ix.Page.OnPageLoad();
    Ix.Containers.RestoreVisibility();
};

// And call it on load
jQuery(Ix.InitAll);

