
LiveStreamStatusCheck = new Class({
    Implements: [Options, Events],
    options: {
        intervalLength: (30000)
    },
    initialize: function(options){
        this.setOptions(options);
        dbug.log(" * LiveStreamStatusCheck: this.options.now: " + this.options.now);
        dbug.log(" * LiveStreamStatusCheck: this.options.page: " + this.options.page);
        dbug.log(" * LiveStreamStatusCheck: this.options.broadcastStatus: " + this.options.broadcastStatus);
        dbug.log(" * LiveStreamStatusCheck: this.options.broadcastStartTime: " + this.options.broadcastStartTime);
        dbug.log(" * LiveStreamStatusCheck: this.options.broadcastEndTime: " + this.options.broadcastEndTime);
        if (this.options.franchiseName) {
            dbug.log(" * LiveStreamStatusCheck: this.options.franchiseName: " + this.options.franchiseName);
        }
        if (this.options.promoImg) {
            dbug.log(" * LiveStreamStatusCheck: this.options.promoImg: " + this.options.promoImg);
        }

        if (!$('countDownDisplay')) {
            var cdDisplay  = new Element('div', {id: 'countDownDisplay'});
            cdDisplay.inject($('overviewHead'), 'after');
        }

        if (this.options.broadcastStartTime) {
            var isValidTime = this.findTimeDifference(this.options.broadcastStartTime)/60;
        } else {
            var isValidTime = null;
        }
        if (this.options.broadcastEndTime) {
            var isEndTime = this.findTimeDifference(this.options.broadcastEndTime)/60;
        } else {
            var isEndTime = null;
        }
        dbug.log(" * LiveStreamStatusCheck: isValidTime: " + isValidTime);
        dbug.log(" * LiveStreamStatusCheck: isEndTime: " + isEndTime);

        // main page, or video page?
        if (this.options.page=="index") {

            if (this.options.broadcastStatus=="IN_PROGRESS") {
                // if IN_PROGRESS start time is valid, show promo. If not, look for an UPCOMING stream
                if (isValidTime >-120 && isValidTime < 0) {
                    if (this.options.franchiseName && this.options.promoImg) {
                        this.displayPromo(this.options.franchiseName, this.options.promoImg, this.options.nodeId, this.options.query, this.options.broadcastStatus);
                    } else {
                        this.getPromoImageData(this.options.nodeId, this.options.query, this.options.broadcastStatus);
                    }
                } else {
                    this.findUpcomingLiveStream();
                }
            } else if (this.options.broadcastStatus=="DONE") {
                // IN_PROGRESS video is >30 minutes past the broadcast end time
                this.findUpcomingLiveStream();
            } else if (this.options.broadcastStatus=="UPCOMING" && (isValidTime > -15 && isValidTime < 60)) {
                // show UPCOMING promo, if time is valid
                if (this.options.franchiseName && this.options.promoImg) {
                    this.displayPromo(this.options.franchiseName, this.options.promoImg, this.options.nodeId, this.options.query, this.options.broadcastStatus);
                    // show is still upcoming but past start time, check if in progress
                    if (isValidTime < 0){
                        this.startInProgressTimer();
                    } else {
                        this.findStartTime();
                    }
                } else {
                    this.getPromoImageData(this.options.nodeId, this.options.query, this.options.broadcastStatus);
                }
            } else {
                // show random promo
                this.getPromoImageData(0, 0, null);
            }

        } else if (this.options.page=="show") {

            if (this.options.broadcastStatus=="UPCOMING") {
                // check for start time
                dbug.log(" * LiveStreamStatusCheck: check for start time: " + this.options.broadcastStatus + " / " + this.options.page);
                this.findStartTime();
            } else if (this.options.broadcastStatus=="IN_PROGRESS") {

                if (isValidTime >-120 && isValidTime < 0 || isEndTime < 0) {
                    dbug.log(" * LiveStreamStatusCheck: IN_PROGRESS, check for end");
                    this.showRestartLink();
                    this.checkForEndTimer();
                } else {
                    // play ondemand stream
                    dbug.log(" * LiveStreamStatusCheck: IN_PROGRESS is over, play ondemand");
                    this.loadOnDemandPlayer();
                }
            }
        }
    },
    findStartTime: function() {
        dbug.log(" * LiveStreamStatusCheck: findStartTime ");


        CNETAPI.register('default', {partTag: 'cntv'});
        videoApi = new CNETAPI.Utils.Video({

            onSuccess: function(item){

                var startTime = item[0].data.BroadcastStartTime.$;
                dbug.log(" * LiveStreamStatusCheck: BroadcastStartTime: " + startTime);


                if (startTime!=undefined) {

                    this.timeRemain = this.findTimeDifference(item[0].data.BroadcastStartTime.$);
                    dbug.log(" * LiveStreamStatusCheck: this.timeRemain: " + this.timeRemain);

                    if (this.timeRemain > 0 && this.timeRemain < 3600) {
                        // live stream hasn't started yet
                        // moo: periodical
                        this.startDisplayTimer();
                    } else if (this.timeRemain < 0){
                        // live stream has already started.
                        this.startInProgressTimer();
                    }
                } else {
                    dbug.log(" * LiveStreamStatusCheck: no BroadcastStartTime available. Fail.");
                }

            }.bind(this),

            onError: function() {
                dbug.log(" * LiveStreamStatusCheck: no results. Fail.");

            }

        }).get(this.options.query, {iod: "broadcast,lowcache", showBroadcast: true});
                //var startTime = this.options.broadcastStartTime;
                //dbug.log(" * LiveStreamStatusCheck: BroadcastStartTime: " + startTime);
                //
                //
                //if (startTime!=undefined) {
                //
                //    this.timeRemain = this.findTimeDifference(startTime);
                //    dbug.log(" * LiveStreamStatusCheck: this.timeRemain: " + this.timeRemain);
                //    //timeRemain is in seconds
                //    if (this.timeRemain > 0 && this.timeRemain < 3600) {
                //        // live stream hasn't started yet
                //        // moo: periodical
                //        this.startDisplayTimer();
                //    } else if (this.timeRemain < 0){
                //        // live stream has already started.
                //        this.startInProgressTimer();
                //    }
                //} else {
                //    dbug.log(" * LiveStreamStatusCheck: no BroadcastStartTime available. Fail.");
                //}

    },

    startDisplayTimer: function() {
        clearInterval(this.timer);
        this.timer = setInterval(this.displayCountdown.bind(this), 1000);
    },
    displayCountdown: function() {

        var thisTime = this.timeRemain;
        var hours = Math.floor(thisTime/(3600));
        thisTime -= (hours*3600);
        var minutes = Math.floor(thisTime/60);
        thisTime -= (minutes*60);
        var seconds = thisTime % 60;

        if (hours < 1) {
            hours = "";
        } else {
            hours += ":";
        }
        if (minutes < 1) {
            minutes = (hours != "") ? "00" : "";
        } else if (minutes < 10 && hours!="") {
            minutes = "0" + minutes; // if showing minutes, add leading 0 to secs <10
        }

        if (seconds < 10) seconds = "0" + seconds; // if showing minutes, add leading 0 to secs <10
        seconds = ":" + seconds;
        if (this.options.page=="index") {
            var cat = this.options.nodeId;
            var id = this.options.query;
            var url = "/9776-" + cat + "_53-" + id + ".html";
            $("pcPromo").getElement("DIV.showStatus").set('html', '<a href="' + url + '" class="upNext">Coming up next in ' + hours + minutes + seconds + '</a>');            
            $("cat"+cat).getElement("DIV.showStatus").set('text', 'Coming up next in ' + hours + minutes + seconds);
        } else {
            $('countDownDisplay').set('text', 'Live stream starts in ' + hours + minutes + seconds);
        }
        if (this.timeRemain > 0) {
            this.timeRemain--;
        } else {
            this.startInProgressTimer();
        }


    },
    showLiveStream: function() {
        this.stopTimer();
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        var movieName = (isIE) ? window["universalVideo"] : document["universalVideo"];
        movieName.showClipsFromPage("live", "live", "live");
    },
    checkForEndOfLiveStream: function(q) {
        dbug.log(" * LiveStreamStatusCheck: checkForEndOfLiveStream: " + q);

        liveStreamIsOver = this.liveStreamIsOver.bind(this);

        CNETAPI.register('default', {partTag: 'cntv'});
        videoApi = new CNETAPI.Utils.Video({

            onSuccess: function(item){
                dbug.log(" * LiveStreamStatusCheck: Status: " + item[0].data.BroadcastStatus.$);
                dbug.log(" * LiveStreamStatusCheck: FranchiseId: " + item[0].data.FranchiseId.$);
                var status = item[0].data.BroadcastStatus.$;

                var diff = findTimeDifference(item[0].data.BroadcastStartTime.$);
                var endTime = findTimeDifference(item[0].data.BroadcastEndTime.$);
                if (diff < -120 || endTime < 0 ) {
                    dbug.log(" * LiveStreamStatusCheck: Stopping timer");
                    liveStreamIsOver();
                } else if (diff < 1 && status != "IN_PROGRESS") {
                    liveStreamIsOver();
                }

            }
        }).get(q, {iod: "broadcast,lowcache", showBroadcast: true});
    },
    findUpcomingLiveStream: function() {
        dbug.log(" * LiveStreamStatusCheck: findUpcomingLiveStream");

        //findTimeDifference = this.findTimeDifference.bind(this);
        //displayPromo = this.displayPromo.bind(this);

        CNETAPI.register('default', {partTag: 'cntv'});
        videoApi = new CNETAPI.Utils.Video({

            onSuccess: function(item){
                if ($defined(item[0])) {
                    dbug.log(" * LiveStreamStatusCheck: Status: " + item[0].data.BroadcastStatus.$);
                    dbug.log(" * LiveStreamStatusCheck: Title: " + item[0].data.Title.$);
                    dbug.log(" * LiveStreamStatusCheck: FranchiseId: " + item[0].data.FranchiseId.$);
                    dbug.log(" * LiveStreamStatusCheck: BroadcastStartTime: " + item[0].data.BroadcastStartTime.$);
                    dbug.log(" * LiveStreamStatusCheck: Category: " + item[0].data.Category.id.toString());
                    dbug.log(" * LiveStreamStatusCheck: VideoId: " + item[0].data.id.toString());

                    var diff = this.findTimeDifference(item[0].data.BroadcastStartTime.$)/60;

                    dbug.log(" * LiveStreamStatusCheck: Time diff: " + diff);

                    if (diff <= 60 && diff > -15) {
                        dbug.log(" * LiveStreamStatusCheck: found good Upcoming stream %o");

                        // Set podcast listing to 'Coming up next'
                        var cat = item[0].data.Category.id.toString();
                        var id = item[0].data.id.toString();
                        var status = item[0].data.BroadcastStatus.$;
                        var showName = item[0].data.FranchiseName.$;
                        var imagesArray = item[0].data.Images.Image;
                        var promoImage = imagesArray.filter(function(item, index){
                            //dbug.log("image width: " + item.width.toString() + ", image height: " + item.height.toString());
                            return item.width.toString() == '360' && item.height.toString() == '203';
                        });
                        var showImg = promoImage[0].ImageURL.$;
                        this.options.query = id;
                        this.options.broadcastStatus = status;
                        this.options.broadcastStartTime = item[0].data.BroadcastStartTime.$;
                        this.options.broadcastEndTime = item[0].data.BroadcastEndTime.$;
                        this.options.nodeId = cat;
                        this.options.franchiseName = showName;
                        this.options.promoImg = showImg;
                        this.displayPromo(showName, showImg, cat, id, status);
                        dbug.log(" * LiveStreamStatusCheck: after displayPromo call");
                        if (diff <= 0){
                            this.startInProgressTimer();
                        } else {
                            this.findStartTime();
                        }


                    } else {
                        dbug.log(" * LiveStreamStatusCheck: display random promo");
                        this.getPromoImageData(0, 0, null);
                    }
                } else {
                    //empty results, check if it's inprogress
                    dbug.log(" * LiveStreamStatusCheck: no results for findUpcomingLiveStream. Fail.");
                    this.options.query = "";
                    this.findInProgressLiveStream();
                }
            }.bind(this),

            onError: function() {
                dbug.log(" * LiveStreamStatusCheck: no results for findUpcomingLiveStream. Fail.");
                this.getPromoImageData(0, 0, null);
            }

        }).search("", {videoIds: "", iod: "images,broadcast,breadcrumb,lowcache", broadcastStatus: "UPCOMING", orderBy: "broadcastStartTime", sortAsc: "true"});
    },

    findInProgressLiveStream: function() {
        dbug.log(" * LiveStreamStatusCheck: findInProgressLiveStream");
            CNETAPI.register('default', {partTag: 'cntv'});
            videoApi = new CNETAPI.Utils.Video({

                onSuccess: function(item){
                    dbug.log(" * findInProgressLiveStream: Status: " + item[0].data.BroadcastStatus.$);
                    if (item[0].data.BroadcastStatus.$ == "IN_PROGRESS") {
                        if (this.options.page=="show"){
                        	this.options.query = item[0].data.id.toString();
                        	this.options.liveEpisodeTitle = item[0].data.Title.$;
                            this.showWatchNowLink();
                        } else if (this.options.page=="index"){

                            clearInterval(this.timer);
                            var cat = item[0].data.Category.id.toString();
                            var id = item[0].data.id.toString();
                            var status = item[0].data.BroadcastStatus.$;
                            var showName = item[0].data.FranchiseName.$;
                            var imagesArray = item[0].data.Images.Image;
                            var promoImage = imagesArray.filter(function(item, index){
                                return item.width.toString() == '360' && item.height.toString() == '203';
                            });
                            var showImg = promoImage[0].ImageURL.$;
                            this.displayPromo(showName, showImg, cat, id, status);
                        }
                    } else {
                        if (item[0].data.BroadcastStatus.$ == "DONE") {
                            dbug.log(" * findInProgressLiveStream: video id: " + item[0].data.id.toString() + " needs to be set to DONE.");
                            this.getPromoImageData(0, 0, null);
                        }
                    }
                }.bind(this),

                onError: function() {
                    dbug.log(" * LiveStreamStatusCheck: no results for findInProgressLiveStream. Fail.");
                }

            }).search("", {videoIds: this.options.query, iod: "images,broadcast,lowcache", showBroadcast: true, broadcastStatus: "IN_PROGRESS", sortDesc: "true" });
    },
    startInProgressTimer: function() {
        dbug.log(" * LiveStreamStatusCheck: startInProgressTimer");
        clearInterval(this.timer);
        this.showWaitaMinute();
        this.timer = setInterval(this.findInProgressLiveStream.bind(this), 30000, true);
    },

    showWatchNowLink: function() {
        dbug.log(" * LiveStreamStatusCheck: showWatchNowLink");
        clearInterval(this.timer);
        var id = this.options.query;
        $('countDownDisplay').set('html', '<a href="javascript:previousLiveClick(\'live\', \'id\', \''+id+'\');updateEpisodeTitle(\''+this.options.liveEpisodeTitle+'\');">Start/restart live stream</a>');
    },
	
    showRestartLink: function() {
        dbug.log(" * LiveStreamStatusCheck: showRestartLink");
        clearInterval(this.timer);	
        var id = this.options.query;
        $('countDownDisplay').set('html', '<a href="javascript:previousLiveClick(\'live\', \'id\', \''+id+'\');updateEpisodeTitle(\''+this.options.liveEpisodeTitle+'\');">Restart live stream</a>');
    },

    showWaitaMinute: function() {
        dbug.log(" * LiveStreamStatusCheck: wait a minute...");
        clearInterval(this.timer);
        if (this.options.page=="index") {
            var cat = this.options.nodeId;
            var id = this.options.query;
            var url = "/9776-" + cat + "_53-" + id + ".html";
            $("pcPromo").getElement("DIV.showStatus").set('html', '<a href="' + url + '" class="upNext">Starts shortly</a>');
            $("cat"+cat).getElement("DIV.showStatus").set('text', 'Starts shortly');
        } else {
            $('countDownDisplay').set('html', 'Live stream will start shortly...');
        }

    },

    makeUTCtime: function(t) {
        // expected input: 2009-05-19 11:13:19 or 2009-03-25 14:12:28.0
        //dbug.log("makeUTCtime: " + t);
        var dateTime = t.split(" ");
        var date = dateTime[0].split("-");
        var time = dateTime[1].split(":");
        var newDate = new Date();

        newDate.setUTCFullYear(date[0])
        newDate.setUTCMonth(date[1]-1)
        newDate.setUTCDate(date[2])

        newDate.setUTCHours(time[0])
        newDate.setUTCMinutes(time[1])
        newDate.setUTCSeconds(Math.round(time[2]))

        return newDate;

    },
    getPromoImageData: function(cat, id, status) {
        dbug.log("getPromoImageData - cat: " + cat + " id: " + id + " status: " + status);
        if (cat==0) {
            // no live promo. choose random
            var promos = $$('DIV.promo');
            var rndPromo = promos.getRandom().get('id');
            if (rndPromo.contains("cat")) rndPromo = rndPromo.slice(3);
            cat = rndPromo;
        }


        // Set promo image
        var showName = "";
        var showImg = "";

        // Get image from api
        dbug.log("getting image from api with cat: " + cat);
        CNETAPI.register('default', {partTag: 'cntv'});
        videoApi = new CNETAPI.Utils.Video({

            onSuccess: function(item){
                dbug.log(" * LiveStreamStatusCheck: FranchiseName: " + item[0].data.FranchiseName.$);
                dbug.log(" * LiveStreamStatusCheck: Images: " + item[0].data.Images.toString());
                dbug.log(" * LiveStreamStatusCheck: Category: " + item[0].data.Category.id.toString());
                dbug.log(" * LiveStreamStatusCheck: VideoId: " + item[0].data.id.toString());
                showName = item[0].data.FranchiseName.$;
                var imagesArray = item[0].data.Images.Image;
                var promoImage = imagesArray.filter(function(item, index){
                    //dbug.log("image width: " + item.width.toString() + ", image height: " + item.height.toString());
                    return item.width.toString() == '360' && item.height.toString() == '203';
                });
                showImg = promoImage[0].ImageURL.$;
                this.displayPromo(showName, showImg, cat, id, status);
            }.bind(this),

            onError: function() {
                dbug.log(" * LiveStreamStatusCheck: no results for image search. set defaults.");
                cat = "19709";
                showName = "Buzz Out Loud";
                //showImg =  "http://cnettv.cnet.com/i/pod/images/bol_video_300x300.jpg";
                showImg =  "http://i.d.com.com/i/lumiere/2008/04/23/BOL_Logo_1-50001958-20080423_104742-360x203.jpg";
                status = null;
                this.displayPromo(showName, showImg, cat, id, status);
            }.bind(this)
        }).search("", {categoryIds: cat, iod: "images", limit: "1", orderBy: "broadcastStartTime", sortDesc: "true"});
    },
    displayPromo: function(showName, showImg, cat, id, status) {
        dbug.log('displayPromo: showName= ' + showName + ', showImg= ' + showImg + ', cat= '+ cat + ', status=' + status);

        var url = "/9776-" + cat + "_53-" + id + ".html";
        var p = '<div id="pcpWrap">';
        p += '<div class="overlay">';
        p += '<div class="showName"><a href="' + url + '">' + showName + '</a></div>';
        p += '<div class="showStatus"></div>';
        p += '<div class="watchLink"><a href="' + url + '">Watch</a></div>';
        p += '</div>';
        p += '<a href="' + url + '"><img src="' + showImg + '" width="360" height="203" border="0" alt="' + showName + '" /></a>';
        p += '</div>';


        $("pcPromo").set('html', p);

        /*
         $("pcPromo").getElement("DIV.showName").set('text', showName);
         $("pcPromo").getElement("IMG").set('src', showImg);
         */

        if (status=="UPCOMING") {
            $("pcPromo").getElement("DIV.showStatus").set('html', '<a href="' + url + '" class="upNext">Coming up next</a>');
            $("pcPromo").getElement("DIV.showStatus").set('style', "position: relative");
            $("pcPromo").getElement("DIV.showName").set('style', "padding-top:5px");

            $("cat"+cat).getElement("DIV.showStatus").set('text', 'Coming up next');

        } else if (status=="IN_PROGRESS") {
            $("pcPromo").getElement("DIV.showStatus").set('html', '<a href="' + url + '" class="onAir">On the air now</a>');
            $("pcPromo").getElement("DIV.showStatus").set('style', "position: relative");
            $("pcPromo").getElement("DIV.showName").set('style', "padding-top:5px;");

            $("cat"+cat).getElement("DIV.showStatus").set('text', 'On the air now');
            $("cat"+cat).addClass('showOnAir');
        } else {
            $("pcPromo").getElement("DIV.showStatus").set('html', "");
            $("pcPromo").getElement("DIV.showStatus").set('style', "position: absolute");
            $("pcPromo").getElement("DIV.showName").set('style', "font-size: 16px;padding-top:12px;");
        }



    },
    findTimeDifference: function(vidTime) {
        var t1 = this.makeUTCtime(vidTime);
        var t2 = this.makeUTCtime(this.options.now);

        /*
         dbug.log(" * LiveStreamStatusCheck: findTimeDifference: t1: " + t1 + " = " + (typeof t1));
         dbug.log(" * LiveStreamStatusCheck: findTimeDifference: t2: " + t2 + " = " + (typeof t2));
         dbug.log(" * LiveStreamStatusCheck: findTimeDifference: t1.getTime: " + t1.getTime() );
         dbug.log(" * LiveStreamStatusCheck: findTimeDifference: t2.getTime: " + t2.getTime() );
         */

        var diff = t1.getTime()-t2.getTime();

        var diffHours = diff / (1000*60*60);
        var diffMins = Math.round(diff / (1000*60));
        var diffSecs = Math.round(diff / (1000));

        //dbug.log(" * LiveStreamStatusCheck: Diff in mins: " + diffMins);

        return diffSecs;

    },
    liveStreamIsOver: function() {
        if (this.options.page == "show"){
            $('countDownDisplay').set('html', '');
        }
    },
    checkForEndTimer: function() {
        dbug.log(" * LiveStreamStatusCheck: checkForEndTimer");
        bindFunc = this.checkForEndOfLiveStream.bind(this);
        clearInterval(this.options.timer);
        this.options.timer = setInterval(bindFunc, this.options.intervalLength, this.options.query)
    },
    stopTimer: function() {
        dbug.log(" * LiveStreamStatusCheck: Timer stopped");
        clearInterval(this.options.timer);
    },

    loadOnDemandPlayer: function() {
        dbug.log(" * LiveStreamStatusCheck: loadOnDemandPlayer: " + $('universalPlayer0') );

        //if ($('universalPlayer0')==null) this.loadOnDemandPlayer();

        this.options.timer = setInterval(this.checkIfPlayerLoaded.bind(this), 1000);


        //previousLiveClick("", "nodeId", this.options.nodeId);

        /*
         var script = "<script type=\"text/javascript\">";
         script += "loadUniversalPlayer({";
         script += "parentElement: $('universalVideo'),";
         script += "playOverlayText: 'PLAY VIDEO',";
         script += "lumiereQueryType: 'nodeId',";
         script += "lumiereQueryValue: "+this.options.nodeId+",";
         script += "autoPlay: true,";
         script += "preRollAd: true,";
         script += "firstVideoPostAd: false,";
         script += "firstVideoPostRoll: false,";
         script += "contentPostRollAd: false,";
         script += "useCurrentPageUrl: false,";
         script += "hideTabs: true,";
         script += "hideEmailBtn:true,";
         script += "externalLinks:true,";
         script += "relatedVideo:false";
         script += "});";
         script += "</script>";

         $("livePlayer").set('html', script);
         */

    },

    checkIfPlayerLoaded: function() {
        dbug.log(" * LiveStreamStatusCheck: checkIfPlayerLoaded");
        if ($('universalPlayer0')!=null) {
            clearInterval(this.options.timer);
            previousLiveClick("", "nodeId", this.options.nodeId);
        }
    }


});

