//Global variables
var $j = jQuery.noConflict();
var numPerPage = 15; 
var numReturned = 90;
var tempRetNum = 0;
var currentPage = 1; 
var lastpagefetched = 0; 
var sales=new Array();
var showpage = true; 
var fetching = false; 
var more = true;
var showMessage = true; 

function fetchResults() {
	//Use getJSON for now
	var data = getSearchParameters(); 
	$j.getJSON("local.sales.json.html", data, function(json){
	     parseJSON(json);
    });	
}

function contructLink(page) {
   //var store = $j("#storeName").val();
   //if (store=="") store="all";   
   //var category = $j("#category").val();
   //if (category=="") category="all";
   var link = page;
   //create the anchor
   $j("#toplink").html('<a name="'+link+'" ></a>');
   //var href = new String(this.location.href + "#" + link);
   self.location.hash = link;
   return; 
}

function parseJSON(j) {
   if (j.sales.length) {
		for (var i = 0; i < j.sales.length; i++) {
    		window.sales.push(j.sales[i]);  
		}
		if ( i < window.numReturned ) window.more = false;  
	}
	else  window.more = false;
	
	window.fetching=false;
	//notify bar update
	window.showMessage = false; 
	loadingMessage();
	displaypage(); 	
}

function getSearchParameters() {
  //page
  window.searchCriteria = 
  window.lastpagefetched+=1;	
  var page = window.lastpagefetched;
  var psonly = false  
  //store name
  var store = $j("#storeName").val();
  var category = $j("#category").val(); 
  //PS only
  if ((document.getElementById('psonly')!=null) && document.getElementById('psonly').checked) var psonly = true;
  
  var returnNum = window.numReturned; 
  if (window.tempRetNum>0) {
	  returnNum = window.tempRetNum;
	  window.tempRetNum = 0;
	  window.lastpagefetched=Math.ceil(returnNum / window.numReturned);
  }
  
  if (psonly) return {'page': page, 'storeName': store, 'category': category, 'retNum': returnNum, 'psonly': 1};
  else return {'page': page, 'storeName': store, 'category': category, 'retNum': returnNum};
};

function searchSales() {
	  //alert("Dumping old Data"+window.lastCriteria);
	  window.currentPage = 1; 
      window.lastpagefetched = 0; 
      window.sales=new Array();
      window.showpage = true; 
      window.fetching = false; 
      window.more = true;
	  window.lastPage = "";	  
      $j('#localsales').html("");
	  $j('.lsprevlink').css('display','none');
	  moreOff();
	  fetchLocalSavings();
}


function fetchLocalSavings()  {
	if (window.fetching==false) {
		window.fetching=true;
		fetchResults();
		//notify bar update
		window.showMessage = true; 
		loadingMessage();
	}
}

var timer = 0;
function loadingMessage() {
	if (window.showMessage) {   
	    window.timer += 1; 
		var ntfSearching = "<img src='images/json_loading.gif' width='16' height='16'>";
		switch(timer)
		{
			case 2:
	 			ntfSearching += "Searching millions of local prices";			
				break;
			case 3:
				ntfSearching += "Restricting results to stores near you";
				break;
			case 4:
				ntfSearching += "Calculating prices near you";
				break;
			case 5:
				ntfSearching += "Receiving local sale data";
				break;
			default:
				ntfSearching += "Retrieving more local sales";		
		}			
		//if (window.marquee==null) { 
			window.marquee = window.setTimeout('loadingMessage()', 3000);
		//}
	}
	else { 
		ntfSearching = ""; 
		clearTimeout(window.marquee); 
		window.marquee=null;
		window.timer = 0;
	}
	
	$j('.notification').html(ntfSearching); 
}


function displaypage() {
	if (arguments[0]!=undefined) { 
		window.lastPage = window.currentPage;
		window.currentPage = arguments[0];
		window.showpage = true; 
	}
	if ((window.showpage==true) && (window.lastPage!=window.currentPage)) {
        var page = window.currentPage;

        contructLink(page);

		//Fetch the next results when getting close to the end
		if ((page * window.numPerPage) > (window.sales.length-(3*window.numPerPage)) && window.more==true) fetchLocalSavings(); 
		
		if (page <= Math.ceil(window.sales.length / window.numPerPage)) {
		  var shtml = formatSalesForDisplay(page); 
		  $j('#localsales').html(shtml);
   		  window.showpage = false; 
 	    }
		
		if (window.sales.length==0) {
			html = '<tr><td colspan="5" class="nonefound">No local sales were found matching that criteria.</td></tr>';
			$j('#localsales').html(html);
   		    window.showpage = false; 
		}
		//disable the more when we have no more. 
		//alert(window.sales.length);
		if ((page * window.numPerPage) >= (window.sales.length) && window.fetching==false) moreOff(); 
		else moreOn();
		
		//disable the back when we have no back
		if (page==1) $j('.lsprevlink').css('display','none');
		else $j('.lsprevlink').css('display','inline');	
		
	}
}

