//TODO: convert to plugin
//TODO: convert to plugin
var comment_field_textbox_help = "Make a comment...";
var search_textbox_help = 'themes, songs, users';
var txt_video_title_textbox_help = 'search for a song to add...';
var CreateItemYtLink_textbox_help = 'Link to youtube goes here...';

var divLoading;
var divHeader;
var lnkMyTheme;
var lnkAllTheme;
var lnkMyFeed;
var loginPopup;
var loginIntervalId;
var contentId;
var innerContentId;
var contentMainClass;
var contentInnerClass;

var mainContentElement = '#divContentMain';
var innerContentElement = '#divContentInner';

var currentContentUrl = '';
var currentInnerContentUrl = '';
var title = '';

var addthis_share = {
    templates: { twitter: '{{title}}: {{url}} via @meltinpop' }
}

String.prototype.capitalize = function () {
    if (this == null)
        return '';

    return this.replace(/(^|\s)([a-z])/g, function (m, p1, p2) { return p1 + p2.toUpperCase(); });
};

function activateSideBarLink(element) {
    // deselect all sidebar links
    $('.sidebar_tab').each(function (index) {
        $(this).removeClass('sidebar_tab_selected');
        $(this).addClass('sidebar_tab_unselected');
    });

    // select the one which was clicked
    $(element).parent().removeClass('sidebar_tab_unselected');
    $(element).parent().addClass('sidebar_tab_selected');

    title = $(element).attr("title") == null ? document.title : $(element).attr("title").capitalize();
    document.title = title;
}


