// JavaScript Document

//open browser windo
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//select all
function selectBox(formName, fldName, fldValue)
{
	if(!document.forms[formName])
		return;
	var objBoxes = document.forms[formName].elements[fldName];
	if(!objBoxes)
		return;
	var countCheckBoxes = objBoxes.length;
	if(!countCheckBoxes)
		objBoxes.checked = fldValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objBoxes[i].checked = fldValue;
}


//clear search field

function ClearInput(){
var x=document.getElementById('close').value
	if(x != ""){	
document.getElementById('search').value = 'Enter a product, example: corned beef';
document.getElementById('search').focus();
	}
}



//show all
function show(object,val) { 
document.getElementById(object).style.visibility = val; 
}


//javascript base64 encode

   function base64_encode( data ) {
    // Encodes string using MIME base64 algorithm  
    // 
    // version: 902.2516
    // discuss at: http://phpjs.org/functions/base64_encode
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}



//close notification if is open when you click on a new tab
closetab = function()
{
 var divval2 = document.getElementById('divstate').innerHTML;
		  if(divval2 =='1')
		  {
		  clearTimeout(p);
		  notification_close.start();
		  
		  }
}



//pause time for notification
var pausetime = function()
{
	
	
	  p = setTimeout("notification_close.start()", 8000);
	  Spry.Utils.setInnerHTML('divstate', '1');	
	  return p;
	  
	
}
//set the notification state to 0 onclose	
var closenow = function()
{
	Spry.Utils.setInnerHTML('divstate', '0');	
	
}


//set default tab
var setdefault = function(){
	
	var mytab = parseInt(2);
	return mytab;
}

//check all checkboxes
function checkall()
{
  
   var x=document.getElementById("frm_updatecart");
   var e = "";
   
   
   //run checkimput to make sure update text box and chk boxes are not set
   checkinput();
  
	   
	   for (var i=0;i<x.length;i++)
	   {
		  //split element name at the deleimeter "_" so as to not do unneeded elements
		   e = x.elements[i].name.split("_");
		   if(e[0] == "delete" && x.chk_deleteall.checked == true){
		    document.getElementById('sbt_updatecart').style.display = "none";
		    x.elements[i].checked=true;
		
		   
		   }
		   else if(e[0] == "delete" && x.chk_deleteall.checked == false)
		   {
			  document.getElementById('sbt_updatecart').style.display = "block"; 
			   x.elements[i].checked=false;
			   
		   }
		 
		
	   }
	  
    
	   
    
	
}





//check all checkboxes
function checkall_merchants()
{
 
   var x=document.getElementById("addtomerchant");
   var e = "";
   var q;
   var parishes = document.getElementById('parishes').value;
   var divval = document.getElementById('divstate').innerHTML;
   var image = '<div id="notification_image"><img src="images/template_image/icons/warning.png" /></div>';

  
   
   //check if  parishes filter is on "All Parishes" then set a notification
   if(parishes == "-1")
   { 
     if(divval == 0)
	 {
		document.getElementById('notification_content').innerHTML=image+'<div id="notification_message">Please filter by a parish before you check all merchants!</div>';
		notification.start(); 
		document.getElementById("ch_unck_merchants").checked=false;
		 
	 }else{
		//alert('Please filter by a parish first!'); 
		document.getElementById("ch_unck_merchants").checked=false;
		closetab();
	 }
	   
   } else {
	   //check if notification is opened and close it
	   if(divval == 1){ closetab();}
	   
	   for (var i=0;i<x.length;i++)
	   {
		   
		   
		   
		  //split element name at the deleimeter "_" so as to not do unneeded elements
		   e = x.elements[i].name.split("_");
		   if(e[0] == "merchant" && x.ch_unck_merchants.checked == true){
		    
		    x.elements[i].checked=true;
		
		   
		   }
		   else if(e[0] == "merchant" && x.ch_unck_merchants.checked == false)
		   {
			  
			   x.elements[i].checked=false;
			   
		   }
		 
		
	   }
	  
   }
	   
    
	
}










