/* BEGIN: header/header_constants */

var MENU_WIDTH = 920;
var PADDING = 10;

var MENU_COLOR      = '#FFFFFF',
    MENU_HIGHLIGHT  = '#AAAAAA';
    
var NUM_CHANNEL_ROWS = 5;
var NUM_DEVICE_ROWS = 4;

/* BEGIN: header/header_controller */

function HeaderController()
{
}

HeaderController.prototype.init = function (_headerModel, _globalModel) {

    pageModel.addRootChannelModels(_headerModel.MyShowsChannelModels);

    this.headerModel = _headerModel;
    this.globalModel = _globalModel;

    this.menuView = new MenuView();
    this.menuView.init(this.headerModel);

    this.searchView = new SearchView();
    this.searchView.init();

    this.playlistTabView = new HeaderPlaylistTabView();
    this.playlistTabView.updatePlaylistTab(this.globalModel);
}

HeaderController.prototype.updateMyChannels = function() {

    this.menuView.updateMyChannels();
}

HeaderController.prototype.addMyDevice = function(_name) {

    for(var i=0; i < this.headerModel.MoreDeviceModels.length; i++) {
        if(this.headerModel.MoreDeviceModels[i].Name == _name) {
            this.headerModel.MyDeviceModels.push(this.headerModel.MoreDeviceModels[i]);
            this.headerModel.MoreDeviceModels.splice(i, 1);
            break;
        }
    }

    this.menuView.updateDevices(this.headerModel);
}

HeaderController.prototype.removeMyDevice = function(_name) {

    for(var i=0; i < this.headerModel.MyDeviceModels.length; i++) {
        if(this.headerModel.MyDeviceModels[i].Name == _name) {
            this.headerModel.MoreDeviceModels.push(this.headerModel.MyDeviceModels[i]);
            this.headerModel.MyDeviceModels.splice(i, 1);
            break;
        }
    }

    this.menuView.updateDevices(this.headerModel);
}

HeaderController.prototype.search = function() {

    var value = $('#searchBox').val();    
    window.location = "/Areas/Search/" + encodeURIComponent(value);
}

HeaderController.prototype.hideMenu = function() {
    this.menuView.hideMenu();
}

HeaderController.prototype.refreshPlaylist = function() {

    var params = {
        doRefresh: false,
        onSuccess: function () { window.location.reload(); },
        onFailure: function (error) { alert("Error refreshing playlist"); },
        method: '/WebServices/SubscriptionService_v2_0.asmx/InvalidatePlaylist'
    };

    webService.invoke(params);
}

HeaderController.prototype.updateHeader = function (_channelModels) {

    this.globalModel.PlaylistImage = GREY_PLAYLIST_INFERRED;

    this.playlistTabView.updatePlaylistTab(this.globalModel);
}

/* BEGIN: header/header_menu_view */

function MenuView()
{
    this.playlistItemTemplate = TrimPath.parseDOMTemplate("playlistItemTemplate");
    this.deviceItemTemplate = TrimPath.parseDOMTemplate("deviceItemTemplate");
}

MenuView.prototype.init = function () {

    this.populateMenu("browseTopicItems", NUM_CHANNEL_ROWS);
    this.populateMenu("browseSourceItems", NUM_CHANNEL_ROWS);
    this.populateMenu("communityItems", NUM_CHANNEL_ROWS);

    this.updateMyChannels();
    this.populateMenu("mediaflyCollectionItems", NUM_CHANNEL_ROWS);

    this.populateMenu("myDeviceItems", NUM_DEVICE_ROWS);
    this.populateMenu("moreDeviceItems", NUM_DEVICE_ROWS);

    this.positionMenus();
    this.bindListeners();
}

MenuView.prototype.updateMyChannels = function () {

    var channels = pageModel.getRootChannelModels();

    var playlistHtml = new StringBuilder();
    for (var i = 0; i < channels.length; i++) {

        var channel = new clone(channels[i]);

        channel.ChannelIconClass = (channel.EpisodeCount > 0) ? "channelIcon" : "emptyChannelIcon";
        channel.Type = "MyChannel";
        channel.DisplayInferred = (channel.IsInferred) ? "" : "none";
        channel.Path = (channel.Slug != ALL_CHANNEL_SLUG) ? "/MyShows/" + channel.Path : "/MyShows";

        playlistHtml.append(this.playlistItemTemplate.process(channel));
    }

    $('.MyShowsItems').html(playlistHtml.toString());

    this.populateMenu("MyShowsItems", NUM_CHANNEL_ROWS);

    this.bindMenuItemListeners($('.MyShowsItems'));
}