$(function () {
    divHeader = $('#header_content_container');
    divLoading = $('#divLoading');
    lnkMyTheme = $('a:#lnkMyThemes');
    lnkAllTheme = $('a:#lnkAllThemes');
    lnkMyFeed = $('a:#lnkMyFeed');

    contentId = 'c';
    innerContentId = 'ic';
    contentMainClass = 'content';
    contentInnerClass = 'inner';

    var modalClass = 'modal';
    var logOnClass = 'logOn';
    var logOffClass = 'logout';
    var moreClass = "more";
    var moreItemsClass = "items";
    var morePlayersClass = "players";
    var moreFeedsClass = "feeds";
    var moreUsersClass = "users";


    var createThemeClass = 'createTheme';
    var createThemeCloseClass = 'createThemeClose';
    var settingsClass = "settings";
    var inviteClass = 'invite';
    var vSearchClass = 'vSearch';
    var reportClass = 'report';
    var deleteThemeClass = 'deleteTheme';
    var deleteItemClass = 'deleteItem';
    var deleteCommentClass = 'deleteComment';
    var floatingClass = 'floating';
    var followClass = 'follow_btn';
    var unfollowClass = 'unfollow_btn';
    var statFollowClass = 'stat_follow_btn';
    var statUnfollowClass = 'stat_unfollow_btn';
    var likeClass = 'like_on';
    var unlikeClass = 'like_off';
    var statLikeClass = 'stat_love_on';
    var statUnlikeClass = 'stat_love_off';
    var blockClass = 'block_on';
    var unblockClass = 'block_off';

    $(window).bind('hashchange', function (e) {
        //load main content - c
        urlContent = $.bbq.getState(contentId) || '';
        urlInner = $.bbq.getState(innerContentId) || '';

        if (urlContent != currentContentUrl || (urlInner == '' && urlContent != '')) {
            currentInnerContentUrl = '';
            var tokenizedInnerContent = jQuery.deparam.fragment(urlContent).ic;
            urlContent = urlContent.replace(tokenizedInnerContent, '');
            if ($(mainContentElement).length != 0)
                loadContentMain(urlContent, tokenizedInnerContent);
        }
        else if (urlInner != currentInnerContentUrl && urlInner != '')
            if ($(innerContentElement).length != 0)
                loadContentInner(urlInner);

        return;
    });

    //meltinpop action
    $('a.mpa').live('click', function () {
        var element = $(this);
        var url = element.attr("href");
        title = element.attr("title").capitalize();
        // Navigation Url, Content, Title
        if (element.hasClass(contentMainClass)) {
            loadContentMain(url);
        }
        //delete Theme
        if (element.hasClass(deleteThemeClass)) {
            deleteTheme(element, url);
        }
        //delete Item
        if (element.hasClass(deleteItemClass)) {
            deleteItem(element, url);
        }
        //delete comment
        if (element.hasClass(deleteCommentClass)) {
            deleteComment(element, url);
        }
        //floating
        if (element.hasClass(floatingClass)) {
            showFloating(title, element, url);
        }

        //follow
        if (element.hasClass(followClass) || element.hasClass(unfollowClass)) {
            followHandler(element, url, followClass, unfollowClass);
        }

        if (element.hasClass(statFollowClass) || element.hasClass(statUnfollowClass)) {
            followHandler(element, url, statFollowClass, statUnfollowClass);
        }

        //like
        if (element.hasClass(likeClass) || element.hasClass(unlikeClass)) {
            likeHandler(element, url, likeClass, unlikeClass);
        }

        //block
        if (element.hasClass(blockClass) || element.hasClass(unblockClass)) {
            blockHandler(element, url, blockClass, unblockClass);
        }
        return false;
    });

    //meltinpop navigation
    $('a.mpn').live('click', function () {
        var element = $(this);
        var url = element.attr("href");
        title = element.attr("title").capitalize() || document.title;
        var state = {};


        //login
        if (element.hasClass(logOnClass)) {
            loginPopup = window.open(url, "logon", "menubar=no,width=1000,height=600,toolbar=no,resizable=yes");
            loginIntervalId = setInterval(WaitForLoginClose, 1000);
            return false;
        }
        //logOff
        if (element.hasClass(logOffClass)) {
            $.ajax({
                url: url,
                cache: false,
                success: function (data) {
                    title = "Meltinpop";
                    loadHeader();
                    document.location = "/";
                }
            });

            //loginWindow.onClose(alert('test'));
            return false;
        }
        //More Navigation
        if (element.hasClass(moreClass)) {
            if (element.hasClass(moreItemsClass)) {
                document.title = title;
                loadMoreItems(url);
            }
            if (element.hasClass(morePlayersClass)) {
                document.title = title;
                loadMorePlayers(url);
            }
            if (element.hasClass(moreUsersClass)) {
                loadMoreUsers(url);
            }
            if (element.hasClass(moreFeedsClass)) {
                document.title = title;
                loadMoreFeeds(url);
            }

            return false;
        }

        //Dialogs
        if (element.hasClass(modalClass)) {
            if (element.hasClass(createThemeClass)) {
                createThemeDialogOpen(url, title);
            }
            if (element.hasClass(createThemeCloseClass)) {
                createThemeDialogClose();
            }

            if (element.hasClass(inviteClass)) {
                inviteDialogOpen(url, title);
            }
            if (element.hasClass(settingsClass)) {
                settingsDialogOpen(url, title);
            }
            if (element.hasClass(vSearchClass)) {
                vSearchDialogOpen(url, title);
            }
            if (element.hasClass(reportClass)) {
                reportDialogOpen(url, title);
            }
            return false;
        }
        // Navigation Url, Main Content, Title
        if (element.hasClass(contentMainClass)) {
            state[contentId] = url;
        }
        // Navigation Url, Inner Content, Title
        if (element.hasClass(contentInnerClass)) {
            state[innerContentId] = url;
        }

        $.bbq.pushState(state);

        return false;
    });

    //trigger for direct access.
    $(window).trigger('hashchange');
});

