﻿//$(function() {
//    $("#feed_pager").setPager();
//});
//(function($) {
//    $.fn.setPager = function(options) {

//    var settings = $.extend({}, $.fn.setPage.defaults, options);
//        return $(this).each(function() {
//            var t = $(this);
//            t.html("dsjklfjlksfdj");
//        });
//    };

//    $.fn.setPage.defaults = {
//        totalResults: 0,
//        startIndex: 0,
//        itemsPerPage: 0,
//        onResultPage: null
//    };
//})(jQuery);


function setPager(totalResults, startIndex, itemsPerPage, onResultPage) 
{
    //limit total resultes
    totalResults = (totalResults > 1000) ? 1000 : totalResults;

    var html = ['Displaying <span id="page_lower">0</span> - <span id="page_upper">0</span> of <span id="page_total">0</span>&nbsp;'];
    html.push('&nbsp;&nbsp;<a class="page_prev" href="javascript:;">Prev</a> | <a class="page_next" href="javascript:;">Next</a>');

    //top pager
    var $feedTop = $('#feed_top')
    var $container = $('#feed_container')
    var $pager = $('#feed_pager')
    $pager.html(html.join(""));

    var upperIndex = parseInt(startIndex + itemsPerPage - 1);
    if (upperIndex > totalResults) totalResults = upperIndex;
    $('#page_lower', $pager).html(startIndex)//.format({ format: "#,###", locale: "US" });
    $('#page_upper', $pager).html(upperIndex)//.format({ format: "#,###", locale: "US" });
    $('#page_total', $pager).html(totalResults)//.format({ format: "#,###", locale: "US" });
    
    $pager.fadeIn('slow');
    $feedTop.fadeIn('slow');

    var pagerSet = 5; //3,5,9 // there may be a limit of 16 pages on youtube
    getPageIndex['itemsPerPage'] = itemsPerPage;
    getPageIndex['currentPage'] = 1;
    html = [''];
    
    if (totalResults > 0) {
        html.push('<a class="page_prev" href="javascript:;">Prev</a>&nbsp;&nbsp;');
        if (pagerSet == 0) {
            for (var i = 1; i < totalResults + 1; i++) {
                html.push(getPageIndex(i, i));
            }
        }
        else {
            var currentPage = (startIndex > 1) ? ((startIndex - 1) / itemsPerPage) : 1;
            var lowerSet = currentPage - pagerSet;
            var upperSet = currentPage + pagerSet;
            var pageCount = Math.ceil(totalResults / itemsPerPage);
            var pcLessPad = pageCount + 1 - pagerSet;

            if ((pageCount * itemsPerPage) >= totalResults) pageCount--
            getPageIndex['currentPage'] = currentPage;

            //print lower set
            for (var i = 1; i < pageCount + 1; i++) {
                html.push(getPageIndex(i, i));
                if (i == pagerSet) break;
            }

            //print ...
            if ((pagerSet - lowerSet) < -1) {
                html.push(getPageIndex('...', Math.ceil((lowerSet + pagerSet) / 2)))
            }

            //print middle set
            for (var i = lowerSet; i < upperSet - 1; i++) {
                if (i == pcLessPad) break;
                if (i > pagerSet) html.push(getPageIndex(i, i));
            }

            //print ...
            if ((upperSet - pcLessPad) < -1) {
                html.push(getPageIndex('...', Math.ceil((upperSet + pcLessPad) / 2)))
            }

            //print upper set
            for (var i = pcLessPad; i < pageCount + 1; i++) {
                if (i > pagerSet) html.push(getPageIndex(i, i));
            }
        }
        html.push('&nbsp;&nbsp;<a class="page_next" href="javascript:;">Next</a>');
    }

    //top pager
    var $pager = $('#feed_navigator')
    $pager.html(html.join(""));

    //next result
    //$('.page_next', $container).each(function() {
    $('.page_next').each(function() {
        if (upperIndex < totalResults) {
            $(this).click(function() {
                if (onResultPage) onResultPage(parseInt(upperIndex + 1));
            });
        }
        else {
            $(this).addClass('no_pager')
        }
    })

    //prev result
    $('.page_prev', $container).each(function() {
        if (startIndex > itemsPerPage) {
            $(this).click(function() {
                if (onResultPage) onResultPage(parseInt(startIndex - itemsPerPage));
            });
        }
        else {
            $(this).addClass('no_pager')
        }
    })

    //page index
    $('.page_indx', $container).each(function() {
        $(this).click(function() {
            if (onResultPage) onResultPage($(this).attr('page'));
        });
    })

    $pager.fadeIn('slow');
}

function getPageIndex(text, index) {
    if (getPageIndex['currentPage'].toString() == index.toString()) {
        return '<a class="page_curr"> ' + text + '</a>&nbsp;';
    }
    else {
        var targetPage = (parseInt(getPageIndex['itemsPerPage']) * index) + 1;
        return '<a href="javascript:;" class="page_indx" page="' + targetPage + '";">' + text + '</a>&nbsp;';
    }
}

function verifyContent() {
    var $feed_loader = $("#feed_loader");
    if ($feed_loader.is(":visible")) {
        var NOT_FOUND = '<div style="float: left; margin:right: 10px;"><img src="/app_ui/images/icon/source-left.gif" /></div>';
        NOT_FOUND += '<div style="float: left; margin: 10px;"><b>Sorry! Unable to retrieve content...</b><div class="bold red">Choose another Source.</div></div>';
        NOT_FOUND += '<div class="clear"></div>';

        if (ListItems['object'].OnError == null) {
            $feed_loader.html(NOT_FOUND).show();
        }
        else {
            $feed_loader.html('').hide();
            ListItems['object'].OnError();
        }
    }
}

