/**
 * 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);

			//if (Basket.addProduct) {
			if (Basket.expandBasket) {
				setTimeout('Effect.BlindDown(\'slider\')', 10);
				$('minibasket-close').show();
				Basket.setMinibasketCloseTimer();
				
				//addProduct = false;
				expandBasket = false;
			}
		}
	}
};

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,
	//minibasketOpen: false,
	//minibasketTimeout: 0,
	//minibasketSliderTimer: null,
	//addProduct: false,

	/** 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.addProduct = true;
			//this.minibasketTimeout = 5000;

			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 _this = this;
				var onResponse = function(zajax, json) {
					var add = _this.addMessage(zajax, json);
					document.location.href = '/basket.html';
				}
				var zAjax = new Ajax.Updater(
					false, //{ success: 'minibasket' }
					url + '&js=true', {
						method: 'post',
						parameters: Form.serialize(form),
						evalScripts: true,
						onSuccess: onResponse
					}
				);
				
			}
			//location.hash = "wrapper";
			return true;
			
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	/** expand full minibasket */
	expandMinibasket: function()
	{
		try {
			this.expandBasket = true;
			this.minibasketTimeout = 0;
			
			this.hideMessages();
			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 _this = this;
			var onResponse = function(zajax, json) {
				var add = _this.addMessage(zajax, json);
			}

			var zAjax = new Ajax.Updater(
				{ success: 'minibasket' },
				'/index.php?_event_=a_minibasket&js=true', {
					method: 'get',
					parameters: null,
					evalScripts: true
				});
			location.hash = "wrapper";
			this.minibasketOpen = true;
			return true;
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	closeMinibasket: function()
	{
		try {
			Effect.BlindUp('slider');
			$('minibasket-close').hide();
			this.minibasketOpen = false;
			return true;
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	toggleMinibasket: function()
	{
		try {
			if(this.minibasketOpen) this.closeMinibasket();
			else this.expandMinibasket(); 
			
			return true;
		}
		catch (ex) { if(_debug) throw ex; return false; };
	},

	setMinibasketCloseTimer: function(timeout)
	{
		if(!(timeout > 0)) timeout = this.minibasketTimeout;
		if(timeout > 0) this.minibasketSliderTimer = setTimeout('Basket.closeMinibasket()', timeout);
	},

	clearMinibasketCloseTimer: function()
	{
		if(this.minibasketSliderTimer) clearTimeout(this.minibasketSliderTimer);
	},

	/** 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;
	},

	update: function(id) {
			var form = $('form_'+id);
			var save_item = $('save_item_'+id);
			save_item.checked = true;
			save_item.disabled = false;
			form.submit();
			return true;
	},

	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));
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Compare
 */
var Compare = {

	cmpPage: 'compare_page',
	cmpBox: 'compare_box_top',
	cmpBox2: 'compare_box_bottom',
	waitMsg: null,
	
	/** add product to compare */
	add: function(check, url) {
		try {
			var operation = (check.checked) ? 'add' : 'del';
			url = url.replace(/%s/, operation);
			var zAjax = new Ajax.Updater(
				{	success: this.cmpBox }, 
				url, {
				 	method: 'get', parameters: 'js=true', 
					evalScripts: true
					 });
			var zAjax2 = new Ajax.Updater(
				{	success: this.cmpBox2 }, 
				url, {
				 	method: 'get', parameters: 'js=true', 
					evalScripts: true
					 });
			return true;
		} 
		catch (ex) { if(_debug) throw ex; return false; };
	},
	
	/** remove compared product */
	remove: function(link, sku) {
		try {
			// uncheck checkbox
			if (sku) {
				var chk = $('chk_'+sku+'_cmp');
				if (chk) chk.checked = false;
			} else {
				var data = $A(document.getElementsByTagName('input'));
				data.each( function(chk) {
					if (chk.id.match('chk_[0-9]+_cmp')) {
						chk.checked = false; 
					}
				});
			}
			this.hideColumn('cmptd_'+sku);
			// send zAjax request
			var zAjax = new Ajax.Updater(
				{	success: this.cmpBox }, 
				link.href.replace(/&redir=\S+/, ''),
				{ 	method: 'get', parameters: 'js=true',
					evalScripts: true }
				);
			var zAjax2 = new Ajax.Updater(
				{	success: this.cmpBox2 }, 
				link.href.replace(/&redir=\S+/, ''),
				{ 	method: 'get', parameters: 'js=true',
					evalScripts: true }
				);
			return true;
		} 
		catch (ex) { if(_debug) throw ex; return false; };	
	},
	
	/** hide product compare table column */
	hideColumn: function(className) {
		try {
			var tds = $A(document.getElementsByClassName(className, $(this.cmpPage)));
			tds.each( function(td) { Element.hide(td); });
			return true;
		}
		catch (ex) { if(_debug) throw ex; return false; };
	}

}

/*----------------------------------------------------------------------------------------------------------------------------
 * Login
 */
var Login = {
	show: function(myaccount) {
		if ($('js_myaccount')) {
			$('js_myaccount').value = (myaccount == true);
		}
		var login = $('login');
		if (login.visible()) {
			login.hide();
		} else {
			login.show();
			if (typeof cmCreateConversionEventTag == 'function')
				cmCreateConversionEventTag("Login","1","LoginProcess","10");
		}
		return true;
	},
	hide: function() {
		Element.hide('login');
		return true;
	}
}

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 insertAccessoriesProduct( checkbox, accessory_product_id, action )
{
	var inputs_container = $('product_accesories_to_add_on_services');
	if(inputs_container && IsNumeric(accessory_product_id))
	{
		var inputs = inputs_container.getElementsBySelector('input');
		
		var name = "add[]";
		var value = '1;0;' + accessory_product_id + ';1'; 

		if(action) name = "add_" + action + "[]";
				
		// remove (always)
		for(var i=0; i<inputs.length; i++)
		{
			if(inputs[i].name == name && inputs[i].value == value)
			{
				inputs[i].parentNode.removeChild(inputs[i]);
			}
		}
		
		if(checkbox.checked)
		{
			var new_input = document.createElement('input');
			new_input.type = 'hidden';
			new_input.name = name;
			new_input.value = value;
			inputs_container.appendChild(new_input);
		}
		return true;
	}
	return false;
}

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), 250);
		//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) {
			//$('suggest-container').removeChild(this.data);
			$('suggest-container').innerHTML = '';
			this.data = null;
		}
	},

	// create suggest box
	create: function(data) {
		var ul = document.createElement('ul');
		$(ul).addClassName('suggest-box');
		var i=0;
		var 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 += '</a></li>';//<span>'+item.c+'x</span>
		});
		ul.innerHTML = html;
		this.data = ul;
		this.selected = -1;
		var div = document.createElement('div');
		div.innerHTML = '<div class="suggest-head">Search suggestions</div>';
		div.appendChild(ul);
		$('suggest-container').appendChild(div);
		
		//$(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;
		}
		Search.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) {
			if (workMsg) workMsg.hide();
			onResponse();
			var mailbody = zajax.responseText.match('(?:<body.*?>)((\n|\r|.)*?)(?:<\/body>)');
			$('js_email_detail_'+emailId).innerHTML = mailbody[1];
		}

		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.Request(
				url + '&js=true' , {
					method: 'get',
					onComplete: onResponseShow
			});
		return true;
	}
}

