Navigation = Class.create({
    initialize: function(element) {
        this.element = $(element);
        this.items = this.element.childElements();
        this.items.invoke('observe', 'mouseover', this.onItemOver.bindAsEventListener(this));
        this.items.invoke('observe', 'mouseout', this.onItemOut.bindAsEventListener(this));
        this.timer = null;
    },
    onItemOver: function(event) {
        // obtain the root <li>
        var item = event.element().up('li[class]') || event.findElement('li');

        if (this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(this.showMenu.bind(this,item), 250);
        
    },
    onItemOut: function(event) {
        if (this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(this.hideMenu.bind(this), 250);
    },
    showMenu: function(item) {
        if (this.element.className != item.className) {
            this.element.className = item.className;
        }
    },
    hideMenu: function() {
        this.element.className = '';
    }
});
Navigation.init = function() {
    Navigation.instance = new Navigation('Navigation');
}
Event.observe(document, 'dom:loaded', Navigation.init);

// 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('img')[0];
        this.toggleLink = element.select('a.view_mini_schedule')[0] || null;

        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));
        }

        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
        this.groups.invoke('hide');
        this.groups[group].show();

        // update logo image
        var channel = $A(this.groups[group].classNames()).without('list');
        this.logo.src = '/SiteImagesLib/' + MiniSchedule.channelLogos[channel];
        this.logo.className = channel + '_logo';

        // per STZOM00000431 - toggle the 'View More' link
        this.toggleLink.removeClassName('collapsed');
        this.toggleList();
    },
    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('<img src="/SiteImagesLib/starz_arrow_up_02.gif" /> 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

            //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;

                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();
                            
                            revealedItems++;
                        }
                    } else {
                        li[i].hide();
                    }
                }

                channelItemsArray[totalChannels] = channelItems;
                revealedItemsArray[totalChannels] = revealedItems;
                totalChannels++;
            });

            // determine if we need to show the 'View More' link

            // > 3 airings in the schedule for the one channel.
            if (totalChannels == 1 && totalItems > 3) showToggleLink = true;

            //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
            if (totalChannels > 1 && totalItems > 3) {

                // which channel is currently selected ?  
                    
                //alert('revealed items in this channel: ' + revealedItemsArray[this.currentGroup] + "\r\n\r\n" +
                //       'total items in this channel: ' + channelItemsArray[this.currentGroup]);

                if (revealedItemsArray[this.currentGroup] <= 3) showToggleLink = false;
                if (channelItemsArray[this.currentGroup] > 3)   showToggleLink = true;           
                
            }
            
            if (this.toggleLink) { // pretty sure this always resolves to true
                this.toggleLink.addClassName('collapsed');
                this.toggleLink.update('<img src="/SiteImagesLib/starz_arrow_down_02.gif" /> 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': 'mm_starz.gif',
    'starz_cinema': 'mm_starz_cinema.gif',
    'starz_comedy': 'mm_starz_comedy.gif',
    'starz_edge': 'mm_starz_edge.gif',
    'starz_in_black': 'mm_starz_in_black.gif',
    'starz_kids': 'mm_starz_kids_family.gif',
    'encore': 'mm_encore.gif',
    'encore_action': 'mm_encore_action.gif',
    'encore_drama': 'mm_encore_drama.gif',
    'encore_love': 'mm_encore_love.gif',
    'encore_mystery': 'mm_encore_mystery.gif',
    'encore_wam': 'mm_encore_wam.gif',
    'encore_western': 'mm_encore_western.gif',
    'indieplex': 'mm_indieplex.gif',
    'movieplex': 'mm_movieplex.gif',
    'retroplex': 'mm_retroplex.gif',
    'all': 'mm_all.gif'
}

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];
        }
    }
}

Search = {
    SEARCH_URL: '/search/starz/',
    SEARCH_INPUT: 'searchTerm',
    keypress: function(event) {
        if(event.keyCode == Event.KEY_RETURN) {
            Search.submit(event);
        }
    },
    submit: function(event) {
        event.stop();
        var term = $(Search.SEARCH_INPUT).getValue().gsub(/[^a-zA-Z0-9_ ]/,''); 
        window.location.href = Search.SEARCH_URL+term;
    }
}

Event.observe(window, 'load', function() {
    $$('.print a').each(function(printer) {
        printer.observe('click', function(event) {
            event.stop();
            window.print();
        });
    });
    
    $('btnSearch').observe('click', Search.submit);
    $('searchTerm').observe('keypress', Search.keypress);
});


/* 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;
		
        // this is specific to the schedule, don't change these values
        if(this.className==".listview_tab" || this.className==".gridview_tab")
        {
            currentSelectedScheduleTab(this.className.split(".")[1]);
        }
        if(this.className==".listview_tab")
        {
            createScheduleList($$('.listview_tab'));
        }
        
        
        
    },
    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();
};



Event.observe(document, 'dom:loaded',  function(){
    setTimeout("initTabs()", 750);
});

function createScheduleList(new_container)
{
    var scheduleList = new ScheduleList(new_container);
}

var currentScheduleTab;

function currentSelectedScheduleTab(cst)
{
    currentScheduleTab = cst;
}

function onScheduleListChange(obj)
{
    var loc = '/schedule?date='+obj.value+'&#'+currentScheduleTab;
    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);