window.addEvent('domready', function(){
	$('mainnav').set('html', $('m').get('html'));
	$('m').destroy();
	$('mainnav').getElements('li.menu').each(function(elem){
		var list = elem.getElement('ul');
		if (list){
			list.fade('hide');
			list.setStyles({'left': 'auto'});
			elem.addEvents({
				'mouseenter' : function(){list.fade(0.8);},
				'mouseleave' : function(){list.fade('out');}
			});
		}
	});
	var a=document.getElementsByTagName('a');for(i=0; i < a.length;i++){if(a[i].href.indexOf(location.host)==-1 && a[i].href.match(/^http\:\/\//i))a[i].target='_blank';}
	if ($('sp')){
		var stxt = 'Search all products...';
		var sform = new Element('form', {'class':'minisearch','action':base+'search.php','method':'get'});
		var s = new Element('input',{'type':'text','name':'s','value':stxt, events:{
			'focus':function(){if(this.value == stxt) this.value = '';},
			'blur': function(){if(this.value.trim() == '') this.value = stxt;}
		}}).inject(sform);
		sform.addEvent('submit', function(){if(s.value.trim() == '') return false;});
		sform.inject($('sp'));
	}
});

function drawLogin(){
	var e = new Element('div', {'id':'login'});
	var p = new Element('p', {'html':'Registered Customers','style':'text-align:center'}).inject(e);
	var p = new Element('p').inject(e);
	var l = new Element('label', {'html':'username'}).inject(p);
	var un = new Element('input',{'type':'text'}).inject(p);
	if (Cookie.read('run')) un.set('value', Cookie.read('run'));
	var p = new Element('p').inject(e);
	var l = new Element('label', {'html':'password'}).inject(p);
	var pw = new Element('input',{'type':'password'}).inject(p);
	if (Cookie.read('rpw')) pw.set('value', Cookie.read('rpw'));
	var sm = new Element('input',{'type':'button','value':'login »', events:{'click':function(){ if(un.value.trim() != '' && pw.value.trim() != '') login(un.value.trim(),pw.value.trim());}}}).inject(p);
	e.inject($('header'));
	un.addEvent('keydown', function(event){if (event.key == 'enter' && un.value.trim() != '') pw.focus();});
	pw.addEvent('keydown', function(event){if(event.key == 'enter' && un.value.trim() != '' && pw.value.trim() != '') login(un.value.trim(),pw.value.trim());});
}

function login(u,p){
	var h = new Hash({'u': u, 'p': p});
	var jsonRequest = postJSON(base+"login", h.toQueryString(), function(r){
		var myU = Cookie.write('run', u, {path: '/', duration: 256});
		var myP = Cookie.write('rpw', p, {path: '/', duration: 256});
    location.reload(true);
	});
}

function postJSON(myurl, mydata, func){
	var myRequest = new Request({method: 'post', url: myurl,
		onSuccess: function(response){
			var result = $try(function(){return myObject = JSON.decode(response);},function(){ return false;});
			if (result){ func(result);}
			else{errorMSG(response);}
		},
		onFailure: function(response){errorMSG('Error retrieving data from '+myurl);}
	}).send(mydata);
}

function errorMSG(msg){
	var h = new Element('div');
	var p = new Element('p',{'html':'There has been an error:','style':'font-weight:bold;'}).inject(h)
	var e = new Element('p',{'class':'error','text':msg}).inject(h);
	new fbPopup({title: 'Error',width: 500, overlayOpacity: 0.4, offsetTop: -50, data: h});
}

function logout(){
	var agree = confirm('Do you wish to log out?');
	if (!agree) return false;
	var jsonRequest = postJSON(base+"login?logout", false, function(r){
		if (Cookie.read('run')) Cookie.dispose('run', {path: '/'});
		if (Cookie.read('rpw')) Cookie.dispose('rpw', {path: '/'});
    location.reload(true);
	});
}





window.addEvent('domready', function(){
	linkProducts();
});

function linkProducts(){
	$$('div.product').each(function(e){
		var pid = e.id.replace('p_','');
		var img = e.getElement('div.img').getElement('img');
		if (img){img.setStyle('cursor','pointer').addEvent('click',function(){pInfo(pid)});;}
		var h3 = e.getElement('h3');
		var n = new Element('span',{'html':h3.get('html'),events:{'click':function(){pInfo(pid)}}});
		n.inject(h3.empty());
		if (reseller) var a = new Element('div',{'html':'Order','class':'ato',events:{'click':function(){pInfo(pid)}}}).inject(e,'top');
		else var a = new Element('div',{'html':'Info','class':'ato',events:{'click':function(){pInfo(pid)}}}).inject(e,'top');
	});	
}

function pInfo(i){
	postJSON(base+'ascripts/product.php', 'id='+i, function(result){
		var tbl = new Element('table',{'class':'prodtable'});
		var table = new Element('tbody').inject(tbl);
		var tr = new Element('tr').inject(table);
		var td = new Element('td',{'class':'img'}).inject(tr);
		if (result.image)
			var im = new Element('img',{'src':base+'images/products/large/'+result.image+'.jpg','height':result.ih,'width':result.iw}).inject(td);
		else
			var im = new Element('img',{'src':base+'images/products/large/noimage.png','height':149,'width':220}).inject(td);
		var td = new Element('td').inject(tr);
		
		if (reseller) {
			var ac = new Element('div',{'class':'atc'}).inject(td);
			var p = new Element('p').inject(ac);
			if (result.options){
				var s = new Element('span',{'html':'Size:'}).inject(p);
				var mySel = new Element('select').inject(p);
				result.options.each(function(o){ new Element('option',{'value':o,'html':o}).inject(mySel);});
			}
			var s = new Element('span',{'html':'Qty:'}).inject(p);
			var qty = new Element('input',{'type':'text'}).inject(p);
			var btn = new Element('input',{'type':'button','value':'Add',events:{'click':function(){
				if (!(/^\d*$/.test(qty.value)) || qty.value.trim() == '') {qty.select(); return false;}
				var pData = new Hash();
				pData.extend({'i':i});
				if (result.options) pData.extend({'o':mySel.value});
				pData.extend({'q':qty.value.trim()});
				postJSON(base+'ascripts/atc.php', pData.toQueryString(), function(answer){
					var m = answer.m;
					atcConfirm(m);
					showCartIcon(1);
					prod.destruct();
				});
			}}}).inject(p);
		}
		var t = new Element('h2',{'html': result.t}).inject(td);		
		var de = new Element('p',{'html':result.d}).inject(td);
		
		if (!reseller && result.options){
			var s = result.options.join(', ');
			var reg = new RegExp(/(\d)(\s+)(\w)/g);
			var nstr = s.replace(reg, '$1$3');
			var p = new Element('p',{'html':'<label>Available In:</label>'+nstr}).inject(td);
		}		
		if (result.pdf_info){
			var p = new Element('p',{'html':'<label>Info Sheet:</label>'}).inject(td);
			var d = new Element('a',{'html':'Download PDF','href':base+'product_info/'+result.pdf_info}).inject(p);
		}
		if (result.pdf_msds){
			var p = new Element('p',{'html':'<label>MSDS Sheet:</label>'}).inject(td);
			var d = new Element('a',{'html':'Download PDF','href':base+'msds/'+result.pdf_msds}).inject(p);
		}
		var p = new Element('p', {'style':'text-align:center;margin-top: 20px;'}).inject(td);
		var enq = new Element('input',{'type':'button','value':'Enquire about product',events:{
			'click': function(){
				var u = encodeURI(result.t);
				location.href=base+'contact?subject='+u+'#tof';
			}
		}}).inject(p);
		prod = new fbPopup({title: result.t,width: 640, overlayOpacity: 0.4, offsetTop: -50, data: tbl});
	});
}




/* Extra Libs */
var fbPopup = new Class({
	Implements: [Options, Events],
	options: {
		title: 'no title',
		width: 450,
		height: false,
		overlay: true,
		overlayEscapes: true,
		overlayOpacity: 0.6,
		closeButton: true,
		closeButtonText: 'Close',
		allowEscape: true,
		allowFade: true,
		offsetTop: 0,
		data: new Element('div')
	},
	initialize: function(options){
		this.setOptions(options);
		this.escapeModal = function(e) { if(e.key == 'esc') { this.destruct(); } }.bind(this);
		this.closeModal = function() { this.destruct();}.bind(this);
		this.drawPopup();
	},
	drawPopup: function(){
		if(this.options.overlay) this.createOverlay();
		this.popup();
	},
	createOverlay: function(){
		this.overlay = new Element('div').setProperty('class', 'fboverlay').injectInside(document.body);
		this.overlay.setStyles({opacity: this.options.overlayOpacity});
	},
	getScrollbarWidth: function(){
		if (!Browser.Engine.webkit) return 0;
		document.body.style.overflow = 'hidden';
		var width = document.body.clientWidth;
		document.body.style.overflow = 'scroll';
		width -= document.body.clientWidth;
		if(!width) width = document.body.offsetWidth-document.body.clientWidth;
		document.body.style.overflow = '';
		return width;
	},
	positionEls: function(){
		if(this.overlay) {
			this.overlay.setStyles({top: Window.getScrollTop()+'px', height: Window.getHeight()+'px', width: (Window.getWidth() + Window.getScrollLeft()-this.getScrollbarWidth())+'px'});
		}
		var fbpopupHeight = this.infobox.getHeight() / 2;
		var totop = (window.getSize().y / 2)  + this.options.offsetTop + window.getScrollTop() - fbpopupHeight;
		if (totop < 0) totop = 0;
		var toleft = (window.getSize().x / 2) - (this.options.width /2);
		if (toleft < 0) toleft = 0;
		this.infobox.setStyles({top: totop+'px', left: toleft + 'px'});
	},
	popup: function (){
		this.infobox = new Element('table').setProperty('class', 'fbtable');
		if(this.options.allowFade) {
			this.infobox.setStyles({'opacity': 0, 'visibility': 'hidden'});
		}
		this.infobox.injectInside(document.body);
		this.infobox.setStyle('width', this.options.width+'px');
		var tbody = new Element('tbody').injectInside(this.infobox);
		var trow = new Element('tr').injectInside(tbody);
		var tl = new Element('td').setProperty('class', 'fbtl').injectInside(trow);
		var tm = new Element('td').setProperty('class', 'fbtm').injectInside(trow);
		var tr = new Element('td').setProperty('class', 'fbtr').injectInside(trow);
		var trow = new Element('tr').injectInside(tbody);
		var ml = new Element('td').setProperty('class', 'fbm').injectInside(trow);
		this.m = new Element('td').setProperty('class', 'fbcontent').injectInside(trow);
		var mr = new Element('td').setProperty('class', 'fbm').injectInside(trow);
		var trow = new Element('tr').injectInside(tbody);
		var bl = new Element('td').setProperty('class', 'fbbl').injectInside(trow);
		var bm = new Element('td').setProperty('class', 'fbbm').injectInside(trow);
		var br = new Element('td').setProperty('class', 'fbbr').injectInside(trow);
		if (this.options.title) var title = new Element('h2', {'html': this.options.title, 'class': 'fbtitle'}).inject(this.m);
		this.content = new Element('div').injectInside(this.m);
		if (this.options.height) this.content.setStyles({
			'height': this.options.height+'px',
			'overflow-y': 'auto'
		});
		var dataType = typeof (this.options.data);
		if (dataType == 'object'){
			this.options.data.inject(this.content);
		} else { this.content.set('html', this.options.data);}
		if (this.options.closeButton) {
			var closeDiv = new Element('div', {'class':'statusbar'}).inject(this.m);
			this.close = new Element('input', {'type':'button','class':'button', 'value':this.options.closeButtonText, events: {
				'click': this.destruct.bind(this)
			}}).inject(closeDiv);
		}
		this.positionEls();
		if(this.options.allowFade)  {
			var myFx = new Fx.Tween(this.infobox);
			myFx.start('opacity', '0', 1);
		}
		if(this.options.allowEscape)  document.addEvent('keydown',this.escapeModal);
		this.centerItems = function(){	this.positionEls();}.bind(this)
		window.addEvents({ 
			'resize': this.centerItems,
			'scroll': this.centerItems
		});
		if (this.options.overlay && this.options.overlayEscapes) this.overlay.addEvent('click', this.closeModal);
	},
	destruct: function(){
		if(this.options.allowEscape) document.removeEvent('keydown', this.escapeModal);
		window.removeEvent('resize', this.centerItems);
		window.removeEvent('scroll', this.centerItems);
		if (this.overlay) this.overlay.destroy();
		if(this.options.allowFade) {
			new Fx.Tween(this.infobox).start('opacity',0).chain(
				function(){ this.infobox.destroy(); }.bind(this)
			);
		} else this.infobox.destroy();
	}
});
