var selectedInjury = null;
var youtubeContent = "";
var flickrContent = "";
var twitterContent = "";
var communityLoaded = 0;

$(document).ready(function()
{
    //youtube
	$("#youtube .container, #flickr .container").css("marginTop","0px")

    $('#toptentips li h3, .trainingaims .aim h4, .choosing .which h3').each(function()
    {
        $(this).html('<a href="#">' + $(this).html() + '</a>');
    })

    $('#toptentips li .body, .trainingaims .aim .body, .choosing .which .body').each(function(i)
    {
        if (i > 0)
        {
            $(this).addClass('hidden');
        }
    })

    $('#toptentips li h3 a, .trainingaims .aim h4 a, .choosing .which h3 a').click(function()
    {
        var ref = $(this).parent().parent().children('.body');
        var parentContainer = $(this).parent().parent();

        if (ref.hasClass('hidden') == true)
        {
            ref.removeClass("hidden");
        }
        else
        {
            ref.addClass("hidden");
        }

        return false;
    })

    $('.enhanced').each(function()
    {
        $(this).html($(this).html().replace("<!--", "").replace("-->", ""));
    })

    //
    $('#issues').css('display', 'none');

    $('#injuredman a').hover(function()
    {
        if (selectedInjury)
        {
            $('#injuriescontent').removeClass(selectedInjury);
        }
        $('#injuriescontent').addClass($(this).attr('href').split('#')[1]);
    }, function()
    {
        $('#injuriescontent').removeClass($(this).attr('href').split('#')[1]);
        if (selectedInjury)
        {
            $('#injuriescontent').addClass(selectedInjury);
        }
    }).click(function()
    {
        selectedInjury = $(this).attr('href').split('#')[1];
        $('#injuryinfo').css('display', 'none');
        $('#injuryselected').html($('#' + selectedInjury).html());
        return false;
    })

    //
    $('#trainingprograms, #programme, #progfoot').css('display', 'none');

    var displayprogramme = function()
    {
        var distance = $('input[name=rdistance]:checked').attr('id');
        var level = $('input[name=rlevel]:checked').attr('id');
        var infoPanel = $('#selectdis');
        infoPanel.hide();

        if (!distance && level)
        {
            $('#mTraining h3').html('Now select a distance');
            infoPanel.show();
        }
        else if (distance && !level)
        {
            $('#mTraining h3').html('Now select a level');
            infoPanel.html('Please select a level').show();
        }
        else if (!distance && !level)
        {
            $('#mTraining h3').html('Select a level and distance to display your training programme')
        }
        else
        {
            $('#mTraining h3').html('Select another level or distance to display your training programme')
        }

        if ($('#' + level + distance).length)
        {
            $('#programmedetail').html($('#' + level + distance).html());
            $('#progfoot a').attr('href', $('#' + level + distance + ' h4 a').attr('href'));

            $('#programme, #progfoot').css('display', 'block');
            $(window).scrollTo($('#programme'), 800);
        }
    }

    $('#distance input.radio, #level input.radio').click(function() { displayprogramme(); })
    displayprogramme();

    // ADD HOVER EFFECT TO SEARCH BTN (IE6)
    $('#btnSearch').hover(function()
    {
        $(this).addClass('hover');
    },
	function()
	{
	    $(this).removeClass('hover');
	});

    //lightbox
	if($("#flickr").length)
	{
		$("#flickr .featured a, #flickr .morebox a, #flickr .morebox .newcontent a").lightBox({
			overlayBgColor: "#333",
			overlayOpacity: 0.9,
			imageLoading: "/running/_assets/images/lightbox-ico-loading.gif",
			imageBtnClose: "/running/_assets/images/lightbox-btn-close.gif",
			imageBtnPrev: "/running/_assets/images/lightbox-btn-prev.gif",
			imageBtnNext: "/running/_assets/images/lightbox-btn-next.gif",
			imageBlank: "/running/_assets/images/lightbox-blank.gif"
		});
	}

    twitStartHeight = $("#twitter .morebox dl:first").height() + $("#twitter .morebox dl").eq(1).height() + 25 + "px";
    blogStartHeight = $("#blog .morebox ul:first").height() + 10 + "px";
    tubeStartHeight = $("#youtube .morebox dl:first").height() + $("#youtube .morebox dl").eq(1).height() + 45 + "px";
	
//	if($("#flickr .morebox").text().indexOf("emptyfeederr") != -1) $("#flickr").addClass("hide");
	
	$("#flickr").lazyload('getContent', {
	    url: "/running/jsp/flickr.jsp?load=false",
		text:"photos",
		contentName:"flickrContent",
		isYouTube: false, 
		startHeight: flikStartHeight,
		amountShown:9
	});
	
//	if($("#twitter .morebox").text().indexOf("emptyfeederr") != -1) $("#twitter").addClass("hide");

	$("#twitter").lazyload('getContent', {
	    url: "/running/jsp/twitter.jsp?load=false",
		text:"tweets",
		contentName:"twitterContent",
		isYouTube: false, 
		startHeight: twitStartHeight,
		amountShown:3
	});

	
//	if($("#youtube .morebox").text().indexOf("emptyfeederr") != -1) $("#youtube").addClass("hide");
			
	$("#youtube").lazyload('getContent', {
	    url: "/running/jsp/youtube.jsp?load=false",
		text:"videos",
		contentName:"youtubeContent",
		isYouTube: true, 
		startHeight: tubeStartHeight,
		amountShown:3
    });


    $("#blog").lazyload('getContent', {
        url: "/running/jsp/wordpress.jsp?load=false",
        text: "posts",
        contentName: "blogContent",
        isYouTube: false,
        startHeight: blogStartHeight,
        amountShown: 2
    });
		
});