function ListItems(SearchText, DataSource) 
{
    ListItems['object'] = this;
    window.setTimeout(function() { verifyContent() }, 10000);
    var LOADER_IMG = '<div style="text-align: center; margin: 20px;"><img src="http://wahchinga.com/app_ui/images/wait/loading.gif" style="border: 0px;" /></div>';
    
    //drop the content area on the page
    if (!document.getElementById("feed_container")) {
        document.write('<div id="feed_loader"></div>');
        document.write('<div id="feed_container">');
        document.write('<div id="feed_top">');
        document.write('<div id="feed_pager"></div>');
        document.write('<div id="feed_right"></div>');
        document.write('</div>');
        document.write('<div id="feed_content"></div>');
        document.write('<div id="feed_navigator"></div>');
        document.write('</div>');
    }
    
    //hide the feed
    $("#feed_loader").html(LOADER_IMG).show();
    $("#feed_top, #feed_navigator, #feed_container").hide();

    this.PageSize = 10;
    this.CurrentPage = 1;
    this.EnablePaging = true;
    this.CallbackMode = true;
    this.AppendToUrl = new String();
    this.SearchType = new String();
    this.SearchText = (typeof (SearchText) == "undefined") ? new String() : SearchText;
    this.DataSource = (typeof (DataSource) == "undefined") ? new String() : DataSource;
    this.OnComplete = function() { };
    this.OnError = null;
    this.URL = new String();

    this.GetResults = function(pageIndex) {
        if (pageIndex > 0) this.CurrentPage = pageIndex;
        var search_url = this.GetListUrl();

        if (this.SearchText == "")
            showMessage("Search keyword is not specified", true);
        else if (search_url.length == 0)
            showMessage("Search URL is not specified", true);
        else {
            if (this.CallbackMode) {
                search_url += "&callback=g_callback";
                $.getScript(search_url, function() { });
            }
            else {
                if (this.AppendToUrl != "") this.AppendToUrl += "&"
                search_url = BASE_URL + "/handlers/proxy.ashx?" + this.AppendToUrl + "url=" + encodeURIComponent(search_url);
                $.getFeed({ url: search_url, success: function(feed) { window.g_callback(feed, true); } });
            }
        }
    }

    this.PageResult = function(currentPageIndex) {
        $("#feed_container").slideUp(250, function() {
            list.GetResults(currentPageIndex);
        });
    }

    this.ProcessFeed = function(data) {
        var totalResults = 0;
        var startIndex = 0;
        var itemsPerPage = 0;
        var feed_items = null;

        switch (this.DataSource.toLowerCase()) {
            case "google":
                feed_items = $("#feed_xml_template").parseTemplate(data);
                break;
            case "yahoo":
                feed_items = $("#feed_xml_template").parseTemplate(data);
                break;
            case "bing":
                feed_items = $("#feed_xml_template").parseTemplate(data);
                break;
            case "ebay":
                feed_items = $("#feed_xml_template").parseTemplate(data);
                break;
        }

        //feed pager
        if (this.EnablePaging) {
            setPager(totalResults, startIndex, itemsPerPage, this.PageResult);
        }

        $("#feed_loader").hide();
        $("#feed_content").html(feed_items);
        $("#feed_container").slideDown(250);
        this.OnComplete();
    }

    this.GetListUrl = function() {
        var data_url = new String();
        switch (this.DataSource.toLowerCase()) {
            case "google":
                //data_url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=" + encodeURIComponent(this.SearchText)
                //http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=Kobe%20Bryant&key=ABQIAAAA0-7PHOTWgdEyf5cMfqMH3RSx34mEVKzqrqqD3Krip4K1CEN03hT31xaVJJV4OqIZH6WmdE3IGyYNVg"

                //specific settings for google
                this.EnablePaging = false;
                this.CallbackMode = false;
                data_url = "http://news.google.com/news?q=" + encodeURIComponent(this.SearchText) + "&output=rss&num=25";
                break;

            case "yahoo":
                //specific settings for google 
                this.EnablePaging = false;
                this.CallbackMode = false;
                data_url = "http://news.search.yahoo.com/news/rss?ei=UTF-8&fl=0&x=wrt&p=" + encodeURIComponent(this.SearchText);
                break;

            case "bing":
                //specific settings for google 
                this.EnablePaging = false;
                this.CallbackMode = false;
                data_url = "http://api.bing.com/rss.aspx?Source=News&Market=en-US&Version=2.0&Query=" + encodeURIComponent(this.SearchText);
                break;

            case "ebay":
                //http://shop.ebay.com/i.html?_nkw=clash+of+the+titans&_adv=1&_dmd=1&_fsct=&_in_kw=1&_ipg=200&_oexkw=&_okw=kelly+clarkson&_rss=1&_sop=12&_udhi=&_udlo=

                //specific settings for google
                this.EnablePaging = false;
                this.CallbackMode = false;
                data_url = "http://shop.ebay.com/i.html?_nkw=" + encodeURIComponent(this.SearchText) + "&_adv=1&_dmd=1&_fsct=&_in_kw=1&_ipg=200&_oexkw=&_okw=&_rss=1&_sop=12&_udhi=&_udlo=";
                break;

            case "amazon":

                //specific settings for google
                this.EnablePaging = false;
                this.CallbackMode = false;
                data_url = "http://www.amazon.com/rss/tag/" + this.SearchText.replace(",", " ") + "/new/ref=tag_rsh_hl_ersn_brp?length=100&tag=wah06-20";
                break;

            default:
                data_url = this.URL;
                break;
        }

        if (data_url != "")
            data_url += '&cb=' + parseInt(new Date().getTime().toString().substring(0, 10));

        return data_url;
    }
}
