// Toggle Actor/Director list
Event.observe(window, 'load', function() {
    $$('a.toggle_list').invoke('observe', 'click', function(event) {
        event.stop();
        var target = event.element();
        target.up().down('span.full_list').toggle();
        target.update(target.innerHTML=='Hide Full List' ? 'Show Full List' : 'Hide Full List' );
    });
});

// Mini schedule switcher & toggler
//<img src="/SiteImagesLib/starz_arrow_down_02.gif" /> View More
//<img src="/SiteImagesLib/starz_arrow_up_02.gif" /> Close
MiniSchedule = Class.create({
    initialize: function (element) {
        this.element = element;
        this.groups = element.select('ul.list');
        this.previous = element.select('a.previous_group')[0];
        this.next = element.select('a.next_group')[0];
        this.currentGroup = 0;
        this.logo = element.select('span.miniScheduleLogoStarz')[0];
        if (this.logo == null) this.logo = element.select('span.miniScheduleLogoEncore')[0];
        if (this.logo == null) this.logo = element.select('span.miniScheduleLogoMovieplex')[0];
        this.toggleLink = element.select('a.view_mini_schedule')[0] || null;
        fixIEReminders();

        if (this.previous) {
            this.previous.observe('click', this.showPreviousGroup.bindAsEventListener(this));
        }
        if (this.next) {
            this.next.observe('click', this.showNextGroup.bindAsEventListener(this));
        }
        if (this.toggleLink) {
            this.toggleLink.observe('click', this.toggleList.bindAsEventListener(this));

            //IDSTARZDOTCOM-2272 - NOTE:    prototype is somehow making the :hover visible after the click event fires
            //                              so we need to manually unset the text-decoration to none/underline accordingly
            this.toggleLink.observe('mouseover', this.toggleLinkMouseOver.bindAsEventListener(this));
            this.toggleLink.observe('mouseout', this.toggleLinkMouseOut.bindAsEventListener(this));
        }

        for (var i = 1; i < this.groups.length; i++) {
            this.groups[i].hide();
        }
        this.toggleList();
    },
    showPreviousGroup: function (event) {
        event.stop();
        this.currentGroup = this.currentGroup == 0 ? this.groups.length - 1 : this.currentGroup - 1;
        this.showGroup(this.currentGroup);
    },
    showNextGroup: function (event) {
        event.stop();
        this.currentGroup = this.currentGroup == this.groups.length - 1 ? 0 : this.currentGroup + 1;
        this.showGroup(this.currentGroup);
    },
    showGroup: function (group) {
        // show proper list
        fixIEReminders();
        this.groups.invoke('hide');
        this.groups[group].show();

        // update logo image
        var channel = $A(this.groups[group].classNames()).without('list');
        this.logo.className = MiniSchedule.channelLogos[channel];
        //this.logo.src = '/SiteImagesLib/' + MiniSchedule.channelLogos[channel];
        this.logo.className += " " + channel;

        // per STZOM00000431 - toggle the 'View More' link
        if (this.toggleLink && this.toggleLink.hasClassName('collapsed')) {
            this.toggleLink.removeClassName('collapsed');
        }

        this.toggleList();
    },
    toggleLinkMouseOver: function (event) {
        this.toggleLink.setStyle({ 'text-decoration': 'underline' });
    },
    toggleLinkMouseOut: function (event) {
        this.toggleLink.setStyle({ 'text-decoration': 'none' });
    },
    toggleList: function () {
        // when collapsing:
        // - show the first 3 items (<p>)
        // - hide remaining items (<p>) inside the current day (<li>)
        // - hide remaining days (<li>)
        // when showing:
        // - show all items and days
        if (this.toggleLink && this.toggleLink.hasClassName('collapsed')) {
            // expand
            this.groups.each(function (group) {
                group.select('li, p').invoke('show');

            });

            this.toggleLink.removeClassName('collapsed');
            this.toggleLink.update('<span class="starzArrowUp"></span> Close');

        } else {

            /* per STZOM00000431
            The View More link on the Movie Details pages 
            should only display if there are 
            more than three airings in the scehdule for the title,
                
            If the title is on multiple channels 
            and has more than three airings the link appears 
                
            If the title is on multiple channels 
            and there are more than three airings display link, 
            if there are less than three airings for the next channel, 
            suppress link (also suppress Close link).  
            */

            var showToggleLink = false;         // flag to show/hide the "View More" link based on rules stated above
            var totalChannels = 0;              // total channels this title is appearing on
            var totalItems = 0;                 // total items that could be revealed
            var revealedItemsArray = [];        // the total revealed, indexed per channel
            var channelItemsArray = [];         // the total items, indexed per channel
            var channelHiddenItemsArray = [];         // the total items, indexed per channel

            //debugger;    

            // this collapse code needs to comb its hair if it ever wants to get a date
            this.groups.each(function (group) {


                var li = group.select('li').reject(function (n) {
                    return (n.hasClassName('even') || n.hasClassName('odd'));
                });

                var revealedItems = 0;
                var channelItems = 0;
                var hiddenItems = 0;
                for (var i = 0; i < li.length; i++) {

                    if (li[i].className == "info") continue;

                    totalItems++;
                    channelItems++;

                    if (revealedItems < 3) {
                        var p = li[i].select('li');
                        for (var j = 0; j < p.length; j++) {

                            if (revealedItems < 3) {
                                p[j].show();
                            }
                            else {
                                p[j].hide();
                                hiddenItems++;
                            }


                            revealedItems++;
                        }
                    } else {
                        li[i].hide();
                        hiddenItems++;

                    }
                }
                //Added ChannelHiddenItemsArray to track hidden items per group
                channelHiddenItemsArray[totalChannels] = hiddenItems;
                channelItemsArray[totalChannels] = channelItems;
                revealedItemsArray[totalChannels] = revealedItems;
                totalChannels++;

            });

            // determine if we need to show the 'View More' link
            showToggleLink = false;
            if (channelHiddenItemsArray[this.currentGroup] != 0) showToggleLink = true;
            if (this.toggleLink) { // pretty sure this always resolves to true

                this.toggleLink.addClassName('collapsed');
                this.toggleLink.update('<span class="starzArrowDown"></span> View More');
                (showToggleLink == true) ? this.toggleLink.show() : this.toggleLink.hide();
            }


            /***** DEBUG ****
            var crlf = "\r\n\r\n";

            var alertString = '' +
            'toggleLink: ' + this.toggleLink + crlf +
            'collapsed? ' + this.toggleLink.hasClassName('collapsed') + crlf +
            'totalChannels: ' + totalChannels + crlf +
            'totalItems: ' + totalItems;

            alert(alertString);*/
            /***** END DEBUG *****/

        }
    }

});
MiniSchedule.init = function() {
    var schedules = $$('.mini_schedule_one, .mini_schedule_two');
    schedules.each(function(schedule){
        new MiniSchedule(schedule);
    });
}
MiniSchedule.channelLogos = {
    'starz': 'miniScheduleLogoStarz',
    'starz_cinema': 'miniScheduleLogoStarzCinema',
    'starz_comedy': 'miniScheduleLogoStarzComedy',
    'starz_edge': 'miniScheduleLogoStarzEdge',
    'starz_in_black': 'miniScheduleLogoStarzBlack',
    'starz_kids': 'miniScheduleLogoStarzFamily',
    'encore': 'miniScheduleLogoEncore',
    'encore_action': 'miniScheduleLogoEncoreAction',
    'encore_drama': 'miniScheduleLogoEncoreDrama',
    'encore_love': 'miniScheduleLogoEncoreLove',
    'encore_mystery': 'miniScheduleLogoEncoreMystery',
    'encore_wam': 'miniScheduleLogoEncoreWam',
    'encore_western': 'miniScheduleLogoEncoreWestern',    
    'indieplex': 'miniScheduleLogoIndieplex',
    'movieplex': 'miniScheduleLogoMovieplex',
    'retroplex': 'miniScheduleLogoRetroplex',
    'all': 'miniScheduleLogoAll'


}

