function RenderItemTemplate($f, item) {

    if ($f == null) {
        return;
    }
    
    var Id = replaceAll($f.html(), "${Id}", item.Id);
    var FirefoxId = replaceAll(Id, "$%7BId%7D", item.Id);

    var Title = replaceAll(FirefoxId, "${Title}", item.Title);
    var FirefoxTitle = replaceAll(Title, "$%7BTitle%7D", item.Title);

    var Description = replaceAll(FirefoxTitle, "${Description}", item.Description);
    var FirefoxDescription = replaceAll(Description, "$%7BDescription%7D", item.Description);

    var PublishDate = replaceAll(FirefoxDescription, "${PublishDate}", item.Date);
    var FirefoxPublishDate = replaceAll(PublishDate, "$%7BPublishDate%7D", item.Date);

    var PrettyDate = replaceAll(FirefoxPublishDate, "${PrettyDate}", item.PrettyDate);
    var FirefoxPrettyDate = replaceAll(PrettyDate, "$%7BPrettyDate%7D}", item.PrettyDate);

    var ItemContent = replaceAll(FirefoxPrettyDate, "${ItemContentPreview}", item.ItemContentPreview);
    var FirefoxItemContent = replaceAll(ItemContent, "$%7BItemContentPreview%7D", item.ItemContentPreview);

    var SourceLink = replaceAll(FirefoxItemContent, "${SourceLink}", item.SourceLink);
    var FirefoxSourceLink = replaceAll(SourceLink, "$%7BSourceLink%7D", item.SourceLink);

    var Data = replaceAll(FirefoxSourceLink, "${Data}", item.Data);
    var FirefoxData = replaceAll(Data, "$%7BData%7D", item.Data);

    var SourceId = replaceAll(FirefoxData, "${SourceId}", item.SourceId);
    var FirefoxSourceId = replaceAll(SourceId, "$%7BSourceId%7D", item.SourceId);

    var CommentCount = replaceAll(FirefoxSourceId, "${CommentCount}", item.CommentCount);
    var FirefoxCommentCount = replaceAll(CommentCount, "$%7BCommentCount%7D", item.CommentCount);

    var SourceTypeName = replaceAll(FirefoxCommentCount, "${SourceTypeName}", item.SourceTypeName);
    var FirefoxSourceTypeName = replaceAll(SourceTypeName, "$%7BSourceTypeName%7D", item.SourceTypeName);

    var SourceTitle = replaceAll(FirefoxSourceTypeName, "${SourceTitle}", item.SourceTitle);
    var FirefoxSourceTitle = replaceAll(SourceTitle, "$%7BSourceTitle%7D", item.SourceTitle);

    return FirefoxSourceTitle;
}

function replaceAll(OldString, FindString, ReplaceString) {

    var SearchIndex = 0;

    var NewString = "";
    
    while (OldString.indexOf(FindString, SearchIndex) != -1) {
        NewString += OldString.substring(SearchIndex, OldString.indexOf(FindString, SearchIndex));
        NewString += ReplaceString;
        SearchIndex = (OldString.indexOf(FindString, SearchIndex) + FindString.length);
    }
    NewString += OldString.substring(SearchIndex, OldString.length);
    return NewString;
}

encodeHTML = function(original) {
    return EscapeHTML(original).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
};

encodeHTMLWhiteList = function(original) {
    return original.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace('\n','<br/>');
};

decodeHTML = function(original) {
    return original.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
};

RenderButtonRollovers = function() {

    $(".ro").mouseover(
        function() {
            if ($(this).attr("src").indexOf("_active") == -1) {
                var newSrc = $(this).attr("src").replace("_up.png", "_active.png");
                $(this).attr("src", newSrc);
            }
            
        }
    )

        $(".ro").mouseout(
        function() {
            if ($(this).attr("src").indexOf("_active") != -1) {
                var newSrc = $(this).attr("src").replace("_active.png", "_up.png");
                $(this).attr("src", newSrc);
            }

        }
    )


    }

