/**
=========================================================================

ScheduleListViewsUtil

=========================================================================
*/

var ScheduleListViewsUtil = Class.create({
    initialize: function () {
    },

    getFormattedStartDate: function (dt) {
        return dt + " 00:00";
    },

    getFormattedEndDate: function (dt) {
        return dt + " 23:59";
    },

    getFormattedDateFromDropDown: function () {
        var scheduleDays = $$('select.scheduleDays')[0].value.split("/");
        return [scheduleDays[2], "-", scheduleDays[0], "-", scheduleDays[1]].join("");
    },
    formatChannelName: function (channelName) {
        channelName = channelName.split("inblack").join("in black");
        return channelName.split("_").join(" ");
    },
    formatTimeToDisplay: function (startTime, duration, beginDate, feed) {

        var makeOppositeEnd = false;
        var makeOppositeStart = false;
        if (startTime < 0) {
            startTime = 1440 + startTime;
        }
        //        if(feed=="west") 
        //        {
        //            //startTime = startTime + (3 * 60);
        //        }
        var startHour = Math.floor(startTime / 60);
        if (startHour >= 24 || startHour < 0) makeOppositeStart = true;
        startHour = (startHour == 0) ? 12 : startHour;
        startHour = (startHour > 12) ? startHour - 12 : startHour;
        startHour = (startHour > 12) ? startHour - 12 : startHour;
        startHour = (startHour < 0) ? startHour + 12 : startHour;

        var startMinute = startTime % 60;
        startMinute = (startMinute < 10) ? '0' + startMinute : startMinute;
        var startMeridium = (startTime > 720) ? "PM" : "AM";

        //var endTime   = (startTime + duration) % 720;
        var endTime = (startTime + duration);
        var endHour = Math.floor(endTime / 60);

        if (endHour >= 24 || endHour < 0) makeOppositeEnd = true;
        endHour = (endHour == 0) ? 12 : endHour;
        endHour = (endHour > 12) ? endHour - 12 : endHour;
        endHour = (endHour > 12) ? endHour - 12 : endHour;
        endHour = (endHour < 0) ? endHour + 12 : endHour;

        var endMinute = endTime % 60;
        endMinute = (endMinute < 10) ? '0' + endMinute : endMinute;
        var endMeridium = (endTime > 720) ? "PM" : "AM";

        if (makeOppositeEnd) endMeridium = (endMeridium == "AM") ? "PM" : "AM";
        if (makeOppositeStart) startMeridium = (startMeridium == "AM") ? "PM" : "AM";

        return [startHour, ":", startMinute, " ", startMeridium, " - ", endHour, ":", endMinute, " ", endMeridium].join("");
        // return [beginDate + " - ", startHour,":",startMinute,startMeridium,"-",endHour,":",endMinute,endMeridium].join("");
    },
    getDateFromBeginDate: function (beginDate) {
        var aDate = beginDate.split("/");
        return new Date(aDate[2], aDate[1] - 1, aDate[0] - 1);
    },
    addDate: function (dt, num) {
        var tempDate = new Date();
        tempDate.setDate(dt.getDate() + num);
        return tempDate;
    },
    formatDate: function (dt) {
        return ([dt.getMonth() + 1, dt.getDate() + 1, dt.getFullYear()].join("/"));
    },
    getImagePathByChannel: function (channel) {
        var chantype;
        chantype = channel.split("starz");
        if (chantype.length > 1) {
            if (chantype[1] == "_inblack") chantype[1] = "_black";
            if (chantype[1] == "") return "/SiteImagesLib/schedule_starz_logo.gif";
            return ["/SiteImagesLib/schedule_starz_logo", chantype[1], ".gif"].join("");
        }
        chantype = channel.split("encore");
        if (chantype.length > 1) {
            if (chantype[1] == "_wam") 
                return "/siteImagesLib/schedule_encore_logo_family.gif"
            else if (chantype[1] == "_mystery")
                return "/siteImagesLib/schedule_encore_logo_suspense.gif"
            else
                return ["/SiteImagesLib/schedule_encore_logo", chantype[1], ".gif"].join("");
        }

        return ["/SiteImagesLib/schedule_", channel, "_logo.gif"].join("");
    }

});

/**
=========================================================================

ScheduleListViewIcons:
Description: This class attaches the view reminder icons

=========================================================================
*/

