$xmlTree = null;
$uniqueMediaLeaves = null;
$wkiccCarouselItems = null;
var sermonXmlGragment = '';


$(document).ready(function() {
    
    LoadSermonByType();
    ConfigurePlayer();
    ConfigureDynamicMediaTree();
});

function ConfigurePlayer() 
{
    ConfigureJQueryCorner();
    ConfigureJQueryNewsTicker();
    ConfigureDynamicCss();
}

function wkiccCarousel_ItemLoadCallbackFunction(carousel, state) {

    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });

    $wkiccCarouselItems = GetWkiccCarouselItems();
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }

        if (i > $wkiccCarouselItems.length) {
            break;
        }
        carousel.add(i, GetCarouselItemHTML($wkiccCarouselItems[i - 1]));
    }
}

function GetCarouselItemHTML($mediaValue) {

    return "<div id='mediaCarouselItem' style='padding-top:10px;'>" +
                "<div class='mediaId hidden'>" + $mediaValue["MediaIdKey"] + "</div>" +
                "<div class='mediaShortDescription' style='color:#FFFFFF'>" + $mediaValue["ShortDescriptionKey"] + " </div>" +
                "<div style='margin-top:5px; color: Green'>" + $mediaValue["DurationKey"] + "</div>" +
                "<div style='color: Green'>" + $mediaValue["DateReleasedKey"] + "</div>" +                
            "</div>";
}

function GetCarouselItems() {

    var $mediaLeaves = [];
    $mediaTree = GetMediaXmlTree();
    
    $($mediaTree).find("Sermon").each(function()
    {
        $mediaLeaf = new Object();
        $mediaLeaf["MediaIdKey"] = $(this).attr("Id");
        $mediaLeaf["TitleKey"] = $(this).attr("Title");
        $mediaLeaf["ShortDescriptionKey"] =  GetTruncatedString($(this).attr("ShortDescription"), 50);
        $mediaLeaf["DateReleasedKey"] = $(this).attr("ReleaseDate");
        $mediaLeaf["DurationKey"] = $(this).attr("Duration");
        
        $mediaLeaves[$mediaLeaves.length] = $mediaLeaf;
    });
    return $mediaLeaves;
}

function GetMediaXmlTree() {
    if ($xmlTree == null) {
    
        $xmlFragment = $("div#allSermons").text();        
        $xmlTree = loadXMLDoc($xmlFragment, false);
    }    
    return $xmlTree;
}

function GetWkiccCarouselItems() {

    if ($wkiccCarouselItems == null) {
        $wkiccCarouselItems = GetCarouselItems();
    }
    return $wkiccCarouselItems;
}

function ConfigureDynamicCss() {

    //Configure more info holder
    $("#moreInfo").live("click", function() {
        $(this).children("#moreInfoHolder").each(function() {
            ToggleDisplay($(this));
        });
    })
    .live("mouseover", function() {
        $(this).css({ cursor: "hand", cursor: "pointer" });
    })
    .live("mouseout", function() {
        $(this).css({ cursor: "default" });
    });


    //Configure .mediaShortDescription and loadMediaClass to play media onClick
    $(".mediaShortDescription, .loadMediaClass").live("click", function(e) {
        e.preventDefault();
        $mediaId = $(this).prev("div").text();
        loadMedia($mediaId);
    })
    .live("mouseover", function() {
        $(this).css({ cursor: "hand", cursor: "pointer" });
    })
    .live("mouseout", function() {
        $(this).css({ cursor: "default" });
    });

    $("img#WatchOurTvProgramme").live("mouseover", function() {
        $(this).css({ cursor: "hand", cursor: "pointer" });
    })
    .live("mouseout", function() {
        $(this).css({ cursor: "default" });
    });

    $("div.mediaInfo").children(":last-child").css({ fontWeight: "900", textAlign: "center" });

    $(".clearSearchResult").live("click", function() {

        $searchResultHeader = $(this).closest("div#searchResultHeader");
        ToggleDisplay($searchResultHeader);
    })
    .live("mouseover", function() {
        $(this).css({ cursor: "hand", cursor: "pointer" });
    })
    .live("mouseout", function() {
        $(this).css({ cursor: "default" });
    });

    $(".branch").css({ display: "none" });

    //Display media info on mouse over on tree view.
    $("a.loadMediaClass").live("mouseover", function() {
        $mouseOverMediaInfo = $("div.mediaInfo").clone();
    });

    //Sermon search image click
    $("img#SermonSearchImage").live("click", function() {
        SearchWkiccMediaGallery();
    });

    AttachOnClickEventToSermonTitle();
}