///check if check boxes are filled out and text fields are filled out also, if true, call notification//
function checkinput()
{

var chked = 0;
var txt = 0;
var divval = document.getElementById('divstate').innerHTML;

var image = '<div id="notification_image"><img src="images/template_image/icons/warning.png" /></div>';

var x=document.getElementById("frm_updatecart");


for (var i=0;i<x.length;i++)
  {
   	 //check if check box is checked 
     if(x.elements[i].checked)
	 {
		 
	     chked = 1;
		//alert(x.elements[i].value); 
		 
	 } 
	 
	//check if text box has value
	if(x.elements[i].value != 'First' && x.elements[i].value != 'Prev' && x.elements[i].value != 'Next' && x.elements[i].value != 'Last'  &&  x.elements[i].value != ' ' && x.elements[i].value != 'on' &&  x.elements[i].value != '' && isNaN(x.elements[i].value) == false)
	{
		//check if is a number
	
		 txt = 1;
		 //alert(x.elements[i].value);
		
	}
	
		 
  }
  
 if(chked == 1 && txt == 1)
	{

	 //remove buttons
	 document.getElementById('sbt_deletecart').style.display = "none";
	 document.getElementById('sbt_updatecart').style.display = "none";
	 
	  if(divval == 0)
	  {
		  
		  document.getElementById('notification_content').innerHTML=image+'<div id="notification_message">Sorry! Either check the checkbox to perform a delete action or enter a text box value to perform an update action!</div>';
		  notification.start();
		  
	  }
	} 
	else if(chked == 1 && txt == 0)
	{
		txt = 0;	
		document.getElementById('sbt_updatecart').style.display = "none";	
		document.getElementById('sbt_deletecart').style.display = "block";	
		
	} else if(txt == 1 && chked == 0)
	{	
	    chked = 0;
		document.getElementById('sbt_deletecart').style.display = "none";	
		document.getElementById('sbt_updatecart').style.display = "block";	
		
		
	}else if(chked == 0 && txt == 0)
	{
		document.getElementById('sbt_deletecart').style.display = "block";	
		document.getElementById('sbt_updatecart').style.display = "block";	
	}

}






//call javascript function
function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function totalitems(region, lookupFunc)
   { 
     var pluralize = "";
     var merchants = lookupFunc("{dsAllmerchants::ds_RowCount}");
     var products = lookupFunc("{dsAllmerchantPrices::ds_RowCount}");
     var totalitems = products/merchants;
     var product_count = parseInt(totalitems);
	 
	  if(product_count == 1)
	  {
		 pluralize ='Product';
	  } else 
	  {
		 pluralize ='Products';  
	  }
	   return product_count+' '+pluralize+' Available';
   }

function dollarsign(region, lookupFunc)
{
	var price = lookupFunc("{dsAllmerchantPrices::price}");
	var is_special = lookupFunc("{dsAllmerchantPrices::is_special}");
	
	//var ampId = lookupFunc("{dsAllmerchantPrices::merchant_id}");
	//var amId = lookupFunc("{dsAllmerchants::merchant_id}");
	
	  if(price != "Not Available!" && is_special =="Y")
	  {
		 return "<span style='color:#FF0000; font-weight: bold;'>*</>$";
		  
	  } else if(price != "Not Available!" && is_special =="N")
	  {
		 return "$";
		  
	  }
}
function showdollarsign(region, lookupFunc)
{
	var price = lookupFunc("{dsShowMerchantPrices::price}");
	 if(price != "Not Available!")
	  {
		 return "$";
		  
	  } 
	
}
function image(region, lookupFunc)
{
	var image = lookupFunc("{pvMerchantitemsData::image}");
	
	
	 
	
	  if(image != "")
	  {
		 
		 return image;
		     
	  } else 
	  {
		 return 'no_image.png';
		  
	  }
}




function makelarge(rowid)
{
	
	var image = document.getElementById('image'+rowid).innerHTML;
	if(image != "")
	{
	   //sepeare image name at the deleimeter "_" and use first part
	    var splitimage = image.split("_");
		 var extension = image.split(".");
		var theimage = '<img src="product_image/'+splitimage[0]+'.'+extension[1]+'" />';
		document.getElementById('showthisimage').innerHTML=theimage;
		enlarge.start()
	}
	
}

function showresultsimage(region, lookupFunc)
{
	var image = lookupFunc("{dsResultsSummary::image}");
	
	if(image != ""){
		//sepeare image name at the deleimeter "_" and use first part
	    var splitimage = image.split("_");
		var theimage = '<img src="product_image/'+splitimage[0]+'.jpg" width="75" height="75" />';
		return theimage;
		
	} else {
		
		return'<img src="images/template_image/icons/warning_64.png" width="64" height="64" />';
	}
	
}