function wireUpElements() {
    var activeLink = $('#active_sidebar_link').attr('value');
    if (activeLink != null)
        activateSideBarLink(activeLink);

    hiConfig0 = {
        sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
        interval: 200, // number = milliseconds for onMouseOver polling interval
        timeout: 200, // number = milliseconds delay before onMouseOut
        over: function () {
            var spanCounter = $(this).children('span');
            if (parseInt(spanCounter.html()) > 0) {
                undelayClose();
                showFloating('Lovers', $(this), '/Widgets/ItemLikers/?id=' + $(this).attr('itemId'));
            }
        }, // function = onMouseOver callback (REQUIRED)
        out: function () {
            if (!getDelayClose())
                $('.likesDiv').dialog('close');
        } // function = onMouseOut callback (REQUIRED)
    }

    $('.like_on').hoverIntent(hiConfig0);
    $('.like_off').hoverIntent(hiConfig0);

    $('#search').textboxhelp({ help: search_textbox_help });

    // *********************** theme details control ****** //
    $("#CreateItemYtLink").textboxhelp({ help: CreateItemYtLink_textbox_help });
    $("#txt_video_title").textboxhelp({ help: txt_video_title_textbox_help });
    $("#txtCreateItemArtist").autocomplete(
		'/Search/AutoComplete/Artist/',
		{
		    max: 10
		});
    $("#txtCreateItemTitle").autocomplete(
		'/Search/AutoComplete/Title/',
		{
		    max: 10
		});

    $('#divCreateNewItem').hide();
    $('#video_short_search').show();
    //	$("#txt_video_title").focus();
    // ************************************************** //

    //$('.music_item_container .addthis_toolbox').css('display', 'none');
    $('.comment_field').textboxhelp({ help: comment_field_textbox_help });

    $('.new_comment_placeholder .avatarpic').css('display', 'none');
    $('.new_comment_placeholder .add_comment_btn').css('display', 'none');

    $('.comment_field').focus(function () {
        $(this).parents(".new_comment_placeholder").find(".avatarpic").css('display', 'block');
        $(this).parents(".new_comment_placeholder").find(".add_comment_btn").css('display', 'block');
    });

    $('.comment_field').blur(function () {
        if ($(this).val() == comment_field_textbox_help) {
            $(this).parents(".new_comment_placeholder").find(".avatarpic").css('display', 'none');
            $(this).parents(".new_comment_placeholder").find(".add_comment_btn").css('display', 'none');
        }
    });

    // mobile mode
    if (mobileMode) {
        $('.playicon_onImg').each(function (index) {
            $(this).attr('onclick', 'javascript:void(0)');
            var id = $(this).attr('youtubeId');
            $(this).attr("href", "http://www.youtube.com/watch?v=" + id);
        });
    }


    // share elements
    addthis.toolbox('.addthis_toolbox');
    addthis.counter('.addthis_counter');
    //set facebook
//    FB.init({ appId: '140717062620062', status: true, cookie: true,
//        xfbml: true
//    });

    // show/hide comments
    $(".showAllComments").toggle(
		function () {
		    itemId = $(this).attr('itemid');
		    $(this).text("Hide...");
		    $("#divPreviousComments_" + itemId).children(".hidden").css("display", "block");
		},
		function () {
		    itemId = $(this).attr('itemid');
		    $(this).text("Show All...");
		    $("#divPreviousComments_" + itemId).children(".hidden").css("display", "none");
		}
	);
}

