function Div(inner, cssClass) { return "<div class=\"" + cssClass + "\">" + inner + " </div>"; }
function Span(inner, cssClass) { return "<span class=\"" + cssClass + "\">" + inner + " </span>"; }
function Ahref(uri, text){ return "<a href=\"" + uri + "\">" +text + "</a>";}

/* Begin db fns */
function BuildDbUrl(db, cmd, by, param1) {
    url = "/data/?db=" + db + "&cmd=" + cmd +"&by=" + by + "&p1=" + param1 + "&out.xml";
    return url;
}
function LoadDbAndIterateResults(db, cmd, by, param1, formater, init) {
    LoadDbAndIterateResultsTo(db, cmd, by, param1, db, formater, init)
}    
function LoadDbAndIterateResultsTo(db, cmd, by, param1, appendTo, formater, init) {
    url = BuildDbUrl(db, cmd, by, param1);
    $.get(url, {}, function(xml) {
        c = $("#" + appendTo);
        c.html("<div/>");
        $('r', xml).each(function(i) {
            c.append(formater($(this)));
        });
        if (init != null)
            init(by);
    });
}
/* End db fns */

/* Begin diary */
function FormatDiaryEntry(xml) {
    d = xml.find("DateText").text();
    t = xml.find("Time").text();
    e = xml.find("Event").text();
    ti= xml.find("Title").text() + " "; 
    st= xml.find("SeriesTitle").text() + " ";
    v = xml.find("Verse").text();

    return Div (
            Div(d, "date") + Div(t, "time") + Div(e, "type") + Div (ti + st+ v, "content"),
            "entry");
}

function Load2WeekDiaryAndDisplay() {
    LoadDbAndIterateResults('diary', 'd', '', 21, FormatDiaryEntry);
}

/* End diary */

/* Begin recording */
function GetMp3FileNameFromXml(xml){
    u = xml.find("Mp3Url").text();  
    return u;
}
function MakeUrlForMp3(mp3) {
    return "/download/mp3/" + mp3;
}
function FormatRecordingEntryBase(xml) {
    d = xml.find("DateText").text();
    s = xml.find("Speaker").text();
    t = xml.find("SeriesTitle").text() + " " + xml.find("Title").text();
    b = xml.find("Passage1").text();
    return Div(d, "date") +
             Div(s, "speaker") +
             Div(t, "title") +
             Div(b, "bible");
}             
function FormatRecordingEntry(xml) {
    return Div(
        FormatRecordingEntryBase(xml) ,
             "entry");

}
function FormatRecordingEntryWithLinks(xml) {
    u = GetMp3FileNameFromXml(xml);
    return Div(
        FormatRecordingEntryBase(xml) +
             Div(
                "<span class=\"play\" value=\"" + u + "\">Play</span>" +
                Span(Ahref(MakeUrlForMp3(u), "download"), "download"),
                "click"),
             "entry");
}

function FormatRecordingAggregator(xml) {
    agg = xml.find("Agg").text();
    o = "";
    if (agg != "")
        o = "<span class=\"agg\" value = \"" + agg + "\">" + Ahref("#",agg) + "</span>,&nbsp;";

    return o;
}

function LoadAggregate(by) {
    byId = "agg" + by;
    LoadDbAndIterateResultsTo('recording', 'agg', by, 0, byId, FormatRecordingAggregator, function(by2) {
        $("#agg" + by2 + " .agg")
            .click(function() {
                m = $(this).attr("value");
                LoadRecordingsAndDisplay('list', by, m);
            });
    });
}

function SetRecordingInPlayerAndPlay(m) {
    uri = MakeUrlForMp3(m);
    url = BuildDbUrl('recording', 'mp3Url', '', m);
    player = document.getElementById("mp3");
    cp = $('#nowPlaying');
    cp.fadeOut(20);

    // set now playing text
    $.get(url, {}, function(xml) {
        $('r', xml).each(function(i) {
            cp.html(FormatRecordingEntry($(this)));
        });
    });

    // set player
    player.sendEvent('STOP');
    player.sendEvent('LOAD', uri);
    player.sendEvent('PLAY', true);
    cp.fadeIn("slow");
}
function LoadRecordingsAndDisplay(cmd, by, param1){
    LoadDbAndIterateResults('recording', cmd, by, param1, FormatRecordingEntryWithLinks, function() {
        $(".recording .play")
            .click(function() {
                m = $(this).attr("value");
                SetRecordingInPlayerAndPlay(m);
            });
    });
}    
function LoadLastest5mp3sAndDisplay(){
    LoadRecordingsAndDisplay ('mp3', '', 5);
}
function LoadLastestMp3AndCreatePlayer(width) {
    LoadDbAndIterateResults('recording', 'mp3', '', 1, function(xml) {
        u = MakeUrlForMp3(GetMp3FileNameFromXml(xml));
        createPlayer("mp3", width, "20", "0", u);
        $('#nowPlaying').append(FormatRecordingEntry(xml));
    });
}
/* End recording */