var Inputs = {
	selectAll: function(input) {
		input.select();
	}
}

var Navigation = function() {

	/**
	 * Item of menu object
	 * @param {Element} element
	 * @param {Integer} level
	 * @return {Item}
	 * @private
	 */
	var Item = function(element, level) {

		var element = element;
		var level = level;
		var iframe = iframe;
		var activeClassName = 'mactive'+ level;

		return {
			timeout: null,
			expand: function() {
				if (!element.hasClassName(activeClassName))
					element.addClassName(activeClassName);
				if (typeof iframe == 'object' && !iframe.hasClassName(activeClassName))
					iframe.addClassName(activeClassName);
			},
			collapse: function() {
				element.removeClassName(activeClassName);
				if (typeof iframe == 'object')
					iframe.removeClassName(activeClassName);
			},

			get: function() {
				return element;
			},

			attachIframe: function() {
				this.expand();
				this.left = this.get().getStyle('left');
				this.get().setStyle({left: '-9999px'});
				iframe = new Iframe(this);
			},

			postAttachIframe: function() {
				this.collapse();
				this.get().setStyle({left: this.left});
			}
		}
	}

	/**
	 * cleate iframe object
	 * @param {Item} item
	 * @return {Element}
	 * @private
	 */
	var Iframe = function(item) {
		var parent = item.get().parentNode;

		var iframe = document.createElement('iframe');
		iframe.src="/empty_page.html";

		var dm = {width: item.get().offsetWidth, height: item.get().offsetHeight};

		Element.setStyle(iframe, {
			'position': 'absolute',
			'top': item.get().getStyle('top'), 'left': item.left,
			'width': dm.width+'px', 'height': dm.height+'px'
		});
		item.get().parentNode.appendChild(iframe);
		return iframe;
	}

	/**
	 * list of items
	 * @type {Object}
	 * @private
	 */
	var elements = {};

	/**
	 * counter of next id
	 * @type {Integer}
	 * @private
	 */
	var nextId = 0;

	/**
	 * attach all elements
	 * @private
	 */
	var attachAll = function() {
		$$('#main-navigation ul.mlvl-2').each( function(e) { attachElement(e, 2) });
		$$('#main-navigation ul.mlvl-3').each( function(e) { attachElement(e, 3) });
		$H(elements).each(function(e){ e[1].attachIframe() });
		$H(elements).each(function(e){ e[1].postAttachIframe() });
	}

	/**
	 * attach element
	 * @param {Element} element
	 * @param {Integer} level
	 * @private
	 */
	var attachElement = function(element, level) {
		var id = element.id = getId();
		var parent = element.parentNode;
		Event.observe(parent, 'mouseover', function() { Navigation.expand(id) }, false);
		Event.observe(parent, 'mouseout', function() { Navigation.collapse(id) }, false);
		elements[id] = new Item(element, level);
	}

	/**
	 * get next element id
	 * @return {String}
	 * @private
	 */
	var getId = function() {
		nextId += 1;
		return 'js_navid_'+ nextId;
	}

	return {
		/**
		 * init navigation
		 */
		init: function() {
			if (!$('main-navigation')) return false;
			this.repositionItems();		
			if (!navigator.appVersion.match('MSIE (5.5|6)')) return false;
			attachAll();
		},

		/**
		 * expand hovered item
		 * @param {String} id
		 */
		expand: function(id) {
			var item = elements[id];
			if (item.timeout) window.clearTimeout(item.timeout)
			elements[id].expand();
		},

		/**
		 * collapse item
		 * @param {String} id
		 */
		collapse: function(id) {
			var item = elements[id];
			if (item.timeout) window.clearTimeout(item.timeout)
			item.timeout = window.setTimeout(function() { elements[id].collapse() }, 10);
		},
		
		repositionItems: function()
		{
			var lvl1 = $$('#main-navigation li.ilvl-1');
			var main_size = $('main-navigation').getDimensions();
			for(var i = 0; i < lvl1.length; i++)
			{
				// all items (2 columns)
				var lvl2_width = 587; // lvl2 width, constant, prototype is unable to measure it
				var pos = Position.positionedOffset(lvl1[i]);
				var lvl2 = lvl1[i].getElementsBySelector('ul.mlvl-2');
				if(lvl2.length > 0 && pos[0] > main_size.width - lvl2_width)
				{
				   lvl2[0].setStyle({'left': (main_size.width - lvl2_width - pos[0]) + 'px'});
				}
				// 3 column items
				lvl2_width = 870;
				lvl2 = lvl1[i].getElementsBySelector('ul.mlvl-2.cols3m');
				if(lvl2.length > 0 && pos[0] > main_size.width - lvl2_width)
				{
				   lvl2[0].setStyle({'left': (main_size.width - lvl2_width - pos[0]) + 'px'});
				}
			}
		}
	}
}();