var ScheduleListViewIcons = Class.create({
    initialize: function (scheduleListViewListItem, channelTitlesHolder, channel) {
        this.icons = new Element('div', { 'class': 'scheduleViewIcons' });
        this.channelTitlesHolder = channelTitlesHolder;
        this.titleWrapper = scheduleListViewListItem.titleWrapper;
        this.idQueryParams = scheduleListViewListItem.idQueryParams;
        this.favorite = scheduleListViewListItem.favorite;
        this.reminder = scheduleListViewListItem.reminder;
        this.isFavorite = (this.favorite.split("add").length == 1);
        this.isReminder = (this.reminder.split("add").length == 1);
        this.channel = channel;
        if (this.isFavorite) {
            if (Starz.LOGGED_IN) {
                this.favoriteNode = new Element('a', { 'title': 'Add to Favorites', 'class': 'scheduleViewFavoriteIconSet' });
            } else {
                this.favoriteNode = new Element('a', { 'title': 'Add to Favorites', 'class': 'scheduleViewFavoriteIconSet login' });
            }

            this.favoriteHeadline = "Removed from Favorite Movies";
        }
        else {
            if (Starz.LOGGED_IN) {
                this.favoriteNode = new Element('a', { 'title': 'Add to Favorites', 'class': 'scheduleViewFavoriteIcon' });
            } else {
                this.favoriteNode = new Element('a', { 'title': 'Add to Favorites', 'class': 'scheduleViewFavoriteIcon login' });
            }
            this.favoriteHeadline = "Added to Favorite Movies";
        }

        this.reminderId = 'list_reminder_' + scheduleListViewListItem.id;

        if (this.isReminder) {
            if (Starz.LOGGED_IN) {
                this.reminderNode = new Element('a', { 'title': 'Set a Reminder', 'class': 'scheduleViewReminderIconSet', 'id': this.reminderId });
            } else {
                this.reminderNode = new Element('a', { 'title': 'Set a Reminder', 'class': 'scheduleViewReminderIconSet login', 'id': this.reminderId });
            }
        }
        else {
            if (Starz.LOGGED_IN) {
                this.reminderNode = new Element('a', { 'title': 'Set a Reminder', 'class': 'scheduleViewReminderIcon', 'id': this.reminderId });
            } else {
                this.reminderNode = new Element('a', { 'title': 'Set a Reminder', 'class': 'scheduleViewReminderIcon login', 'id': this.reminderId });

            }
        }
        this.icons.appendChild(this.reminderNode);
        this.icons.appendChild(this.favoriteNode);
        this.titleWrapper.appendChild(this.icons);
        this.favoriteNode.observe('click', this.onFavoriteNodeClick.bind(this));
        this.reminderNode.observe('click', function (evt) {
            this.onReminderNodeClick(evt);
        } .bind(this));

        // by attaching the tool tip now, it avoids having to have two events later.
        if (!Starz.LOGGED_IN) {
            // This is handled in JQuery
        }
        else {
            Tooltip.attach(this.favoriteNode, FavoriteScheduleViewTooltip, [this.favoriteHeadline]);
        }

    },
    onFavoriteNodeClick: function () {
        if (!Starz.LOGGED_IN) {
            // This is handled in JQuery
        }
        else {
            this.setFavorite();

        }
    },
    setFavorite: function () {
        var request = new Ajax.Request('/ajax/scheduleFavorite.aspx' + this.idQueryParams + this.favorite, {
            method: 'post',
            onSuccess: function () {

                if (this.isFavorite) {
                    this.favoriteHeadline = "Added to Favorite Movies";
                    this.favoriteNode.removeClassName("scheduleViewFavoriteIconSet");
                    this.favoriteNode.addClassName("scheduleViewFavoriteIcon");
                    this.favorite = this.favorite.split("remove").join("add");
                    var element = this.channelTitlesHolder;
                }
                else {
                    this.favoriteHeadline = "Removed from Favorite Movies";
                    this.favoriteNode.removeClassName("scheduleViewFavoriteIcon");
                    this.favoriteNode.addClassName("scheduleViewFavoriteIconSet");
                    this.favorite = this.favorite.split("add").join("remove");
                }
                Tooltip.attach(this.favoriteNode, FavoriteScheduleViewTooltip, [this.favoriteHeadline]);
                this.isFavorite = !this.isFavorite;
            } .bind(this)
        });
    },
    onReminderNodeClick: function (evt) {
        if (!Starz.LOGGED_IN) {
            // this is handled in JQuery
        }
        else {
            this.setReminder(evt);
        }
    },
    setReminder: function (evt) {
        var headline;
        var request = new Ajax.Request('/ajax/ScheduleReminder.aspx' + this.idQueryParams + this.reminder, {
            method: 'post',
            onSuccess: function (transport) {
                // add a reminder
                if (!this.isReminder) {
                    // if fail
                    if (transport.responseText.indexOf("action=add") != -1) {
                        if (transport.responseText.indexOf("reminderSet=false") != -1) {
                            this.reminderHeadline = "You will not receive an email reminder. If you wish to receive email reminders in the future, you must update your user preferences."
                        }
                        else {
                            this.reminderHeadline = "This title will be airing in the next 12 hours and therefore a reminder can no longer be set.  Click the title name to see future air dates."
                        }
                    }
                    // if success
                    else {
                        if (transport.responseText.indexOf("reminderSet=false") != -1) {
                            this.reminderHeadline = "You will not receive an email reminder. If you wish to receive email reminders in the future, you must update your user preferences."
                        }
                        else {

                            this.reminderHeadline = "Reminder Set";
                            this.reminderNode.removeClassName("scheduleViewReminderIcon");
                            this.reminderNode.addClassName("scheduleViewReminderIconSet");
                            this.reminder = this.reminder.split("add").join("remove");
                            this.isReminder = !this.isReminder;
                        }
                    }




                    // remove a reminder
                } else {
                    // if fail
                    if (transport.responseText.indexOf("action=remove") != -1) {
                        this.reminderHeadline = "Failed to remove reminder.";
                    }
                    // if success
                    else {
                        this.reminderHeadline = "Reminder Removed";
                        this.reminderNode.removeClassName("scheduleViewReminderIconSet");
                        this.reminderNode.addClassName("scheduleViewReminderIcon");
                        this.reminder = this.reminder.split("remove").join("add");
                        this.isReminder = !this.isReminder;
                    }

                }
                //this.channelRef = $$("."+this.channel);

                try {
                    this.eastWestFeed = $$('div.' + this.channel + ' p.zone')[0].className.match(/east|west/)[0];
                } catch (e) {
                    var sel = $$('select.addToMySchedule')[0];
                    this.eastWestFeed = sel.select('option[value=' + this.channel + ']')[0].title;
                }

                if (this.rtt == null) this.rtt = new ReminderScheduleViewTooltip(this.reminderNode, [this.eastWestFeed, this.reminderHeadline]);
                this.rtt.show([this.eastWestFeed, this.reminderHeadline]);

            } .bind(this)
        });
    }


});

