/* =========================================================================

NAME: page-sort.js

AUTHOR: Istvan Siposs , Y-Times Publications, LLC
DATE  : 5/31/2007

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 = "<img border=0 align=absmiddle src=/lib/yhst-57040721399257/sortdown.gif>";
var SORTUP = "<img border=0 align=absmiddle src=/lib/yhst-57040721399257/sortup.gif>";
var DEFAULTSORT = "";

function PageObject(sortfields,src)
{
    this.sortfields = sortfields;
    this.src = src;
}

if (queryString('page')=='false')
{
  if (GetCookie("viewall") == 'yes')
    CurrentPage = 0;
  else
    CurrentPage = 1;
}
else
  CurrentPage = queryString('page') * 1;

if (CurrentPage != 0)
  DeleteCookie("viewall");

if (CurrentPage == 0 && GetCookie('viewall') != 'yes')
{
  SetCookie("viewall","yes");
}

var sf = queryString('sf');
if (sf == 'false')
{
  sf = GetCookie('sf');
  if (!sf)
  {
      sf = DEFAULTSORT;
  }
}
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=100%><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 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)
            document.write("<a href=" + PageID + ".html?page=" + i + "&sf=" + sf + "&sd=" + sd + "#sortblock>" + i + "</a>");
        else
            document.write("<b>" + i + "</b>");
        document.write(" | ");
    }
    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>");
        if (CurrentPage == 0)
            document.write("<b>");
        document.write("VIEW ALL");
        if (CurrentPage == 0)
            document.write("</b>");
        document.write("</a> ");
    }
    document.write("</td></tr>")
    if (SortFields.length > 0)
    {
        document.write ("<tr><td class=sortblock>");
        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++)
          {
              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 ("</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; border-top: 1px solid silver; padding-bottom: 5px; margin-bottom: 5px'>");
    ShowPageControls();
    document.write ("</div>");
    document.write ("<table border=0 width=" + wid + " cellpadding=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; border-bottom: 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)); 
}
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";
}