EscapeHTML = function(original) {
    var eHtml = escape(original);
    eHtml = eHtml.replace(/\//g, "%2F");
    eHtml = eHtml.replace(/\?/g, "%3F");
    eHtml = eHtml.replace(/=/g, "%3D");
    eHtml = eHtml.replace(/&/g, "%26");
    eHtml = eHtml.replace(/@/g, "%40");
    return eHtml;
}

AjaxFailure = function(XMLHttpRequest, textStatus, errorThrown) {

    if (textStatus == "timeout") {
        alert("Sorry, there was a delay in accessing the site database and the request has timed out. The site may be busy or having problems. If this problem persists, please contact the site administrator.");
    }
    else {
        alert("Sorry, there was an error and the request could not be completed. The site may be busy or having problems. If this problem persists, please contact the site administrator.");
    }
};
/*
* jQuery pager plugin
* Version 1.0 (12/22/2008)
* @requires jQuery v1.2.6 or later
*
* Example at: http://jonpauldavies.github.com/PagerDemo.html
*
* Copyright (c) 2008-2009 Jon Paul Davies
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* 
* Read the related blog post and contact the author at http://www.j-dee.com 
*
* This version is far from perfect and doesn't manage it's own state, therefore contributions are more than welcome!
*
* Usage: .pager({ pagenumber: 1, pagecount: 15, buttonClickCallback: PagerClickTest });
*
* Where pagenumber is the visible page number
*       pagecount is the total number of pages to display
*       buttonClickCallback is the method to fire when a pager button is clicked.
*
* buttonClickCallback signiture is PagerClickTest = function(pageclickednumber) 
* Where pageclickednumber is the number of the page clicked in the control.
*
*/
(function($) {

    $.fn.pager = function(options) {

        var opts = $.extend({}, $.fn.pager.defaults, options);

        return this.each(function() {

        // empty out the destination element and then render out the pager with the supplied options
            $(this).empty().append(renderpager(parseInt(options.pagenumber), parseInt(options.pagecount), options.buttonClickCallback));
            
            // specify correct cursor activity
            $('.pages li').mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; });
        });
    };

    // render and return the pager with the supplied options
    function renderpager(pagenumber, pagecount, buttonClickCallback) {

        // setup $pager to hold render
        var $pager = $('<ul class="pages"></ul>');

        // add in the previous and next buttons
        $pager.append(renderButton('first', pagenumber, pagecount, buttonClickCallback)).append(renderButton('prev', pagenumber, pagecount, buttonClickCallback));

        // pager currently only handles 10 viewable pages ( could be easily parameterized, maybe in next version ) so handle edge cases
        var startPoint = 1;
        var endPoint = 9;

        if (pagenumber > 4) {
            startPoint = pagenumber - 4;
            endPoint = pagenumber + 4;
        }

        if (endPoint > pagecount) {
            startPoint = pagecount - 8;
            endPoint = pagecount;
        }

        if (startPoint < 1) {
            startPoint = 1;
        }

        // loop thru visible pages and render buttons
        for (var page = startPoint; page <= endPoint; page++) {

            var currentButton = $('<li class="page-number">' + (page) + '</li>');

            page == pagenumber ? currentButton.addClass('pgCurrent') : currentButton.click(function() { buttonClickCallback(this.firstChild.data); });
            currentButton.appendTo($pager);
        }

        // render in the next and last buttons before returning the whole rendered control back.
        $pager.append(renderButton('next', pagenumber, pagecount, buttonClickCallback)).append(renderButton('last', pagenumber, pagecount, buttonClickCallback));

        return $pager;
    }

    // renders and returns a 'specialized' button, ie 'next', 'previous' etc. rather than a page number button
    function renderButton(buttonLabel, pagenumber, pagecount, buttonClickCallback) {

        var $Button = $('<li class="pgNext">' + buttonLabel + '</li>');

        var destPage = 1;

        // work out destination page for required button type
        switch (buttonLabel) {
            case "first":
                destPage = 1;
                break;
            case "prev":
                destPage = pagenumber - 1;
                break;
            case "next":
                destPage = pagenumber + 1;
                break;
            case "last":
                destPage = pagecount;
                break;
        }

        // disable and 'grey' out buttons if not needed.
        if (buttonLabel == "first" || buttonLabel == "prev") {
            pagenumber <= 1 ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); });
        }
        else {
            pagenumber >= pagecount ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); });
        }

        return $Button;
    }

    // pager defaults. hardly worth bothering with in this case but used as placeholder for expansion in the next version
    $.fn.pager.defaults = {
        pagenumber: 1,
        pagecount: 1
    };

})(jQuery);