/**
=========================================================================

ReminderScheduleViewTooltip:
Description: This class attaches the Reminder tooltip

=========================================================================
*/

ReminderScheduleViewTooltip = Class.create(Tooltip, {
    TYPE: 'reminder',
    initialize: function (target, options) {
        this.target = $(target);
        this.element = new Element('div', { id: 'tooltip' });
        this.options = options;
    },
    show: function (options) {
        this.options = options;
        if (this.timer != null) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        this.add();
        this.timer = window.setTimeout(this.hide.bind(this), 4000);
    },
    getTemplate: function () {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">' +
            '<h4>#{headline}</h4>#{extra}<a href="/mystarz/#{prefPage}">&raquo; Manage All Reminders</a>' +
            '</div></div><div class="bot"></div>');
    },
    position: function () {
        this.element.className = this.TYPE + '_tooltip';

        var position = this.target.cumulativeOffset();
        var topOffset = -(this.element.offsetHeight - 10);
        var leftOffset = this.target.offsetWidth / 2;

        position.left += leftOffset;
        position.top += topOffset;
        this.element.setStyle({ left: position.left + 'px', top: position.top + 'px' })
    },
    writeContent: function () {
        // The feed is passed in from the static tooltip attach method 
        var feed = '';
        var zonefeed = (Object.isArray(this.options)) ? this.options[0] : this.options;
        if (zonefeed && zonefeed.capitalize() != "Add" && ScheduleTooltip.TIMEZONE != "undefined") {
            feed = '<p>' + Schedule.TIMEZONE + ' ' + zonefeed.capitalize() + ' Feed <a href="/mystarz/myschedule/">&raquo; Change</a></p>';
        }
        // The headline is passed in from the static tooltip attach method as well
        var headline = (Object.isArray(this.options)) ? this.options[1] : '';
        this.element.update(this.getTemplate().evaluate({ headline: headline, prefPage: 'myreminders', extra: feed }));
    }
});

