﻿// This document contains all site javascript, except for the swfObject injection calls

var _JsonObj = null; // Holds an object for updating JSON
var _iTweetCount = 0; // Tweet count
var _sTwitterSearchUrl = "http://search.twitter.com/search.json";
var _sTwitterRefreshUrl = "";
var _bFirstTime = true;
var _aTweetArray = new Array();
var _iTweetCounter = 0; // keep count of tweets added
var _sTweetContainerId = "twitterFeed";
var _isInternetExplorer;
var _aColorArray = ['ff409d', '25aae1', '8dc63f'];
var _iPageInit = false; // Flag to show if page is
var _jsReady = false;
var _iTweetTextHeight = 62;
var _sDisclaimerCookie = "BGDisclaimerRead";
var _userEntries = new Array(); // Array to hold user entries for Employee Bio Twitter feed

// The "Site" object is create on the page's domready event

var Site = {
    // Add general site initialization functions here

    start: function() {
	
	try {
        //Site.setupMenuAnimation();
        Site.setupDisclaimer();
        Site.setupMediaList();
        Site.setupTabbedList();
        Site.setupTwitterFeed();
        Site.initFlashCommunication();
	} catch (ex) {
	
	}
    },

    // Sets up the button to close the disclaimer for the TweetGarden on the home page
    setupDisclaimer: function() {

        // Inject disclaimer text into div via JS (to prevent search engines from seeing it)
        var elemDisclaimer = $("disclaimer");
        var elemDisclaimerInner = elemDisclaimer.getFirst("div.inner");
        var elemDiscText = new Element('div', { id: 'test' });
        elemDiscText.set('html', sDisclaimerCopy);
        elemDiscText.inject(elemDisclaimerInner, 'top');
 
        // Set up the code to hide the Disclaimer
        var aHomeCheck = $$('.bghomepage'); // If the array has a length of 1, we are on the home page
        var elemDiscClose = $("closeButton"); // Close button, duh!

        if (aHomeCheck.length == 1) {
            // If we are on the home page

            // Get the cookie
            disclaimerCookie = Cookie.read(_sDisclaimerCookie);

            // If the cookie has not been set to 1 then display the disclaimer
            if (disclaimerCookie != "1") {
                elemDisclaimer.setStyles({
                    display: 'block'
                });
            }
        }

        // Handle disclaimer close button click 
        elemDiscClose.addEvent('click', function(event) {

            event.stop();
            var elem = new Element(event.target);

            // 
            elemDisclaimer.setStyles({
                display: 'none'
            });

            // Set the cookie
            var disclaimerCookie = Cookie.write(_sDisclaimerCookie, '1', { duration: 7 });

            /* Removed effect due to bad frame rate from Flash animation */
            /*
            var myEffect = new Fx.Morph(elemDisclaimer.id, { duration: 500, transition: Fx.Transitions.Quad.easeOut });

            myEffect.start({
            'height': 0, //Morphs the height
            'border-bottom': 0
            });
            */
        });

    } // End  setupDisclaimer: function() { ...

    ,

    // Sets up rollover animations on the main nav
    setupMenuAnimation: function() {

        var aNavElems = $$('#mainnav li a');


        var iBounceHeight = 8;
        var n = 0; // Counter

        aNavElems.each(function(navElem) {
            n += 1;

            navElem.set("id", "nav" + n);

            navElem.originalColor = navElem.getStyle('color');
            navElem.getParent().navItem = navElem.id;

            navElem.originalHeight = 20; // Should be set to height of navItem from css (getting this in JS is unreliable)


            navElem.addEvent('mouseover', function(event) {

                event.stop();
                var elem = new Element(event.target);


                var myEffect1 = new Fx.Morph(elem.id, { link: 'ignore', duration: 300, transition: Fx.Transitions.Quad.easeOut });

                myEffect1.start({

                    //'bottom': [0, iBounceHeight], //Morphs the 'height' style from 10px to 100px.
                    'height': [navElem.originalHeight, navElem.originalHeight + iBounceHeight], //Morphs the 'height' style from 10px to 100px.

                    'color': '#FFFFFF',
                    'background-color': '#EC008C'

                });


            });


            navElem.addEvent('mouseout', function(event) {

                event.stop();
                var elem = new Element(event.target);

                var navElem = $(elem.id);


                var myEffect2 = new Fx.Morph(navElem.id, { link: 'ignore', duration: 300, transition: Fx.Transitions.Quad.easeOut });

                myEffect2.start({

                    //'bottom': [iBounceHeight, navElem.originalBottom], //Morphs the 'height' style from 10px to 100px.
                    'height': [navElem.originalHeight + iBounceHeight, navElem.originalHeight], //Morphs the 'height' 

                    'color': navElem.originalColor,
                    'background-color': '#FFFFFF'


                });

            });


        });

    } // End setupMenuAnimation: function() {    ...

    ,

    // Sets up an accordion list of media items
    setupMediaList: function() {

        // Get container element
        var eAccordionContainer = $('media');

        // Exit if container doesn't exist
        if (eAccordionContainer == undefined) {
            return;
        }

        var sToggleItems = 'ul#media h4.toggler';
        var sContentItems = 'ul#media div.mediaItem';

        // Put the accordion Togglers into an array
        var aItems = $$(sToggleItems);

        // Add a property called "index" to each toggler element
        var iCount = 1;
        aItems.each(function(toggler) {

            toggler.index = iCount;
            iCount += 1;

        });


        // Setup Accordion
        var myAccordion = new Accordion(eAccordionContainer, sToggleItems, sContentItems, {
            opacity: true,
            onActive: function(toggler, element) {

                // Clear all active styles on the items
                var aElems = $$('ul#media li');

                aElems.each(function(item) {
                    item.removeClass('active');
                });

                // Make the clicked LI class "active"
                var eParent = toggler.getParent();
                eParent.addClass('active');


                // Send a pause command when an item is opened
                var aElems = $$('ul#media li');
                for (var i = 0; i < aElems.length; i++) {
                    var iNumber = i + 1;
                    var sFlashElemId = 'myFlashContent' + iNumber;
                    sendToActionScript(sFlashElemId, 'pauseVideo');
                }

            },

            onComplete: function() {

                // Put onComplete code here

                _iPageInit = true; // Set this flag to true when the first accordion opens

                /* 
                
                // Removed this because we don't want flash to play on start
                
                var aElems = $$('ul#media li');
                var elemActive;
                var iActiveIndex = 1;

                        for (var i = 0; i < aElems.length; i++) {
                if (aElems[i].getAttribute('class') == 'active') {
                elemActive = i + 1;
                break;
                }
                iActiveIndex += 1;
                }

                        // Send "Play" command to displayed flash

                        
                var sFlashElemId = 'myFlashContent' + elemActive;
                var f = function() { sendToActionScript(sFlashElemId, 'playVideo'); };
                setTimeout(f, 500);
                */


            }


        });



        eAccordionContainer.setStyle('visibility', 'visible');
    } // End setupMediaList: function() {

	,

    // Sets up a mootools driven tabbed list of content
    setupTabbedList: function() {

        // Get an array of tab togglers
        var aElems = $$('ul.tabbedList a.toggler');

        // For each toggler
        aElems.each(function(toggler) {

            // Add the click event
            toggler.addEvent('click', function(event) {
                event.stop();

                var elem = event.target;
                var eParent = elem.getParent();

                // Clear the active tabes
                clearActiveTabs();

                // Set the parent LI to active
                eParent.addClass('active');

            });

        });

        // Clear the active tab classes
        var clearActiveTabs = function() {
            var aElems = $$('ul.tabbedList li');

            aElems.each(function(item) {
                item.removeClass('active');
            });
        };

    } // End setupTabbedList: function() {
	,


    // Set up the twitter feed display on Employee pages
    // The feeds are driven from the "_sUserField" JS variable
    // which is output from the CMS in BGEmployeeDetail.master
    // _sUserField contains the employee's Twitter UserName

    setupTwitterFeed: function() {

        if ($(_sTweetContainerId) == undefined) {
            // If the tweet container does not exist, exit
            return;
        }


        var url = "/handlers/TweetBio.ashx"; // Tweet XML page 
        var xml = new JKL.ParseXML(url); // Load up XML parser
        var data = xml.parse(); // Parse XML data

        var entries = data.feed.entry; // Get object to store entries

        // Array of entries for this user
        _userEntries = new Array();

        // Loop through entries
        for (var i = 0; i < entries.length; i++) {

            var sUser = entries[i].bgusername;

            // If the username on the entry matches the current user
            if (sUser.toLowerCase() == _sUserField.toLowerCase()) {
                // Store the entry in the userEntries array
                _userEntries[_userEntries.length] = entries[i];
            }
        }
        
        // If there are no tweets, hide the tab
        if (_userEntries.length == 0) {
            $("tweetTab").setStyle('visibility', 'hidden');
        } else {
            $("tweetTab").setStyle('visibility', 'visible');
        }


        // These vars will need to be dynamic
        var sSearchField = '';

        var dataUrl = "";

        // create the URL string to send to Twitter Search API
        var createQuery = function() {

            var sQuery = "q=" + sSearchField + "+from%3A" + _sUserField;
            dataUrl = _sTwitterSearchUrl + '?' + sQuery;

        };

        // create the URL string to send to Twitter Search API
        createQuery();

        // Get the container
        var elContainer = $(_sTweetContainerId);

        elContainer.set('html', '<span style=\'color: #666666\'>Getting tweets...</span>');

        var aButtonGet = $$('a.butGetTweets');

        // Add event on the "FEEDS" tab to get new tweets when clicked
        aButtonGet[0].addEvent('click', function(event) {
            event.stop();
            var elem = event.target;
            
            displayTweets(_userEntries);

        });


        // Update tweets
        var displayTweets = function(results) {
            results.each(function(result) {

                // Get the container
                var elContainer = $(_sTweetContainerId);

                var iColorIndex = _iTweetCount % _aColorArray.length;

                // Create the tweet display element
                var elTweet = new Element('div', { 'class': 'tweetContainer' });

                // Get Data from XML Object array

                // Get date (ex. '2010-01-12T14:58:30Z')
                var sDatePub = result.published["#text"];
                
                // Get date information from string

                //alert("YEAR = " + sDatePub.substring(0, 4) + " Month = " + sDatePub.substring(5, 7) + " sDay = " + sDatePub.substring(8, 10));
                
                var sYear = parseInt(sDatePub.substring(0, 4)); // Get year
                var sMonth = sDatePub.substring(5, 7); // Get Month
                var sDay = sDatePub.substring(8, 10); // Get Day
                var sHours = parseInt(sDatePub.substring(11, 13)) - 1; // Get Time
                var sMins = parseInt(sDatePub.substring(14, 16)); // Get Time
 				  //alert(sDay);
 		var stringDay = sDatePub.substring(8, 10);
	 
		if(stringDay.substring(0,1) == "0") {
			stringDay = stringDay.substring(1,2)	
		}
		
                var sUserName = result.bgusername; // Get username
                var sText = result.content["#text"]; // Get tweet content

                // Get date data
                var dDate = new Date(sYear, sMonth, sDay, sHours, sMins);
				//alert(dDate);
                var iMonth = dDate.getMonth();
                var iDay = dDate.getDate();
                var iYear = dDate.getFullYear();


                var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

                // Construct time display HTML
                var iHours = dDate.getHours() + 1;
                var sMinutes = dDate.getMinutes();

                if (sMinutes < 10) {
                    sMinutes = "0" + sMinutes;
                }

                iDay = "<span style='color: #" + _aColorArray[iColorIndex] + "'>" + stringDay + "</span>";
                var sAmPm = "AM";

                if (iHours > 12) {
                    sAmPm = "PM"
                    iHours -= 12;
                }
                var sTimeInfo = iHours + ":" + sMinutes + " " + sAmPm;

                // Construct time display HTML
				//alert(iMonth + " - " + sMonth + " - " + dDate ); 
                var sDateHtml = "<span class='tweetDate'><b>" + m_names[iMonth -1].substring(0, 3).toUpperCase() + " " + iDay + "</b><br /><span class='tweetTime'>" + sTimeInfo + "</span></span>";

                var aTextItems = sText.split(" ");

                sText = "<span style='color: #" + _aColorArray[iColorIndex] + "'>" + aTextItems[0] + "</span> ";

                // Color the items 
                for (var n = 1; n < aTextItems.length; n++) {
                    sText += aTextItems[n] + " ";
                }

                // Concat the string of HTML to add to the tweet element
                var sDisplay = sDateHtml + "<span class='tweetText'>" + sText + "</span>";

                elTweet.set("html", sDisplay);

                // Add the element to the array

                if (_bFirstTime) {
                    // put each tweet below the other on the first go through
                    //elTweet.inject(elContainer, 'bottom');

                    _aTweetArray.push(elTweet);

                } else {
                    // after the first time add them to the top
                    //elTweet.inject(elContainer, 'top');
                    _aTweetArray.push(elTweet);
                }

                _iTweetCount += 1

            });

            var elContainer = $(_sTweetContainerId);

            if (_bFirstTime) {
                _bFirstTime = false;
            }

            if (_userEntries.length == 0) {
                // No tweets to display
                elContainer.set('html', '<span style=\'color: #666666\'>No recent tweets found.</span>');
            } else {
                // Clear the container
                elContainer.set('html', '');
            }

            // Start adding tweet elements to the page
            Site.populateTweet();

            if (_iTweetCounter == 0) {
                // No tweets to display
                elContainer.set('html', '<span style=\'color: #666666\'>No recent tweets found.</span>');
            }

            // Set the dataUrl to the URL path to get the JSON data
            dataUrl = _sTwitterSearchUrl + _sTwitterRefreshUrl;

        }; // End var displayTweets = function(results) {


    } // setupTwitterFeed: function() {

	,

    // Adds a single tweet element to the tweet container element of the page
    populateTweet: function() {

        // Get the tweet container
        var elContainer = $(_sTweetContainerId);

        // if there are no tweets, return
        if (_aTweetArray.length == 0) {
            return;
        }

        // get a tweet from the array
        var elemTweet = _aTweetArray.pop();

        var iTweetHeight = _iTweetTextHeight;

        // Set the styles
        elemTweet.setStyle('height', 0);
        elemTweet.setStyle('overflow', 'hidden');
        elemTweet.inject(elContainer, 'top');

        // Create a tween effect for the height
        myFx = new Fx.Tween(elemTweet, {
            link: 'cancel',
            transition: Fx.Transitions.Quad.easeIn,
            onStart: function(elem) {
                //Start functions go here 
            },
            onComplete: function(elem) {
                // When the height animation is complete, add the next item
                Site.populateTweet();
            }
        });

        //then we create three tween elements, one for each var above
        myFx.start('height', iTweetHeight);

        _iTweetCounter += 1;


    } // end populateTweet: function() {

    ,


    // Sets Flash communication call
    initFlashCommunication: function() {

        // Handle all the FSCommand messages in a Flash movie.
        _jsReady = true;


    } // End  initFlashCommunication: function() {

} // End Site object



