/*
 * Doco-International
 * (c) 2010 Omines - www.omines.nl - All rights reserved
 */

function Debug(msg)
{
	if (window.console && console.log)
		console.log(msg);
}
var Site = {
	start: function()
	{
		$$('.billboard').each(function(el) { new Billboard(el); });
		if ($('faqlist'))
			FaqList.initialize();
		LightBox.initialize();
		if ($('widget-search'))
		{
			var i = $('widget-search').getElements('.submit')[0];
			var e = new Element('a').set({href:'/search/search.html', title:i.get('title'), 'class':'submit'});
			e.addEvent('click', function(){$('widget-search').submit();}).inject(i, 'after');
			i.dispose();
		}
		if ($('product-found-display'))
		{
			$('product-found-display').setStyle('cursor','pointer');
			$('product-found-display').addEvent('click', function(){
				window.location	= $('product-found-display').getFirst('a').get('href');
			});
		}
		$('language-selected').addEvent('hover', function(){ $('language-options').addClass('active'); });
		$('language-selected').getParent().addEvent('mouseleave', function(){ $('language-options').removeClass('active'); });
	},
	initHomepage: function()
	{
	}
};
var FaqList = {
	initialize: function()
	{
		$$('.question.list a').each(function(a){
			var ac			= a.getNext('.answer');
			if (!ac) return;
			var acHeight	= ac.measure(function(){ var t = this.getSize(); return t.y + 24; });
			ac.store('origHeight', acHeight+'px');
			ac.set('tween', {
				'duration':500,
				'onComplete': function(){ if (this.subject.hasClass('opened')) { this.subject.setStyle('height', this.subject.retrieve('origHeight')); } }
			});
			a.addEvent('click', function(){
				var ac	= this.getNext('.answer');
				if (!ac) return;
				ac.toggleClass('opened');
				if (!ac.hasClass('opened'))
					ac.tween('height', '0px');
				else
					ac.setStyle('height', '0px').tween('height', ac.retrieve('origHeight'));
				return false;
			});
		}.bind(this));
	}
};
var Billboard = new Class({
	initialize: function(root)
	{
		this.root = root;
		this.sheets = root.getElements('.sheet');
		this.pager = root.getElement('.pager');
		this.count = this.sheets.length;
		this.active = 0;
		if(this.count < 2) return;
		this.sheets.each(function(el, idx) {
			var page = new Element('a').set('text', idx+1).set('href', '#sheet');
			page.addEvent('click', function(e) {
				e.stop();
				$clear(this.autonext);
				this.autonext = this.goNext.periodical(6500, this);
				if(idx != this.active) this.morphTo(idx);
			}.bindWithEvent(this));
			page.inject(this.pager);
			if(idx > 1) el.setStyle('visibility','hidden');
			el.hover = el.getElement('.sheethover').set('morph', {duration:1500,link:'chain',transition:Fx.Transitions.Sine.easeOut});
			el.content = el.getElement('.sheetcontent').set('morph', {duration:1500,link:'chain',transition:Fx.Transitions.Sine.easeOut});
			el.content.setStyle('top',0);
		}.bind(this));
		this.sheets[0].inject(this.root);
		this.pager.getElement('a').addClass('active');
		this.autonext = this.goNext.periodical(5000, this);
		this.root.addEvent('click', function(){ window.location = this.sheets[this.active].getElement('.sheetcontent a').get('href'); }.bind(this));
		Debug('Billboard loaded');
	},
	unblock: function()
	{
		this.running = false;
	},
	goNext: function()
	{
		this.morphTo((this.active + 1) % this.count);
	},
	morphTo: function(to)
	{
		if(this.running) return; 
		this.running = true;
		this.sheets.each(function(el, idx) { el.setStyle('z-index',0); }.bind(this));
		var from = this.sheets[this.active];
		this.active = to;
		to = this.sheets[to];
		from.setStyle('z-index',2);
		to.setStyle('z-index',1);
		to.hover.setStyles({'opacity':0.85,'left':'','right':''});
		to.content.setStyles({'opacity':1,'top':0});
		if(from.hover.hasClass('right'))
			from.hover.morph({'opacity':0,'right':15});
		else
			from.hover.morph({'opacity':0,'left':15});	
		from.content.morph({'opacity':0,'top':-15});
		this.unblock.delay(1000, this);
		this.pager.getElements('a').each(function(el, idx) {
			if(idx == this.active) el.addClass('active'); else el.removeClass('active');
		}.bind(this));
	}
});