function loadContentMain(url, urlInner) {
    currentContentUrl = url;
    // Animate - start
    //$(mainContentElement).fadeOut('normal');
    divLoading.show();
    //load the content of the new page into the content of the current page.
    $.ajax({
        url: url,
        dataType: 'html',
        cache: false,
        success: function (result) {
            _gaq.push(['_trackPageview', url]);
            $(mainContentElement).html(result);
            if (urlInner != null && urlInner != '')
                loadContentInner(urlInner);
            else {
                wireUpElements();
            }
        },
        complete: function (result) {
            // Animate - end
            divLoading.hide();
            document.title = title;
        },
        error: function (result) {
            alert('Error(MPN280):Could not load main content.');
        }
    });
}
function loadContentInner(url) {
    currentInnerContentUrl = url;
    // Animate - start
    //$(mainContentElement).fadeOut('normal');
    divLoading.show();
    //load the content of the new page into the content of the current page.
    $.ajax({
        url: url,
        dataType: 'html',
        cache: false,
        success: function (result) {
            $(innerContentElement).html(result);
            wireUpElements();
        },
        complete: function (result) {
            // Animate - end
            divLoading.hide();
        },
        error: function (result) {
            alert('Error(MPN233):Could not load inner content.');
        }
    });
}
function loadHeader() {

    // Animate - start
    divHeader.fadeOut('normal');
    divLoading.show();
    //load the content of the header into the the current page.
    $.ajax({
        cache: false,
        url: "/Home/Header",
        dataType: "html",
        type: "POST",
        success: function (result) {
            divHeader.html($(result).filter('#header_content_container'));
        },
        complete: function (result) {
            // Animate - end
            divLoading.hide();
            divHeader.fadeIn('normal');
            loggedInUserName = jQuery.trim($("#bubble_txt_box a").text());
            $('#search').textboxhelp({ help: search_textbox_help });
        },
        error: function (result) {
            alert('Error(150):Could not load header.');
        }
    });
}

function loadMoreItems(url) {
    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            $('#divItems').append($(result).find('#divItems > div'));
            $('#bottom_nav_div').replaceWith($(result).find('#bottom_nav_div'));
            wireUpElements();
        },
        error: function (result) {
            alert('Error(176):Could not load items.');
        }
    });
}
function loadMorePlayers(url) {
    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            $('#xxx_list_widget_div').append($(result).filter('#xxx_list_widget_div'));
            $('#divMorePlayers').replaceWith($(result).filter('#divMorePlayers'));
        },
        error: function (result) {
            alert('Error(297):Could not load users.');
        }
    });
}
function loadMoreUsers(url) {
    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            $('.search_list').append($(result).find('.search_list'));
            $('#bottom_nav_div').replaceWith($(result).find('#bottom_nav_div'));
        },
        error: function (result) {
            alert('Error(297):Could not load users.');
        }
    });
}
function loadMoreFeeds(url) {
    // Animate - start
    //$(mainContentElement).fadeOut('normal');
    divLoading.show();
    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            $('#user_feed_div').append($(result).find('ul.user_stories'));
            $('#divMoreFeed').replaceWith($(result).find('#divMoreFeed'));
        },
        complete: function (result) {
            // Animate - end
            divLoading.hide();
            $(mainContentElement).fadeIn('normal');
        },
        error: function (result) {
            alert('Error(310):Could not load feeds.');
        }
    });
}
function deleteTheme(element, url) {

    $('<div Title="Delete comment"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to delete this?</p></div>').dialog({
        resizable: false,
        height: 140,
        modal: true,
        buttons: {
            "Delete": function () {
                loadContentMain(url);
                $(this).dialog("close");

            },
            Cancel: function () {
                $(this).dialog("close");
                return false;
            }
        }
    });


}

function deleteItem(element, url) {

    $('<div Title="Delete Item"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to delete this?</p></div>').dialog({
        resizable: false,
        height: 140,
        modal: true,
        buttons: {
            "Delete": function () {
                loadContentMain(url);
                $(this).dialog("close");

            },
            Cancel: function () {
                $(this).dialog("close");
                return false;
            }
        }
    });


}

