/* =========================================================================

NAME: page-sort.js

AUTHOR: Istvan Siposs , Y-Times Publications, LLC
DATE  : 5/31/2007
REV   : 2/09/2009

COMMENT: Advanced Yahoo! Store pagination and sorting.

============================================================================ */

// CONFIGURATION VARIABLES //

var SHOWALL = true;         // set to False if VIEW ALL should not be displayed.
var PAGENEXT = "NEXT";
var PAGEPREV = "PREVIOUS";
var SORTCONTROL = "LINK" // set it to LINK or DROPDOWN
var SORTDOWN = "";
var SORTUP = "";
var DEFAULTSORT = "";
var sortFormat = "";

function PageObject(sortfields, src, prodId, image, prodName, price, salePrice, abstract) {
    this.sortfields = sortfields;
    this.src = src;
    this.prodId = prodId;
    this.image = image;
    this.prodName = prodName;
    this.price = price;
    this.salePrice = salePrice;
    this.abstract = abstract;
}

if (queryString("frm") == "false") {
    if (GetCookie("frm") == "list")
        sortFormat = "list";
    else
        sortFormat = "grid";
    SetCookie("frm", sortFormat);
}
else
    SetCookie("frm", queryString("frm"));
sortFormat = GetCookie("frm");

if (queryString('page') == 'false') {
    if (GetCookie("viewall") == 'yes')
        CurrentPage = 0;
    else
        CurrentPage = 1;
}
else
    CurrentPage = queryString('page') * 1;

if (CurrentPage != 0)
    DeleteCookie("viewall");

var pagesize = queryString('ps');
if (pagesize == 'false') {
    pagesize = GetCookie("ps");
    if (!pagesize) {
        pagesize = pagesizes[0];
    }
}
SetCookie('ps', pagesize);

if (CurrentPage == 0 && GetCookie('viewall') != 'yes') {
    SetCookie("viewall", "yes");
}

var sf = queryString('sf');
if (sf == 'false') {
    sf = GetCookie('sf');
    if (!sf || sf == 'false') {
        sf = DEFAULTSORT;
    }
}
SetCookie('sf', sf);

var sd = queryString('sd');
if (sd == 'false') {
    sd = GetCookie('sortd');
    if (!sd || sd == 'false')
        sd = 'a';
}
SetCookie('sortd', sd);

function PageSortFunction(a, b) {
    if (sf == 'false' || sf == '')
        return 0;
    if (typeof (a) == 'undefined' || typeof (b) == 'undefined')
        return 0;

    if (sd == 'false' || sd == '')
        sd = 'a';

    if (sd == 'a') {
        if (!isNaN(a.sortfields[sf]) && !isNaN(b.sortfields[sf]))
            return (a.sortfields[sf] - b.sortfields[sf]);
        else {
            if (a.sortfields[sf] > b.sortfields[sf])
                return 1;
            else if (a.sortfields[sf] < b.sortfields[sf])
                return -1;
            else
                return 0;
        }
    }
    else {
        if (!isNaN(a.sortfields[sf]) && !isNaN(b.sortfields[sf]))
            return (b.sortfields[sf] - a.sortfields[sf]);
        else {
            if (a.sortfields[sf] < b.sortfields[sf])
                return 1;
            else if (a.sortfields[sf] > b.sortfields[sf])
                return -1;
            else
                return 0;
        }
    }
}