function scrollers(action, current) {

    var context = (current == 'blog') ? $("#ourCommunity") : $("#yourCommunity"); 

	if(action=="close") {

		var scrollUp = context.find(".up");
		var scrollDown = context.find(".down");
		scrollUp.slideUp(250);
		scrollDown.slideUp(250);
	}
	else
	{
	    var scrollUp = context.find("#" + current).find(".up");
	    var scrollDown = context.find("#" + current).find(".down");
		scrollUp.slideDown(250);
		scrollDown.slideDown(250);
	}
}

/**
jQuery plugin checks for lazyload
*/
jQuery.fn.lazyload = function(func, arg) {
    var path = '/running/_assets/js/' + func + '.js';
    var status = "";
    var $that = $(this);
    var func = func;
    var needToLoadScript = true;
	
    $that.each(function() {
        if (needToLoadScript) {
            $.ajax({
                url: path,
                type: "GET",
                dataType: "script",
                cache: true,
                success: function() {
                    $that.each(function() {
                        var strFn = "jQuery.fn." + func;
                        eval(strFn).apply($(this), new Array(arg));
                    })
                }
            });
        }
        needToLoadScript = false;
    })
}

var ytplayer;
var vidPlayId;
var moreBoxClicked = false;
var playerState;

function onYouTubePlayerReady()
{
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState)
{
    if (newState == -1)
    {
        loadNewVideo(vidplayId, 0);
    }
    if (newState == 5 && !($("#player").hasClass("hidden")))
    {
        ytplayer.playVideo();
    }

    playerState = newState;
}

function fireUpPlayer(id)
{
    var params = { allowScriptAccess: "always", bgcolor: "#cccccc", wMode: "transparent", allowFullScreen: true };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/" + id + "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer&amp;fs=1",
                             "ytapiplayer", "220", "190", "8", null, null, params, atts); 
}

function cueNewVideo(id, startSeconds)
{
    if (ytplayer)
    {
        ytplayer.cueVideoById(id, startSeconds);
    }
}

function loadNewVideo(id, startSeconds)
{
    if (ytplayer)
    {
		ytplayer.loadVideoById(id, startSeconds);
    }
}

var playerInitiated = false;