/*function Myscroller(notificationType, notifier, data)
{
	if(notificationType == 'onDataChanged')
	{
		scrollcheapest.start();
		Spry.Debug.trace("Observer Callback: " + notificationType);

	}
}
rsTop2merchants.addObserver(Myscroller); */
function showadvanced(rdRowCounter)
{
 	
	
	
    //alert(rdRowCounter);
	var searchtxt = document.getElementById('search').value;
	var rscount = rdRowCounter;
  
	if(rscount == 0 && searchtxt != "Enter a product, example: corned beef")
	{
	  document.getElementById('advanced_search').style.display = "block";
	}
	else if(rscount == 0 && searchtxt == "Enter a product, example: corned beef" )
	{
	  
	  document.getElementById('advanced_search').style.display = "none";	
		
	} 
	 else if(rscount == '' && searchtxt == "Enter a product, example: corned beef")
	{
		 document.getElementById('advanced_search').style.display = "none";	
		
	}
	else if(rscount > 0 && searchtxt != "Enter a product, example: corned beef")
	{
		 document.getElementById('advanced_search').style.display = "none";	
		
	}
	

}


function showadvanced_search()
{
	var search_query = document.getElementById('search').value;
	document.getElementById('maincategory_sel').value = 0;
    document.getElementById('advanced_search_txt').value = search_query;
	show_advanced_search.start();
	
	
}