var LightBox = {
	initialize: function()
	{
		this.lbLinks	= $$('a.lightbox') || [];
		if (this.lbLinks.length == 0)
			return;
		this.defaultStyles	= {'display':'none', 'opacity':0};
		this.overlay		= new Element('div', {'id':'lb-overlay','tween':{'duration':300}}).setStyles(this.defaultStyles).inject(document.body, 'bottom');
		this.container		= new Element('div', {'id':'lb-container','tween':{'duration':400}}).setStyles(this.defaultStyles).inject(document.body, 'bottom');
		this.closer			= new Element('img', {'id':'lb-close','src':'/static/images/cross.png','alt':'[X]'}).inject(this.container);
		this.image			= new Element('img', {'src':'/static/images/menu-doco-logo.png', 'alt':''}).inject(this.container);
		this.title			= new Element('h4', {'text':'Doco International'}).inject(this.container);

		this.closer.addEvent('click', function(){this.closeLightBox();}.bind(this));
		this.overlay.addEvent('click', function(){this.closeLightBox();}.bind(this));
		$$('a.lightbox').each(function(e){
			e.addEvent('click', function(){this.showLightBox(e);return false;}.bind(this));
		}.bind(this));
	},
	closeLightBox: function()
	{
		this.overlay.setStyles(this.defaultStyles);
		this.container.setStyles(this.defaultStyles);
	},
	showLightBox: function(e)
	{
		this.overlay.setStyle('display','block').tween('opacity', 0.6);
		this.container.setStyle('display','block').tween('opacity', 1);
		this.image.set({'src': e.get('href'), 'alt':e.get('title')});
		this.title.set('text', e.get('title'));
		if ($('fullImage'))
		{
			var di = $('fullImage').setStyle('display','').getSize();
			$('fullImage').setStyle('display','none');
			this.image.setStyles({'height': di.y+'px','width': di.x+'px'});
		}
		var dw = window.getSize();
		var dc = this.container.getSize();
		this.container.setStyle('left', ((dc.x / (dw.x / 100)) / 2).round()+'%');
	}
};

var Shop = {
	urlBase: '',
	start: function()
	{
		this.urlBase	= urlBase;
		if (document.id('shop-login-processing'))
		{
			console.log('Starting post-login');
			this.postLogin();
		}
		if ($('product-detail'))
			AddToCart.initialize();
		$$('.addCart').each(function(a){
			if (a.hasClass('hidden'))
				a.removeClass('hidden');
			a.addEvent('click', function(){
				var pData	= JSON.decode(a.getProperty('data-obj'));
				AddToCart.show(pData.id, pData.code, pData.name, pData.desc);
				return false;
			}.bind(this));
		}.bind(this));

		['invoice-address-select', 'delivery-address-select'].each(function(parentId){
			if (document.id(parentId))
			{
				document.id(parentId).getElements('input[type="radio"]').each(function(input){
					if (!input.checked) input.getParent('label').removeClass('active');
					input.addEvent('change', function(){
						input.getParent('label').getSiblings('label').each(function(label){ label.removeClass('active'); });
						input.getParent('label').toggleClass('active');
					});
				});
			}
		});
	},
	postLogin: function()
	{
		if (typeof postLoginRedirect == 'undefined')
			var postLoginRedirect = this.urlBase+'shop/account';
		console.log('Performing check');
		var req	= new Request.JSON({
			method: 'get',
			onComplete: function() {
				$('processing-wait').setStyle('display', 'none');
			},
			onFailure: function(xhr) {
				$('processing-failure').setStyle('display', 'block');
				this.redirect.delay(3000, this, [postLoginRedirect]);
			}.bind(this),
			onSuccess: function(result) {
				$('processing-success').setStyle('display', 'block');
				this.redirect.delay(3000, this, [postLoginRedirect]);
			}.bind(this)
		}).send('update=1');
	},
	redirect: function(url)
	{
		window.location.href	= url;
	}
};