function AjaxManager(parameterObject, serviceMethodName, successCallback, errorCallBack) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        timeout:25000,
        url: serviceMethodName,
        data: parameterObject,
        success: function(msg) { successCallback(msg) },
        error: function(XMLHttpRequest, textStatus, errorThrown) { errorCallBack(XMLHttpRequest, textStatus, errorThrown) }
    });
}
/// <reference path="jquery.intellisense.js"/>
/// <reference path="AjaxManager.js"/>

var PageSize;
var PageCount;
var PageNumber = 1;
var ItemFilterType = "None";
var ItemFilterArgument = "None";
var TagPage = 1;
var init = true;

$(document).ready(function() { $("body").hide(); LoadTemplate(); });

LoadTemplate = function() {

    $("#TemplateDump").load("Themes/" + ThemeName + "/" + ThemeName + ".template.html", function() { TemplateLoaded(); }).hide();
};

TemplateLoaded = function() {

    $('#Stylesheet').attr('href', "Themes/" + ThemeName + "/" + ThemeName + ".template.css");
    $("#TemplateDump").find("#MasterTemplate").appendTo("#TemplateHolder");
    PageSize = $("#PageSize").text();
    LoadAndRenderTags();
    LoadAndRenderChannels();
    LoadAndRenderFeatures();
    RenderItemTypes();
    $("#alertbox").mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; }).hide().click(function() { ChannelResetClick(); });
    InitializeSearch();

    LoadAndRenderFeedItemPackage();
    $.browser.mozilla ? $("body").keypress(checkForEnter) : $("body").keydown(checkForEnter);
};

PagerClick = function(pageclickednumber) {
    PageNumber = pageclickednumber;
    LoadAndRenderFeedItemPackage();
}

LoadAndRenderFeedItemPackage = function() {

        var parameterObject = '{"PageSize":"' + PageSize + '", "PageNumber":"' + PageNumber + '", "ItemFilterType":"' + ItemFilterType + '", "ItemFilterArgument":"' + ItemFilterArgument + '"}';

        var method;

        init ? method = "UIService.asmx/GetInitItemsPackage" : method = "UIService.asmx/GetItemsPackage";

        AjaxManager(parameterObject, method, ProcessFeedItemPackage, AjaxFailure);
};

ProcessFeedItemPackage = function(data) {

    $("#TemplateItemsHolder").empty().hide();
    $('html, body').animate({ scrollTop: 0 }, 'slow');
    
    var feeditempackage = eval('(' + data.d + ')');

    if (init) {
        if (feeditempackage.Settings.Title.length == 0) {
            $("#title").hide();
            document.title = "AmpliFeeder";
        }
        else {
            $("#title").html('<a href="default.aspx">' + feeditempackage.Settings.Title + '</a>');
            document.title = feeditempackage.Settings.Title;
        }

        if (feeditempackage.Settings.Tagline.length == 0) {
            $("#tagline").hide();
        }
        else {
            $("#tagline").html(feeditempackage.Settings.Tagline);
        }

        if (feeditempackage.Settings.About.length == 0) {
            $("#about").hide();
        }
        else {
            $("#about").html(feeditempackage.Settings.About);
            var meta = $('meta')[0];
            if (meta) {
                meta.name = 'description';
                meta.content = feeditempackage.Settings.About;
            }
        }

        if (feeditempackage.Settings.CustomCSS.length > 0) {
            $("head").append('<style>' + feeditempackage.Settings.CustomCSS + '</style>');
        }

        init = false;
    }

    PageCount = feeditempackage.PageCount;

    $.each(feeditempackage.FeedItems, function(i, item) { ProcessFeedItem(item); });

    $("#TemplateItemsHolder").fadeIn(300);

    $("#pager").pager({ pagenumber: PageNumber, pagecount: PageCount, buttonClickCallback: PagerClick });

    if ($("body").is(":hidden"))
    {
        $("body").fadeIn(300);
    }

    if (typeof MasterPageRendered == 'function') { MasterPageRendered(); }
};

ProcessFeedItem = function(item) {

    var $f = $("#TemplateDump").find("." + item.SourceTypeName).clone();
    if ($f.length == 0) {
        $("#TemplateItemsHolder").append("<br/>Cannot find " + item.SourceTypeName + " item template. You may need to create one or get an updated version of this theme<br/>");  
    }
    else {
        $("#TemplateItemsHolder").append(RenderItemTemplate($f, item));
    }
};

LoadAndRenderFeatures = function() {

    $(".Feature").each(function(i,item){ LoadFeature(item)})

}