Event.observe(window, 'load', MiniSchedule.init);

SavedFavoriteSet = Class.create({
    initialize: function(element) {
        this.el = element;

        this.favorites = $(this.el.parentNode).select('.savedfavorite');
        if(this.favorites.length < 1) {
            this.favorites = $(this.el.parentNode).select('input');
            this.el.observe('click', this.clearFavoritesInputSet.bindAsEventListener(this));
        } else {
            this.el.observe('click', this.removeFavoritesFromSet.bindAsEventListener(this));
        }
    },
    removeFavoritesFromSet: function(event) {
        event.stop();

        params = { favorites: [] }
        this.favorites.each(function(favorite) {
            params.favorites.push(favorite);
        });

        new Ajax.Request(this.el.href, {
            method: 'post',
            params: params,
            onComplete: this.removeElements.bind(this)
        });
    },
    removeElements: function() {
        this.favorites.each(function(favorite) {
            if(favorite.parentNode.className == 'row') {
                favorite.up('div.row').remove();
            } else {
                favorite.remove();
            }
        });
    },
    clearFavoritesInputSet: function(event) {
        event.stop();
        
        this.favorites.each(function(favorite) {
            favorite.setValue(false);
        });
    }
});
SavedFavorite = Class.create({
    initialize: function(element) {
        this.el = element;
        this.el.observe('click', this.removeFavorite.bindAsEventListener(this));
    },
    removeFavorite: function(event) {
        event.stop();
        new Ajax.Request(this.el.href, {
            method: 'post',
            onComplete: this.removeElement.bind(this)
        });
    },
    removeElement: function() {
        if(this.el.parentNode.className == 'row') {
            this.el.up().remove();
        } else {
            this.el.remove();
        }
    }
});
SavedFavorite.init = function() {
    if($$('.savedfavorite').length > 0) {
        $$('.savedfavorite').each(function(favorite) {
            new SavedFavorite(favorite);
        });
    }
    if($$('.clear_selections').length > 0) {
        $$('.clear_selections').each(function(clearbutton) {
            new SavedFavoriteSet(clearbutton);
        });
    }
}

