/*****************************************************************************************
 *
 * "peckhams_main.js"   Main database code for peckhams client-side database
 * ------------------
 *                      Only the "contants" section of this file should be modified.
 */

/*****************************************************************************************
 *
 * CONSTANTS   User defined constants
 * ---------
 *             This section may be modified if the directory structure of the site is
 *             modified later. The quotes (") and trailing slash (/) are essential!
 */

var __SiteBase=''                       // root directory of site from document location. May be set in the file itself.
var __Database="db/"                    // base directory for the database .js files
var __ImageBase="images/"               // base directory for general images
var __PictureImageBase="db/pictures/"   // base directory for pictures of items in the database
var __TitleImageBase="db/titles/"       // base directory for title images used in database

/*****************************************************************************************
 *
 * CATEGORY CONSTANTS   Category constants
 * ------------------
 *                      This section should not need modification. It merely allows for a
 *                      consistent way to reference categories. At this time only two
 *                      categories are required so only two constants are declared.
 *
 *                      Note that the value of each constant must correspond to the
 *                      directory where the .js files for that category are stored.
 *                      This directory is relative to the "__Database" constant declared
 *                      in "peckhams_main.js"
 */

var dbGift="giftboxes"  // base directory for gift boxes
var dbHamper="hampers"  // base directory for hampers
var dbWines="wines"  // base directory for wines
var dbWhiskies="whiskies"  // base directory for whiskies


/*****************************************************************************************
 *
 * FUNCTIONS   Functions used by the databse
 * ---------
 *             This section should not be modified or the database may not work.
 */

function MkName(){__unique_num++;return 'Obj'+__unique_num}
function IncludeScript(name){document.write('<scr'+'ipt src="'+name+'.js"><!--\nError: cannot load script! this page will not display correctly. Try clicking refresh or visit the site again in a few hours if the problem persists.\n//--></scr'+'ipt>')}
function TrimSpaces(v){v=''+v;while(v.substring(0,1)==' ')v=v.substring(1,v.length);while(v.substring(v.length-1,v.length)==' ')v=v.substring(0,v.length-1);return v}
function GetQuery(k,d){return (__Query[k])?__Query[k]:d}

function __NewDatabaseItem(n,p){this.name=''+n;this.price=p*1}

function AddDatabaseItem( category, key, name, price )
{
  // Tidy up input
	category=TrimSpaces(category)
	key=TrimSpaces(key)
	name=TrimSpaces(name)
	price=TrimSpaces(price)*1
	
  // Check key is unique etc.
	if(  (!__DatabaseItems[category])
	  || (!price||isNaN(price))
	  || (!isNaN(key))
	  || (__DatabaseItems[category][key])
	  ) return
	  
  // Check name is unique
	for(var i in __DatabaseItems[category])if(__DatabaseItems[category][i].name.toLowerCase==name.toLowerCase())return

	// Add item to database
	__DatabaseItems[category][key] = new __NewDatabaseItem( name, price )
}

function ParseQuery()
{
	var str=location.search
	if(str.length>1) str=str.substring(1,str.length)
	else return
	var querystrings=str.split('&')
	for(var i in querystrings)
	{
		var temp=querystrings[i].split('=')
		if(temp.length==2) __Query[temp[0]]=temp[1]
	}
}

function NumToPrice(n)
{
	var str
	n*=1
	if(n&&!isNaN(n))
	{
		n=Math.floor(n*100)/100
		str = '£'+n;
		if( str.indexOf('.') < 0 ) str += '.00';
		else while( str.indexOf('.') >= str.length-2 ) str += '0';
	}
	else str = '£P.O.A';
	return str
}

function __CookieFixYear(a){if(a<1000) return a+1900;return a;}
function __CookieName(owner, cat, key){return escape(owner)+'&'+escape(cat)+'&'+escape(key)}

function Set_Cookie( owner, cat, key, val )
{
	var str = escape( __CookieName(owner, cat, key) ) + "=" + escape( val )
	document.cookie = str;
}