function ShowPageControls(which) {
    var numpages = Math.ceil(PageObjects.length / pagesize);

    //    var sf = queryString('sf');
    //    if (sf == 'false')
    //        sf = '';
    //    var sd = queryString('sd');
    //    if (sd == 'false')
    //        sd = '';

    document.write("<a name=sortblock></a><div class='paginate pagingHeader'>");

    document.write("<table border=0 cellpadding=2 cellspacing=0 width=100%><tr>");


    // stats

    if (which == "top") {
        document.write("<td>");
        if (sortFormat == "list") {
            document.write("<b>List View <img border=0 src=/lib/pchcables/listview.gif></b> <a href=" + PageID + ".html?frm=grid#sortblock>Grid View <img border=0 src=/lib/pchcables/gridview.gif></a><br>");
        }
        else {
            document.write("<a href=" + PageID + ".html?frm=list#sortblock>List View <img border=0 src=/lib/pchcables/listview.gif></a> <b>Grid View <img border=0 src=/lib/pchcables/gridview.gif></b><br>");
        }
        document.write("Products per page: ");
        for (var x = 0; x < pagesizes.length; x++) {
            if (pagesize != pagesizes[x])
                document.write("<a href=" + PageID + ".html?page=1&ps=" + pagesizes[x] + "&sf=" + sf + "&sd=" + sd + "#sortblock>");
            else
                document.write("<b>");
            document.write(pagesizes[x]);
            if (pagesize != pagesizes[x])
                document.write("</a> ");
            else
                document.write("</b>");
            document.write(" ");
        }
        if (SHOWALL && numpages > 1) {
            document.write(" | <a href=" + PageID + ".html?page=0&sf=" + sf + "&sd=" + sd + "#sortblock>");
            if (CurrentPage == 0)
                document.write("<b>");
            document.write("VIEW ALL");
            if (CurrentPage == 0)
                document.write("</b>");
            document.write("</a> ");
        }

        document.write("</td><td style='text-align:right'>");
        if (SortFields.length > 0 && which == "top") {
            document.write("<b>Sort by:</b> ");
            if (SORTCONTROL == "DROPDOWN") {
                document.write("<select name=sf onchange=" + '"');
                document.write("javascript:location.href='" + PageID + ".html?sf=' + this.options[this.selectedIndex].value + '#sortblock'");
                document.write('">');
                document.write("<option value=''></option>");
                for (var i = 0; i < SortFields.length; i++) {
                    document.write("<option value='" + i + "'");
                    if (parseInt(sf) == i)
                        document.write(" selected ");
                    if (typeof (SortLabels) != 'undefined')
                        document.write(">" + SortLabels[i] + "</option>");
                    else
                        document.write(">" + SortFields[i] + "</option>");
                }
                document.write("</select>");
            }
            else if (SORTCONTROL == "LINK") {
                /*
                if ( sf == '') document.write ("<b>");
                document.write ("<a href=" + PageID + ".html?sf=&sd=a#sortblock>Default Sort</a>");
                if (sf == '' ) document.write ("</b>");
                */
                for (var i = 0; i < SortFields.length; i++) {
                    if (i > 0) document.write(" | ");
                    if (parseInt(sf) == i) {
                        document.write("<b>");
                    }
                    var newsd;
                    if (parseInt(sf) == i) {
                        if (sd == 'a')
                            newsd = 'd';
                        else
                            newsd = 'a';
                    }
                    else
                        newsd = 'a';
                    document.write("<a href=" + PageID + ".html?sf=" + i + "&sd=" + newsd + "#sortblock>");
                    if (typeof (SortLabels) != 'undefined')
                        document.write(SortLabels[i]);
                    else
                        document.write(SortFields[i]);

                    document.write("</a>");
                    if (parseInt(sf) == i) {
                        document.write("</b>");
                        if (sd == 'd')
                            document.write(SORTDOWN);
                        else if (sd == 'a')
                            document.write(SORTUP);
                    }
                }
            }
            document.write("<br>");
        }

        if (CurrentPage > 0) {
            var ItemsFrom = (CurrentPage - 1) * pagesize + 1;
            var ItemsTo = parseInt(ItemsFrom) + parseInt(pagesize) - 1;
            if (ItemsTo > PageObjects.length)
                ItemsTo = PageObjects.length;

            document.write("Showing " + ItemsFrom + " - " + ItemsTo + " of " + PageObjects.length);
            if (CurrentPage < numpages && CurrentPage > 0)
                document.write(" | <a href=" + PageID + ".html?page=" + (CurrentPage + 1) + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + PAGENEXT + "</a>");
            document.write("<br>");
        }
        else
            document.write("Showing all " + PageObjects.length + " items.<br>");
        document.write("</td>");
    }

    if (which == "bottom") {
        document.write("<td align=right class=pageNums>")
        if (CurrentPage > 1)
            document.write("<a href=" + PageID + ".html?page=" + (CurrentPage - 1) + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + PAGEPREV + "</a> | ");

        for (var i = 1; i <= numpages && numpages > 1; i++) {
            if (CurrentPage != i) {
                if (numpages <= 10 || i <= 2 || i > numpages - 2 || (i >= CurrentPage - 1 && i <= CurrentPage + 1)) {
                    document.write("<a href=" + PageID + ".html?page=" + i + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + i + "</a>");
                    document.write(" | ");
                }
            }
            else {
                document.write("<b>" + i + "</b>");
                document.write(" | ");
            }
            if ((numpages > 10) && (i < numpages) && (i > 2) && (i < numpages - 1) &&
                (
                  (CurrentPage == i - 2) ||
                  (CurrentPage == i + 2)
                )
               ) {
                document.write(" ... ");
            }
        }
        if (CurrentPage < numpages && CurrentPage > 0)
            document.write("<a href=" + PageID + ".html?page=" + (CurrentPage + 1) + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + PAGENEXT + "</a>");
    }
    document.write("</td></tr>")
    document.write("</table>");
    document.write("</div>");
}