/**
=========================================================================

FavoriteScheduleViewTooltip:
Description: This class attaches the Favorite tooltip

=========================================================================
*/

FavoriteScheduleViewTooltip = Class.create(Tooltip, {
    TYPE: 'favorite',
    show: function (event) {
        event.stop();
        if (this.timer != null) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        this.add();
        this.timer = window.setTimeout(this.hide.bind(this), 2000);
    },
    getTemplate: function () {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">' +
            '<h4>#{headline}</h4>#{extra}<a href="/mystarz/#{prefPage}">&raquo; Manage All Favorites</a>' +
            '</div></div><div class="bot"></div>');
    },
    position: function () {
        this.element.className = this.TYPE + '_tooltip';

        var position = this.target.cumulativeOffset();
        var topOffset = -(this.element.offsetHeight - 10);
        var leftOffset = this.target.offsetWidth / 2;

        position.left += leftOffset;
        position.top += topOffset;
        this.element.setStyle({ left: position.left + 'px', top: position.top + 'px' })
    },
    writeContent: function () {
        // The headline is passed in from the static tooltip attach method as well
        var headline = (Object.isArray(this.options)) ? this.options[0] : '';
        this.element.update(this.getTemplate().evaluate({ headline: headline, prefPage: 'myfavorites' }));
    }
});


/**
=========================================================================

ScheduleList:
Description: This class creates the schedule list

=========================================================================
*/