function Get_Cookie( owner, cat, key )
{
	var str = "" + document.cookie
	var ca = str.split( "; " )
	var name=__CookieName(owner, cat, key)
	for( var i = 0; i < ca.length; i++ )
	{
		var c = ca[i].split( "=" )
		if( c.length == 2 && name == unescape( c[0] ) ) return unescape(c[1]);
	}
	return null;
}

function Delete_Cookie( owner, cat, key )
{
	var exp = new Date ()
	exp.setYear( __CookieFixYear( exp.getYear() ) - 1 )
	exp = exp.toGMTString();
	var str = escape( __CookieName(owner, cat, key) ) + "=; expires=" + exp;
	document.cookie = str;
}

function __Kill_Cookie( name )
{
	var exp = new Date ()
	exp.setYear( __CookieFixYear( exp.getYear() ) - 1 )
	exp = exp.toGMTString();
	var str = escape( name ) + "=; expires=" + exp;
	document.cookie = str;
}

function Kill_Cookies( owner, cat, key )
{
	var str = "" + document.cookie
	var ca = str.split( "; " )
	for( var i = 0; i < ca.length; i++ )
	{
		var c = ca[i].split( "=" )
		if( c.length == 2 )
		{
			c[0]=unescape( c[0] )
			var cn=c[0].split('&')
			if(owner&&cn.length==3)
			{
				cn[0]=unescape(cn[0])
				cn[1]=unescape(cn[1])
				cn[2]=unescape(cn[2])
				if(key&&cat&&owner==cn[0]&&cat==cn[1]&&key==cn[2]) Delete_Cookie( c[0] )
				else if(cat&&owner==cn[0]&&cat==cn[1]) Delete_Cookie( c[0] )
				else if(owner==cn[0]) __Kill_Cookie( c[0] )
			}
			else __Kill_Cookie( c[0] )
		}
	}
}

function ReadBasketQty(cat,key)
{
	var c=Get_Cookie('Basket',cat,key)*1
	if(c&&!isNaN(c))return c
	return 0
}

function ReadShoppingBasket()
{
	var basket=new Array()
	var str = "" + document.cookie
	var ca = str.split( "; " )
	for( var i = 0; i < ca.length; i++ )
	{
		var c = ca[i].split( "=" )
		if( c.length == 2 )
		{
			var cn=unescape(c[0]).split('&')
			var n=unescape(c[1])*1
			if(cn.length==3&&unescape(cn[0])=='Basket'&&n&&!isNaN(n))
			{
				var cat=unescape(cn[1])
				var key=unescape(cn[2])
				if(basket[cat])basket[cat][key]=n
				else
				{
					basket[cat]=new Array()
					basket[cat][key]=n
				}
			}
		}
	}
	return basket
}

function __WriteBasket(cat,key,n){Set_Cookie('Basket',cat,key,n)}

function Buy(cat,key,n)
{
	
	if(!n||isNaN(n))n=1
	if(!cat||!key||!__DatabaseItems[cat]||!__DatabaseItems[cat][key]){alert('Sorry, you cannot buy that.');return}
	var qty=ReadBasketQty(cat,key)
	__WriteBasket(cat,key,qty+n)
	document.location=document.location
	
}

function Remove(cat,key)
{
	if(!cat||!key||!__DatabaseItems[cat]||!ReadBasketQty(cat,key)){alert('Sorry, you cannot remove that from your basket.');return}
	Delete_Cookie('Basket',cat,key)
	document.location=document.location
}

function ClearBasket()
{
	Kill_Cookies('Basket')
	document.location=document.location
}

function __MenuMap_IEOver(st,l,t,r,b){st.clip="rect("+t+" "+r+" "+b+" "+l+ ")";st.visibility='visible'}
function __MenuMap_NSOver(st,l,t,r,b){st.clip.left=l;st.clip.right=r;st.clip.top=t;st.clip.bottom=b;st.visibility='visible'}
function __MenuMap_Out(st){st.visibility='hidden'}