/* media player begin */
function deletePlayer(theWrapper, thePlaceholder, thePlayerId) {
    swfobject.removeSWF(thePlayerId);
    var tmp = document.getElementById(theWrapper);
    if (tmp) { tmp.innerHTML = "<div id=" + thePlaceholder + "></div>"; }
}



autoPlay = null;

function createPlayer(id, width, height, playListSize, theFile) {
    theWrapper = id+"w";
    thePlaceholder= id+"p";
    thePlayerId = id;
    
    deletePlayer(theWrapper, thePlaceholder, thePlayerId);

    var flashvars = {
        file: theFile,
        autostart: false,
        playlist: "bottom",
        playlistsize: playListSize
    }

    var params = {
        allowfullscreen: "true",
        allowscriptaccess: "always",
        wmode: "opaque",
        mute:"true",
        callback: onPlayerLoaded
    }

    var attributes = {
        id: thePlayerId,
        name: thePlayerId
    }

    swfobject.embedSWF("/src/jwplayer.4.5/player.swf", thePlaceholder, width, height, "9.0.115", false, flashvars, params, attributes);

}

function onPlayerLoaded(e) {         
    if (autoPlay != null)
        SetRecordingInPlayerAndPlay(autoPlay);    
}
/* media player begin */


/* artical begin */


function FormatArticleEntry(xml) {
    t = xml.find("TITLE").text();
    ht = xml.find("HASTITLE").text();
    d = xml.find("DateText").text();
    h = xml.find("HTML").text();

    if (ht == "1")  
        d = "";
    
    $('#title').text(t);
    
    return Div(
            "<h3>" +t +"</h3><div>" +d + "</div>" + h,
            "");
}

function FormatArticleEntryAsListItem(xml) {
    t = xml.find("TITLE").text();
    ht = xml.find("HASTITLE").text();
    d = xml.find("DateText").text();

    if (ht == "1")  
        d = "";
    
    
    return Div(
            "<div>" +t +"</div><div>" +d + "</div>",
            "");
}


function LoadArticleAndDisplay(db, count) {
    id = "articles-" + db;
    LoadDbAndIterateResultsTo(db, 'last', '', count, id, FormatArticleEntry);
}

function LoadArticleByIdAndDisplay(db, artical_id) {
    id = "articles-" + db;
    LoadDbAndIterateResultsTo(db, 'id', '', artical_id, id, FormatArticleEntry);
}

function xxxLoadArticlesAndList(db, count) {
    id = "articles-" + db;
    LoadDbAndIterateResultsTo(db, 'last', '', count, id, FormatArticleEntryAsListItem);
}

function LoadLastestnNewsAndDisplay(n) {
    LoadArticleAndDisplay('cn', n);
}

function LoadLastest5NewsAndDisplay() {
    LoadLastestnNewsAndDisplay(5);
}

function LoadLastestPrayDiaryAndDisplay() {
    LoadArticleAndDisplay('pd', 1);
}

function FormatArticleList(xml) {
    t = xml.find("TITLE").text();
    d = xml.find("DateText").text();
    i = xml.find("ID").text();
    o = "";
        o = "<div class=\"list\" value = \"" + i + "\">" + Ahref("#", t +"&nbsp;<span class='i small'>"+ d+ "</span>") + "</div>&nbsp;";

    return o;
}

function LoadAritcalAndListAll(by) {
    byId = "list-" + by;
    LoadDbAndIterateResultsTo(by, 'list', '', 0, byId, FormatArticleList, function(by2) {
        $("#list-" + by + " .list")
            .click(function() {
                m = $(this).attr("value");
                LoadArticleByIdAndDisplay(by, m);
            });
    });
}    
/* artical end */

function SetUpToolTips() {
    // see http://craigsworks.com/projects/qtip/ for further help
    // By suppling no content attribute, the library uses each elements title attribute by default
    $('a[href][title]').qtip({
        content: {
            text: false // Use each elements title attribute
        },
        style: 'blue' // Give it some style
    });
}



$(document).ready(function () {
    SetUpToolTips();
});