function AttachOnClickEventToSermonTitle() {

    $(".searchSermonTitle").live("click", function() {
        loadSearchedMedia($(this).text(), $(this).siblings('.sermonOtherInfo'));
    })
    .live("mouseover", function() {
        $(this).css({ cursor: "hand", cursor: "pointer" });
    })
    .live("mouseout", function() {
        $(this).css({ cursor: "default" });
    });

    $(".showDetails").live("click", function(e) {
        $(this).siblings('.searchMediaHolder').children('.sermonOtherInfo').slideToggle("slow");
        if ($(this).siblings('.searchMediaHolder').children('.sermonOtherInfo').hasClass('hidden')) {
            $(this).siblings('.searchMediaHolder').children('.sermonOtherInfo').removeClass("hidden");
            $(this).attr("src", "images/spindown-open.gif");
        }
        else {
            $(this).siblings('.searchMediaHolder').children('.sermonOtherInfo').addClass("hidden");
            $(this).attr("src", "images/spindown-closed.gif");
        }
    })
    .live("mouseover", function() {
        $(this).css({ cursor: "hand", cursor: "pointer" });
    })
    .live("mouseout", function() {
        $(this).css({ cursor: "default" });
    });
}

function ConfigureJCarousel() {

    jQuery('#wkiccCarousel').jcarousel({
        size: GetWkiccCarouselItems().length,
        auto: 2,
        wrap: 'both',
        visible: 2,
        itemLoadCallback: { onBeforeAnimation: wkiccCarousel_ItemLoadCallbackFunction }
    });
}

function ConfigureJQueryCorner() {
    
    $("#wkiccMediaGallery").corner("round 10px").parent().css('padding', '10px').corner("round 10px");
}

function ToggleDisplay($element) {
    if ($element.is(':visible')) {
        $element.hide(400);
    }
    else {
        $element.show(400);
    }
}

function ConfigureJQueryNewsTicker() {

    var newnews = $("<ul>").attr("class", "newsticker");
    newnews.append("<li>Winners Kingdom International Christian Center</li>");
    newnews.append("<li> ... raising winners, fulfilling destinies.</li>");
    newnews.append("<li>The Winners Kingdom Media Center</li>");
    newnews.append("<li>... where the winners assemble</li>");
    newnews.append("<li>... where Jesus turns losers to winners</li>");    
    newnews.append("<li>... where you can watch and listen to life changing sermons</li>");
    newnews.appendTo("div#wkiccMediaHeading").newsTicker();

    $("#wkiccMediaHeadingNewsTicker").newsticker();
}

function ConfigureDynamicMediaTree()
{
    $("div.trigger, div.branch, div.leaf, img.leafholderImg").live("click", function(e) {
    
        if ($(this).hasClass("leaf") || $(this).hasClass("leafholder") || $(this).hasClass("leafholderImg"))
        {
            return;
        }
        
        //Toggle the element display
        var childrenHolderDivId = $(this).children("div:first").attr("id");
        var el = document.getElementById(childrenHolderDivId);
        
        if ("none" != el.style.display)
        {
            el.style.display = "none";
        }
        else
        {
            el.style.display = "";
        }
        
        //Swap image
        var openImg = new Image();
        var closedImg = new Image();
        openImg.src = "images/folderopen.gif";
        closedImg.src = "images/folderclosed.gif";
        var imageId = "I" + $(this).attr("id");
        objImg = document.getElementById(imageId);
        if (null != objImg)
        {
            if (objImg.src.indexOf('images/folderclosed.gif') > -1)
            {
                objImg.src = openImg.src;
            }
            else
            {
                objImg.src = closedImg.src;
            }
        }
        e.preventDefault();
    });
}
