// setup the top-level name space, if it hasn't already been done
if (typeof(KCRW) == 'undefined') {
    KCRW = {};
}
var saverow;
// setup the second-level namespace if it hasn't already been done.
if (typeof(KCRW.ChannelPlayer) == 'undefined') {
    KCRW.ChannelPlayer = {};
}

// convenience vars for accessing parts of MochiKit
var tag = MochiKit.DOM;
var mka = MochiKit.Async;
var mkb = MochiKit.Base;
var mkd = MochiKit.DOM;

// Math.random()*10 will return a value between 1 (0?) and 10 
var LIVE_CALL_INTERVAL = 20 + Math.random()*10;
var SCHED_CALL_INTERVAL = 110 + Math.random()*10;

// index vars used when accessing JSON data arrays
var LIVE = 0;
var MUSIC = 1;
var NEWS = 2;
//set up dictionary for channel id mappings
var channel_mapping={'0':'kcrwlive', '1':'kcrwmusic', '2':'kcrwnews'};

//Set up channel: request should come in as http://host/media_player_channel?channel=1
selected_channel_id=channel_mapping[location.search.split('=')[1]];

// zope configuration
var ZOPE='http://'+location.host;
// testing JSON data
var NOW_PLAYING = ZOPE+'/getJSONDataNowPlaying/' + selected_channel_id;
var SCHEDULE = ZOPE+'/getJSONDataSchedule/' + selected_channel_id;

// create some tags not included in MochiKit.DOM
H4 = tag.createDOMFunc('h4', null);
H5 = tag.createDOMFunc('h5', null);
EM = tag.createDOMFunc('em', null);


KCRW.ChannelPlayer.ScheduleLoader = function () {
    this.nowDiv = null;
    this.nowBoxNav = null;
    this.nowHeading = null;
    this.nowPic = null;
    this.nowPlayingDetails = null;
    this.nowProgramName = null;
    this.nowProgramTime = null;
    this.nowBottomLinks = null;
    this.currentNowTab = null;
    this.nowJSON = null;
    this.nowDeferred = null;

	//Added for np popup
	
	this.nowPlayingLink = null;
	
    this.schedBoxNav = null;
    this.schedFull = null;
    this.currentSchedTab = null;
    this.schedJSON = null;
    this.schedDeferred = null;

    bindMethods(this);
};