$.fn.videoSetUp = function()
{
    $(this).click(function(e)
    {
        e.preventDefault();
		youtubeFutureState = "video";
        moreBoxClicked = false;
        var vidId = $(this).attr("href").split("v=")[1];

        if ($("#player").hasClass("hidden"))
        {
            playerInitiated = true;
            $("#youtube .morecomm").click();
            $("#player").removeClass("hidden");
			fireUpPlayer(vidId);
			if (playerState == 5 && $.browser.msie) ytplayer.playVideo();
        }
        else
        {
            vidplayId = vidId;
            if (ytplayer) loadNewVideo(vidplayId, 0);
        }

        //switch details to main video player
        var parentElm = $(this).parents("dl");

        $("#videodetails .title").html(parentElm.find(".title").html());
        $("#videodetails .user").html(parentElm.find(".user").html());
        $("#videodetails .rating").html(parentElm.find(".rating").html());
        $("#videodetails .views").html(parentElm.find(".views").html());

    });
}
var bCurPos = "0px";
var tCurPos = "0px";
var fCurPos = "0px";
var yCurPos = "0px";
var yState = 0;
var youtubeCurrentState = "initial";
var youtubeFutureState = "initial";

function setCurrentPositions()
{
	if(!($("#twitter .morecomm").hasClass("closed")))
	{
		tCurPos = $("#twitter .morebox").css("marginTop");
    }
    if (!($("#blog .morecomm").hasClass("closed"))) 
    {
        bCurPos = $("#blog .morebox").css("marginTop");
    }
	if(!($("#youtube .morecomm").hasClass("closed")))
	{
		yCurPos = $("#youtube .morebox").css("marginTop");
	}
	if(!($("#flickr .morecomm").hasClass("closed")))
	{
		fCurPos = $("#flickr .morebox").css("marginTop");
	}
}

$.fn.closeAll = function()
{
    $(this).each(function()
    {
		setCurrentPositions();
        var name = $(this).find(".morecomm").text().split(" ")[1];
		scrollers("close");
		
		$(this).find(".morecomm").text("More " + name);
		
        $(this).find(".morecomm").addClass("closed");
        $(this).find(".wrapper").animate({
            height: "0px"
        }, 400);
    });
}

var twitStartHeight = "";
var blogStartHeight = "";
var flikStartHeight = "179px";
var tubeStartHeight = "";

$.fn.resetAll = function () {
    
    $(this).each(function () {
        var sHeight = "0px";
        var sPos = $(this).find(".morebox").css("marginTop");

        //setCurrentPositions();
        switch ($(this).attr("id")) {
            case "twitter":
                sHeight = $("#twitter .morebox dl:first").height() + $("#twitter .morebox dl").eq(1).height() + 25 + "px";
                break;
            case "blog":
                sHeight = $("#blog .morebox ul:first").height() + 10 + "px";
                break;
            case "youtube":
                sHeight = $("#youtube .morebox dl:first").height() + $("#youtube .morebox dl").eq(1).height() + 45 + "px";
                break;
            case "flickr":
                sHeight = flikStartHeight;
                break;
        }


        var name = $(this).find(".morecomm").text().split(" ")[1];

        //reset margin top - store margin for reopening
        $(this).find(".morebox").css("marginTop", "0px");
        scrollers("close");

        /* $(this).find(".morecomm").text("More " + name).addClass("closed");*/
        $(this).find(".wrapper").animate({
            height: sHeight
        }, 400);
    });
}

$.fn.headingLink = function()
{
	$(this).each(function(){
		var relatedLink = $(this).parents(".community").find(".morecomm");
		$(this).wrapInner('<a href="#"></a>').click(function(e){
			e.preventDefault();
			relatedLink.trigger("click");
		});
	});
}