function deleteComment(element, url) {

    $('<div Title="Delete comment"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to delete this?</p></div>').dialog({
        resizable: false,
        height: 140,
        modal: true,
        buttons: {
            "Delete": function () {
                $.ajax({
                    cache: false,
                    url: url,
                    success: function (result) {
                        var counter = parseInt(element.parents('.item_comments').find('.comments_counter').html());
                        if (!isNaN(counter)) {
                            element.parents('.item_comments').find('.comments_counter').html(counter - 1);
                        }
                        element.closest('#divCommentWrapper').remove();
                    },
                    error: function (result) {
                        alert('Error(227):Could not delete comment.');
                    }
                });

                $(this).dialog("close");

            },
            Cancel: function () {
                $(this).dialog("close");
                return false;
            }
        }
    });


}
function followHandler(element, url, followclass, unfollowclass) {

    var spanCounter = element.children('span');

    if (element.hasClass(followclass)) {
        //change class
        element.removeClass(followclass);
        element.addClass(unfollowclass);
        //update counter
        spanCounter.html(parseInt(spanCounter.html()) + 1);
        //change link
        element.attr('href', url.replace('True', 'False'));
    }
    else {
        //change class
        element.removeClass(unfollowclass);
        element.addClass(followclass);
        //update counter
        if (parseInt(spanCounter.html()) > 0) {
            spanCounter.html(parseInt(spanCounter.html()) - 1);
        }
        //change link
        element.attr('href', url.replace('False', 'True'));
    }

    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            spanCounter.html(parseInt(result));
        },
        error: function (result) {
            alert('Error(MPA371):Could not follow.');
        }
    });

    return false;
}

function likeHandler(element, url, likeClass, unlikeClass) {

    var spanCounter = element.children('span');

    if (element.hasClass(likeClass)) {
        //change class
        element.removeClass(likeClass);
        element.addClass(unlikeClass);
        //update counter
        if (parseInt(spanCounter.html()) > 0)
            spanCounter.html(parseInt(spanCounter.html()) - 1);
        //change link
        element.attr('href', url.replace('False', 'True'));
    }
    else {
        //change class
        element.removeClass(unlikeClass);
        element.addClass(likeClass);
        //update counter
        spanCounter.html(parseInt(spanCounter.html()) + 1);
        //change link
        element.attr('href', url.replace('True', 'False'));
    }

    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            spanCounter.html(parseInt(result));
        },
        error: function (result) {
            alert('Error(MPA371):Could not follow.');
        }
    });

    return false;
}

function blockHandler(element, url, blockClass, unblockClass) {

    if (element.hasClass(blockClass)) {
        //change class
        element.removeClass(blockClass);
        element.addClass(unblockClass);

        element.text('Mute');

        //change link
        element.attr('href', url.replace('False', 'True'));
    }
    else {
        //change class
        element.removeClass(unblockClass);
        element.addClass(blockClass);

        element.text('Unmute');

        //change link
        element.attr('href', url.replace('True', 'False'));
    }

    $.ajax({
        cache: false,
        url: url,
        success: function (result) {
            if (parseInt(result)) {
                element.removeClass(unblockClass);
                element.addClass(blockClass);
                element.attr('href', url.replace('True', 'False'));
            }
            else {
                element.removeClass(blockClass);
                element.addClass(unblockClass);
                element.attr('href', url.replace('False', 'True'));
            }
        },
        error: function (result) {
            alert('Error(MPA371):Could not follow.');
        }
    });

    return false;
}

var init = false;
var playerInit = false;


function youtubePlayerInit(videoId) {
    playerInit = true;
    $('#Player_main_box').show();
    jQuery("#youtube-player-container").tubeplayer('distroy');
    jQuery("#youtube-player-container").tubeplayer({
        width: 298, // the width of the player
        height: 200, // the height of the player
        allowFullScreen: "true", // true by default, allow user to go full screen
        initialVideo: videoId, // the video that is loaded into the player
        playerID: "youtube-player", // the ID of the embedded youtube player
        preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
        onPlay: function (id) { }, // after the play method is called
        onPause: function () { }, // after the pause method is called
        onStop: function () { }, // after the player is stopped
        onSeek: function (time) { }, // after the video has been seeked to a defined point
        onMute: function () { }, // after the player is muted
        onUnMute: function () { } // after the player is unmuted
    });
}
function youtubePlay(videoId) {
    if (!playerInit) {
        youtubePlayerInit(videoId);
    }
    else {
        $("#youtube-player-container").tubeplayer("play", videoId);
    }
    return false;
}