//update episode title/callout for cnet live show
 function updateEpisodeTitle(title){
	document.getElementById('episodeTitle').innerHTML=title;
	if(title.indexOf("LIVE!") != -1)
	{
		//document.getElementById('calloutImg').src="http://i.i.com.com/cnwk.1d/i/cnettv/cnetlive/CNETLive_ONAIR_130x20.gif";
		document.getElementById('calloutImg').src="http://i.i.com.com/cnwk.1d/i/cnettv/cnetlive/on_air_red_holiday.png";
	}
	else
	{
		//document.getElementById('calloutImg').src="http://i.i.com.com/cnwk.1d/i/cnettv/cnetlive/CNETLive_ONDEMAND_130x20.gif";
		document.getElementById('calloutImg').src="http://i.i.com.com/cnwk.1d/i/cnettv/cnetlive/on_demand_red_holiday.png";
	}
}

// Set up nav for IE

function addHoverClass(nav) {
    var navroot = document.getElementById(nav);
    var currentMenu=null;
    if (navroot != null) {
        // Get all the list items within the menu
        var lis=navroot.getElementsByTagName("LI");
        for(i=0;i<lis.length;i++){

            try {
                if (lis[i].childNodes.length>1 && lis[i].childNodes[2].tagName=="UL"){
                    // This LI is nav heading
                    var myParent = lis[i].childNodes[0].firstChild.nodeValue;

                    lis[i].childNodes[0].onmouseover=function(){
                        if (this.firstChild.nodeValue!=currentMenu) {
                            trackEvent("NavMenuExpand;" + this.firstChild.nodeValue + ";" + pageName());
                            currentMenu = this.firstChild.nodeValue;
                        }
                    };

                    lis[i].onmouseout=lis[i].onclick=function(){
                        this.className="";
                    };

                    lis[i].onmouseover=function(){
                        this.className="over";
                    };



                } else {
                    // This LI is in a submenu. Set the rev attribute to the parent menu name for tracking
                    lis[i].firstChild.setAttribute('rev', myParent);
                }
            } catch(e) {
            }
        }
    }
}



/* ADD FUNCTIONS RAN ON DOM READY HERE */
window.addEvent('domready', function() {
    addHoverClass('mainMenu');
});