// Flash/JS communication calls :: START
// These functions are required so JS knows the "swf/vidplayer.swf" is ready,
// due to the fact it is contained lies within a mootools accordion control

    // isReady() is called by the Flash movie to determine if ExternalInterface communication with JavaScript is ready
    function isReady() {
        return _jsReady;
    }
       
    // sendToActionScript() sends commands to the Flash Video Player
    function sendToActionScript(sFlashObjectId, sCommand) {
        
        // Need to wrap this in a try catch because the flash may not be ready to
        // receivve commands for a few hundred milliseconds after the page loads

        try {
            // If the page is initialized, commands can be sent
            if (_iPageInit) {

                // if the Flash element exists and the "sendToActionScript" function is defined
                if (($(sFlashObjectId) != undefined) && ($(sFlashObjectId).sendToActionScript != undefined)) {
                    // call the AS function with the command string
                    $(sFlashObjectId).sendToActionScript(sCommand)
                }
            }

        } catch (e) {
            // If an error occurs here, it is most likely because the Flash control is not ready
            // console.log("Flash is not ready for ExternalInterface commands.");
        }
        
    }

    // sendToJavaScript() recieves commands from the Flash movie to JavaScript
    function sendToJavaScript(value) {
        // console.log(value);    
    }

// Flash/JS communication calls :: END

// Activate the site function on domready
window.addEvent('domready', Site.start);

function rand(max) {
    return Math.floor(Math.random() * (max + 1))
}