var ScheduleList = Class.create({
    initialize: function (new_container) {

        if (new_container) {
            this.channels = $H({
                'Starz':
                    ['starz', 'starz_edge', 'starz_inblack', 'starz_comedy', 'starz_cinema', 'starz_family'],
                'Encore':
                    ['encore', 'encore_espanol', 'encore_action', 'encore_love', 'encore_westerns', 'encore_mystery', 'encore_drama', 'encore_wam'],
                'MoviePlex':
                    ['movieplex', 'indieplex', 'retroplex']
            });
            var idName = new_container[0].id;
            this.scheduleListViewsUtil = new ScheduleListViewsUtil();
            this.currentSelectedDate = this.scheduleListViewsUtil.getFormattedDateFromDropDown();
            this.new_container = $(idName);
            this.aStartDate = [];
            this.aSelectedDate = this.currentSelectedDate.split("-");
            this.selectedDate = new Date(this.aSelectedDate[0], this.aSelectedDate[1] - 1, this.aSelectedDate[2]);
            this.tempDate = new Date();

            switch (idName) {
                case "listview":
                    // hide add combo
                    if (Starz.LOGGED_IN) {
                        $$('.add').invoke('hide');
                    }
                    this.structureDatesForAJAX(1, idName);
                    break;

                case "gridview":
                    // show add combo
                    if (Starz.LOGGED_IN) {
                        $$('.add').invoke('show');
                    }
                    // do nothing because this is all handled by schedule.js
                    break;
            }

        }
    },
    structureDatesForAJAX: function (numberOfDays, idName) {

        this.aStartDate.push(this.selectedDate);
        this.startDate = this.scheduleListViewsUtil.getFormattedStartDate([this.selectedDate.getFullYear(), "-", this.selectedDate.getMonth() + 1, "-", this.selectedDate.getDate()].join(""));
        this.finishDate = this.scheduleListViewsUtil.getFormattedEndDate([this.selectedDate.getFullYear(), "-", this.selectedDate.getMonth() + 1, "-", this.selectedDate.getDate()].join(""));

        // only make the call one time...
        if (this.new_container.empty()) {
            this.makeAJAXCall();
        }
    },
    makeAJAXCall: function () {
        this.new_container.update();

        // make a loading screen helper
        this.loadingScreen = new Element("div", { "class": "scheduleViewLoading" }).update("<img src='/SiteImagesLib/loading.gif' />");
        this.new_container.appendChild(this.loadingScreen);

        this.searchChannels = [];
        this.channels.keys().each(function (p) {
            var c = this.channels.get(p).each(function (c) {
                this.searchChannels.push(c);
            } .bind(this));

        } .bind(this));

        var request = new Ajax.Request('/ajax/scheduleData.aspx', {
            method: 'get',
            requestHeaders: { Accept: 'application/json' },
            evalJSON: 'force',
            parameters: { channels: this.searchChannels, start: this.startDate, finish: this.finishDate },
            onSuccess: function (transport) {
                this.json = transport.responseJSON;
                //debugger;
                if (Object.values(this.json).length != 0) {

                    this.aStartDate.each(function (s) {
                        this.dateDiv = new Element("div", { "class": "scheduleViewDate" });
                        this.printableDate = [s.getMonth() + 1, s.getDate(), s.getFullYear()].join("/");
                        this.dateText = new Element("div", { "class": "left" }).update("&nbsp;");
                        this.createCombo();
                        this.dateDiv.appendChild(this.dateText);
                        this.dateDiv.appendChild(this.channelCombo);
                        this.new_container.appendChild(this.dateDiv);
                        this.createChannelFamily(s);
                    } .bind(this));
                }
            } .bind(this)
        });
    },
    createCombo: function () {
        this.channelCombo = new Element("select", { "class": "scheduleViewCombo", "name": "scheduleViewCombo" });
        this.channelCombo.observe('change', function (evt) {
            this.onChannelComboChange($(Event.element(evt)));
        } .bind(this));
        this.comboItem = new Element("option", { "value": "all channels", "class": "scheduleViewViewAllOption" });
        this.comboItem.appendChild(document.createTextNode('All Channels'));
        this.viewAllHD = new Element("option", { "value": "all hd channels", "class": "scheduleViewViewAllOption" });
        this.viewAllHD.appendChild(document.createTextNode('All HD Channels'));
        this.channelCombo.appendChild(this.comboItem);
        this.channelCombo.appendChild(this.viewAllHD);
    },
    onChannelComboChange: function (element) {
        var currentOption = element.value;
        // hide everything
        for (var i = 0; i < element.options.length; i++) {
            var option = element.options[i].value;
            if (option != "all channels" && option != "all hd channels") $(option).hide();
        }
        // if the item selected is a channel family
        if (currentOption.indexOf("family_") == 0) {
            // show the channel family container that was selected
            $(currentOption).show();
            // loop through the channel family and show all of the channels in the family
            var channelFamily = currentOption.split("family_").join("");
            // update the date text
            //this.dateText.update("all " + channelFamily + " family channels for " + this.printableDate);
            this.channels.get(channelFamily).each(function (channel) {
                $(channelFamily + "_channel_" + channel).show();
            } .bind(this));
        }
        else if (currentOption.indexOf("channel_") != -1) {
            // locate the parent
            var familyOfCurrentItem;
            this.channels.keys().each(function (channelFamily) {
                this.channels.get(channelFamily).each(function (channel) {
                    if (channel == currentOption.split(channelFamily + "_channel_").join("")) {
                        familyOfCurrentItem = channelFamily;
                    }
                } .bind(this));
            } .bind(this));
            $("family_" + familyOfCurrentItem).show();
            $(currentOption).show();
            // update the date text
            var chHeader = "" + currentOption.split(familyOfCurrentItem + "_channel_").join("") + " channel for " + this.printableDate
            //this.dateText.update(this.scheduleListViewsUtil.formatChannelName(chHeader));
        }
        else if (currentOption == "all hd channels") {
            $('family_Starz').show();
            $('family_Encore').show();
            $$('.alsoInHD').invoke('show');
            // this.dateText.update("all HD channels for " + this.printableDate);
        }
        else {
            // show everything
            for (var i = 0; i < element.options.length; i++) {
                var option = element.options[i].value;
                if (option != "all channels" && option != "all hd channels") $(option).show();
            }
            this.dateText.update("&nbsp;");
        }
    },
    createChannelFamily: function (startDate) {
        // iterate over the channel families

        this.channels.keys().each(function (channelFamily) {
            
            // create the channel family div
            this.channelFamily = channelFamily;
            this.channelFamilyDiv = new Element("div", { "class": "scheduleViewChannelFamily", "id": "family_" + this.channelFamily });
            
            this.dateDiv.appendChild(this.channelFamilyDiv);

            // create the combo box
            this.comboItem = new Element("option", { "value": "family_" + this.channelFamily, "class": "scheduleViewFamilyOption" });
            this.comboItem.appendChild(document.createTextNode("All " + toTitleCase(channelFamily) + " Channels"));
            this.channelCombo.appendChild(this.comboItem);

            // create each channel

            this.createChannel(this.channels.get(this.channelFamily));

        } .bind(this));   

        this.loadingScreen.removeClassName("scheduleViewLoading");
        this.loadingScreen.addClassName("scheduleViewLoadingHidden");
    },
    createChannel: function (item) {
        // iterate over each channel within the family
        item.each(function (channel) {
            this.channel = channel;
            // create the channel div and attach it to the family holder
            this.channelDiv = new Element("div", { "class": "scheduleViewChannel", "id": this.channelFamily + "_channel_" + channel });
            this.channelFamilyDiv.appendChild(this.channelDiv);

            // attach the channel image
            this.scheduleViewChannelHeader = new Element("div", { "class": "scheduleViewChannelHeader" });
            this.channelDiv.appendChild(this.scheduleViewChannelHeader);

            this.imagePath = this.scheduleListViewsUtil.getImagePathByChannel(this.channel);
            this.image = new Element("img", { "src": this.imagePath });
            this.channelImage = new Element("div", { "class": "scheduleViewChannelImageHolder" }).update(this.image);
            this.scheduleViewChannelHeader.appendChild(this.channelImage);
            if (Schedule.CHANNELS_IN_HD.indexOf(this.channel) >= 0) {
                this.scheduleViewChannelHeader.appendChild(new Element('p').update('also in HD'));
                this.channelDiv.addClassName("alsoInHD");
            }


            // attach the date 
            this.channelDateDiv = new Element("div", { "class": "scheduleViewChannelDate" }).update($$('select.scheduleDays')[0].value);
            this.scheduleViewChannelHeader.appendChild(this.channelDateDiv);

            // add channel options to the combo box
            this.comboItem = new Element("option", { "value": this.channelFamily + "_channel_" + this.channel, "class": "scheduleViewChannelOption" });
            this.comboChannel = this.channel;
            if (this.comboChannel == "starz_family") this.comboChannel = "starz kids & family";
            if (this.comboChannel == "starz_inblack") this.comboChannel = "starz in black";
            this.comboChannel = toTitleCase(this.comboChannel.split('_').join(' '));
            this.comboItem.appendChild(document.createTextNode(this.comboChannel));
            this.channelCombo.appendChild(this.comboItem);


            if (typeof document.body.style.maxHeight != "undefined") {
                this.collapseIcon = new Element('div', { 'class': 'scheduleViewCollapse', 'id': "collapse_" + this.channel });
                // before the icon is attached listen for the click events
                this.collapseIcon.observe('click', function (evt) {
                    var icon = Event.element(evt).id;
                    this.toggleView($(icon.split("collapse").join("holder")));
                    if ($(icon).classNames().toArray()[0] == "scheduleViewCollapse") {
                        $(icon).removeClassName('scheduleViewCollapse');
                        $(icon).addClassName('scheduleViewExpand');
                    }
                    else if ($(icon).classNames().toArray()[0] == "scheduleViewExpand") {
                        $(icon).removeClassName('scheduleViewExpand');
                        $(icon).addClassName('scheduleViewCollapse');
                    }
                } .bind(this));
                this.scheduleViewChannelHeader.appendChild(this.collapseIcon);
            }



            // add the channel holder
            this.channelTitlesHolder = new Element("div", { 'id': 'holder_' + this.channel, 'class': 'scheduleViewChannelHolder' });
            this.channelDiv.appendChild(this.channelTitlesHolder);
            //Chris Calzaretta Added Try Catch to solve the issue of breaking ... Need to pass this on to Sean
            //TODO SEAN LOOK AT.. Why do i need to put a try catch around this
                                                      try
                                                      {
                                                          // create the titles     
                                                          this.createTitles();

                                                      }
                                                      catch (e)
                                                      {
                                                         // alert(e);
                                                      }

        } .bind(this));

    },
    toggleView: function (target) {
        this.effect = new Fx.Style(target, 'height', {
            duration: 600,
            onComplete: this.effectDone.bind(this)
        });
        // 22 because the padding and the border...
        if (target.offsetHeight > 22) this.effect.custom(target.offsetHeight, 0);
        else this.effect.custom(0, target.scrollHeight);

    },
    effectDone: function () {
    },
    showTitleToolTip: function () {
        Tooltip.attach(this.titleWrapper, ScheduleTooltip);
    },
    createTitles: function () {
        // retrieve the json data by channel 


        this.channelFamilyChannelsJSON = this.json[this.channel.toLowerCase()];

        // for each channel's worth of data create the title

        this.channelFamilyChannelsJSON.each(function (titleData) {
            try {
                this.titleData = titleData;
                // Data Elements
                this.title = this.titleData.title;
                this.url = this.titleData.url;
                this.beginDate = this.titleData.startDate;
                this.favoriteCast = this.titleData.favoriteCast;
                this.id = this.titleData.id;
                this.showId = this.titleData.showId;
                this.lStartTime = this.titleData.startTime;
                this.duration = this.titleData.duration;
                this.favorite = (this.titleData.favorite) ? '&action=remove' : '&action=add';
                this.reminder = (this.titleData.reminder) ? '&action=remove' : '&action=add';
                this.tId = this.titleData.tId;
                this.eNbr = this.titleData.eNbr;
                this.canPromoteNow = this.titleData.canPromoteNow;
                // form the tool tip query params
                this.idQueryParams = '?version_id=' + this.id.split('_')[0];
                this.idQueryParams += '&eNbr=' + this.titleData.eNbr;
                this.idQueryParams += '&service_code=' + this.id.split('_')[1];
                this.idQueryParams += '&exhib_dtm=' + this.id.split('_')[2].split('X')[0].split('-')[1] + '/';
                this.idQueryParams += this.id.split('_')[2].split('X')[0].split('-')[2] + '/';
                this.idQueryParams += this.id.split('_')[2].split('X')[0].split('-')[0];
                this.idQueryParams += '%20';
                this.idQueryParams += this.id.split('_')[2].split('X')[1].gsub('-', ':');


                try {
                    this.eastWestFeed = $$('div.' + this.channel + ' p.zone')[0].className.match(/east|west/)[0];
                } catch (e) {
                    var sel = $$('select.addToMySchedule')[0];
                    this.eastWestFeed = sel.select('option[value=' + this.channel + ']')[0].title;
                }

                // format the time
                this.sTime = this.scheduleListViewsUtil.formatTimeToDisplay(this.lStartTime, this.duration, this.beginDate, this.eastWestFeed).toString();
                // create the title wrapper
                if (this.canPromoteNow == "1") {
                    this.titleWrapper = new Element('div', { 'class': 'scheduleViewTitle', 'title': '/ajax/ScheduleDialog.aspx' + this.idQueryParams });
                } else {
                    this.titleWrapper = new Element('div', { 'class': 'scheduleViewTitle' });
                }

                // create the time div
                this.timeDiv = new Element("div", { "class": "scheduleViewTime" }).update(this.sTime);
                // create the title text
                if (this.canPromoteNow == "1") {
                    this.titleNode = new Element('a', { 'class': 'scheduleViewTitleLink', 'href': this.url }).update(this.title);
                } else {
                    this.titleNode = new Element('a', { 'class': 'scheduleViewTitleNoLink' }).update(this.title);
                }
                this.titleWrapper.appendChild(this.timeDiv);
                this.titleWrapper.appendChild(this.titleNode);
                // create the icons
                this.icons = new ScheduleListViewIcons(this, this.channelTitlesHolder, this.channel);
                this.channelTitlesHolder.appendChild(this.titleWrapper);

                // by attaching the tool tip now, it avoids having to have two events later.
                // to fix this a new tool tip would need to be created for schdule views...known. JH
                if (this.canPromoteNow == "1") {
                    Event.observe(this.titleNode, 'mouseover', function (event) {
                        this.showTitleToolTip();
                    } .bind(this));
                    Tooltip.attach(this.titleWrapper, ScheduleTooltip);
                }
            } catch (e) {
                // this is a prototype pluck error...it's okay to swallow here...Related to above JH
            }


        } .bind(this));

    }

});



function toTitleCase(str) {
    return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