Loader.push(function() { Navigation.init() });

/*----------------------------------------------------------------------------------------------------------------------------
 * 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 && fbrand.value != 0) brand = fbrand.options[fbrand.selectedIndex].text;
		if (fcategory && fcategory.value != 0) category = fcategory.options[fcategory.selectedIndex].text;
		if (fquery && fquery.value == fquery.defaultValue) fquery.value = '';

		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 = {
	/**
	 * init images
	 * @param {Array} images
	 */
	init: function(images) {
		return false;
	},

	/**
	 * show image
	 * @param {Integer} id
	 * @return {Boolean}
	 */
	show: function(image_path, flashURL) {
		var image = null
		try
		{
			image = image_path.match('(^|/)([0-9_]+.jpg)')[2];
		}
		catch(e)
		{
			image = image_path.match('(^|/)([0-9_]+)/[^/]+.jpg')[2] + '.jpg';
		}
		
		Popup.open(flashURL+'&image='+image, {width: 650, height:660});
		return true;
	}
}


/*----------------------------------------------------------------------------------------------------------------------------
 * 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();
				}
			}
			$('js_add_string').value = sink.add_string;
			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);
	}
}


/*----------------------------------------------------------------------------------------------------------------------------
 * Interim pages
 */
var Interim = {};
Interim.Accessories = {
	/**
	 * get more interim accessories
	 * @param {String} url
	 * @param {Integer} id
	 * @return {Boolean}
	 */
	get: function(url, id) {
		if (!this.remove(id)) {
			var result = function(xmlhttp) {
				if(this.waitMsg) this.waitMsg.hide();
				if (xmlhttp.responseText) {
					var html = xmlhttp.responseText;
					new Insertion.After('js_add_after_'+ id, html);
				}
			}

			if(this.waitMsg) this.waitMsg.hide();
			this.waitMsg = new Message('<p>Please wait...</p><img src="images/please_wait.gif" />', { className:'msg_wait'});

			var zajax = new Ajax.Request(
					url + '&js=true' , {
						method: 'post',
						onComplete: result.bind(this)
				});
		}
		return true;
	},

	/**
	 * remove more accessories
	 * @param {Integer} id
	 * @return {Boolean}
	 */
	remove: function(id) {
		// check if more exists and remove it
		var exists = false;
		$$('#accessories li.more_accessories_'+ id).each(
			function(li) {
				li.parentNode.removeChild(li);
				exists = true;
			}
		);
		return exists;
	}
}