LoadFeature = function(destination) {
    var count = $(destination).find(".itemcount").text();
    var type = $(destination).find(".itemtype").text();

    var parameterObject = '{"itemtype":"' + type + '", "numberToReturn":"' + count + '"}';

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        timeout: 25000,
        url: "UIService.asmx/GetFeature",
        data: parameterObject,
        success: function(msg) { FeatureLoaded(destination, msg) },
        error: function(XMLHttpRequest, textStatus, errorThrown) { AjaxFailure(XMLHttpRequest, textStatus, errorThrown) }
    });
    
}

FeatureLoaded = function(destination,data) {

    var items = eval('(' + data.d + ')');

    if (items.count == 0) {
        $(destination).hide();
        return;
    }

    var type = $(destination).find(".itemtype").text();
    var $f = $("#TemplateDump").find("." + type).clone();
    var destparent = $(destination).parent();
    destparent.empty();

    $.each(items, function(i, item) { RenderFeature(destparent, item, type, $f); });
}

RenderFeature = function(destparent, item, type, $f) {

    if ($f.length == 0) {
        $(destparent).append("<br/>Cannot find " + type + " feature template. You may need to create one or get an updated version of this theme<br/>");
    }
    else {
        $(destparent).append(RenderItemTemplate($f, item));
    }

}

LoadAndRenderTags = function() {

    $("#TagList").mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; });

    var parameterObject = '{"TagPage":"' + TagPage + '"}';
    AjaxManager(parameterObject, "UIService.asmx/GetTags", RenderTags, AjaxFailure);
};

RenderTags = function(data) {

    var items = eval('(' + data.d + ')');

    if (items.count == 0) {
        $("#tagtitle").hide();
        return;
    }

    $("#TagList").empty();
    $.each(items, function(i, item) { RenderTag(item); });

    $("<div id='tagpager' >more...</div>").click(function() { TagPage = TagPage + 1; LoadAndRenderTags(); }).appendTo($("#TagList"));

};

RenderTag = function(item) {

    $("<span class='tag' id='" + item.Id + "'>'" + item.Name + "'</span>").click(function() { TagClick(this.id, item.Name); }).append(" ").appendTo($("#TagList"));
};

TagClick = function(id,name) {

$("#alertbox").html("Currently just showing the items that match the tag '<strong>" + name + "</strong>'. Click here to show all items.").show();
    ItemFilterType = "Tag";
    ItemFilterArgument = id;
    PageNumber = 1;
    LoadAndRenderFeedItemPackage();
};

ChannelResetClick = function() {

    ItemFilterType = "None";
    ItemFilterArgument = "None";
    LoadAndRenderFeedItemPackage();
    $("#alertbox").hide();
};

InitializeSearch = function() {

    $SearchButton = $('<span class="btn">search</span>').click(function() { DoSearch(); }).mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; });
    $("#Search").append("<input type='text' id='txtsearch' />").append($SearchButton);
};

DoSearch = function() {

    ItemFilterType = "Search";
    ItemFilterArgument = encodeHTML($("#txtsearch").val());
    if (ItemFilterArgument !== "") {
        $("#txtsearch").val("");
        $("#alertbox").html("Currently just showing the items that match your search for '<strong>" + ItemFilterArgument + "</strong>'. Click here to show all items.").show();
        PageNumber = 1;
        LoadAndRenderFeedItemPackage();
    }
};

LoadAndRenderChannels = function() {

    var parameterObject = '{}'; 
    AjaxManager(parameterObject, "UIService.asmx/GetActiveSources", RenderChannels, AjaxFailure);
    
};

RenderChannels = function(data) {

    var items = eval('(' + data.d + ')');
    $.each(items, function(i, item) { RenderChannel(item); });

    if (items.length > 1 && $("#channels").length > 0) {
        RenderAllChannel();
    }
};

RenderChannel = function(item) {

    var $f = $("#TemplateDump").find("#ChannelTemplate").html();

    if ($f == null) {
        return;
    }
    var Idx = replaceAll($f, "${Id}", item.Id);
    var FirefoxIdx = replaceAll(Idx, "$%7BId%7D", item.Id);

    var Titlex = replaceAll(FirefoxIdx, "${Title}", item.Title);
    var FirefoxTitlex = replaceAll(Titlex, "$%7BTitle%7D", item.Title);

    var FeedUrix = replaceAll(FirefoxTitlex, "${FeedUri}", item.FeedUri);
    var FirefoxFeedUrix = replaceAll(FeedUrix, "$%7BFeedUri%7D", item.FeedUri);

    var SourceTypeNamex = replaceAll(FirefoxFeedUrix, "${SourceTypeName}", item.SourceTypeName);
    var FirefoxSourceTypeNamex = replaceAll(SourceTypeNamex, "$%7BSourceTypeName%7D", item.SourceTypeName);

    $(FirefoxSourceTypeNamex).mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; }).click(function() { ChannelClick(this.id, item.Title); }).appendTo($('#channels'));
};