//Event.observe(document, 'dom:loaded', SavedFavorite.init);
Event.observe(window, 'load', SavedFavorite.init);


// General purpose Starz functions
Starz = {
    isLoggedIn: function() {
        return (Starz.LOGGED_IN)
    },
    preloadImages: function(images) {
        var image;
        for (var i=0; i<images.length; i++) {
            image = new Image();
            image.src = images[i];
        }
    }
}

/* Monkeypatching from Sharepoint .js files since they iterate over an array 
   of strings in a dumb way that breaks when Prototype enters the MS ecosystem */
Event.observe(document, 'load', function() {
    AP_PopulateFromSerializedObjectQString = function(objectToPopulate, queryStringSegment) {
        var currentWorkingQString=queryStringSegment
        var indexOfQStringStart=queryStringSegment.indexOf("?");
    
        if(-1!=indexOfQStringStart) {
            currentWorkingQString=queryStringSegment.substr(indexOfQStringStart);
        }
    
        var propArray=currentWorkingQString.split("&");
        for(var i=0; i<propArray.length; i++) {
            var nameValuePair=propArray[i].split("=");
            if(nameValuePair.length==2) {
                objectToPopulate[nameValuePair[0]]=decodeURIComponent(nameValuePair[1]);
            }
        }
    }
});


TabControl = Class.create({
    initialize: function() {
        this.tabs = [];
        $$('.tabSwitch').each(function(el) {
            this.addTab(el);
        }.bind(this));
        if(window.location.href.indexOf('#') != -1 && this.tabs.length > 0) {
            var hash = window.location.href.split('#')[1];
            for(var i = 0; i < this.tabs.length; i++) {
                if(this.tabs[i].link.getAttribute('href').split('#')[1] == hash) {
                    this.tabs[i].select(null, this);
                }
            }
        } else if(this.tabs.length > 0) {
            this.currentTab = this.tabs[0];
            this.tabs[0].select(null, this);
        }
    },
    addTab: function(el) {
        this.tabs.push(new Tab(el));
    },
    editorFixer: function() {
        if(this.currentTab && $$('ul.playing_now_featured'+this.currentTab.className).length >= 1) {
            $$('ul.playing_now_featured'+this.currentTab.className).invoke('setStyle', 'display', 'block');
        }
    }
});