function moreOff() { 
$j('.lsnextlink').css('display','none'); 
}
function moreOn() { 
$j('.lsnextlink').css('display','inline'); 
}

function lsNext() {
	var page = window.currentPage + 1;
	displaypage(page);
}

function lsPrev() {
	var page = window.currentPage - 1;
	displaypage(Math.max(page,1));
}

function formatSalesForDisplay(page) {
	var start; 
	var html=""; 
	if (page < 1) page = 1; 
	if (page == 1) 	start = 0;
	else start = ((page - 1) * window.numPerPage);
	var end = start + window.numPerPage; 
	if (end > window.sales.length) {
		var diff = window.sales.length - start; 
		var end = start + diff;
	}
	
	for (var i = start; i < end ; i++) {
		html = html + getSaleRow(window.sales[i]); 
	}
	return html; 
}

var rowCounter = 0;
function getSaleRow(row) {
	var image = "";
	var classTD = "";
	var psBack = "";	
	var qpon=false;
	if (rowCounter % 2) classTD="alt"; 
	if (row["qSave"]>0) { 
		qpon=true; 
		classTD+="ps";
  	    psBack = "psdecal";			
	}
	
    if (row["photo"]!="") { 
		image = "<td class='nobg'><img src='/img/t_"+row["photo"]+"' border='0'>";
		if (qpon) image +=	"<img src='/dev/images/ps.decal.png' class='psdecal'>";
		image += "</td>";
	}
	else { 
		image = "<td class='nobg'><img src='/images/nophoto.jpg' width='70' height='70'>";
		if (qpon) image +=	"<img src='/dev/images/ps.decal.png' class='psdecal'>";		
		image += "</td>";
	}
    html = "<tr>"; 
    html += image;
	html += "<td class='"+classTD+"'><div class='expires'>expires: "+row["expires"]+"</div><a href='productDetail.html?id=" + row["productID"] + "'>" + row["name"] + "</a> " + row["description"] + "<br><a href='javascript:updateShoppingCartData("+row["productID"]+");'><img src='http://www.pricible.com/images/square.check.png' alt='' width='18' height='16' border='0' align='absmiddle' /></a> <a href='javascript:updateShoppingCartData("+row["productID"]+");'>Add to list</a></td>";
	
    if (!qpon) html += "<td class='"+classTD+"'>$" + row["savings"] + "</td>";
	else { 
		html += "<td class='"+classTD+"'>" + formatCurrency(row["totalSavings"]); 
		if (row["couponMin"]>1) html += " on " + row["couponMin"];
		html += "</td>";
	}
    if (!qpon) html += "<td class='"+classTD+"'> $"+row["special_price"]+" <del>$"+row["price"]+"</del></td>";
	else {
		html += "<td class='"+classTD+"'>";
		html += "<span class='qptext'><img src='images/powersaver.micro.png' alt='Power Saver Feature'><a href='power.saver.coupon.html?qid="+row['qid']+"'>";
		if (row["totalPrice"]>0) html+= formatCurrency(row["totalPrice"]); 
		else html+= "FREE ";
		if (row["couponMin"]>1) html += " for " + row["couponMin"];		
		html += " with coupon</a></span><br>"+formatCurrency(row["special_price"])+" <del>$"+row["price"]+"</del></td>";
	}
    html += "<td class='"+classTD+"'>" + row["storeName"] +"</td>";
	html += "</tr>";
	
	rowCounter++;
	return html; 
}

function setTempRetNum(page) {
 var minRecordsNeeded = Math.max(((page * window.numPerPage) + window.numPerPage), window.numReturned);
 window.tempRetNum = minRecordsNeeded;
 window.currentPage = parseInt(page);
 window.lastPage = page-1; 
 return;
}

$j(function() {
  var hash = self.location.hash.substring(1);
  if (hash == parseInt(hash)) setTempRetNum(hash); 			
  fetchLocalSavings();
});

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