KCRW.ChannelPlayer.ScheduleLoader.prototype = {
    "initialize": function () {
        //log("ScheduleLoader.initialize", null);


        // prepare the "Now Playing" 
        dl = this.loadFromURL(NOW_PLAYING, 'now playing');
        // Always use 'LIVE', because we only have one data set coming back
        dl.addCallback(this.loadNowLive);

        // prepare the "Schedule" tabs
        ds = this.loadFromURL(SCHEDULE, 'schedule');
        ds.addCallback(this.loadSchedLive);

        // get all the now elements we'll need to manipulate
        var divNP=mkd.getElement('now_playing');
        var emNHeading=mkd.getElement('now_heading');
        var divSong=mkd.getElement('song');
        var divAlbum=mkd.getElement('album');
        var divSong=mkd.getElement('artist');
        var divP=mkd.getElement('previous');
        var emPHeading=mkd.getElement('previous_heading');
        var divPSong=mkd.getElement('previous_song');
        var divAlbum=mkd.getElement('previous_album');
        var divSong=mkd.getElement('previous_artist');
        this.nowProgramTime = mkd.getElement('program_time');
        this.nowPlayingDetails = mkd.getElement('playing_details');

		// Added for NP pop:
		this.nowPlayingLink = mkd.getElement('now_playing_link');

        this.showHost=null;
        this.nowPlayingDetails=null;
        this.showAlbum=null;
        this.songArtist=null;
        // get all the sched elements we'll need to manipulate
        this.schedFull = mkd.getElement("full_schedule");
        this.schedTable = mkd.getElement("lyr1");
        this.songArtist = mkd.getElement('artist');
        this.showDesc = mkd.getElement('show_description');
    },

    /*******************************
    JSON DATA-RELATED METHODS
    *******************************/

    "loadFromURL": function(url, tabType) {
        // Get the JSON data.
        //log('loadFromURL for URL '+url+' and tab type '+tabType);
        var d = mka.loadJSONDoc(url);
        switch (tabType) {
            case "now playing":
                if (this.nowDeferred) {
                    this.nowDeferred.cancel();
                };
                this.nowDeferred = d;
                // keep track of the current deferred, so that we can
                // cancel it
                var self = this;
                // on success or error, remove the current deferred
                // because it has completed, and pass through the result
                // or error
                d.addBoth(function (res) {
                    self.nowDeferred = null; 
                    //log('loadFromURL "now playing" success');
                    return res;
                });
                break;

            case "schedule":
                if (this.schedDeferred) {
                    //log('loadFromURL "schedule" cancelled');
                    this.schedDeferred.cancel();
                };
                this.schedDeferred = d;
                var self = this;
                d.addBoth(function (res) {
                    self.schedDeferred = null; 
                    //log('loadFromURL "schedule" success');
                    return res;
                });
                break;
        }
        // on success, time another call...
        //log('loadFromURL another call');
        d.addCallback(this.setupNextCall, url, tabType);
        // once it's ready, set the data
        d.addCallback(this.setJSONData, tabType);
        // if anything goes wrong, except for a simple cancellation,
        // then log the error and show the logger
        d.addErrback(function (err) {
            if (err instanceof CancelledError) {
                    //log('loadFromURL cancel error');
                return;
            }
            logError(err);
            logger.debuggingBookmarklet();
        });
        return d;
    },

    "setupNextCall": function(url, tabType, data) {
        // This method is our scheduler.
        ////log('setupNextCall for tab type', tabType.toString());
        switch (tabType) {
            case "now playing":
                interval = LIVE_CALL_INTERVAL;
                break;

            case "schedule":
                interval = SCHED_CALL_INTERVAL;
                break

        }
        d = callLater(interval, this.loadFromURL, url, tabType);
        d.addCallback(this.refreshDOM, tabType);
        return data;
    },

    "setJSONData": function(tabType, data) {
        switch (tabType) {
            case "now playing":
                this.nowJSON = data;
                break;

            case "schedule":
                this.schedJSON = data;
                break

        }
    },

    /*******************************
    DOM GENERATING METHODS
    *******************************/

    "makeScheduleRow": function(rowData) {
        ////log('makeScheduleRow called, program title =' + rowData.programTitle);
        if (mkb.isUndefinedOrNull(rowData.programTitle)) {
            ////log('ProgramTitle is null');
            return null;
        }
        
        // Check if show is 'current'
        var newDetails=null;
        var showHost=null;
        var showDesc=null;
        var nowPlayingDetails=null;
        var showAlbum=null;
        var songArtist=null;
		var nowPlayingLink = null;
        if (rowData.isCurrent == true) {
           rowAttr = { 'id':'current', 'class':'show' };
           ////log('Found current Row');
           showHost = this.showHost;
           if (mkb.isUndefinedOrNull(showHost)) {
              showHost = tag.P({'id':'show_host','class':'host'},null);
           }
           showDesc=self.showDesc;
           if (mkb.isUndefinedOrNull(showDesc)) {
              showDesc=tag.P({'id':'show_description','class':'description'},null);
           }
           nowPlayingDetails=this.nowPlayingDetails;
           if (mkb.isUndefinedOrNull(nowPlayingDetails)) {
              nowPlayingDetails=tag.DIV({'id':'playing_details',  'class':'nowplaying'},''); 
           }
		   // For np popup
		   nowPlayingLink=this.nowPlayingLink;
		   if (mkb.isUndefinedOrNull(nowPlayingLink)) {
  		     nowPlayingLink=tag.DIV({'id':'now_playing_link'},''); 
           }
		   if(rowData.programCategory=="MUSIC")	{
		   
		    	if(selected_channel_id == 'kcrwlive')	{
					nowPlayingLink = tag.appendChildNodes(nowPlayingLink,tag.P({'class':'info'},tag.A({'href' : '/nowPlayPopLive','target':'_blank','onclick':'liveNowPlaying();return false;'}, 'View Now Playing')));
				}	else	{
					newNowPlayingLink = tag.appendChildNodes(nowPlayingLink,tag.P({'class':'info'},tag.A({'href' : '/nowPlayPopMusic	','target':'_blank','onclick':'musicNowPlaying();return false;'}, 'View Now Playing')));
				}
		   
		   
		   	
		 	//  nowPlayingLink = tag.appendChildNodes(nowPlayingLink,P({'class':'info'},A({'href' : '#'}, 'View Now Playing')));
		   
		   }
		   
		   
           showAlbum=this.showAlbum;
           if (mkb.isUndefinedOrNull(showAlbum)) {
              showAlbum=tag.DIV({'id':'album'},null); 
           }
           songArtist=this.songArtist;
           if (mkb.isUndefinedOrNull(songArtist)) {
              songArtist=tag.DIV({'id':'artist'},''); 
           }
           //log('Found current Row: Applied tags');
        } else  {
           rowAttr = { 'class':'show' };
        }

        if (mkb.isNotEmpty(rowData.showTitle)) {
            //log('Has show data');
            showData = H5(null,
                tag.A({'href':rowData.showURL, 'target':'_blank', 
                  'onclick':"javascript:openPage('" + rowData.showURL + "');return false;"},
                    rowData.showTitle));
        } else {
            ////log('show Data is nothing');
            showData = '';
        }

        //get time tag 
        showTime=tag.DIV({'class':'time'},
                rowData.startTime+'-'+rowData.endTime );

        //get program info
        ////log('Program Data ' + rowData.programURL);
        programData = H4(null,
                tag.A({'href':rowData.programURL, 'target':'_blank', 
                  'onclick':"javascript:openPage('" + rowData.programURL + "');return false;"},
                    rowData.programTitle));
        //log('RETURNING FROM make schedule show npd=' + nowPlayingDetails);
        return tag.DIV(rowAttr,[showTime,programData,showData,showHost,showDesc,nowPlayingDetails,showAlbum,songArtist,nowPlayingLink]);

    },

    "makeAllScheduleRows": function(data) {
        ////log("Making schedule rows...");
        var rows = new Array();
        for (var i in data.showData) {
            rowData = data.showData[i];
            rows.push(this.makeScheduleRow(rowData));
        }
        ////log(rows.length + " Making schedule rows made");
        return rows;
        return tag.TBODY(null, 
            map(partial(function(row) {return row}),rows),
            tag.TR(null,
                tag.TD(null, tag.BR()),
                tag.TD(null, tag.BR())));
        //return tag.UL(attrs, map(partial(tag.LI, null), rows));

    },

    /*******************************
    DOM SWAPPING METHODS
    *******************************/
/*
    "swapTab": function(tabType, activeTab, newNav) {
        log("swapTab", tabType, activeTab);
        var firstID;
        var firstMethod;
        var secondID;
        var secondMethod;
        var data;
        var tabMethod
        switch (tabType) {
            case "now playing":
                data = this.nowJSON;
                tabMethod = 'Now';
                this.nowBoxNav = mkd.swapDOM(this.nowBoxNav, newNav);
                break;
            case "schedule":
                data = this.schedJSON;
                tabMethod = 'Sched';
                this.schedBoxNav = mkd.swapDOM(this.schedBoxNav, newNav);
                break;
        }
        switch (activeTab) {
            case "live":
                firstID = data[MUSIC].tabID;
                secondID = data[NEWS].tabID;
                firstMethod = 'load'+tabMethod+'Music'
                secondMethod = 'load'+tabMethod+'News'
                break;
            case "music":
                firstID = data[LIVE].tabID;
                secondID = data[NEWS].tabID;
                firstMethod = 'load'+tabMethod+'Live'
                secondMethod = 'load'+tabMethod+'News'
                break;
            case "news":
                firstID = data[LIVE].tabID;
                secondID = data[MUSIC].tabID;
                firstMethod = 'load'+tabMethod+'Live'
                secondMethod = 'load'+tabMethod+'Music'
                break;
        }

        // these event connections are here because they need to be created
        // every time the nav portion of the DOM gets recreated.
        connect(firstID, 'onclick', this, firstMethod);
        connect(secondID, 'onclick', this, secondMethod);
    },
*/
/*
    "swapPic": function(tabData) {
        var imgURL = tabData.imageSrc;
        //var imgURL = 'pic_pink_martini_lg.jpg';
        var newLivePic = tag.DIV({'class':'pic', 'id':'live_pic'},
            tag.IMG({'src':imgURL,'border':'0'}));
        this.nowPic = mkd.swapDOM(this.nowPic, newLivePic);
    },
    "swapProgramName": function(tabData) {
        var newName = tag.DIV({'id':'program_name'},
            H4(null,
                tag.A({'href':tabData.programURL},
                    tabData.programName)));
        this.nowProgramName = mkd.swapDOM(this.nowProgramName, newName);
    },

    "swapProgramTime": function(tabData) {
        ////log('---- swapProgramTime');
        var newTime = tag.DIV({'id':'program_name'},
            H4(null,
                tag.DIV({'class':'date','id':'program_time'},
                    tabData.startTime+' - '+tabData.endTime)));
        ////log('---- B) swapProgramTime ' + this.nowProgramTime);
        this.nowProgramTime = mkd.swapDOM(this.nowProgramTime, newTime);
    },
*/

    "swapPlayingDetails": function(tabData) {
        var showTitle = tabData.showTitle;
        var showURL = tabData.showURL;
        var artistName = tabData.artistName;
        var artistURL = tabData.artistURL;
        var songTitle = tabData.songTitle;
        var currentTime = tabData.currentTime;
        var artistLink = null;
        var songLine = null;
        var linkDicts = tabData.linkDicts;
        var albumTitle = tabData.albumTitle;
        var artistSep = ', ';
        var hostDicts= tabData.hostDicts;
        var hostHeading = tabData.hostHeading;
        var description = tabData.shortDescription;
        var buyLink ;
        var artistDicts= tabData.artistDicts;
        var artists = new Array();
        var artistTag = tag.DIV({'id':'artist'},null);
        var albumTag= tag.DIV({'id':'artist'},null);
        var descTag=tag.P({'id':'show_description','class':'description'},null);
        this.showHost = mkd.getElement('show_host');
        this.showDesc = mkd.getElement('show_description');
        this.showAlbum = mkd.getElement('album');
        this.songArtist = mkd.getElement('artist');
   
        //Loop through artistDicts, create a list of artists
        //log('DESCRIPTION =' + description);
        artists=[]
        if(artistDicts.length>0){
          for (var i = 0; i < artistDicts.length; i++) {
             //log('---- artistname = ' + artistDicts[i].artist_name);
          /*  To add artist link
              //if( artistDicts[i].artist_url ) {
             //    artists.push(tag.A({ 'href': artistDicts[i].artist_url },
             //                       artistDicts[i].artist_name) );
              //   if (i+1 < artistDicts.length){artists.push(', ');}
             // } else 
           */ 
             if(artistDicts[i].artist_name != '') {
                 artists.push( tag.SPAN({'class':'artist'}, artistDicts[i].artist_name) );
                 ////log('---- artists.length = ' + artists.length);
                 if (i+1 < artistDicts.length){artists.push(', ');}
              }
           }
           artistTag=tag.DIV({'id':'artist','class':'artist_info'},artists);
        }
        //log('---- ArtistDict tag = ' + artistTag);
        //artistTag=tag.DIV({'id':'artist','class':'artist_info'},'artists');

        hosts=null;
        if((!(linkDicts==[] || linkDicts=='' || linkDicts==null)) &&  (albumTitle != null && albumTitle != '') ) {
           //log('---- Creating buy link ' + linkDicts.length);
           for (var i = 0; i < linkDicts.length; i++) {
             if(linkDicts[i].link_type=='Amazon') {
                
                albumTag=tag.DIV( {'id':'album','class':'album_info'},
                   tag.SPAN({'class':'album'}, 
                        tag.A( {'href':linkDicts[i].url,'target':'blank_'},albumTitle)
                           )
                   );
                break;
             }
          } 
        } 
        if (albumTitle != null && albumTitle != '' && albumTag==null) {
                  //log('---- NO link, creating album text');
                albumTag=tag.DIV( {'id':'album','class':'album_info'},
                   tag.SPAN({'class':'album'}, albumTitle
                           )
                   );
        }


        //log('---- ALBUM TITLE ' + albumTitle);
        if(hostDicts.length>0) {
        host_list=[hostHeading];
        for (var i = 0; i < hostDicts.length; i++) {
          host_list.push( hostDicts[i].title );
          if (i+1 < hostDicts.length){host_list.push(', ');}
        } 
          hosts=tag.P({'id':'show_host','class':'host'}, host_list);
        }

        if(description){
            descTag=tag.P({'id':'show_description','class':'description'},description);
        }

        //log('---- song title =' + songTitle);
        if (songTitle != null) {
            songLine = tag.DIV({'class':'song_info'}
                  ,tag.SPAN({'class':'song'},songTitle), ' '
                  ,tag.SPAN({'class':'time'},currentTime)
                );
        }
        //log('---- song title DONE =' + songTitle);
        emContent='';
        if( songTitle !='' && songTitle != null)  {emContent='Now Playing';}
        var newDetails = tag.DIV({'id':'playing_details', 'class':'nowplaying'},
            EM(null,emContent), songLine);
			
        this.nowPlayingDetails = mkd.getElement('playing_details');
       
        this.nowPlayingDetails = mkd.swapDOM(this.nowPlayingDetails, 
            newDetails);
        this.showHost = mkd.swapDOM(this.showHost, hosts);
        this.showDesc = mkd.swapDOM(this.showDesc, descTag);
        this.showAlbum = mkd.swapDOM(this.showAlbum, albumTag);
        this.songArtist = mkd.swapDOM(this.songArtist, artistTag, tag.DIV({'id':'artist','class':'artist_info'},'artists') );
    },

    "swapBottomDetails": function(tabData) {
        var newLinks = tag.DIV({'class':'bottom_links', 'id':'now_bottom_links'},
            tag.P({'class':'links'},
                tag.A({'href':tabData.podcastURL, 'class':'podcast'},
                    'Podcast')));
        this.nowBottomLinks = mkd.swapDOM(this.nowBottomLinks, newLinks);
    
    },

    "swapNowPlayingDOM": function(data) {
        ////log("Swapping out 'Now Playing' DOM...");
        this.swapPlayingDetails(data);
        //log("--- swapPlayingDetails");
        nowPlayingDetails = mkd.getElement('playing_details');
       
    },

    "swapFullSchedule": function(data) {
        ////log("Swapping full schedule link to ", data.fullScheduleURL);
        var newFull = tag.DIV({'class':'schedule_link', 'id':'full_schedule'},
         tag.A({'href':data.fullScheduleURL,'onclick':"javascript:openPage('" + data.fullScheduleURL + "');return false;"}, data.scheduleTitle));
        this.schedFull = mkd.swapDOM(this.schedFull, newFull);
    },

    "swapScheduleTable": function(data) {
        NP=this.nowJSON;
        var attrs = {'id': 'lyr1', 'class': 'content2'};
        var newDiv = tag.DIV(attrs, this.makeAllScheduleRows(data));
        this.schedTable = mkd.swapDOM(this.schedTable, newDiv);
        var currentSection= mkd.getElement('current');
        if (  !mkb.isUndefinedOrNull(currentSection) && !mkb.isUndefinedOrNull(NP) ){
           //IF there's a current section, update playing details 
           this.swapPlayingDetails(this.nowJSON[LIVE]);
        }
    },

    "swapSchedDOM": function(data) {
        // swap full schedule link
        this.swapFullSchedule(data);
        // swap data table
        this.swapScheduleTable(data);
        //initt scrollbar
        initScrollLayer();
        setItUp();
    },

    "refreshDOM": function(tabType, data) {
        ////log("Refreshing DOM...", tabType);
        var jsonData;
        var tab;
        var func;
        switch (tabType) {
            case "now playing":
                ////log('Tab now playing');
                jsonData = this.nowJSON;
                tab = this.currentNowTab;
                func = this.swapNowPlayingDOM;
                break;
            case "schedule":
                ////log('Tab Schedule');
                jsonData = this.schedJSON;
                tab = this.currentSchedTab;
                func = this.swapSchedDOM;
                break;
        }
        data=jsonData[0];
        func(data);
    },

    /*******************************
    CONTENT LOADER METHODS
    *******************************/

    "loadNowLive": function(evnt) {
        //log("ScheduleLoader.loadNowLive");
        this.swapNowPlayingDOM(this.nowJSON[LIVE]);
    },
    "loadSchedLive": function() {
        //log("ScheduleLoader.loadSchedLive");
        this.swapSchedDOM(this.schedJSON[LIVE]);
    },

    "loadSchedMusic": function(evnt) {
        ////log("ScheduleLoader.loadSchedMusic");
        evnt.preventDefault();
        evnt.stopPropagation();
        this.currentSchedTab = 'music';
        this.swapToMusicTab('schedule');
        this.swapSchedDOM(this.schedJSON[MUSIC]);
    },

    "loadSchedNews": function(evnt) {
        ////log("ScheduleLoader.loadSchedNews");
        evnt.preventDefault();
        evnt.stopPropagation();
        this.currentSchedTab = 'news';
        this.swapToNewsTab('schedule');
        this.swapSchedDOM(this.schedJSON[NEWS]);
    }
};

//MochiKit.LoggingPane.createLoggingPane();
scheduleLoader = new KCRW.ChannelPlayer.ScheduleLoader();
addLoadEvent(scheduleLoader.initialize);