function MenuMap(typ,x,y,std,ovr,sel)
{
	function _OvrFn(name,l,t,r,b){if(document.all) return '__MenuMap_IEOver(document.all.'+name+'Over.style,'+l+','+t+','+r+','+b+')';else if(document.layers) return '__MenuMap_NSOver(document.'+name+'Holder.document.'+name+'Over,'+l+','+t+','+r+','+b+')';else return ''}
	function _OutFn(name){if(document.all) return '__MenuMap_Out(document.all.'+name+'Over.style)';else if(document.layers) return '__MenuMap_Out(document.'+name+'Holder.document.'+name+'Over)';else return ''}
	this.HTML=function()
	{
		var s=''
		var ovrfn="",outfn=""
		var name=MkName()
		var l=this._links,e=this._edges
		s+='<map name="'+name+'Map">'
		if(this._mode=='h') for(var i=1;i<l.length;i++){s+='<area shape="rect" coords="'+e[i-1]+', 0, '+e[i]+', '+this._height+'" href="'+l[i]+'" onmouseover="'+_OvrFn(name,e[i-1],0,e[i],this._height)+'" onmouseout="'+_OutFn(name)+'">'}
		else for(var i=1;i<l.length;i++){s+='<area shape="rect" coords="0, '+e[i-1]+', '+this._width+', '+e[i]+'" href="'+l[i]+'" onmouseover="'+_OvrFn(name,e[i-1],0,e[i],this._height)+'" onmouseout="'+OutFn(name)+'">'}
		s+='</map>'
		if(document.all||document.layers)
		{
			s+='<style type="text/css">#'+name+'Holder{position:relative;left:0px;top:0px;width:'+this._width+'px;height:'+this._height+'px;}#'+name+'Spacer{position:relative;left:0px;top:0px;width:'+this._width+'px;height:'+this._height+'px;}#'+name+'Normal{position:absolute;left:0px;top:0px;width:'+this._width+'px;height:'+this._height+'px;}#'+name+'Over{position:absolute;left:0px;top:0px;width:'+this._width+'px;height:'+this._height+'px;visibility:hidden}#'+name+'Selected{position:absolute;left:0px;top:0px;width:'+this._width+'px;height:'+this._height+'px;visibility:hidden}</style>'
			s+='<div id="'+name+'Holder"><table border="0" cellspacing="0" cellpadding="0" width="'+this._width+'" height="'+(this._height-19)+'"><tr><td><div id="'+name+'Normal"><img src="'+this._std+'" usemap="#'+name+'Map" width="'+this._width+'" height="'+this._height+'" border="0"></div><div id="'+name+'Over"><img src="'+this._ovr+'" usemap="#'+name+'Map" width="'+this._width+'" height="'+this._height+'" border="0"></div><div id="'+name+'Selected"><img src="'+this._sel+'" width="'+this._width+'" height="'+this._height+'" border="0"></div></td></tr></table></div>'
		}
		else s+='<img src="'+this._std+'" usemap="#'+name+'Map" border="0">'
		return s
	}
	this.Add=function(lnk,size){var l=this._links,e=this._edges;n=l.length;l[n]=''+lnk;e[n]=e[n-1]+(size*1)}
	this.Select=function(n){this._selected=n}
	this._std=std
	this._ovr=ovr
	this._sel=sel
	this._links=new Array()
	this._edges=new Array()
	this._links[0]='#'
	this._edges[0]=0
	this._selected=0
	this._mode=(typ.substring(0,1).toLowerCase()=='v')?'v':'h';
	this._width=x
	this._height=y
}

/*****************************************************************************************
 *
 * GLOBALS   Global variables and non-user constants used for the databse
 * -------
 *           This section should not be modified or the database may not work.
 */

var __unique_num=0
var __Query=new Array()
__DatabaseItems = new Array()
__DatabaseItems[ dbGift ] = new Array()
__DatabaseItems[ dbHamper ] = new Array()
__DatabaseItems[ dbWines ] = new Array()
__DatabaseItems[ dbWhiskies ] = new Array()
var dbCurrentCat=0
var dbCurrentKey=0
ParseQuery()