var d = null;
var dc = false;

function delayClose() {
    dc = true;
}

function undelayClose() {
    dc = false;
}

function getDelayClose() {
    return dc;
}

function showFloating(title, element, url) {
    if (d != null) {
        d.dialog('destroy');
        $('.likesDiv').remove();
        d = null;
    }

    $.ajax(
	{
	    url: url,
	    dataType: 'html',
	    success: function (data) {
	        if (data != null && data != '') {
	            d = $('<div class="likesDiv" Title="' + title + '">' + data + '</div>');
	            d.dialog({
	                dialogClass: 'tooltip',
	                resizable: false,
	                width: 240,
	                modal: false,
	                show: 'fade',
	                hide: 'fade',
	                position: [element.offset().left + element.width() - $(document).scrollLeft(), element.offset().top + element.height() - $(document).scrollTop()]
	            });

	            d.parent().hoverIntent({
	                sensitivity: 3,
	                interval: 0,
	                timeout: 200,
	                over: function () { delayClose(); },
	                out: function () { d.dialog('close'); }
	            });

	        }
	    },
	    cache: false
	});

    return false;
}

function WaitForLoginClose(intervalID, popup) {
    if (loginPopup == null || loginPopup.closed) {
        clearInterval(loginIntervalId);
        loadHeader();
        url = $.bbq.getState(contentId) || '';
        if (url == '') {
            url = document.location.pathname;
        }
        $("#divJoinUs").hide();
        loadContentMain(url, '');
    }
}

function initializePlayer() {
    $("#youtube-player-container").tubeplayer({
        width: 300, // the width of the player
        height: 27, // the height of the player
        allowFullScreen: "true", // true by default, allow user to go full screen
        initialVideo: "7MXClMbzFJ0", // the video that is loaded into the player
        playerID: "youtube-player", // the ID of the embedded youtube player
        preferredQuality: "medium", // preferred quality: default, small, medium, large, hd720
        onPlay: function (id) { ensurePlayerIsOpen() }, // after the play method is called
        onPause: function () { }, // after the pause method is called
        onStop: function () { }, // after the player is stopped
        onPlayerEnded: function () { next(); }, // when the player returns a state of ended
        onPlayerUnstarted: function () { }, // when the player returns a state of unstarted
        onErrorNotFound: function () { failAndNext(); }, // if a video cant be found
        onErrorNotEmbeddable: function () { failAndNext(); }, // if a video isnt embeddable
        onSeek: function (time) { }, // after the video has been seeked to a defined point
        onMute: function () { }, // after the player is muted
        onUnMute: function () { } // after the player is unmuted
    });

    $.tubeplayer.defaults.onError = function ($player) { failAndNext(); }

    $('#Player_main_box').css("height", 76);
    $("#prev_player").click(function () { prev(); });
    $("#next_player").click(function () { next(); });
    $("#shuffle_player").click(function () { shuffle(); });

    $("#open_close_player").toggle(
		function () {
		    showing = true;
		    $('#youtube-player').css("height", 225);
		    $('#Player_main_box').css("height", 274);
		    $('#open_close_player').toggleClass("open_player_btn");
		    $('#open_close_player').toggleClass("close_player_btn");
		},
		function () {
		    showing = false;
		    $('#youtube-player').css("height", 27);
		    $('#Player_main_box').css("height", 76);
		    $('#open_close_player').toggleClass("open_player_btn");
		    $('#open_close_player').toggleClass("close_player_btn");
		}
	);

    //default=hide.
    mobileMode = DetectSmartphone();
    if (mobileMode)
        $('#Player_main_box').hide();

    //playerInit = false;
}