var DIALOGUE_TYPE_NONE		= 0;
var DIALOGUE_TYPE_ALERT		= 1;
var DIALOGUE_TYPE_CONFIRM	= 2;
var Dialogue = new Class({
	Implements: [Options, Events],
	options: {
		'cssId': 'ui-dialogue',
		'cssClass': 'ui-dialogue',
		'title': 'Dialogue',
		'dialogueType': DIALOGUE_TYPE_ALERT,
		'dialogueBlock': true
	},
	locale: {
		buttonConfirm: 'OK',
		buttonCancel: 'Cancel'
	},
	initialize: function(options)
	{
		this.setOptions(options);
		if (this.options.dialogueBlock === true)
			this.dialogueOverlay	= new Element('div', {'id':this.options.cssId, 'class':this.options.cssClass+'-overlay'}).inject($(document.body), 'bottom');
		this.dialogueContainer	= new Element('div', {'id':this.options.cssId, 'class':this.options.cssClass}).inject($(document.body), 'bottom');
		this.dialogueContainer.set('morph', {duration: 250, transition: Fx.Transitions.Sine.easeOut});
		this.dialogueContent	= new Element('div', {'class':this.options.cssClass + '-content'}).inject(this.dialogueContainer);
		this.dialogueTitle		= new Element('h3', {'text':this.options.title}).inject(this.dialogueContent);
		this.dialogueFooter		= new Element('div', {'class':this.options.cssClass + '-footer'}).inject(this.dialogueContent);
		this.buttonConfirm		= false;
	},
	position: function()
	{
		var db	= $(document.body).getDimensions();
		var dp	= this.dialogueContainer.setStyles({'display':'block', 'top':'50%'}).getDimensions();
		this.dialogueContainer.setStyles({
			'left': ((db.x / 2) - (dp.x / 2)).toInt(),
			'top': this.dialogueContainer.offsetTop.toInt() - (dp.y / 2).toInt()
		});
	},
	hide: function()
	{
		this.dialogueContainer.setStyle('display','none');
		if (this.options.dialogueBlock === true)
			this.hideOverlay();
	},
	show: function()
	{
		if (this.options.dialogueBlock === true)
			this.showOverlay();

		/** Adding buttons when showing the form, to allow localized text and events to be added **/
		if (!this.buttonConfirm && this.options.dialogueType != DIALOGUE_TYPE_NONE)
		{
			this.buttonConfirm	= new Element('a', {
				'id':this.options.cssId + '-confirm',
				'class':this.options.cssClass + '-button '+ this.options.cssClass + '-confirm',
				'href':'#confirm',
				'text':this.locale.buttonConfirm
			}).inject(this.dialogueFooter).addEvent('click', function(){ this.fireEvent('confirm'); }.bind(this));
			switch (this.options.dialogueType)
			{
				case DIALOGUE_TYPE_CONFIRM:
					this.buttonCancel	= new Element('a', {
						'id':this.options.cssId + '-cancel',
						'class':this.options.cssClass + '-button '+ this.options.cssClass + '-cancel',
						'href':'#cancel',
						'text':this.locale.buttonCancel
					}).inject(this.dialogueFooter).addEvent('click', function(){ this.fireEvent('cancel'); }.bind(this));
					break;
			}
		}

		this.position();
		this.dialogueContainer.setStyles({
			'display': 'block',
			'opacity': 0
		}).morph({'opacity':1});
	},
	hideOverlay: function()
	{
		if (this.options.dialogueBlock !== true)
			return;
		this.dialogueOverlay.setStyle('display','none');
	},
	showOverlay: function()
	{
		if (this.options.dialogueBlock !== true)
			return;
		var h	= Math.max(
			Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
			Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
			Math.max(document.body.clientHeight, document.documentElement.clientHeight)
   		);
		this.dialogueOverlay.setStyles({
			'display': 'block',
			'height': h
		});
	},
	populateContent: function (element)
	{
		element.inject(this.dialogueFooter, 'before');
	}
});