Tab = Class.create({
    initialize: function(el) {
        this.link = el;
        this.tab = el.up();
        this.className = '.'+this.link.getAttribute('href').split('#')[1];
        this.link.observe('click', this.select.bindAsEventListener(this));
    },
    select: function(event, tabcontrol) {
        if(event) { event.stop(); }
        if(tabcontrol) { TabControl.instance = tabcontrol; }
        TabControl.instance.tabs.each(function(tab) { tab.deselect(); });
        TabControl.instance.currentTab = this;
        this.tab.addClassName('current');
        $$(this.className).invoke('setStyle', { display: 'block' });
        // this is needed for some reason because sharepoint sucks
        TabControl.instance.editorFixer();
        this.toggleWidows();
        this.toggleLinks();
		
		var url = location.href;
		url = url.split("#")[0];
		url = url + "#" + this.className.split(".")[1];
		location.href = url;
		
    },
    deselect: function() {
        $$(this.className).invoke('setStyle', { display: 'none' });
        this.tab.removeClassName('current');
    },
    toggleWidows: function() {
        if(!$$('.tabcontent')[0]) { return; }
        var tabcontent = $$('.tabcontent')[0];
        
        tabcontent.select('ul').each(function(list) {
            if(!list.hasClassName('playing_now_featured')) {
                var display = '';
                for(var i = 0; i < list.select('li').length; i++) {
                    if(!list.select('li')[i].hasClassName('section')) {
                        (list.select('li')[i].style.display == 'none' && display != true) ? display=false : display=true;
                    }
                }
                (!display) ? list.hide() : list.show();
				
            }
        });
    },
    toggleLinks: function() {
        if(!$$('.browse_genres')[0] || typeof(this.className) == 'undefined') { return; }
        $$('.browse_genres')[0].select('a').each(function(link) {
            link.href = link.href.split('#')[0]+'#'+this.className.replace('.', '');
        }.bind(this));

        
    }
});

TabControl.init = function() {
    TabControl.instance = new TabControl();
};

var currentScheduleTab;

function currentSelectedScheduleTab(cst)
{
    currentScheduleTab = cst;
}

function onScheduleListChange(obj)
{
    var tabToDisplay = document.location.hash;
	// studid ie hack
	tabToDisplay = tabToDisplay.split("/").join("");
	if(tabToDisplay != "#listview_tab" && tabToDisplay != "#gridview_tab")
	{
		tabToDisplay = "#gridview_tab";
	}
	var loc = '/schedule?date='+obj.value+'&'+tabToDisplay;
    window.location = loc;
}

function drawTabs()
{
    if(!!TabControl.instance) {
        TabControl.instance.editorFixer();
    }
}

function initTabs()
{
    TabControl.init();
    setTimeout("drawTabs()", 750);
}



/* Draggable stuff for title picker*/
Draggables = Class.create({
    initialize: function() {
        this.draggables = this.getDraggables();
    },
    getDraggables: function() {
        var draggables = [];
        $$('.draggable').each(function(el) {
            draggables.push(new Draggable(el));
        });
        return draggables;
    },
    unsetAll: function() {
        this.draggables.each(function(draggable) {
            draggable.parent.setStyle({ position: 'static', top: '0', left: '0', height: 'auto', width: 'auto' });
        });
    }
});


Draggable = Class.create({
    initialize: function(el) {
        this.el = el;
        this.parent = el.up('table').up('div');
        
        this.bStartDrag = this.startDrag.bindAsEventListener(this);
        this.bDrag = this.drag.bindAsEventListener(this);
        this.bEndDrag = this.endDrag.bindAsEventListener(this);
        
        this.el.observe('mousedown', this.bStartDrag);
    },
    startDrag: function(event) {
        this.parent.absolutize();
        this.el.stopObserving('mousedown', this.bStartDrag);
        document.observe('mouseup', this.bEndDrag);
        document.observe('mousemove', this.bDrag);
    },
    drag: function(event) {
        this.parent.setStyle({
            top: event.pageY-this.parent.getOffsetParent().cumulativeOffset()[1]+'px',
            left: event.pageX-this.parent.getOffsetParent().cumulativeOffset()[0]+'px'
        });
    },
    endDrag: function(event) {
        document.stopObserving('mouseup', this.bEndDrag);
        document.stopObserving('mousemove', this.bDrag);
        this.el.observe('mousedown', this.bStartDrag);
    }
});

Draggables.init = function() {
    Draggables.instance = new Draggables();
}

Event.observe(window, 'load', Draggables.init);

///hides "extra" clocks" by redrawing
function fixIEReminders()
{
     if (navigator.appVersion.indexOf("MSIE") > 0)
     {
        jQuery(".has_tooltip").hide();
        jQuery(".has_tooltip").show();
     }
}

function masterReadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