$.fn.showMore = function (name, content, isYouTube, startHeight) {
    var stubcontent = eval(content);

    $("#yourCommunity").css("paddingBottom", "0");
    var wrappa = $(this).find(".wrapper");
    var morebox = $(this).find(".morebox");
    var boxheight = $(this).find(".morebox").height();
    var wrapperheight = wrappa.height();
    var scrollUp = $(this).find(".up");
    var scrollDown = $(this).find(".down");

    var boxheightStore = boxheight;
    var wrapperheightStore = wrapperheight;

    var startHeight = startHeight;
    wrappa.height(startHeight);

    var currentPos = 0;

    //do this once all three communitys have loaded
    if (communityLoaded == 3) {
        $(".community h4").headingLink();
        $(".loadingmore").remove();
        $("#youtube dl .inplay").videoSetUp();
        $('#footerMain').addClass('IEredraw');
        $('#listHolder').addClass('IEredraw');
    }

    $(this).find(".morecomm").click(function (e) {
        e.preventDefault();

        var inPlay = playerInitiated == true ? true : false;
        setCurrentPositions();

        if ($(this).hasClass("closed")) {
            youtubeCurrentState = "initial";
            if (inPlay) {
                youtubeFutureState = "video";
            }
            else {
                youtubeFutureState = "expanded";
            }
        }
        else {
            if ($("#player").hasClass("hidden")) {
                youtubeCurrentState = "expanded";
                if (inPlay) {
                    youtubeFutureState = "video";
                }
                else {
                    youtubeFutureState = "initial";
                }
            }
            else {
                youtubeCurrentState = "video";
                youtubeFutureState = "initial";
            }
        }

        switch (youtubeCurrentState) {
            case "video":
                yState = 1;
                break;
            case "expanded":
                yState = 0;
                break;
            case "initial":
                yState = yState;
                break;
        }

        /*here*/

        if (playerInitiated == true) {
            var nHeight = $("#youtube .morebox dl:first").height() + $("#youtube .morebox dl").eq(1).height() + 30;
            $("#youtube").addClass("mini");
            boxheight = nHeight;
            wrapperheight = nHeight;
            playerInitiated = false;
        }
        else {
            $("#youtube").removeClass("mini");
            boxheight = boxheightStore;
            wrapperheight = wrapperheightStore;
        }


        switch (name) {
            case "videos":
                if (yState == 1 && youtubeFutureState == "video") //small
                {
                    currentPos = yCurPos;
                }
                else if (yState == 0 && youtubeFutureState == "video") //big
                {
                    if ((parseInt(yCurPos) >= -245)) {
                        currentPos = "0px";
                    }
                    else {
                        currentPos = (parseInt(yCurPos) - 245) + "px";
                    }
                }
                else if (yState == 1 && youtubeFutureState == "expanded") {
                    if (parseInt(yCurPos) <= -245) {
                        currentPos = (parseInt(yCurPos) + 245) + "px";
                    }
                    else {
                        currentPos = "0px";
                    }

                }
                else if (yState == 0 && youtubeFutureState == "expanded") {
                    currentPos = yCurPos;
                }
                break;
            case "photos":
                currentPos = fCurPos;
                break;
            case "tweets":
                currentPos = tCurPos;
                break;
            case "posts":
                currentPos = bCurPos;
                break;
        }

        if (ytplayer) {
            moreBoxClicked = true;
            $("#player").addClass("hidden");
            if (playerState == 1) {
                ytplayer.stopVideo();
            }
        }

        scrollDown.css({
            "position": "absolute",
            "bottom": "-1px"
        });

        var scrollerHeight = scrollUp.height() * 2;

        if ($(this).hasClass("closed") || inPlay == true) {
            var parentId = $(this).parent(".community").attr("id");

            inPlay = false;

            $("#yourCommunity .community:not('#" + $(this).parent().attr('id') + ")").closeAll();
            $("#ourCommunity .community:not('#" + $(this).parent().attr('id') + ")").closeAll();

            $(this).text("Less " + name).removeClass("closed");

            if (parentId == "flickr") {
                var setHeight = wrapperheight + scrollerHeight - 2 + "px"; //95
            }
            else if (parentId == "youtube") {
                var setHeight = wrapperheight + scrollerHeight + 0 + "px"; //85
            }
            else if (parentId == "blog") {
                var setHeight = wrapperheight + scrollerHeight + 45 + "px"; //48
            }
            else {
                var setHeight = wrapperheight + scrollerHeight + 10 + "px"; //48
            }

            wrappa.animate({
                height: setHeight
            }, 400,
				function () {
				    scrollers("open", parentId);
				    morebox.css("marginTop", currentPos);
				});
        }
        else {
            var parentId = $(this).parent().attr("id");

            $(this).text("More " + name);

            $(this).addClass("closed");

            $("#yourCommunity .community:not('#" + $(this).parents(".community").attr("id") + "')").resetAll();
            $("#ourCommunity .community:not('#" + $(this).parents(".community").attr("id") + "')").resetAll();

            wrappa.animate({
                height: startHeight
            }, 400, function () {
                scrollers("close", parentId);
                setCurrentPositions();
                morebox.css("marginTop", "0px");
            });
        }
        if ($(this).parent().find(".newcontent").length == 0) {
            morebox.append(stubcontent);

            if ($(this).parents("#flickr").length > 0) {
                $("#flickr .newcontent a, #flickr .morebox a").lightBox({
                    overlayBgColor: "#333",
                    overlayOpacity: 0.9,
                    imageLoading: "/running/_assets/images/lightbox-ico-loading.gif",
                    imageBtnClose: "/running/_assets/images/lightbox-btn-close.gif",
                    imageBtnPrev: "/running/_assets/images/lightbox-btn-prev.gif",
                    imageBtnNext: "/running/_assets/images/lightbox-btn-next.gif",
                    imageBlank: "/running/_assets/images/lightbox-blank.gif"
                });
            }
            else if ($(this).parents("#youtube").length > 0) {
                $("#youtube .newcontent dl .inplay, #youtube dl.newvid .inplay").videoSetUp();
            }
        }
    });

    scrollDown.click(function (e) {
        e.preventDefault();
        if ($(this).find("a").hasClass("disabled") == true || $(this).hasClass("clicked") == true) return false;
        $(this).addClass("clicked");
        scrollUp.find("a").removeClass("disabled");

        var newContHeight = $(this).parents(".wrapinner").find(".newcontent").height();

        var playerOn = false;
        if (!($("#player").hasClass("hidden")) && $(this).parents("#youtube")) {
            playerOn = true;
            newContHeight = $(this).parents(".wrapinner").find(".morebox").height() - boxheight;
        }

        var mTop = parseInt(morebox.css("marginTop"));
        var heightRemaining = newContHeight + mTop;
        var marginAdj;

        if (heightRemaining > boxheight) {
            marginAdj = "-" + (boxheight - mTop) + "px";
        }
        else {
            marginAdj = "-" + (heightRemaining - mTop) + "px";
            $(this).find("a").addClass("disabled");
        }
        morebox.animate({
            marginTop: marginAdj
        }, 800, function () {
            scrollDown.removeClass("clicked");
        });
        switch ($(this).parents(".community").attr("id")) {
            case "youtube":
                yCurPos = mTop + "px";
                break;
            case "flickr":
                fCurPos = mTop + "px";
                break;
            case "twitter":
                tCurPos = mTop + "px";
                break;
            case "blog":
                bCurPos = mTop + "px";
                break;
        }
    });
    scrollUp.click(function (e) {
        e.preventDefault();
        if ($(this).find("a").hasClass("disabled") == true || $(this).hasClass("clicked") == true) return false;
        $(this).addClass("clicked");
        scrollDown.find("a").removeClass("disabled");

        var mTop = parseInt(morebox.css("marginTop"));
        var marginAdj;
        if (mTop < 0) {
            if (mTop < (-boxheight)) {
                marginAdj = (mTop + boxheight) + "px";
            }
            else {
                marginAdj = "0px";
                $(this).find("a").addClass("disabled");
            }
            morebox.animate({
                marginTop: marginAdj
            }, 800, function () {
                scrollUp.removeClass("clicked");
            });
        }
        else {
            return false;
        }
        switch ($(this).parents(".community").attr("id")) {
            case "youtube":
                yCurPos = mTop + "px";
                break;
            case "flickr":
                fCurPos = mTop + "px";
                break;
            case "twitter":
                tCurPos = mTop + "px";
                break;
            case "blog":
                bCurPos = mTop + "px";
                break;
        }
    });

}