function getvisinities()
{
	
	var category = document.getElementById('maincategory_sel').value;
	//document.getElementById('advancedSearchResponseInnerdiv').style.display="none";
	//alert(category);
	if(category != "-1"){
		
    var formData = 'category='+category;
   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
   formData = encodeURI(formData);
   var url ="includes/get_advanced_search_visinities.php";
   
   //show the loader
   document.getElementById('loader').style.display="block";
   
   Spry.Utils.loadURL('POST', url, true, ReturnWithEffect, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
   
	}else{
		
     document.getElementById('loader').style.display="none"; 
	 document.getElementById("advanced_search_visinities").style.display="none";  
		
	}

}


function ReturnWithEffect(req){
   //We use xhRequest to received notification from server side, usually the process file will return with an echo/write.
   var result = req.xhRequest.responseText; 
   
  
   
   if(result != ""){
   document.getElementById('loader').style.display="none";
   
   document.getElementById("advanced_search_visinities").style.display="block";
   document.getElementById("advanced_search_visinities").innerHTML = result;
   advanced_search_visinities.start();
   } else {
	   
	 document.getElementById('loader').style.display="none"; 
	 document.getElementById("advanced_search_visinities").style.display="none";  
   }
   
}  


function process_search_elements(fd){
	
var x=document.getElementById("advancedsearchform");
var action = fd;


	if(action=="fade")
	{
	    for (var i=0;i<x.length;i++)
        {
   	      if
		  ( x.elements[i].name!="advanced_search_txt"){
           x.elements[i].disabled=true;
		  }
		 
		}
		faded_advanced_search_visinities.start();
        faded_advanced_search_content_txt.start();

	}
	else
	{
		  for (var i=0;i<x.length;i++)
           {
   	  
            x.elements[i].disabled=false;
	     
		   }
		document.getElementById("loader").style.display = "none";
		//document.getElementById("advanced_search_txt").value="Enter a product, example: corned beef";
		advanced_search_visinities.start();
		advanced_search_content_txt.start();
	}
}


function sort_by(row)
{
	var table_row = row;
	//alert(table_row);
	if(table_row == 'product_type')
	{
	  
	   
	   //check sort by cookie
	   if(readCookie("sort_by") != "")
	   {
		   if(readCookie("sort_by") == "sort_by_brand")
		   {
		   
			 document.getElementById('sort_by_brand').style.backgroundColor="#fff";
			 document.getElementById('sort_by_brand').style.color="#999";
			 
			 
			 document.getElementById('sort_by_product_type').style.backgroundColor="#666";
			 document.getElementById('sort_by_product_type').style.color="#ccc";
			 
			 //update cookie value
			 writeCookie('sort_by','sort_by_product_type', '24');
			 
			 //do the sort
			 pvMerchantitemsData.sort('product_name', 'ascending');
			 
		   }
	   } 
	   else
	   {
		     document.getElementById('sort_by_brand').style.backgroundColor="#fff";
			 document.getElementById('sort_by_brand').style.color="#999";
			 
			 
			 document.getElementById('sort_by_product_type').style.backgroundColor="#666";
			 document.getElementById('sort_by_product_type').style.color="#ccc";
			 
			 //create cookie value
			 writeCookie('sort_by','sort_by_product_type', '24');
			 
			 //do the sort
			 pvMerchantitemsData.sort('product_name', 'ascending');
		   
	   }
	   
	   
	
	} 
	else 
	{
	    //check sort by cookie
	   if(readCookie("sort_by") != "")
	   {
		   if(readCookie("sort_by") == "sort_by_product_type")
		   {
			 document.getElementById('sort_by_product_type').style.backgroundColor="#fff";
			 document.getElementById('sort_by_product_type').style.color="#999";
			 
			 
			 document.getElementById('sort_by_brand').style.backgroundColor="#666";
			 document.getElementById('sort_by_brand').style.color="#ccc";
			 
			 //update cookie value
			 writeCookie('sort_by','sort_by_brand', '24');
			 
			 //do the sort
			 pvMerchantitemsData.sort('brand', 'ascending');
		   }
	   }
	   else
	   {
		     document.getElementById('sort_by_product_type').style.backgroundColor="#fff";
			 document.getElementById('sort_by_product_type').style.color="#999";
			 
			 
			 document.getElementById('sort_by_brand').style.backgroundColor="#666";
			 document.getElementById('sort_by_brand').style.color="#ccc";
			 
			 //create cookie value
			 writeCookie('sort_by','sort_by_brand', '24'); 
			 
			  //do the sort
			 pvMerchantitemsData.sort('brand', 'ascending');
		   
	   }
	   
	
	}
	
}



function FilterData()
{
	var tf = document.getElementById("filterTF");
	if (!tf.value)
	{
		// If the text field is empty, remove any filter
		// that is set on the data set.

		pvMerchantitemsData.filter(null);
		return;
	}

	// Set a filter on the data set that matches any row
	// that begins with the string in the text field.

	var regExpStr = tf.value;
	
	//if (!document.getElementById("containsCB").checked)
	//	regExpStr = "^" + regExpStr;

	var regExp = new RegExp(regExpStr, "i");
	
	var filterFunc = function(ds, row, rowNumber)
	{
		var str = row["product"];
		if (str && str.search(regExp) != -1)
			return row;
		return null;
	};

	pvMerchantitemsData.filter(filterFunc);
}

function StartFilterTimer()
{
	if (StartFilterTimer.timerID)
		clearTimeout(StartFilterTimer.timerID);
	StartFilterTimer.timerID = setTimeout(function() { StartFilterTimer.timerID = null; FilterData(); }, 100);
}







//write cookie
function writeCookie(name, value, hours)

{

  var expire = "";

  if(hours != null)

  {

    expire = new Date((new Date()).getTime() + hours * 3600000);

    expire = "; expires=" + expire.toGMTString();

  }

  document.cookie = name + "=" + escape(value) + expire;

}


//read cookie
// Example:

// alert( readCookie("myCookie") );
function readCookie(name)

{

  var cookieValue = "";

  var search = name + "=";

  if(document.cookie.length > 0)

  { 

    offset = document.cookie.indexOf(search);

    if (offset != -1)

    { 

      offset += search.length;

      end = document.cookie.indexOf(";", offset);

      if (end == -1) end = document.cookie.length;

      cookieValue = unescape(document.cookie.substring(offset, end))

    }

  }

  return cookieValue;

}



function calculate_by(row)
{
	
	
  var table_row = row;
  var formData = 'calculate_by='+table_row;
   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
   formData = encodeURI(formData);
   var url ="includes/spry_calculate_by.php";
   
   Spry.Utils.loadURL('POST', url, true, ReturnCalculate_by, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
  	
	
}

function ReturnCalculate_by(req){
   //We use xhRequest to received notification from server side, usually the process file will return with an echo/write.
   var result = req.xhRequest.responseText; 
   //alert(result);
   
   if(result == "product_type")
   {
   
             document.getElementById('calculate_by_brand').style.backgroundColor="#fff";
			 document.getElementById('calculate_by_brand').style.color="#999";
			 
			 
			 document.getElementById('calculate_by_product_type').style.backgroundColor="#666";
			 document.getElementById('calculate_by_product_type').style.color="#ccc";
			 
			 
			 
			 
			 
   }
   else
   {
	         document.getElementById('calculate_by_product_type').style.backgroundColor="#fff";
			 document.getElementById('calculate_by_product_type').style.color="#999";
			 
			 
			 document.getElementById('calculate_by_brand').style.backgroundColor="#666";
			 document.getElementById('calculate_by_brand').style.color="#ccc";
	   
   }
   
   
   //load datasets
   dsMycart.loadData();
   rsTop2merchants.loadData();
  // rsWatchMerchant.loadData();
   //rsMyproducts.loadData();
   
}

//control for auto sorting and styling merchant sort elements on page load

function defaultsortControl()
{
	Spry.Data.Region.removeObserver("merchant_listings", myObserver);
	//alert("defaultsortControl called!")
	if(readCookie("sort_by") != "")
	{
		if(readCookie("sort_by") == "sort_by_brand")
		{	   
		   //alert(readCookie("sort_by")+" 1");
		   document.getElementById('sort_by_brand').style.backgroundColor="#666";
		   document.getElementById('sort_by_brand').style.color="#ccc";
		   pvMerchantitemsData.sort('brand', 'ascending');
		  
		} 
		else 
		{  // alert(readCookie("sort_by")+" 2");
			document.getElementById('sort_by_product_type').style.backgroundColor="#666";
			document.getElementById('sort_by_product_type').style.color="#ccc";
			pvMerchantitemsData.sort('product_name', 'ascending');
			
		}
		
		
	}
	else
	{   //alert(readCookie("sort_by")+" 3");
		document.getElementById('sort_by_brand').style.backgroundColor="#666";
		document.getElementById('sort_by_brand').style.color="#ccc";
		
		 //create cookie value
		 writeCookie('sort_by','sort_by_brand', '24');
		 pvMerchantitemsData.sort('brand', 'ascending');
			   
	}
	
	
	

}



function first_run_notification(im,mes)
{

//alert('test');
var the_image = im;
var the_message = mes;
var image = '<div id="notification_image"><img src="images/template_image/icons/'+the_image+'" /></div>';
document.getElementById('notification_content').innerHTML=image+'<div id="notification_message">'+the_message+'</div>';

notification.start();	



Spry.Data.Region.removeObserver("merchant_listings", first_run_notify);


}







function newXPath(parishID)
{
	
	if(parishID != -1)
	{
		
		//update cookie value
	    writeCookie('xpath',parishID, '24');
	    allmerchants.setXPath('export/row[parish_id='+parishID+']')
	    //allmerchants.loadData();
		//clear previous selected chk_unck_merchant select box
		document.getElementById("ch_unck_merchants").checked=false;
		
	} 
	else
	{
		
		//update cookie value
	    writeCookie('xpath','-1', '24');
	    allmerchants.setXPath('export/row');
	    //allmerchants.loadData();
		//clear previous selected chk_unck_merchant select box
		document.getElementById("ch_unck_merchants").checked=false;
	}
	 
	//dosessionSelect("0");
	
}


function newXPath2(parishID)
{
	
	if(parishID != -1)
	{
		
		//update cookie value
	    writeCookie('xpath2',parishID, '24');
	    dsVisinity.setXPath('export/row[parish_id='+parishID+']')
	   // dsVisinity.loadData();
		
		
	} 
	else
	{
		
		//update cookie value
	    writeCookie('xpath2','-1', '24');
	    dsVisinity.setXPath('export/row')
	   // dsVisinity.loadData();
		
	}
	 
	
	
}





function defaultSelectXPath()
{
	
	
	if(readCookie("xpath") == "")
	{
		 writeCookie('xpath','-1', '24');
		 document.getElementById("parishes").value = "-1";
	}
	else if(readCookie("xpath") == "-1")
	{
		 writeCookie('xpath','-1', '24');
		 document.getElementById("parishes").value = "-1";
		
	} 
	else 
	{
		 var cookieparish = readCookie("xpath");
		 allmerchants.setXPath('export/row[parish_id='+cookieparish+']')
		 document.getElementById("parishes").value = cookieparish;
	     allmerchants.loadData();	
		
	}
	
	
	//dosessionSelect("0");
	
	Spry.Data.Region.removeObserver("merchant_names", merchant_namesObserver);
}

function defaultSelectXPath2()
{
	Spry.Data.Region.removeObserver("my_search_results", merchant_namesObserver2);
	
	if(readCookie("xpath2") == "")
	{
		 writeCookie('xpath2','-1', '24');
		 document.getElementById("parishes").value = "-1";
	}
	else if(readCookie("xpath2") == "-1")
	{
		 writeCookie('xpath2','-1', '24');
		 document.getElementById("parishes").value = "-1";
		
	} 
	else 
	{
		 var cookieparish = readCookie("xpath2");
		 dsVisinity.setXPath('export/row[parish_id='+cookieparish+']')
		 document.getElementById("parishes").value = cookieparish;
	     dsVisinity.loadData();	
		
	}
	
	
	//dosessionSelect("0");
	
	
}



function dosessionSelect(ids)
{
  

  var ids = ids;
  var  e = ids.split(",");
  var ids_cnt = e.length;
  alert(e+" with "+ids_cnt+" elements!");
  alert("got cookie value ="+readCookie("myselled"));
  
   if(ids != "0")
  {
	
	for(i=0;i<ids_cnt;i++)
	 {  
	    
		document.getElementById("merchant_"+e[i]).checked = true;
		alert("just did merchant_"+e[i]);
	 }
	 var nwStr = e.join("_");
	 writeCookie('myselled',nwStr, '0');
	 alert("wrote cookie ids with these values: "+nwStr)
  }
   else if(readCookie("myselled") != "")
	  {
		  var ckies_std = readCookie("myselled").split("_");
		  var ckies_len = ckies_std.length;
		  for(var i=0;i<ckies_len;i++)
	      {  
	    
		    document.getElementById("merchant_"+ckies_std[i]).checked = true;
		    alert("just did merchant_"+ckies_std[i]+" from cookies");
	      }
		  
	  }

}

function notification_merchants_tab()
{
	 var x=document.getElementById("addtomerchant");
	 var e = "";
	 var show_notification = "yes";
	 var divval = document.getElementById('divstate').innerHTML;
     var image = '<div id="notification_image"><img src="images/template_image/icons/warning.png" /></div>';
	 var PostString = '';

	  for (var i=0;i<x.length;i++)
	   {
		  //split element name at the deleimeter "_" so as to not do unneeded elements
		   e = x.elements[i].name.split("_");
	      if(e[0] == "merchant" && x.elements[i].checked)
		   {
			
			
			   show_notification = "no";
			   //build PostString
			   PostString += "merchant_"+e[1]+"="+e[1]+"&";
		   }
		 
		
	   }
	
	
if(show_notification == "yes")
	{
	if(divval == 0)
	  {
		  
		  document.getElementById('notification_content').innerHTML=image+'<div id="notification_message">Please select the merchants that you want to have compared in your grocery basket, then press the "Add Merchants" button!</div>';
		  
		  notification.start();
		 
		  
	  }
	   
       
	}
	
	
	
if(show_notification == "no")	
{
	
	 
	var formData = PostString;
	//alert(formData);
   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
   formData = encodeURI(formData);
   var url ="includes/addtomerchant.php";
   
   
   Spry.Utils.loadURL('POST', url, true, testPost, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
   
   
   
	
}
	

}





function testPost(req){
   //$_SESSION['runcount'] is returned
   var result = req.xhRequest.responseText; 
   rsTop2merchants.loadData();
   mymerchants.loadData();
   dsMycart.loadData();
   window.location.reload();
   
  
   
}


function add_products_notification()
{
	
	 
    var formData = 'get_first_run=1';
   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
   formData = encodeURI(formData);
   var url ="includes/spry_chk_first_run.php";
   
   Spry.Utils.loadURL('POST', url, true, get_first_run, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
   
   
   
}

function get_first_run(req)
{
   
   var result = req.xhRequest.responseText; 
   var rs = result.split("_");
   //alert(result+'->'+rs[0]+' '+rs[1]+' '+rs[2]);
   //rs[0] is runcount - tell me that merchants was added
   //rs[1] is first_run - tells me how many times the website was reloaded
   //rs[3] is ran_add_product_notification - tells me that the notification was ran already
   
    if(rs[0] == 1 && rs[1] > 2 && rs[2] == "")
   {
	 var divval = document.getElementById('divstate').innerHTML;
     var image = '<div id="notification_image"><img src="images/template_image/icons/info.png" /></div>';  
	 if(divval == 0)
	  {
		  
		  document.getElementById('notification_content').innerHTML=image+'<div id="notification_message">Now that you have added your merchant(s), you may add your products!</div>';
		  
		  notification.start();
		 
		 
		//set a session that tells the server that ran_add_product_notification was already ran, 
		//so that it does not run every time the page loads
		
		var formData = 'chk_run_add_product_notification=1';
	   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
	   formData = encodeURI(formData);
	   var url ="includes/spry_chk_first_run.php";
	   
	   Spry.Utils.loadURL('POST', url, true, null, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
		  
	  }
	  
   }
   
   
	
}



function notification_products_tab(){
	
	
	var formData = 'get_first_run=1';
   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
   formData = encodeURI(formData);
   var url ="includes/spry_chk_first_run.php";
   
   Spry.Utils.loadURL('POST', url, true, notification_products_response, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
	
	
}
 
 
 function notification_products_response(req)
{
   var result = req.xhRequest.responseText; 
   var x=document.getElementById("addtocart");
   var show_notification = "yes";
   var e="";
   var PostString='';
   var rs = result.split("_");
   var divval = document.getElementById('divstate').innerHTML;
   //rs[0] is runcount - tell me that merchants was added
    //check if merchants was added
    if(rs[0] >= 1)
	{
		//chk if the txt box has a value by doing a loop through all the txt boxes
		 for (var i=0;i<x.length;i++)
	   {
		  //split element name at the deleimeter "_" so as to not do unneeded elements
		   e = x.elements[i].name.split("_");
		   if(e[0] == "cartitem" && x.elements[i].value != "" && isNaN(x.elements[i].value) == false ){
		    
		    show_notification = "no";
			//add all the txt box values to this var
			
		    PostString += "cartitem_"+e[1]+"="+x.elements[i].value+"&";
			//remove the value from the txt box
		    document.getElementById("item_count"+e[1]).value="";
		   }
		   
	   }
	   
		   if(show_notification == "yes")
		   {
			   
			 if(divval == 0)
			 {  
			 
			     first_run_notification('warning.png','Please enter a number in the text box!');
				 
			 
			 }
			 else
			 {
				closetab(); 
			 }
			 
		   }else{
			 
			     
			var formData = PostString;
			//alert(formData);
		   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
		   formData = encodeURI(formData);
		   var url ="includes/addtocart.php";
			 
			 
		   Spry.Utils.loadURL('POST', url, true, post_products_response, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
			 
			   
		   }
		
	}
	//no merchant was added notification
	else
	{    if(divval == 0)
	    {
		  first_run_notification('warning.png','Please press the "Merchants" tab to start adding merchants, after which you may add products!');
	    }
		else
		{
		  closetab();
		  
		}
	}
	
	
}



function post_products_response(req)
{
	var result = req.xhRequest.responseText;
	//alert(result);
	if(result == 1)
	{    
		rsTop2merchants.loadData();
	    rsMyproducts.loadData();
	    dsMycart.loadData();
		
	}
}

function sendcontactEmail()
{
	var name = document.getElementById("name").value;
	/*var phone = document.getElementById("phone").value;
	var email = document.getElementById("email").value;
	var subject = document.getElementById("subject").value;
	var email = document.getElementById("email").value;
	var category = document.getElementById("category").value;
	var message_body = document.getElementById("body").value;*/
	alert('test');
}


function display_cheapest_merchant_info(region, lookupFunc)
{
	var merchant_id = document.getElementById('hidden_merchant_id').innerHTML;
	var formData = 'merchant_id='+merchant_id;
			
   //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
   formData = encodeURI(formData);
   var url ="includes/request_cheapest_merchant_info.php";
	 
			 
  Spry.Utils.loadURL('POST', url, true, request_cheapest_response, {postData: formData, headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
		   
	
}

function request_cheapest_response(req)
{
	var result = req.xhRequest.responseText;
	//alert(result);
	
	document.getElementById('cheapest_response').innerHTML = result;
	
}

function screen_res(p)
{
	//chk if cookie has variable, if not make a query.
	/*if(readCookie("browser_info") == "")
	{*/
	
	
	  var formData = 'page='+p;
      //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
      formData = encodeURI(formData);
      var url ="includes/request_browser_info.php";
	 
			 
      Spry.Utils.loadURL('POST', url, true, request_browser_info_response, {postData: formData, 
						headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});	
	  
	/*} 
	else 
	{
		//split cookie :- parts are broswer_name/browser_version/res_width/res_height/page_name
		var broswer_info = readCookie("browser_info").split("/");
		var browser_name = browser_info[0];
		var browser_version = browser_info[1];
		var res_width = browser_info[2];
		var res_height = browser_info[3];
		var page_name = browser_info[4];
		
	}*/

	
}

function request_browser_info_response(req)
{
	
	var result = req.xhRequest.responseText;
	var rs = result.split("/");
	
	var res_width = screen.width;
	var res_height = screen.height;
	var browser_name = rs[0];
	var browser_version = rs[1];
	var page_name = rs[2];
    var browser_str = browser_name+'/'+browser_version+'/'+res_width+'/'+res_height+'/'+page_name;
	 //write the cookie
	 //writeCookie('browser_info',browser_str, '24');
	
	if(page_name == "index" || page_name == "disclaimer" || page_name == "contact")
	{
		document.getElementById('my_cart_absolute_wrapper').style.display = "none";
		
		if(res_height == "1200")
		{
		 
		  document.getElementById('push').style.height = "600px";
		  document.getElementById('container').style.marginBottom = "-600px";
		  document.getElementById('footer').style.height = "600px";
		  document.getElementById('footer').style.marginBottom = "-600px";
		}
		else if(res_height == "1024")
		{
		  
		  document.getElementById('push').style.height = "400px";
		  document.getElementById('container').style.marginBottom = "-400px";
		  document.getElementById('footer').style.height = "400px";
		  document.getElementById('footer').style.marginBottom = "-400px";
			
		}
		
		else if(res_height == "864")
		{
		  
		  document.getElementById('push').style.height = "300px";
		  document.getElementById('container').style.marginBottom = "-300px";
		  document.getElementById('footer').style.height = "300px";
		  document.getElementById('footer').style.marginBottom = "-300px";
			
		}
		else if(res_height == "768")
		{
		  
		  document.getElementById('push').style.height = "220px";
		  document.getElementById('container').style.marginBottom = "-220px";
		  document.getElementById('footer').style.height = "220px";
		  document.getElementById('footer').style.marginBottom = "-220px";
			
		}
		
	}
	
	
	
	//alert(browser_str);
}


function chk_if_loggedin(bid)
{
	  var formData = 'bid='+bid;
      //The next line is to encode the variables values e.g. weird characters to make it safe for transfer
      formData = encodeURI(formData);
      var url ="includes/chk_if_logged_in.php";
	 
			 
      Spry.Utils.loadURL('POST', url, true, chk_if_logged_Response, {postData: formData, 
						headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
	
}


function chk_if_logged_Response(req)
{
	var result = req.xhRequest.responseText;
	var q="";
	q = result.split("/");
	//alert(result);
	 if(q[0]=="0" && q[1] == "Y")// you are not logged in and the basket was saved so make sure that the basket cannot be edited.
	 {
		 <!--merchants tab-->
		document.getElementById('parishes').disabled="true";
		document.getElementById('chk_submit2').style.display="none";
		document.getElementById('removemerchantall').style.display="none";
		document.getElementById('ch_unck_merchants').style.display="none";
		
		<!--products tab-->
		document.getElementById('chk_submit').style.display="none";
		

		<!--cart tab-->
		document.getElementById('sbt_updatecart').style.display="none";
		document.getElementById('sbt_deletecart').style.display="none";
		document.getElementById('chk_deleteall').disabled="true";
		document.getElementById('delete_chk').disabled="true";
		document.getElementById('my_cart_updatetext').disabled="true";
		
	 }
	 
	
	
	
	
	
}


function show_all_auto()
{
	Spry.Data.Region.removeObserver("merchant_listings", myObserver);
	var params = Spry.Utils.getLocationParamsAsObject();
	
   // alert(params.bid)
	
   if(params.bid != undefined)
	{
		showall.start();
	}
	
}


function login()
{
	alert("login chk!");
	
}
