/**
 * Frontend JS library
 * $Id$
 */

/*----------------------------------------------------------------------------------------------------------------------------
 * zAjax global handler
 */
var workMsg;
var zAjaxGlobalHandlers = {
	onComplete: function(zajax) {
		if(Ajax.activeRequestCount == 0) {
			if (workMsg) workMsg.hide();
			var json = zajax.evalJSON();
			JsonRes.response(json);
		}
	}
};

Ajax.Responders.register(zAjaxGlobalHandlers);

/*----------------------------------------------------------------------------------------------------------------------------
 * Json responder
 */
var JsonRes = {
	/** response on std json calls */
	response: function (json) {
		if (json) {
			// page refresh
			if (json.refresh == true) {
				document.location.reload();
			}
			// page redirect
			if (json.redirect == true) {
				document.location.href = json.url;
			}
		}
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Basket
 */
var Basket = {

	lastMsg: null,
	waitMsg: null,

	/** change basket count */
	changeCount: function(link, sku) {
	},

	/** add to basket */
	add: function(link) {
		try {

			var form = Element.findParentByTagName(link, 'form');
			var url = form.action;

			this.hideMessages();

			if (form && url) {
				this.x = Mouse.x+5; this.y = Mouse.y-20;
				this.waitMsg = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', {x:this.x, y:this.y, className:'msg_wait'});


				var onResponse = function(zajax, json) {
					var add = this.addMessage(zajax, json);
					if (typeof createITT == 'function') {
						var indexstats = createITT();
						indexstats.DOCUMENTNAME = 'Checkout';
						indexstats.DOCUMENTGROUP = 'Add to Basket';
						indexstats.ACTION='7';
						indexstats.submit_action();
					}
				}.bind(this);

				var zAjax = new Ajax.Updater(
					{ success: 'minibasket' },
					url + '&js=true', {
						method: 'post',
						parameters: Form.serialize(form),
						evalScripts: true,
						onSuccess: onResponse
					 });
			}
			return true;
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	/** show add message */
	addMessage: function(zajax, json) {
		this.hideMessages();
		var status = (json == null) ? 'add' : json.status;
		switch (status) {
			case 'add':
				this.lastMsg = new Message('Item was added to the basket', {timer:4000, x:this.x, y:this.y});
				return 1;
				break;
			case 'remove':
				this.lastMsg = new Message('Item was removed from the basket', {timer:4000, x:this.x, y:this.y});
				return -1;
				break;
			case 'redirect':
				document.location.href = json.url;
				break;
		}
	},

	/** hide old messages */
	hideMessages: function() {
		if(this.lastMsg) this.lastMsg.hide();
		if(this.waitMsg) this.waitMsg.hide();
	},

	showSave: function(id) {
		$$('p.js_quantity').each( function(q) { Element.removeClassName(q, 'focused'); });
		$$('input.btn_save').each( function(q) { q.hide(); });
		Element.addClassName('js_quantity_'+id, 'focused');
		$('js_save_' + id).show();
	},

	remove: function(id) {
		if (confirm('Are you sure?')) {
			var js_remove = $('js_remove_'+id)
			js_remove.name = 'remove_item';
			js_remove.disabled = false;
			js_remove.form.submit();
		}
		return false;
	},

	removeNA: function(id) {
		if (confirm('Are you sure?')) {
			var js_remove = $('js_remove_'+id)
			js_remove.name = 'remove_na_item';
			js_remove.disabled = false;
			js_remove.form.submit();
		}
		return false;
	},

	change: function(event) {
		if(event.keyCode == Event.KEY_RETURN) {
			var target = event.target || event.srcElement;
			var js_save = target.form.js_save;
			js_save.name = 'save_item';
			js_save.disabled = false;
			js_save.form.submit();
			return false;
		}
		return true;
	},

	capture: function(element) {
		Event.observe(element, 'keypress', this.change.bindAsEventListener(this));
		this._onblur = function() {
			Event._stopObserving(element, 'onkeypress', this.change);
			Event._stopObserving(element, 'onblur', this._onblur);
		}
		Event.observe(element, 'onblur', this._onblur.bindAsEventListener(this));
	}

}

/*----------------------------------------------------------------------------------------------------------------------------
 * Login
 */
var Login = {
	show: function(myaccount) {
		if ($('js_myaccount')) {
			$('js_myaccount').value = (myaccount == true);
		}
		Element.toggle('login');
		return true;
	},

	hide: function() {
		Element.hide('login');
		return true;
	},

	selectQuestion: function(element) {
		if (element.value == 99) {
			$('js_answer_label').setStyle({visibility: 'hidden'});
			$('answer').setStyle({visibility: 'hidden'});
			element.blur();
		} else {
			$('js_answer_label').setStyle({visibility: 'visible'});
			$('answer').setStyle({visibility: 'visible'});
			$('answer').focus();
		}
	}
}

var toggle_tree = function(element, id) {
	var img = $('js_img_'+id);
	var stat = img.src.match('arr_right.gif');

	var node_list = $A(document.getElementsByClassName('js_collapse_node', $('browse_tree')));
	node_list.each( function(node) { Element.hide(node); });
	var img_list = $A(document.getElementsByClassName('js_node_arrow', $('browse_tree')));
	img_list.each( function(img) {
		if(img.src.match('arr_down.gif'))
			img.src=img.src.replace(/arr_down.gif/, 'arr_right.gif');
	});
	if (stat) {
		img.src=img.src.replace(/arr_right.gif/, 'arr_down.gif');
		Element.show('js_bs_'+id);
	}
	return true;
}

/* IE login bugfix */
Loader.push(function() { if($('login') && $('login').visible()) { $('login').hide(); $('login').show();} });


/*----------------------------------------------------------------------------------------------------------------------------
 * Tree
 */
var Tree = {
	open: function(nodeId) {
		var li = $('js_node_' + nodeId);
		var img = $('js_image_' + nodeId);

		var stat = (Element.hasClassName(li, 'open'));
		if (stat) {
			Element.replaceClassName(li, 'open', 'collapse');
			img.src = img.src.replace(/minus/, 'plus');
		} else {
			Element.replaceClassName(li, 'collapse', 'open');
			img.src = img.src.replace(/plus/, 'minus');
		}
		return true;
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Accessories
 */
var Accessories = {

	toggle: function(element, group, categoryText) {

		var status = false;
		$$('div.product_list li.js_accesory_item_' + group).each(
			function(li) {
				if (Element.visible(li)) status = true;
				li.toggle();
		});

		this.changeLink(element, status, categoryText);
		return true;
	},

	changeLink: function(element, status, categoryText) {
		var text = 'View ';
		text += (status) ? 'more ' : 'less ';
		text += categoryText;
		text += (status) ? ' &#9660;' : ' &#9650;';
		element.innerHTML = text;
	}
}

function window_resize (e) {
	var box = e.document.getElementById ('popup');
	resizeTo(box.offsetWidth+50,box.offsetHeight+30);
	e.innerHeight = e.document.height+15;
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Suggestion tool
 */
var Suggest = {

	timer: null,
	data: null,
	selected: 0,
	keyword: '',
	position: {},

	// prepare for data
	get: function(keyword, position) {
		this.keyword = keyword;
		this.position = position;
		//if (this.timer) window.clearTimeout(this.timer);
		//this.timer = window.setTimeout(this._get.bind(this), '150');
		this._get();
		return true;
	},

	// get data
	_get: function() {
		if (this.keyword != '') {
			var zajax = new Ajax.Request('?_event_=z_search&search_for='+this.keyword, {
				onComplete: this.response.bind(this)});
		} else {
			this.destroy();
		}
	},

	// reponse
	response: function(z) {
		this.destroy();
		var data = eval(z.responseText);

		if (data.length) {
			this.create(data);
		}
	},

	// destroy suggest data
	destroy: function() {
		if (this.data != null) {
			document.body.removeChild(this.data);
			this.data = null;
		}
	},

/*	// create suggest box
	create: function(data) {
		var ul = document.createElement('ul');
		$(ul).addClassName('suggest-box');
		var i=0, html = '';

		var k = this.keyword;
		data.each(function(item){
			html += '<li onmouseover="Suggest.set('+(i++)+');">';
			html += '<a href="#" title="'+item.p+'" onclick="return !Suggest.go(\''+item.p+'\');">';
			html += item.p.replace(k, '<strong>'+k+'</strong>');
			html += '<span>'+item.c+'x</span></a></li>';
		});
		ul.innerHTML = html;
		this.data = ul;
		this.selected = -1;
		document.body.appendChild(ul);
		//$(ul.firstChild).addClassName('s-selected');
		$(ul).setStyle({left:this.position.left+'px', top:this.position.top+'px'});
		//this.suggest(data[0].p);
	},
*/
	suggest: function(suggest) {
		// todo: if search hand, todo this
		var e = $('i-search-for');
		var start = e.value.split('').length;
		e.value = suggest;
		e.selectionStart = start;
		e.selectionEnd = e.value.split('').length;
	},

	// move selected line
	move: function(step) {
		if (this.data != null) {
			var childs = this.data.childNodes;
			var nextStep = this.selected+step;
			//document.title=nextStep+' = '+this.selected+' + '+step;
			if (nextStep == childs.length) nextStep = 0;
			if (nextStep < 0) nextStep = childs.length-1;
			this.set(nextStep);
		}
	},

	// set selected line
	set: function(step) {
		if (this.data != null) {
			var childs = this.data.childNodes;
			if (this.selected >= 0) {
				$(childs[this.selected]).removeClassName('s-selected');
			}
			if ($(childs[step])) {
				$(childs[step]).addClassName('s-selected');
				this.selected = step;
			}
		}
	},

	// submit search
	go: function(keyword) {
		if (keyword != '') {
			$('i-search-for').value = keyword;
		}
		$('i-search-for').form.submit();
		this.destroy();
		return true;
	},
	_go: function() {
		var keyword = '';
		if (this.data != null && this.selected >= 0) {
			keyword = this.data.childNodes[this.selected].firstChild.title;
		}
		this.go(keyword);
		return true;
	}
}
/*----------------------------------------------------------------------------------------------------------------------------
 * Suggestion tool - input controll
 */

Suggest.Controll = {

	// init suggestion
	onfocus: function() {
		/*
		if (this.value == 'Keyword (or Quickfind Code)') {
			this.value = '';
		}
		*/
		this.setStyle({'background':'#FFFFFF'});
		Event.observe(this, 'keypress', this.actions.bindAsEventListener(this), false);
		Event.observe(this, 'keyup', this.change.bindAsEventListener(this), false);
	},

	// deattach suggestion
	onblur: function() {
		Event._stopObserving(this, 'keypress', this.change);
		Event._stopObserving(this, 'keyup', this.actions);
		window.setTimeout(function() { Suggest.destroy() }, '500');
	},

	// key controll
	actions: function(event) {
		switch (event.keyCode) {
			case Event.KEY_DOWN:
				Suggest.move(1);
				return false;
				break;
			case Event.KEY_UP:
				Suggest.move(-1);
				return false;
				break;
			case Event.KEY_RETURN:
				//Suggest._go();
				Search.submit();
				return false;
				break;
		}
		return true;
	},

	// key controll
	change: function(event) {
		switch (event.keyCode) {
			case Event.KEY_DOWN:
			case Event.KEY_UP:
			case Event.KEY_RETURN:
			case Event.KEY_LEFT:
			case Event.KEY_RIGHT:
				break;
			default:
				var pos = Position.cumulativeOffset(this);
				Suggest.get(this.value, {left:pos[0]+1, top:pos[1]+$(this).getHeight()+1});
				return true;
				break;
		}
		return true;
	}
}
Loader.push(function() { if ($('i-search-for')) { Object.extend($('i-search-for'), Suggest.Controll); $('i-search-for').setAttribute('autocomplete', 'off');} });

/*----------------------------------------------------------------------------------------------------------------------------
 * Select box
 */

/**
 *  select (fake input)
 */
var select_stack = [];
var selectieHackObj = null;
var Select = new Class.create();
Object.extend(Select.prototype, {
	label: null,
	value: null,
	data: null,
	ieHackObj: null,
	options: [],

	/** fake select contructor */
	initialize: function(element, options) {
		Object.extend(this.options, options || {});
		this.label = element.firstChild;
		this.data = document.getElementsByClassName('select-data', element.parentNode).first();
		this.value = $A(element.parentNode.getElementsByTagName('input')).first();
		Form.enable(element.parentNode);

		Object.extend(this.data, new SelectData(this));
		var pos = Position.positionedOffset(element);
		$(this.data).setStyle({left:pos[0]+'px', top:pos[1]+$(element).getHeight()+1+'px'});
		if (document.all) {
			this.styleData();
		}
		this.onclick = this.show;
		/*
		this.onmousedown = function() { $(this.label).setStyle({'background-position': 'bottom right'}); };
		this.onmouseup = function() { $(this.label).setStyle({'background-position': 'top right'}); };
		this.onmouseover = this.onmouseup;
		*/
	},

	/** show select's data */
	show: function() {
		this[($(this.data).visible()) ? 'close':'open']();
	},

	/** open data box */
	open: function() {
		select_stack.each(function(s){s.close();});
		$(this.data).show();
		if (document.all) {
			this.ieHack(this.parentNode);
			$(selectieHackObj).show();
		}
	},

	/** close data box */
	close: function() {
		if (selectieHackObj != null) {
			selectieHackObj.parentNode.removeChild(selectieHackObj);
			selectieHackObj = null;
		}
		$(this.data).hide();
	},

	/** set selectbox value */
	set: function(label, value) {
		this.label.innerHTML = label;
		this.value.value = value;
		if (this.options.onselect) {
			this.options.onselect();
		}
		this.close();
	},

	/** apply styles to select */
	styleData: function() {
		$(this.data).show();
		var height = $(this.data).getHeight();
		$(this.data).hide();
		if (height > 290) $(this.data).setStyle({'height': '290px'});
	},

	/** ie z-index hack */
	ieHack: function(parent) {
			selectieHackObj = document.createElement('iframe');
			selectieHackObj.src="/empty_page.html";
			Element.addClassName(selectieHackObj, 'nonie_hide');
			var dm = $(this.data).getDimensions();
			Element.setStyle(selectieHackObj, {
				position: 'absolute',
				top: this.data.style.top, left: this.data.style.left,
				width: dm.width+'px', height: dm.height+'px'
			});
			Element.hide(selectieHackObj);
			parent.appendChild(selectieHackObj);
	}
});

/**
 *	select data (fake popup)
 */
var SelectData = new Class.create();
Object.extend(SelectData.prototype, {
	timer: null,
	select: null,

	initialize: function(parent) {
		this.select = parent;

		$A(parent.data.getElementsByTagName('A')).each( function(a) {
			Object.extend(a, new Link(parent));
		});
		this.onmouseover = this.clear.bind(this);
		this.onmouseout = this.start.bind(this);
	},

	/** clear hidding */
	clear: function() {
		window.clearTimeout(this.timer);
		//Event._stopObserving(document, 'mouseup', this.select.close);
	},

	/** hide data */
	start: function() {
		this.clear();
		this.timer = window.setTimeout(this.select.close.bind(this.select), '3000');
		//Event.observe(document, 'mouseup', this.select.close.bind(this.select), false);
	}
});

/**
 *  select link (fake popup data row)
 */
var Link = new Class.create();
Object.extend(Link.prototype, {
	select: null,
	initialize: function(parent) {
		this.select = parent;
	},

	/** onclick */
	click: function(value) {

		this.select.set(this.innerHTML, value);
		return true;
	},
	/** hide on mouseover */
	onmouseover: function() {
		this.select.data.clear();
	}
});

/*----------------------------------------------------------------------------------------------------------------------------
 * Shopping Assistant
 */
var waitMsgAssistant = null;
var Assistant = {

	/** init */
	init: function() {
		if (!$('shopping-assistant')) return false;
		try {
			this.form = $('shopping-assistant');
			_js_hide('shopping-assistant');
			$$('#shopping-assistant div.select-box div.select-value').each(
				function(s) {
					Object.extend(s, new Select(s, {onselect: Assistant.show.bind(Assistant)})); select_stack.push(s);
			});
			$$('#shopping-assistant select').each(
				function(s) {
					s.parentNode.removeChild(s);
			});
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	/** show assistant response */
	show: function() {
		try {
			if(waitMsgAssistant) waitMsgAssistant.hide();
			var pos = Position.cumulativeOffset($$('div.box.shopping-assistant').first());
			waitMsgAssistant = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', {x:pos[0]+300, y:pos[1], className:'msg_wait'});

			var zAjax = new Ajax.Request(
					this.form.action+'&js=true', {
					method: 'post', parameters: Form.serialize(this.form),
					evalScripts: true,
					onSuccess: this.complete });
			return true;
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	/** add content or submit */
	complete: function(zajax, json) {
		if(json && json.submit) {
			$('shopping-assistant').submit();
		}	else {
			if(waitMsgAssistant) waitMsgAssistant.hide();
			Element.update('sa_content', zajax.responseText);
			Assistant.init();
		}
	}
}
Loader.push(function() { Assistant.init(); });

/*----------------------------------------------------------------------------------------------------------------------------
 * Orders
 */
var Myaccount = new Object();
Myaccount.Orders = {
	show: function(url, orderId) {
		var onResponse = Response.toggle('js_order_'+orderId, 'tr.js_orders');
		if (!onResponse) return true;

		if (workMsg) workMsg.hide();
		workMsg = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', {x:Mouse.x, y:Mouse.y-15, className:'msg_wait', position:'bottom'});

		var zajax = new Ajax.Updater(
				{ success: 'js_order_detail_'+orderId},
				url + '&js=true' , {
					method: 'get',
					onComplete: onResponse
			});
		return true;
	}
}

Myaccount.Emails = {
	show: function(url, emailId) {
		var onResponse = Response.toggle('js_email_'+emailId, 'tr.js_emails');
		if (!onResponse) return true;

		var onResponseShow = function(zajax) {
			try {
				if (workMsg) workMsg.hide();
				onResponse();
				var mailbody = '';
				if (zajax.responseText.match('<body.*?>')) {
					var mail = zajax.responseText.match(/(?:<body.*?>)((\n|\r|.)*)(?:<\/body>)/);
					if (!mail)
						mail = zajax.responseText.match(/(?:<body.*?>)((\n|\r|.)*)/);
					mailbody = mail[1];
				} else {
					mailbody = zajax.responseText;
				}
				mailbody = mailbody.replace(/<\/body>|<\/html>/g, '');
				$('js_email_detail_'+emailId).innerHTML = mailbody;
			} catch(e) { };
		}

		if (workMsg) workMsg.hide();
		workMsg = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', {x:Mouse.x, y:Mouse.y-15, className:'msg_wait', position:'bottom'});

		//url = 'http://fe.faw.vlach.summitmedia.cz/js/test.html?a=a';

		var zajax = new Ajax.Request(
				url + '&js=true' , {
					method: 'get',
					onComplete: onResponseShow
			});
		return true;
	}
}

var Inputs = {
	selectAll: function(input) {
		input.select();
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Popup-menu
 */
var Menu = new Class.create();
Object.extend(Menu.prototype, {
	hider: null,
	data: null,
	ieHackObj: null,

	initialize: function(element) {
		this.data = $A(element.getElementsByTagName('ul')).first();
		if (this.data) {
			element.onmouseover = this.show;
			element.onmouseout = this.hide;
			if (document.all) {
				this.ieHack();
			}
		}
		$(element).setStyle({'width': $(element).getStyle('width')});

	},
	show: function() {
		window.clearTimeout(this.hider)
		if (this.ieHackObj) $(this.ieHackObj).show();
		$(this.data).show();
	},
	hide: function() {
		this.hider = window.setTimeout(this._hide.bind(this), '20');
	},
	_hide: function() {
		if (this.ieHackObj) $(this.ieHackObj).hide();
		$(this.data).hide();
	},

	ieHack: function() {
			this.ieHackObj = document.createElement('iframe');
			this.ieHackObj.src="/empty_page.html";

			Element.addClassName(this.ieHackObj, 'nonie_hide');
			var dm = $(this.data).getDimensions();
			var pos = Position.positionedOffset(this.data);
			Element.setStyle(this.ieHackObj, {
				'position': 'absolute',
				'top': pos[1]+'px', 'left': pos[0]+'px',
				'width': dm.width+'px', 'height': dm.height+'px'
			});
			Element.hide(this.ieHackObj);
			this.data.parentNode.appendChild(this.ieHackObj);
	}
});
Loader.push(function() {
		if ($('main_nav')) {
		var buttons = $('main_nav').getElementsByTagName('li');
		for(var i=0; i<buttons.length;i++) {
			if(buttons[i].className.match('btn_menu')) {
				Object.extend(buttons[i], new Menu(buttons[i]));} }}});

/*----------------------------------------------------------------------------------------------------------------------------
 * Brands
 *
var Brands = {
	init: function() {
		var brand_list = $$('li.js_brand');
		if(brand_list.length >= 1) {
			if (!this.isExpanded()) {
				this.hide();
				new Insertion.After(brand_list.last(), '<li class="brand_link"><a href="#" onclick="Brands.show(); return !Brands.setLink(this, true);">More brands</li>');
			} else {
				new Insertion.After(brand_list.last(), '<li class="brand_link"><a href="#" onclick="Brands.hide(); return !Brands.setLink(this, false);">Less brands</li>');
			}
		}
	},

	hide: function() {
		$$('li.js_brand').each(function(li){$(li).hide();});
		Cookie.set('js_brands_expand', '0');
	},

	show: function() {
		$$('li.js_brand').each(function(li){$(li).show();});
		Cookie.set('js_brands_expand', '1');
	},

	isExpanded: function() {
		return parseInt(Cookie.get('js_brands_expand'));
	},

	setLink: function(element, expand) {
			element.innerHTML = (expand) ? 'Less Brands' : 'More Brands';
			element.onclick = function() { Brands[(expand)?'hide':'show'](); return !Brands.setLink(element, !expand); };
		return true;
	}

}
Loader.push(function() { Brands.init(); });
*/

/*----------------------------------------------------------------------------------------------------------------------------
 * Shop by brand
 */
var Brand = {
	select: function(brand) {
		var options = document.getElementById('i-search_in2').options;
		for(var i=0; i<options.length; i++) {
			options[i] = null;
		}
		options.length = 0;
		options[0] = new Option('Please wait...', '');

		var zajax = new Ajax.Updater(
			'js_insert_category',
			'?_event_=z_search_kit&brand='+brand, {
				method: 'get',
				onComplete: Brand.onSelect
			});
	},
	onSelect: function() {
		$('i-search_in2').focus();
	}
}

var Search = {
	submit: function() {
		var fbrand = $('i-search_in');
		var fcategory = $('i-search_in2');
		var fquery = $('i-search-for');
		var fake = $('i-search-for_fake');
		var brand = '', category = '', query = [];

		if (fbrand.value != 0) brand = fbrand.options[fbrand.selectedIndex].text;
		if (fcategory.value != 0) category = fcategory.options[fcategory.selectedIndex].text;

		if (category) query.push(category.trim());
		if (brand) query.push(brand.trim());
		if (fquery.value) query.push(fquery.value.trim());
		fake.value = query.join(' ');
		fquery.form.submit();
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Images
 */
/**
 * Image / More images show
 */
var Images = {
	/**
	 * @type {Integer} current image
	 */
	shown: null,

	/**
	 * @type {Array} images list
	 */
	images: [],

	/**
	 * init images
	 * @param {Array} images
	 */
	init: function(images) {
		if (images.length && $('js_images_length')) {
			this.images = images;
			this._setImage(0);
			$('js_images_length').innerHTML = images.length;
			this.ieHack();
		}
	},

	/**
	 * show image
	 * @param {Integer} id
	 * @return {Boolean}
	 */
	show: function(id) {
		if (this._setImage(id)) {
			this.center('image_holder');
			this.center(this.ieHackObj);
			$('image_holder').show();
			$(this.ieHackObj).show();
		}
		return true;
	},

	/**
	 * center image holder on page
	 * @param {Object} element
	 */
	center: function(element) {
		var iebody = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
		var topOffset = document.all? iebody.scrollTop : pageYOffset;
		var divOffset = document.body.parentNode.clientHeight / 2 - 250 - 25;
		$(element).setStyle({'top':divOffset+topOffset+'px'});
	},

	/**
	 * hide image
	 * @return {Boolean}
	 */
	hide: function() {
		$('image_holder').hide();
		$(this.ieHackObj).hide();
		return true;
	},

	/**
	 * next image
	 * @return {Boolean}
	 */
	next: function() {
		if (this.shown+1 >= this.images.length) {
			this._setImage(0);
		} else {
			this._setImage(this.shown+1);
		}
		return true;
	},

	/**
	 * previous image
	 * @return {Boolean}
	 */
	previous: function() {
		if (this.shown == 0) {
			this._setImage(this.images.length-1);
		} else {
			this._setImage(this.shown-1);
		}
		return true;
	},

	/**
	 * set actual image
	 * @param {Integer} id
	 * @return {Boolean}
	 */
	_setImage: function(id) {
		this.shown = id;
		if ((typeof this.images[id] == 'undefined') || !$('js_images_current')) return false;
		$('js_images_current').innerHTML = this.shown+1;
		$('placeholder').src = this.images[id].image;
		return true;
	},

	/**
	 * IE hack (iframe on background)
	 */
	ieHack: function() {
		this.ieHackObj = document.createElement('iframe');
		this.ieHackObj.src = "/empty_page.html";
		var image_holder = $('image_holder');
		Element.addClassName(this.ieHackObj, 'nonie_hide');
		var dm = image_holder.getDimensions();
		var pos = Position.positionedOffset(image_holder);

		Element.setStyle(this.ieHackObj, {
			'position': 'absolute',
			'top': '352px', 'left': '265px',
			'width': dm.width+'px', 'height': dm.height+'px'
		});
		Element.hide(this.ieHackObj);
		image_holder.parentNode.appendChild(this.ieHackObj);
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Sink & Taps
 */

var Sinks = {
	sinks: [],
	current: 0,

	init: function(sinks, current) {
		this.sinks = sinks;
		this.set(0);
	},

	next: function() {
		this.set(this.current+1);
		/* cycling
		if (this.current+1 >= this.sinks.length) {
			this.set(0);
			$('sink_prev').hide();
		} else {
			$('sink_prev').show();
			this.set(this.current+1);
		}
		*/
		return true;
	},

	previous: function() {
		this.set(this.current-1);
		/* cycling
		if (this.current == 0) {
			$('sink_prev').show();
			this.set(this.sinks.length-1);
		} else {
			this.set(this.sinks.length-1);
		}
		*/
		return true;
	},

	set: function(id) {
		var sink = this.sinks[id];
		if (sink) {
			$('sink_title').update(sink.title); // + '<span class="center doblock">  ' + sink.pn + '</span>'
			$('sink_price').update(sink.price);
			$('sink_total').update(sink.total);

			if (sink.save > 0){
				$('sink_save').show();
				$('sink_save_title').show();
				$('sink_save').update(sink.save);
			}
			else {
				$('sink_save').hide();
				$('sink_save_title').hide();
			}
			if ($('sink_image')) $('sink_image').src = sink.image;
			if ($('sink_link')) {
				if (sink.href) {
					$('sink_link').onclick = function() { Popup.open(sink.href); return false;};
					$('sink_detail').onclick = function() { Popup.open(sink.href); return false;};
					$('sink_detail').show();
				} else {
					$('sink_link').onclick = function() { return false; };
					$('sink_detail').onclick = function() { return false; };
					$('sink_detail').hide();
				}
			}
			$('sink_add2basket').href = sink.add2basket;
			$('sink_add2basket').onclick= function() { return !Basket.add(this, sink.id, true); }
			this.current = id;

			var end = (this.current+1 >= this.sinks.length) ? true : false;
			var start = (this.current == 0) ? true : false;

			if ((start && end) || (!start && !end)) {
				$('sink_next').setStyle({'visibility': (end)?'hidden':'visible'});
				$('sink_prev').setStyle({'visibility': (start)?'hidden':'visible'});
			} else {
				$('sink_next').setStyle({'visibility': (!start)?'hidden':'visible'});
				$('sink_prev').setStyle({'visibility': (!end)?'hidden':'visible'});
			}
		}
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Delivery details
 */

var Delivery = {

	detail: function(url) {
		if ($('js_delivery_detail').visible()) {
			return this.close();
		}
		$('js_delivery_detail').show();
		$('i-delivery-postcode').focus();
		return true;
	},

	getDays: function(url) {
		if (workMsg) workMsg.hide();
		workMsg = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', {x:Mouse.x, y:Mouse.y-15, className:'msg_wait', position:'bottom'});

		$('js_delivery_result').hide();
		var params = $('i-delivery-postcode').name + '=' + $F('i-delivery-postcode');
		var zajax = new Ajax.Updater(
				{ success: 'js_delivery_result'},
				url + '&js=true' , {
					method: 'post',
					parameters: params,
					onComplete: this.onResult
			});
		return true;
	},

	onResult: function() {
		$('js_delivery_result').show();
	},

	close: function() {
		$('js_delivery_detail').hide();
		$('i-delivery-postcode').blur();
		return true;
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Services
 */
var Services = {
	data: {},
	pricePattern: 'js_%container%_price',
	checkPattern: 'js_%container%_%id%_check',

	/**
	 * Services
	 * @param {String} container
	 * @param {Object} data
	 */
	init: function(data) {
		Services.data = data;
	},

	/**
	 * check item
	 * @param {String} container
	 * @param {Integer} id
	 * @param {Boolean} status
	 */
	check: function(container, id, status, price, mainPriceId, element) {
		if (status) {
			// waranties exception
			if ((typeof element != 'undefined') && $(element).hasClassName('js_waranty')) {
				Services.uncheckAll(container, id, element);
			} else {
				Services.uncheck(container, id);
			}
		}
		Services.changePrice(container, price, status, mainPriceId);
	},

	/**
	 * change price
	 * @param {String} container
	 * @param {Float} price
	 * @param {Boolean} sign
	 */
	changePrice: function(container, price, sign, mainPriceId) {
		var objectPrice = Services.pricePattern.replace(/%container%/, container);
		Services.updatePrice(objectPrice, price, sign);
		if (mainPriceId) {
			Services.updatePrice(mainPriceId, price, sign);
		}
	},

	/**
	 * update element price
	 * @param {String} id
	 * @param {Float} price
	 * @param {Boolean} sign
	 */
	updatePrice: function(id, price, sign) {
		var item_price = Services.getPrice(id);
		if (sign) {
			item_price += price;
		} else {
			item_price -= price;
		}
		item_price = Services.round(item_price).toString();
		$(id).update('&pound;'+item_price);
	},

	/**
	 * get element price
	 * @param {String} id
	 */
	getPrice: function(id) {
		var e = $(id);
		if (e) {
			return parseFloat(e.innerHTML.match('[0-9]+.?[0-9]*'));
		}
		return 0;
	},

	/**
	 * uncheck grouped items
	 * @param {String} container
	 * @param {Integer} groupId
	 * @param {Integer} excludeId
	 */
	uncheck: function(container, id) {
		var data = Services.data;

		if (data && data[id]) {
			for(var i=0; i<data[id].length; i++) {
				var objectCheck = Services.checkPattern.replace(/%container%/, container);
				objectCheck = Services.checkPattern.replace(/%id%/, data[id][i]);
				var check = $(objectCheck);

				if (check && check.checked) {
					check.checked = false;
					check.onclick();
				}
			}
		}
	},

	/**
	 * uncheck all items (waranties exception)
	 * @param {String} container
	 * @param {Integer} id
	 * @param {Object} objectCheck
	 */
	uncheckAll: function(container, id, objectCheck) {
		var ul = Element.findParentByTagName($(objectCheck), 'ul');
		var checkes = ul.getElementsByTagName('input');

		$A(checkes).each( function(check) {
			if ($(check).hasClassName('js_waranty') && check.checked && (check.id != objectCheck.id)) {
				check.checked = false;
				check.onclick();
			}
		});
	},

	/**
	 * round number
	 * @param {Float} price
	 * @return {Float}
	 */
	round: function(price) {
		return parseFloat(Math.round(price*100)/100).toFixed(2);
	}
}


/*----------------------------------------------------------------------------------------------------------------------------
 * Related products
 */
var CategoryList = {
	data: [],
	shown: false,
	init: function() {
		var related = $('js_category_list');
		this.data = $A(related.getElementsByTagName('li'));
		if (this.data.length > 5) {
			new Insertion.Bottom(related, '<li class="more_categories"><a href="#" onclick="return !CategoryList.toggle();" id="js_more_categories" class="arrowlink">View all sections</a></li>');
			this.hide();
		}
	},

	hide: function() {
		for(var i=5, length=this.data.length; i<length; i++) {
			$(this.data[i]).hide();
		}
		var link = $('js_more_categories');
		if (link) link.update('View all sections');
		this.shown = false;
	},

	show: function() {
		for(var i=5, length=this.data.length; i<length; i++) {
			$(this.data[i]).show();
		}
		var link = $('js_more_categories');
		if (link) link.update('View less sections');
		this.shown = true;
	},

	toggle: function() {
		this[this.shown ? 'hide' : 'show']();
		return true;
	}
}

//Loader.push(function() { if ($('js_category_list')) CategoryList.init(); });

/**
 * Tabs
 */
var Tabs = {
	/**
	 * list of tabs nodes
	 * @type {Object}
	 */
	nodes: {},

	/**
	 * last selected tab
	 * @type {String}
	 */
	history: null,

	/**
	 * search for tabbed elements & add to list
	 * select tab history
	 */
	init: function() {
		var ul = document.getElementsByTagName('ul');
		for (var i=0, length=ul.length; i<length; i++) {
			if (ul[i].className.match('js_tabs')) {
				Tabs.attachLinks(ul[i], ul[i].id);
			}
		}
		if (location.hash) {
			Tabs.loadHistory(location.hash);
		}
		window.setInterval(Tabs.handleHistory, 500);
	},

	/**
	 * handle history hash change
	 */
	handleHistory: function() {
		if (Tabs.history != location.hash) {
			Tabs.loadHistory(location.hash);
		}
	},

	/**
	 * load tab from history hash
	 * @param {Object} hash
	 */
	loadHistory: function(hash) {
		var tab = $('js_tab_'+hash.replace(/#/, ''));
		if (tab && typeof tab != 'undefined') {
			Tabs.openTab(tab);
		}
	},

	/**
	 * attach links on main tabs buttons
	 * @param {Object} ul
	 * @param {Object} parent
	 */
	attachLinks: function(ul, parent) {
		var a = Tabs.getTabLinks(ul);
		Tabs.nodes[parent] = [];
		for (var i=0, length=a.length; i<length; i++) {
			var id = a[i].id, data = $(id+'_data');
			if (data && i!=0) data.hide();
			a[i].onclick = function() { Tabs.openTab(this); return false; };
			Tabs.nodes[parent].push(id);
		}
	},

	/**
	 * get all tab links
	 * @param {Object} ul
	 */
	getTabLinks: function(ul) {
		return ul.getElementsByTagName('a');
	},

	/**
	 * open tab
	 * @param {Object} element
	 */
	openTab: function(element) {
		Tabs.closeAll(element);
		element.parentNode.className += ' active';
		var data = $(element.id+'_data');
		if (data) data.style.display = '';
		var match = element.href.match('(#.*)');
		var hash = (match.length > 1) ? match[1] : false;
		if (!hash || hash=='#') {
			return false;
		}
		Tabs.history = hash;
		return true;
	},

	/**
	 * close all tabs
	 * @param {Object} element
	 */
	closeAll: function(element) {
		var parent = element;
		while (parent.nodeName != 'UL') {
			parent = parent.parentNode;
		}
		var nodes = Tabs.nodes;
		if (nodes && nodes[parent.id]) {
			var links = nodes[parent.id];
			for (var i=0, length=links.length; i<length; i++) {
				var id = links[i];
				var e = $(id);
				if (e && e.parentNode.className.match('active')) {
					e.parentNode.className = e.parentNode.className.replace(/active/, '');
					var tab_data = $(id+'_data');
					if (tab_data) {
						tab_data.style.display = 'none';
						var ul = tab_data.getElementsByTagName('ul');
						for (var i=0, length=ul.length; i<length; i++) {
							if (ul[i].className.match('js_tabs')) {
								this.closeAll(ul[i]);
							}
						}
					}
				}
			}
		}
	}

}
Loader.push(function(){ Tabs.init(); });

/**
 * Product freegift
 */
var Freegift = {
	/**
	 * gifts data
	 * @type {Array}
	 */
	data: [],

	/**
	 * selected gift id
	 * @type {Integer}
	 */
	selected: 0,

	/**
	 * constructor
	 * initialize data and selected second gift
	 * @param {Array} data
	 */
	init: function(data) {
		$A(data).each(function(line) {
			if (typeof line.addstring != 'undefined')
				this.data.push(line);
		}.bind(this));

		$('js_freegift_next').onclick = Freegift.next.bind(this);
		$('js_freegift_prev').onclick = Freegift.prev.bind(this);

		this.set(1);
	},

	/**
	 * show more gifsts dialog
	 */
	show: function() {
		var freegifts = $('js_more_freegifts');
		if (freegifts) {
			freegifts.show();
		}
		return true;
	},

	/**
	 * move to next gift
	 */
	next: function() {
		this.set(this.selected+1);
	},

	/**
	 * move to previous gift
	 */
	prev: function() {
		this.set(this.selected-1);
	},

	/**
	 * show/display prev & next button
	 * @param {Object} id
	 */
	manageButtons: function(id) {
		var next = $('js_freegift_next');
		var prev = $('js_freegift_prev');

		if (id < 1)
			prev.style.visibility = 'hidden';
		else
			prev.style.visibility = '';

		if (id >= this.data.length-1)
			next.style.visibility = 'hidden';
		else
			next.style.visibility = '';
	},

	/**
	 * set actual gift
	 * @param {Object} id
	 */
	set: function(id) {
		var title = $('js_freegift_title');
		var addinput = $('js_freegift_addstring');
		var image = $('js_freegift_image');
		var save = $('js_freegift_save');
		var save_text = $('js_freegift_save_text');
		var was = $('js_freegift_was');

		var display_was = this.data[id].display_was;

		if (title) title.update(this.data[id].name);
		if (save) save.update(this.data[id].save);
		if (was) was.update('RRP '+ this.data[id].was);
		if (addinput) addinput.value = this.data[id].addstring;
		if (image) image.src = this.data[id].image;

		save_text[(display_was=='1')?'show':'hide']();
		was[(display_was=='1')?'show':'hide']();

		this.manageButtons(id);
		this.selected = id;
	}
}

/**
 * Atom updater
 */
var Atom = {
	/**
	 * update atom containers
	 * @param {String} url
	 * @param {String|Object} form
	 */
	update: function(url, forms) {
		this.hideMessage();

		this.waitMsg = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', {x:Mouse.store.x || Mouse.x, y:Mouse.store.y || Mouse.y, className:'msg_wait', ieHack: true});
		var params = [];
		if (typeof forms != 'undefined')
			$A(forms).each( function(form) {
				params.push(Form.serialize(form));
			});

		new Ajax.Request(url, {
				method: 'post',
				parameters: params.join('&'),
				onComplete: this.onUpdate.bind(this)
			});
		return true;
	},

	/**
	 * parse xml data and update containers
	 * @param {XMLHttpRequest} x
	 * @param {Object} json
	 */
	onUpdate: function(x, json) {
		var response = x.responseXML;
		if (response != null) {
			var atoms = $A(response.getElementsByTagName('atom'));
			atoms.each( function(atom) {
				var id = atom.getAttribute('id');
				var container = $(id);
				if (container) {
					var text = [];
					$A(atom.childNodes).each( function(node) { text.push(node.data) });
					container.update(text.join(''));
					_js_hide(container);
					_init_hover(container);
				}
			});
		}
		Atom.hideMessage();
		Mouse.clear();
	},

	hideMessage :function() {
		if ((typeof this.waitMsg != 'undefined') && (this.waitMsg != null)) {
			this.waitMsg.hide();
			this.waitMsg = null;
		}
	}
}