/**
 * 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;
		}
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Calendar
 */
var Calendar = {
	buffer: {},

	/** attach calendar on unattached input */
	attach: function(inputId) {
		if (typeof this.buffer[inputId] == 'undefined') {
			this.buffer[inputId] = new Epoch('epoch_popup'+inputId, 'popup' , $(inputId));
		}
		//return true;
	},
	/** show calendar */
	show: function(inputId, toggle) {
		this.attach(inputId);
		this._show(inputId, toggle);
		return true;
	},
	/** show || toggle calendar popup */
	_show: function(inputId, toggle) {
		if (typeof this.buffer[inputId] != 'undefined') {
			if (toggle) {
				this.buffer[inputId].toggle();
			} else {
				this.buffer[inputId].show();
			}
		}
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * TinyMCE holder
 * @author Ondrej Hatala <ondrej@summitmedia.cz>
 */
var EditorHolder = {
	editors: [],

	attach: function(element) {
		if($(element))
		{
			tinyMCE.execCommand('mceAddControl', false, element);
			this.editors.push(element);
		}
	}
}


if(typeof tinyMCE != 'undefined')
{
	tinyMCE.init({
		mode : "none",
		editor_selector : "mceEditor",
		entity_encoding : "raw",
		cleanup : true,
		convert_urls : false,
		theme : "advanced",
		plugins :  "noneditable,pageaddons,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,formatselect,styleselect,separator,cut,copy,paste,pastetext,pasteword",
		theme_advanced_buttons2 : "tablecontrols,separator,image,media,separator,visualchars,nonbreaking,separator,code,separator,hr,removeformat,separator,charmap,separator,link,unlink",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_path_location : "bottom",
		theme_advanced_styles : "Laskys red=mce-laskys-red;Laskys grey=mce-laskys-grey",
		plugin_insertdate_dateFormat : "%Y-%m-%d",
		plugin_insertdate_timeFormat : "%H:%M:%S",
		extended_valid_elements : "hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style|contenteditable]",
		file_browser_callback : "mcFileManager.filebrowserCallBack",
		theme_advanced_resize_horizontal : false,
		theme_advanced_resizing : true,
		nonbreaking_force_tab : true,
		apply_source_formatting : true
	});

	if(typeof mcFileManager != 'undefined'){
		mcFileManager.init({
			relative_urls : true,
			remember_last_path : false
		});
	}

	Loader.push(function() {
		EditorHolder.attach("blog_write_message");
		EditorHolder.attach("blog_write_lead");
	});
}


/*----------------------------------------------------------------------------------------------------------------------------
 * Takes care of ajax file upload
 * @author Ondrej Hatala <ondrej@summitmedia.cz>
 */
var AjaxFileUploader = {
	working: 0,
	check_url: '',
	finished_url: '',
	filename: '',
	iteration: 0,

	startUpload: function(obj,check_url,finished_url) {
		this.check_url = check_url;
		this.finished_url = finished_url;
		this.iteration = 0;

		form = $(obj).form;
		this.filename = $(obj).value.substr($(obj).value.lastIndexOf('\\')+1);
		$(form).submit();

		this._ajaxCheck();
	},

	_ajaxCheck: function() {
		this.iteration += 1;
		new Ajax.Request(this.check_url, {
				method: 'post',
				parameters: 'onclick=iframe_check&filename='+this.filename,
				onComplete	: this.onSuccess.bind(this)
		});
	},

	onSuccess: function(response,json) {
		if(json.ok == 1 || this.iteration >= 20){
			Atom.update(this.finished_url);
		}else{
			this._ajaxCheck();
		}
	}
}

var BlogImages = {

	add: function(what) {
		tinyMCE.execCommand('mceInsertRawHTML',false,what);
	}
}


/*----------------------------------------------------------------------------------------------------------------------------
 * Checkbox
 */
var Checkbox = {

	/** check all checkboxes */
	checkAll: function(state, className, parent) {
		var selector = (parent) ? '#'+parent+' input.'+className : 'input.'+className;
		$$(selector).each( function(e) { e.checked = state; } );
		return true;
	},

	/** check first checkbox in node */
	checkFirst: function(element, parentTag, status) {
		var from;
		var stat = (typeof status == 'undefined') ? true : status;
		if (parentTag) {
			from = Element.findParentByTagName(element, parentTag);
		} else {
			from = element;
		}
		var inpList = $A(from.getElementsByTagName('input'));
		inpList.any( function(ch){
				if (Checkbox._isCheckbox(ch)) {
					ch.checked = stat;
					return true;
				}
			});
		return true;
	},

	/** is any of checkboxes checked */
	isAnyChecked: function(className, parent, silent) {
		var isChecked = false;
		var selector = (parent) ? '#'+parent+' input.'+className : 'input.'+className;
		$$(selector).any( function(e) {
			if(e.checked) {
				isChecked = true;
				return true;
			}
		});

		if (!isChecked && !silent) {
			alert('Please select something first.');
		}
		return isChecked;
	},

	/** checkall and save to session */
	zAjaxCheckAll: function(state, className, parent, params) {
		this.checkAll(state, className, parent);
		var param = '';
		var filter = $(params.filter || 'filter_crm');
		if (filter) {
			var form = Form.serialize(filter);
			if (form) param=form.replace(/_event_=[0-9a-zA-Z_]+(&)?/, '');
		}
		var zAjax = new Ajax.Request(
			params.url+'&js=true', {
			 	method: 'post', parameters: param,
				evalScripts: true
				 });
		return true;
	},

	/** check checkbox and save to session */
	zAjaxCheck: function(element, params) {
		var check = (params.check || 'check');
		var uncheck = (params.uncheck || 'uncheck');
		var action = (element.checked) ? check : uncheck;
		params.url = params.url.replace(/%s/, action);
		var param = '';
		var filter = $(params.filter || 'filter_crm');
		if (filter) {
			var form = Form.serialize(filter);
			if (form) param=form.replace(/_event_=[0-9a-zA-Z_]+(&)?/, '');
		}
		var zAjax = new Ajax.Request(
			params.url+'&js=true', {
			 	method: 'post', parameters: param,
				evalScripts: true
				 });
		return true;
	},

	_isCheckbox: function(input) {
		return (input.type == 'checkbox');
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Freeform composed bundles
 * @author Jan Dvorak <jan.dvorak@summitmedia.cz>
 */

var FreeformBundle = {

	Fetch: function (url)
	{
		var placeHolderId = 'freeform_bundle';
		var fullUrl = '?_event_=z_freeform_bundle&' + url + '&js=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: placeHolderId}, fullUrl, {method: 'get', evalScripts: true}
		);
		return true;
	}

}

/*----------------------------------------------------------------------------------------------------------------------------
 * Tree structure
 * @author Jan Dvorak <jan.dvorak@summitmedia.cz>
 */

var Tree = {

	TriggerSubNodes: function (id)
	{
		var subNodeDiv = $('js_tree_subnodes_'+id);
		if (subNodeDiv) {
			subNodeDiv.style.display = (subNodeDiv.style.display != 'none')
				? subNodeDiv.hide() : subNodeDiv.show();
			return true;
		}
		return false;
	},

	HideAllSubNodes: function (treeId, exceptNodeId)
	{
		var nodes = $$('#'+treeId+' div.blog-tree-subnodes');
		if (nodes) {
			nodes.each(function(itm) {
				if (exceptNodeId == false || !Tree.IsInExceptChain(nodes, exceptNodeId, itm)) {
					itm.hide();
				}
			});
			return true;
		}
		return false;
	},

	IsInExceptChain: function (nodes, endNodeId, currNode)
	{
		// TODO
		//var exceptId = 'js_tree_subnodes_'+endNodeId;
		return false;
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Sending email from static page
 * @author Jan Dvorak <jan.dvorak@summitmedia.cz>
 */

var StaticPageForm = {

	SendEmail: function (placeHolderId)
	{
		var placeHolder = $(placeHolderId);
		if (placeHolder) {
			var fullUrl = '?_event_=z_static_page_form_email&from_url='+escape(window.location.href);

			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: placeHolderId}, fullUrl, {method: 'post', parameters: Form.serialize(placeHolderId), evalScripts: true}
			);
		}
		return false;
	}
}


function IsNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++)
		{
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1)
			{
			IsNumber = false;
		 }
	  }
	return IsNumber;
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Better price form AJAX submit
 * @author jan.tykal@summitmedia.cz
 * @since 14.08.2009
 */

var BetterPriceForm = {
	formId: null,
	resultId: null,

	Submit: function (formId, resultId)
	{
		var form = $(formId);
		if (form)
		{
			this.formId = formId;
			this.resultId = resultId;
			 
			var fullUrl = '/?_event_=z_better_price&js=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: resultId}, fullUrl, {method: 'post', parameters: Form.serialize(formId), evalScripts: true}
			);
			
			document.location.hash = 'better_price';
		}
		return false;
	},
	
	ClearForm: function()
	{
		if(this.formId)
		{
			Form.reset(this.formId);
		}
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Multibuy savings form AJAX submit
 * @author jan.tykal@summitmedia.cz
 * @since 14.08.2009
 */

var MultibuySavings = {
	formId: null,
	resultId: null,

	AddProduct: function (sku, resultId)
	{
		this.resultId = resultId;

		var params = 'multibuysavings[action]=add&multibuysavings[product_sku]=' + sku;		
		var fullUrl = '/?_event_=z_multibuy_savings&js=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: resultId}, fullUrl, {method: 'post', parameters: params, evalScripts: true}
		);

		return false;
	},

	RemoveProduct: function (product_position, resultId)
	{
		this.resultId = resultId;

		var params = 'multibuysavings[action]=remove&multibuysavings[product_position]=' + product_position;
		var fullUrl = '/?_event_=z_multibuy_savings&js=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: resultId}, fullUrl, {method: 'post', parameters: params, evalScripts: true}
		);
			
		return false;
	},

	Save: function (formId, resultId)
	{
		var form = $(formId);
		if (form)
		{
			form.elements['mbfrm_action'].value = 'save';
			this.formId = formId;
			this.resultId = resultId;
			 
			var fullUrl = '/?_event_=z_multibuy_savings&js=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: resultId}, fullUrl, {method: 'post', parameters: Form.serialize(formId), evalScripts: true}
			);
			
		}
		return false;
	},
	
	Submit: function (formId, resultId)
	{
		var form = $(formId);
		if (form)
		{
			form.elements['mbfrm_action'].value = 'submit';
			this.formId = formId;
			this.resultId = resultId;
			 
			var fullUrl = '/?_event_=z_multibuy_savings&js=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: resultId}, fullUrl, {method: 'post', parameters: Form.serialize(formId), evalScripts: true}
			);
			
		}
		return false;
	},
	
	ClearForm: function()
	{
		if(this.formId)
		{
			Form.reset(this.formId);
		}
	},
	
	ScrollToTab: function()
	{
		show_multibuy_savings_tab();
		document.location.hash = 'multibuy_savings';
	}
}