var AddToCart = {
	initialized: false,
	initialize: function()
	{
		if (this.initialized)
			return;
		this.popup				= new Dialogue({
			'cssId':'add-cart-container',
			'title':localeSet['shop-add-cart-dialogue-title'],
			'dialogueType': DIALOGUE_TYPE_CONFIRM
		});
		this.popupConfirm		= this.confirm.bind(this);
		this.popupCancel		= this.cancel.bind(this);
		this.popup.addEvent('confirm', this.popupConfirm);
		this.popup.addEvent('cancel', this.popupCancel);

		this.form				= new Element('form', {'method':'post', 'action':urlBase+'shop/cart'});
		this.form.addEvent('submit', function(){ this.popup.fireEvent('confirm'); }.bind(this));
		new Element('input', {'type':'hidden', 'name':'cart-action', 'value':'addProduct'}).inject(this.form);
		new Element('input', {'type':'hidden', 'name':'json', 'value':1}).inject(this.form);
		this.productIdField		= new Element('input', {'type':'hidden', 'id':'add-cart-pid', 'name':'add-cart-pid', 'value':0}).inject(this.form);
		var fieldList			= new Element('ul').inject(this.form);
		var li					= new Element('li').inject(fieldList);
		var label				= new Element('label', {'for':'add-cart-code', 'text':localeSet['shop-add-cart-label-code']}).inject(li);
		this.productCodeField	= new Element('div', {'id':'add-cart-code', 'text':'-'}).inject(li);
		li						= new Element('li').inject(fieldList);
		label					= new Element('label', {'for':'add-cart-name', 'text':localeSet['shop-add-cart-label-name']}).inject(li);
		this.productNameField	= new Element('div', {'id':'add-cart-name', 'text':'-'}).inject(li);
		li						= new Element('li').inject(fieldList);
		label					= new Element('label', {'text':localeSet['shop-add-cart-label-desc']}).inject(li);
		this.productDescField	= new Element('div', {'id':'add-cart-desc'}).inject(li);
		li						= new Element('li').inject(fieldList);
		label					= new Element('label', {'for':'add-cart-amount', 'text':localeSet['shop-add-cart-label-amount']}).inject(li);
		this.productAmountField	= new Element('input', {'type':'text', 'id':'add-cart-amount', 'name':'add-cart-amount', 'value':1}).inject(li);

		this.popup.populateContent(this.form);
		this.initialized	= true;
	},
	show: function(id, code, name, desc)
	{
		this.popup.show();
		this.productIdField.set('value', id);
		this.productCodeField.set('html', code);
		this.productNameField.set('html', name);
		this.productDescField.set('html', desc);
		this.popup.position();
	},
	confirm: function()
	{
		this.request	= new Request.JSON({
			data: this.form,
			url: this.form.get('action'),
			method: 'post',
			onComplete: function() {
				Shop.redirect(Shop.urlBase+'shop/cart');
				this.popup.hide();
			}.bind(this)
		}).send();
	},
	cancel: function()
	{
		this.popup.hide();
	}
};

if (!urlBase || !urlbase)
{
	var urlBase	= window.location.pathname.substring(0, 4);
	var urlbase	= window.location.pathname.substring(0, 4);
}


// Set event to start running active content when DOM is loaded
window.addEvent('domready', function() {
	Site.start();
	Shop.start();
});

