/* =========================================================================

NAME: page-sort.js

AUTHOR: Istvan Siposs , Y-Times Publications, LLC
DATE  : 4/13/2005

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 = "PREV";
var SORTCONTROL = "LINK" // set it to LINK or DROPDOWN
var SORTDOWN = "<img border=0 align=absmiddle src=/lib/yhst-14269434921819/sortdown.gif>";
var SORTUP = "<img border=0 align=absmiddle src=/lib/yhst-14269434921819/sortup.gif>";

function PageObject(sortfields,src)
{
    this.sortfields = sortfields;
    this.src = src;
}

if (queryString('page')=='false')
  CurrentPage = 1;
else
  CurrentPage = queryString('page') * 1;

var sf = queryString('sf');
if (sf == 'false')
{
  sf = GetCookie('sf');
  if (!sf)
  {
      sf = '';
  }
}
SetCookie('sf', sf);

var sd = queryString('sd');
if (sd == 'false')
{
  sd = GetCookie('sd');
  if (!sd)
     sd = 'a';
}
SetCookie('sd',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()
{
    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>");
    
    document.write("<table border=0 cellpadding=2 cellspacing=0 width=98%><tr>");

    // stats
    if (CurrentPage > 0)
    {
        var ItemsFrom = (CurrentPage - 1) * pagesize + 1;
        var ItemsTo = ItemsFrom + pagesize - 1;
        if (ItemsTo > PageObjects.length)
            ItemsTo = PageObjects.length;
        
        document.write ("<td>Displaying <b>" + ItemsFrom + "</b> to <b>" + ItemsTo + "</b> (of <b>" + PageObjects.length + "</b> items)</td>");
    }
    else
        document.write ("<td>Displaying all " + PageObjects.length + " items.</td>");
    
    document.write("<td align=right>")
    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)
            document.write("<a href=" + PageID + ".html?page=" + i + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + i + "</a> ");
        else
            document.write("<b>" + i + "</b> ");
    }
    if (CurrentPage < numpages && CurrentPage > 0)
        document.write ("<a href=" + PageID + ".html?page=" + (CurrentPage + 1) + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + PAGENEXT + "</a>");
    
    if (SHOWALL && numpages > 1)
    {
        document.write(" | <a href=" + PageID + ".html?page=0&sf=" + sf + "&sd=" + sd + "#sortblock>VIEW ALL</a> ");
    }
    document.write("</td></tr>")
    if (SortFields.length > 0)
    {
        document.write ("<tr><td class=sortblock>");
        document.write ("Sort by: ");
        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 ");
              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++)
          {
              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>" + SortFields[i] + "</a>");
              if (parseInt(sf) == i)
              {
                  document.write ("</b>");
                  if (sd == 'd')
                     document.write(SORTDOWN);
                  else if (sd == 'a')
                       document.write(SORTUP);
              }
          }
        }
        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 = idx0 + pagesize - 1;
        if (idx1 >= PageObjects.length)
            idx1 = PageObjects.length - 1;
    }

    if (sf != 'false' && sf != '')
        PageObjects.sort(PageSortFunction);    

    var idx = idx0;
    document.write ("<div style='border-bottom: 1px solid silver; padding-bottom: 5px; margin-bottom: 5px'>");
    ShowPageControls();
    document.write ("</div>");
    document.write ("<table border=0 width=" + wid + " cellpaddign=0 cellspacing=0>");
    document.write ("<tr valign=top>");
    while (idx <= idx1)
    {
        if (colcnt == cols)
        {
            document.write ("</tr><tr valign=top>");
            colcnt = 0;
        }
        document.write("<td class=pagingcell>" + PageObjects[idx].src.replace(/&#96;/gi, "'") + "</td>");
        colcnt ++;
        idx ++;
    }
    document.write ("</tr></table>");
    document.write ("<div style='border-top: 1px solid silver; padding-top: 5px; margin-top: 5px'>");
    ShowPageControls();
    document.write ("</div>");
}


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)); 
}

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function SetCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function GetCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function DeleteCookie(name, path, domain) {
  if (GetCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixdate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