/*----------------------------------------------------------------------------------------------------------------------------
 * Bundles/accessories expander
 * @author jan.tykal@summitmedia.cz
 * @since 29.10.2009
 */

var Expander = {
	lists: null,

	Register: function(list_id, opener_id, closer_id, limit_count)
	{
		if(!this.lists) this.lists = new Array();
		
		var item = {
			name: list_id,
			list: list_id,
			opener: opener_id,
			closer: closer_id, 
			limit: limit_count
		};	
		
		this.lists.push(item);	
		
	},

	Init: function()
	{
		if(this.lists)
		{
			for(var i=0; i<this.lists.length; i++)
			{
				var list = this.lists[i];
				list.list = $(list.list);
				list.opener = $(list.opener);
				list.closer = $(list.closer);
				
				this.Close(list);
			}
		}
	},
	
	Open: function(list)
	{
		if(typeof list == 'string')
		{
			for(var i=0; i<this.lists.length; i++)
			{
				if(this.lists[i].name == list)
				{
					list = this.lists[i];
					break;
				}
			}
		}

		var items = list.list.children;
		var counter = 0;
		if(items)
		{
			for(var i=0; i<items.length; i++)
			{
				$(items[i]).show();
			}
			
			list.opener.hide();
			if(items.length > list.limit)
			{
				list.closer.show();
			}
			else
			{
				list.closer.hide();
			}
		}
	},
	
	Close: function(list)
	{
		if(typeof list == 'string')
		{
			for(var i=0; i<this.lists.length; i++)
			{
				if(this.lists[i].name == list)
				{
					list = this.lists[i];
					break;
				}
			}
		}
	
		var items = list.list.children;
		var counter = 0;
		if(items)
		{
			for(var i=0; i<items.length; i++)
			{
				if(counter < list.limit)
				{
					$(items[i]).show();
				}
				else
				{
					$(items[i]).hide();
				}
				counter++;
			}
			
			list.closer.hide();
			if(items.length > list.limit)
			{
				list.opener.show();
			}
			else
			{
				list.opener.hide();
			}
		}
	}
}

Loader.push(function() { Expander.Init(); });
