﻿function getShowTitle(grpItem) {
    var title = '';
    try {
        $.each($(grpItem).find('a.active').find('cufon'), function(index, item) {
            title = title + $(item).children('cufontext').html();
        });
    } catch (err) {
        title = err.message;
    }
    try {
        show.name = title;
    } catch (err) {
    }
    return title;
}

function getShowContent(Item) {
    var title = '';
    try {
        $.each($(Item).find('cufon'), function(index, item) {
            title = title + $(item).children('cufontext').html();
        });
    } catch (err) {
        title = err.message;
    }
    return title;
}

function getShowListing() {
    ShowBusy();

    $.ajax({
        type: "POST",
        url: "/ajax/showService.asmx/getShowList",
        data: '{}',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            handleGetShowListResponse(result)
        },
        error: AjaxFailed
    });

}

function HideBusy() {
    $('#ajaxLoading').html('');
}

function initBestOf(startUrl, startName, startDesc) {

    $('a.at').click(function(e) {
        // don't follow href
        e.preventDefault();
        // remove prev selected item
        $('a.at.selected').removeClass('selected');
        // add selection to this item
        $(this).addClass('selected');

        LoadContent($(this).attr('href'));

        $('#media_content').load($(this).attr('href'));
        return false;

    });

    $(document).ready(function() {
        $("#detailPanel").hide();
    });

    $(function() {
        $("#media_content").hover(function() {
            $("#detailPanel").fadeOut("fast");
        });
    });

    var networkID = queryParm('network');
    var showID = queryParm('id');
    var tab = queryParm('tab');

    // if all parms are empty, we have a show alias
    if ((networkID == '') && (showID == '') && (tab == '')) {
        getShowListing();
    } else {
        selectShowAndTab(networkID, showID, tab);
    }

    $(function() {
        $(".media").live("mouseover", function() {
            $("#detailPanel").fadeIn("normal");

            $("#detailPanel").html('<img src="/images/icons/ajax-loader-small.gif" />');
            var videoDetails = "";
            try {
                videoDetails = $(this).attr("detailsUrl");
            }
            catch (err) { }

            $("#detailPanel").load(videoDetails);

        });
    });
    
}

function LoadContent(href) {
    ShowBusy();

    $('#media_content').load(href, function(response, status, xhr) {
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            $("#media_content").html(msg + xhr.status + " " + xhr.statusText);
        }

        // scroll clips window to top of region
        $('#media_content').animate({ scrollTop: 0 }, 1000);

        setBestOfDetails();

        try {
            BestOfDone();
        } catch (err) {
        }

        // hide busy indicator
        HideBusy();
    });
}

function queryParm(name) {
    // credits - see http://www.netlobo.com/url_query_string_javascript.html
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
function queryParmFromUrl(name,url) {
    // credits - see http://www.netlobo.com/url_query_string_javascript.html
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];
}

function selectShowAndTab(networkID, showID, tab) {
    var menuGroup;
    
    if (networkID == 'live') {
        networkID = 'talk';
    }

    if (networkID != '') {
        // load requested network
        menuGroup = $('ul.menu').find('#showbestofafr' + networkID);
        menuGroup.find('a:first').click();
        setTab(menuGroup, tab);
    } else if (showID == '') {
        // no network requested, no show requested
        // load default - first show and first category
        menuGroup = $('ul.menu').find('li:first');
        menuGroup.find('a:first').click();
        setTab(menuGroup, tab);
    } else if (showID != '') {
        // specific show is requested
        menuGroup = $('ul.menu').find('#show' + showID);
        menuGroup.find('a:first').click();
        setTab(menuGroup, tab);
    }

    //setBestOfDetails();
    //LoadContent($('a.at.selected').attr('href'));


}

function setBestOfDetails() {
    // get group title and clicked item
    //              a           li       ul      li
    var grp = $('a.at.selected').parent().parent().parent();
    var item = $('a.at.selected');

    // display show name and desc
    var title = getShowTitle(grp[0]);
    $('#showname').html(title);
    $('#showdesc').html(getShowContent(item[0]));

}

function setTab($menuGroup, tab) {
    var className = '';
    
    switch (tab) {
        case 'video':
            className = 'tabclips';
            break;
        case 'audio':
            className = 'tabaudio';
            break;
        case 'blog':
            className = 'tabblogs';
            break;
        case 'podcasts':
            className = 'tabpodcasts';
            break;
    }

    $menuGroup.find('ul').find('li.' + className + ':first').find('a.at:first').click();

}

function ShowBusy() {
    $('#ajaxLoading').html('<img src="/images/icons/ajax-loader-big-circle-ball.gif" />');
}

function AFA_Show(n) {

    // ============= PUBLIC PROPERTIES ========================
    this.name = n;
}

// ------------- PRIVATE METHODS ( AJAX HANDLERS ) ---------------------

// handle ajax response to getShowDetails
function handleGetShowListResponse(result) {
    if (result.d) {
        handleGetShowListResponse(result.d);
    } else {

        var _shows = new Array();
        var networkID = '';
        var showID = '';
        var tab = '';
        
        $.each(result.RadioShows, function(i, show) {
            _shows.push({
                "id": show.ID,
                "title": show.Title,
                "urlalias": show.UrlAlias
            }); // end push
        });  // end .each

        // remove trailing slash (ex.  http://www.afa.net/FocalPoint/ )
        showName = location.href.substring(0, location.href.lastIndexOf("/"));
        // get showname from last slash to end of string (ex: http://www.afa.net/FocalPoint )
        showName = showName.substring(showName.lastIndexOf("/"));

        for (indexShow in _shows) {
            if (_shows[indexShow].urlalias.toLowerCase() == showName.toLowerCase()) {
                showID = _shows[indexShow].id;
                break;
            }
        }
        
        selectShowAndTab(networkID, showID, tab)
        
        HideBusy();
        
    }  //end else (result.d)
}  // end function

// alert user if ajax request failed
function AjaxFailed(result) {
    alert(result.status + ' ' + result.statusText);
    HideBusy();
}