function ShowPage() {
    var colcnt = 0;

    if (CurrentPage == 0) {
        var idx0 = 0;
        var idx1 = PageObjects.length - 1;
    }
    else {
        var idx0 = (CurrentPage - 1) * pagesize;
        var idx1 = parseInt(idx0) + parseInt(pagesize) - 1;
        if (idx1 >= PageObjects.length)
            idx1 = PageObjects.length - 1;
    }

    if (sf != 'false' && sf != '')
        PageObjects.sort(PageSortFunction);

    var idx = idx0;
    ShowPageControls("top");
    if (sortFormat != "grid")
        document.write('<table width="100%" cellspacing="0" cellpadding="0"><tbody><tr><td width="20%">Image</td><td width="20%">Product Name</td><td width="20%">Sku</td><td width="20%">Price</td><td width="20%">Order</td></tr></tbody></table>');
    document.write("<table border=0 width=" + wid + " cellpaddign=0 cellspacing=0");
    if (sortFormat == "grid") {
        document.write(" id=contents-table class=vertical");
    }
    document.write(">");
    document.write("<tr valign=top>");
    if (sortFormat == "grid") {
        cols = 4;
    }
    while (idx <= idx1) {
        if (colcnt == cols) {
            document.write("</tr><tr valign=top>");
            colcnt = 0;
        }
        if (sortFormat == "grid") {
            document.write("<td class=pagingcell>" + PageObjects[idx].src.replace(/&#96;/gi, "'") + "</td>");
        }
        else {
            document.write("<td class=pagingcell>" + PageObjects[idx].srcList.replace(/&#96;/gi, "'") + "<hr></td>");
        }
        colcnt++;
        idx++;
    }
    document.write("</tr></table>");
    document.write("<div style='border-bottom: 1px solid silver; ");
    if (sortFormat == "grid") {
        document.write("border-top: 1px solid silver; ");
    }
    document.write("padding-top: 5px; margin-top: 5px'>");
    ShowPageControls("bottom");
    document.write("</div>");

    if (sortFormat == "grid") {
        $(window).load(function () {
            $("#contents-table tr").each(function () {
                // find the tallest table
                var maxh = 0;
                $(this).find(".newContItem").each(function () {
                    if ($(this).height() > maxh)
                        maxh = $(this).height();
                });
                $(this).find(".newContItem").height(maxh);
            });
        });
    }
}


function PageQuery(q) {
    if (q.length > 1) this.q = q.substring(1, q.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if (q) {
        for (var i = 0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }
    this.getKeyValuePairs = function () { return this.keyValuePairs; }
    this.getValue = function (s) {
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            if (this.keyValuePairs[j].split("=")[0] == s)
                return this.keyValuePairs[j].split("=")[1];
        }
        return false;
    }
    this.getParameters = function () {
        var a = new Array(this.getLength());
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
    }
    this.getLength = function () { return this.keyValuePairs.length; }
}
function queryString(key) {
    var page = new PageQuery(window.location.search);
    return unescape(page.getValue(key));
}
function GetCookie(name) {

    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function SetCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());
    // if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    if (expires && typeof (expires) == 'number') {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
    var expires_date;
    if (typeof (expires) == 'number')
        expires_date = new Date(today.getTime() + (expires));
    else
        expires_date = expires;
    //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

    document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
}

// this deletes the cookie when called
function DeleteCookie(name, path, domain) {
    if (GetCookie(name)) document.cookie = name + "=" +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