RenderAllChannel = function() {

    var $f = $("#TemplateDump").find("#ChannelTemplate").html();

    if ($f == null) {
        return;
    }
    var Idx = replaceAll($f, "${Id}", "All");
    var FirefoxIdx = replaceAll(Idx, "$%7BId%7D", "All");

    var Titlex = replaceAll(FirefoxIdx, "${Title}", "");
    var FirefoxTitlex = replaceAll(Titlex, "$%7BTitle%7D", "");

    var FeedUrix = replaceAll(FirefoxTitlex, "${FeedUri}", "#");
    var FirefoxFeedUrix = replaceAll(FeedUrix, "$%7BFeedUri%7D", "#");

    var SourceTypeNamex = replaceAll(FirefoxFeedUrix, "${SourceTypeName}", "All");
    var FirefoxSourceTypeNamex = replaceAll(SourceTypeNamex, "$%7BSourceTypeName%7D", "All");

    $(FirefoxSourceTypeNamex).mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; }).click(function() { ChannelResetClick(); }).appendTo($('#channels'));
};

ChannelClick = function(id,name) {

    ItemFilterType = "Source";
    ItemFilterArgument = id;
    $("#alertbox").html("Currently just showing the items that come from <strong>" + name + "</strong>. Click here to show all items.").show();
    PageNumber = 1;
    LoadAndRenderFeedItemPackage();
};

checkForEnter = function(event) {

    if (event.keyCode == 13) {
        event.preventDefault();
        DoSearch();
    }
};

RenderItemTypes = function() {

    if ($("#pages").length > 0)
    {
        RenderHomeItemType();
        RenderItemType("Bookmark");
        RenderItemType("Image");
        RenderItemType("Note");
        RenderItemType("Video");
        RenderItemType("Post");
    }
}

RenderItemType = function(sourcetypename) {
    var $f = $("#TemplateDump").find("#ItemTypeTemplate").html();

    if ($f == null) {
        return;
    }
    var Idx = replaceAll($f, "${Id}", sourcetypename);
    var FirefoxIdx = replaceAll(Idx, "$%7BId%7D", sourcetypename);

    var Titlex = replaceAll(FirefoxIdx, "${Title}", sourcetypename);
    var FirefoxTitlex = replaceAll(Titlex, "$%7BTitle%7D", sourcetypename);

    var SourceTypeNamex = replaceAll(FirefoxTitlex, "${SourceTypeName}", sourcetypename);
    var FirefoxSourceTypeNamex = replaceAll(SourceTypeNamex, "$%7BSourceTypeName%7D", sourcetypename);

    $(FirefoxSourceTypeNamex).mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; }).click(function() { ItemTypeClick(sourcetypename); }).appendTo($('#pages'));
}

RenderHomeItemType = function() {
    var $f = $("#TemplateDump").find("#ItemTypeTemplate").html();

    if ($f == null) {
        return;
    }
    var Idx = replaceAll($f, "${Id}", "Home");
    var FirefoxIdx = replaceAll(Idx, "$%7BId%7D", "Home");

    var Titlex = replaceAll(FirefoxIdx, "${Title}", "item");
    var FirefoxTitlex = replaceAll(Titlex, "$%7BTitle%7D", "item");

    var SourceTypeNamex = replaceAll(FirefoxTitlex, "${SourceTypeName}", "Home");
    var FirefoxSourceTypeNamex = replaceAll(SourceTypeNamex, "$%7BSourceTypeName%7D", "Home");

    $(FirefoxSourceTypeNamex).mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; }).click(function() { ChannelResetClick(); }).appendTo($('#pages'));
}

ItemTypeClick = function(sourcetypename) {
    ItemFilterType = "ItemType";
    ItemFilterArgument = sourcetypename;
    $("#alertbox").html("Currently viewing the <strong>" + sourcetypename + "</strong> page. Click here to show all items.").show();
    PageNumber = 1;
    LoadAndRenderFeedItemPackage();
}