MenuView.prototype.updateDevices = function(_headerModel) {

    this.updateMyDevices(_headerModel);
    this.updateMoreDevices(_headerModel);

    this.bindListeners();
}

MenuView.prototype.updateMyDevices = function(_headerModel) {

    var devicesHtml = new StringBuilder();
    for(var i=0; i < _headerModel.MyDeviceModels.length; i++) {
        devicesHtml.append(this.deviceItemTemplate.process(_headerModel.MyDeviceModels[i]));
    }    
    $('.myDeviceItems').html(devicesHtml.toString());

    this.populateMenu("myDeviceItems", NUM_DEVICE_ROWS);
}

MenuView.prototype.updateMoreDevices = function(_headerModel) {

    var devicesHtml = new StringBuilder();
    for(var i=0; i < _headerModel.MoreDeviceModels.length; i++) {
        devicesHtml.append(this.deviceItemTemplate.process(_headerModel.MoreDeviceModels[i]));
    }    
    $('.moreDeviceItems').html(devicesHtml.toString());

    this.populateMenu("moreDeviceItems", NUM_DEVICE_ROWS);
}

MenuView.prototype.populateMenu = function(_id, _rows) {

    var menu = $('.' + _id);

    var length = menu.find('.menuItem').size();
    if (length > 0) {
                
        menu.find('.menuItem:nth-child(' + _rows + 'n)').css('border-right', '0px');
        
        var columns = Math.ceil((length)/_rows);
        var bottom = ((columns-1)*_rows);
        
        menu.find('.menuItem:eq(' + bottom + ')').css('border-bottom', '0px');
        menu.find('.menuItem:gt(' + bottom + ')').css('border-bottom', '0px');
        
        var width = ((MENU_WIDTH - (2*PADDING)) / _rows)-2;
        menu.find('.menuItem').css('width', width);
    } else {
        
        if(_id == "MyShowsItems") {
            menu.html("<div class='small' style='font-weight: bold; margin: 12px 0px 20px 8px;'>You currently don't have any channels.</div>");
       
        } else if(_id == "myDeviceItems"){
            menu.html("<div class='small' style='font-weight: bold; margin: 12px 0px 20px 8px;'>You are currently not linked to any devices.</div>");
        }
    }
}

MenuView.prototype.positionMenus = function() {

    var ofs = (980 - 920) / 2;
    var w = 0;
    $('.headerDiv').each(function() {
        
        $(this).children('.menu').css('left', -w + ofs);
        w += $(this).width();
    });
}

MenuView.prototype.bindListeners = function() {

    $('.headerDiv').bind('mouseenter', function(_event) {
    
        $(this).children('.box').addClass('headerHover');

        $(this).oneTime(300, "openMenuTimer", function() {

            $(this).children('.menu').fadeIn(100, null);
        });
    });

    $('.headerDiv').bind('mouseleave', function(_event) {

        $(this).children('.menu').hide();

        $(this).stopTime("openMenuTimer");
        $(this).children('.box').removeClass('headerHover');
    });

	this.bindMenuItemListeners($(document));
}

MenuView.prototype.bindMenuItemListeners = function(_div) {

    _div.find('.menuItem').bind('mouseenter', function(_event) {
        $(this).css('background-color', MENU_HIGHLIGHT);
    });

    _div.find('.menuItem').bind('mouseleave', function(_event) {
        $(this).css('background-color', MENU_COLOR);
    });
}

MenuView.prototype.hideMenu = function() {
    $('.menu').hide();
}

/* BEGIN: header/header_playlisttab_view */

function HeaderPlaylistTabView()
{
    this.playlistTabTemplate = TrimPath.parseDOMTemplate("playlistTabTemplate");
}

HeaderPlaylistTabView.prototype.updatePlaylistTab = function (_globalModel) {

    var html = this.playlistTabTemplate.process(_globalModel);
    $('#playlistInfo').html(html);
}

/* BEGIN: header/header_search_view */

var MINIMUM_CHARS = 4;

function SearchView()
{
}

SearchView.prototype.init = function() {

    this.bindListerners();
}

SearchView.prototype.bindListerners = function() {

    $('#searchBox').bind('keyup', function(event) {
        if(event.keyCode == 13) {
            headerController.search();
        }
    });

    $('#searchBox').autocomplete("/SearchAutoSuggest.aspx", {
        width : 220,
        scroll : false
    });
}

