jQuery(document).ready(function() {
	jQuery('.button').hover(function() {
		jQuery(this).addClass('over');
	}, function() {
		jQuery(this).removeClass('over');
	}).mousedown(function() {
		jQuery(this).addClass('click');
	});
	jQuery('body').mouseup(function() {
		jQuery('.button').removeClass('click');
	});

	// Navigation
	jQuery('#nav li').hover(function() {
		jQuery(this).find('div').slideDown(0);
	}, function() {
		jQuery(this).find('div').slideUp(0);
	});

	// CustomSelect
	var html = '<ul>';
	jQuery('.customSelect').wrap('<div class="customSelectDiv" />').find('option').each(function() {
		if(jQuery(this).is(':selected')) {
			html += '<li class="selected '+jQuery(this).attr('class')+'">'+jQuery(this).text()+'</li>';	
		} else {
			html += '<li class="'+jQuery(this).attr('class')+'">'+jQuery(this).text()+'</li>';	
		}
	});
	html += '</ul>';
	html += '<div class="arrow"></div>';
	jQuery('.customSelectDiv').append(html);

	var defaultHeight = new Array();
	var iterate       = 1;
	var big           = false;
	var animationTime = 300;
	jQuery('.customSelectDiv ul').each(function() {
		var selected = jQuery(this).find('li.selected');
		if(selected.length == 0) {
			selected = jQuery(this).find('li:first').addClass('selected');
		}
		var marginTop = selected.position().top;
		var height    = selected.height() + parseInt(selected.css('padding-top').match(/[-0-9]+/)) + parseInt(selected.css('padding-bottom').match(/[-0-9]+/));
		defaultHeight[iterate] = jQuery(this).parent().attr('id', 'customSelectDiv-'+iterate).height();
		jQuery(this).css('margin-top', -marginTop).parent().css('height', height);

		jQuery(this).parent().find('.arrow').click(function() { 
			jQuery(this).parent().find('li.selected').click();
		});
		
		iterate++;
	}).click(function() {
		if(!big) {
			var id = parseInt(jQuery(this).parent().attr('id').match(/[0-9]+/));
			jQuery(this).animate({'margin-top': 0}, animationTime).parent().animate({'height': defaultHeight[id]}, animationTime);
			big = true;
		}
	});

	jQuery('.customSelectDiv ul li').click(function(e) {
		if(big) {
			var lastId    = parseInt(jQuery(this).parent().find('li.selected').attr('class').match(/[0-9]+/));
			var currentId = parseInt(jQuery(this).attr('class').match(/[0-9]+/));
			jQuery('.customSelectDiv ul li').removeClass('selected');
			jQuery(this).addClass('selected');
			var sel = false;
			var marginTop = 0;
			var i = 1;
			jQuery(this).parent().find('li').each(function() {
				if(!sel) {
					if(jQuery(this).is('.selected')) {
						sel = true;
					} else {
						marginTop += jQuery(this).height() +
						            parseInt(jQuery(this).css('padding-top').match(/[-0-9]+/)) +
						            parseInt(jQuery(this).css('padding-bottom').match(/[-0-9]+/)) +
						            parseInt(jQuery(this).css('margin-top').match(/[-0-9]+/)) +
						            parseInt(jQuery(this).css('margin-bottom').match(/[-0-9]+/));
						i++;
					}
				}
			});
			var height = jQuery(this).height() + parseInt(jQuery(this).css('padding-top').match(/[-0-9]+/)) + parseInt(jQuery(this).css('padding-bottom').match(/[-0-9]+/));
			jQuery(this).parent().animate({'margin-top': -marginTop}, animationTime).parent().animate({'height': height}, animationTime);
			jQuery(this).parent().parent().find('option').attr('selected', '');
			jQuery(this).parent().parent().find('option.item-'+i).attr('selected', 'selected');
			big = false;
			if(currentId != lastId) {
				jQuery(this).parent().parent().find('select').change();
			}
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
		}
	});
	jQuery('.customSelectDiv ul li').hover(function() {
		jQuery(this).addClass('hover');
	}, function() {
		jQuery(this).removeClass('hover');
	});
	jQuery('.customSelectDiv ul').hover(function() {
		jQuery(this).find('li.selected').stopTime();
	}, function() {
		if(big) {
			jQuery(this).find('li.selected').oneTime(1500, function() {
				jQuery(this).click();
			});
		}
	});

	// Filter Teaser
	jQuery('.defaultFilter').append('<a href="#" class="next" style="display:none"><span>.</span></a><a href="#" class="last" style="display:none"><span>.</span></a>');
	jQuery('.defaultFilter .next').hover(function() {
		var last = jQuery(this).parent().find('.last');
		var container = jQuery(this).parent().find('.scrollContainer');
		jQuery(this).everyTime(10, function() {
			var previousScrollLeft = container.scrollLeft();
			container.scrollLeft(container.scrollLeft() + 1);
			if(container.scrollLeft() == previousScrollLeft) {
				jQuery(this).hide();
			}
			last.show();
		});
	}, function() {
		jQuery(this).stopTime();
	});
	jQuery('.defaultFilter .last').hover(function() {
		var next = jQuery(this).parent().find('.next');
		var container = jQuery(this).parent().find('.scrollContainer');
		jQuery(this).everyTime(10, function() {
			var previousScrollLeft = container.scrollLeft();
			container.scrollLeft(container.scrollLeft() - 1);
			if(container.scrollLeft() == previousScrollLeft) {
				jQuery(this).hide();
			}
			next.show();
		});
	}, function() {
		jQuery(this).stopTime();
	});
	jQuery('.defaultFilter .scrollContainer').scrollLeft(0);

	jQuery('.defaultFilter li:last').addClass('lastLi');

});
// Use onLoad event to do when images are loaded
jQuery(window).load(function() {
	
	jQuery('.defaultFilter').each(function() {
		var width = 0;
		jQuery(this).find('ol li').each(function() {
			width += jQuery(this).width() + parseInt(jQuery(this).css('margin-right').match(/[-0-9]+/));
		});
		jQuery(this).find('ol').width(width);
		if(width > jQuery(this).width()) {
			jQuery(this).find('.next').show();
		}
	});

});

// Filters ======================================================
navigationLoadInProccess = false;

function startLoadNavigationData() {

	if (navigationLoadInProccess) {
		return false;
	}

	navigationLoadInProccess = true;

	var overlay = $('advanced-navigation-overlay');

	if ($$('div.category-products').length > 0) {

		var element = $$('div.category-products')[0];

	} else if ($$('div.col-main p.note-msg')) {

		var element = $$('div.col-main p.note-msg')[0];

	} else {

		return;
	}

	if (!overlay) {
		overlay = $(document.createElement('div'));
		overlay.id = 'advanced-navigation-overlay';
		document.body.appendChild(overlay);
	}

	var offsets = element.cumulativeOffset();
	overlay.setStyle( {
		'top' : offsets[1] + 'px',
		'left' : offsets[0] + 'px',
		'width' : element.offsetWidth + 'px',
		'height' : element.offsetHeight + 'px',
		'position' : 'absolute',
		'display' : 'block',
		'zIndex' : '2000' // Value mast be more than any element from content have
	});

	var loadinfo = document.createElement('div');

	if (loadimagealign == 'bottom') {

		loadinfo.innerHTML = gomage_navigation_loadinfo_text + '<img src="'
				+ loadimage + '" alt="" class="align-' + loadimagealign + '"/>';

	} else {

		loadinfo.innerHTML = '<img src="' + loadimage
				+ '" alt="" class="align-' + loadimagealign + '"/>'
				+ gomage_navigation_loadinfo_text;

	}

	loadinfo.id = "navigation_loadinfo";
	loadinfo.className = "gan-loadinfo";

	document.body.appendChild(loadinfo);

	return navigationLoadInProccess;

}

function stopLoadNavigationData() {
	var overlay = $('advanced-navigation-overlay');

	if (overlay) {
		overlay.style.display = 'none';
	}

	document.body.removeChild($('navigation_loadinfo'));
	return navigationLoadInProccess = false;
}

function generateUrlWithParams(url, params) {
	var query = {}, keys = url.split('?')[1].split('&'), key = '', glue = '', strQuery = '', i = -1;
	while (++i < keys.length) {
		key = keys[i].split('=');
		query[key[0]] = key[1];
	}

	for (attrname in query) {
		if(!params[attrname]) {
			params[attrname] = query[attrname];
		}
	}

	for (key in params) {
		strQuery += glue + key + '=' + params[key];
		glue = '&';
	}

	if (strQuery != '') {
		url = url.split('?')[0] + '?' + strQuery;
	}
	return url;
}

function submitNavigationForm(form, url, is_ajax) {
	var from = $(form).down('input.navigation-from');
	var to = $(form).down('input.navigation-to');

	var re = /^[0-9]*$/;
	if (!re.test($(from).value)) {
		alert('Please use only numbers (0-9) in this field.');
		return false;
	}
	if (!re.test($(to).value)) {
		alert('Please use only numbers (0-9) in this field.');
		return false;
	}

	if ((parseFloat($(from).value) > parseFloat($(to).value))
			|| ((parseFloat($(from).value) == 0 && parseFloat($(to).value) == 0))) {
		alert('Filter range is invalid.');
		return false;
	}

	is_ajax = typeof (is_ajax) != 'undefined' ? is_ajax : true;

	var url = url.replace(/&amp;/ig, '&');
	var elements = form.elements;
	var params = Object.clone(navigationOpenFilters);

	for ( var i = 0; i < elements.length; i++) {
		element = elements[i];

		switch (element.nodeName) {

		case 'INPUT':
		case 'SELECT':
		case 'TEXTAREA':

			if (element.value) {
				params[element.name] = element.value;
			}
			break
		}
	}

	if (!url) {
		url = form.action;
	}
	if (!is_ajax) {
		setLocation(generateUrlWithParams(url, params));
	} else if (startLoadNavigationData()) {

		var request = new Ajax.Request(url, {
			method : 'GET',
			parameters : params,
			onSuccess : function(transport) {

				var response = eval('(' + (transport.responseText || false)
						+ ')');
				replaceNavigationBlock(response.navigation);
				replaceProductsBlock(response.product_list);
				replaceLeftRightNavigationBlocks('gan-left-nav-main-container',
						response.navigation_left);
				replaceLeftRightNavigationBlocks(
						'gan-right-nav-main-container',
						response.navigation_right);

				if (response.eval_js) {
					eval(response.eval_js);
					navigation_eval_js = response.eval_js;
				}

				stopLoadNavigationData();

			},
			onFailure : function() {
				stopLoadNavigationData();
			}
		});

	}

}

function setNavigationUrl(url) {
	is_ajax = typeof (is_ajax) != 'undefined' ? is_ajax : true;
	var url = url.replace(/&amp;/ig, '&');

	if (startLoadNavigationData()) {

		var request = new Ajax.Request(url, {
			method : 'get',
			parameters : navigationOpenFilters,
			onSuccess : function(transport) {

				var response = eval('(' + (transport.responseText || false)
						+ ')');

				replaceNavigationBlock(response.navigation);
				replaceProductsBlock(response.product_list);
				replaceLeftRightNavigationBlocks('gan-left-nav-main-container',
						response.navigation_left);
				replaceLeftRightNavigationBlocks(
						'gan-right-nav-main-container',
						response.navigation_right);

				if (response.eval_js) {
					eval(response.eval_js);
					navigation_eval_js = response.eval_js;
				}

				stopLoadNavigationData();

			},
			onFailure : function() {
				setLocation(url); //trying redirect to url
			}
		});

	}

}

function replaceProductsBlock(content) {
	if ($$('div.category-products').length > 0) {
		element = $$('div.category-products')[0];
	} else if ($$('div.col-main p.note-msg').length > 0) {
		element = $$('div.col-main p.note-msg')[0];
	} else {
		return;
	}

	if (content && content.toElement) {
		content = content.toElement();
	} else if (!Object.isElement(content)) {
		content = Object.toHTML(content);
		var tempElement = document.createElement('div');
		content.evalScripts.bind(content).defer();
		content = content.stripScripts();
		tempElement.innerHTML = content;

		el = getElementsByClassName('category-products', tempElement);
		if (el.length > 0) {
			content = el[0];
		} else {
			el = getElementsByClassName('note-msg', tempElement);
			if (el.length > 0) {
				content = el[0];
			} else {
				return;
			}
		}
	}
	element.parentNode.replaceChild(content, element);
}

function getElementsByClassName(classname, node) {

	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");

	for ( var i = 0, j = els.length; i < j; i++) {
		if (re.test(els[i].className))
			a.push(els[i]);
	}
	return a;

}

function replaceNavigationBlock(content) {
	var element = $$('div.block-layered-nav')[0];
	if (content && content.toElement) {
		content = content.toElement();
	} else if (!Object.isElement(content)) {
		content = Object.toHTML(content);
		var tempElement = document.createElement('div');
		content.evalScripts.bind(content).defer();
		tempElement.innerHTML = content;
		content = tempElement.firstChild;

	}
	element.parentNode.replaceChild(content, element);
}

function replaceLeftRightNavigationBlocks(element, content) {
	var element = $(element);
	if (content && element) {
		if (content && content.toElement) {
			content = content.toElement();
		} else if (!Object.isElement(content)) {
			content = Object.toHTML(content);
			var tempElement = document.createElement('div');
			content.evalScripts.bind(content).defer();
			tempElement.innerHTML = content;
			content = tempElement.firstChild;
		}
		element.parentNode.replaceChild(content, element);
	}
}

function initSlider(code, min, max, curr_min, curr_max, url, is_ajax) {
	if (min == max) {
		max++;
		if (curr_min == curr_max) {
			curr_max++;
		}
	}
	var handles = [ code + '-handle-from', code + '-handle-to' ];

	var s1 = new Control.Slider(handles, code + '-track', {
		axis : 'horizontal',
		alignY : 0,
		range : $R(min, max),
		sliderValue : [ curr_min, curr_max ],
		restricted : true,
		spans : [ code + "-slider" ]
	});
	s1.options.onChange = function(value) {
		if (isNaN(value[0]) || isNaN(value[1])) {
			return false;
		}

		$(code + '-filter-form').elements[code + '_from'].value = parseInt(value[0]);
		$(code + '-filter-form').elements[code + '_to'].value = parseInt(value[1]);

		if (min == value[0] && max == value[1]) {
			//setNavigationUrl(url);
			submitNavigationForm($(code + '-filter-form'), url, is_ajax);
		} else {
			submitNavigationForm($(code + '-filter-form'), url, is_ajax);
		}

		var htmlvalue = parseInt(value[0]) + ' - ' + parseInt(value[1]);

		if (value[0] >= 0 && value[1] >= 0) {
			$(code + '-value-from').innerHTML = parseInt(1 * value[0])+' &euro;';
			$(code + '-value-to').innerHTML = parseInt(1 * value[1])+' &euro;';
		}

		$(code + '-value').innerHTML = htmlvalue;
	};

	s1.options.onSlide = function(value) {

		if (isNaN(value[0]) || isNaN(value[1])) {
			return false;
		}

		var htmlvalue = parseInt(value[0]) + ' - ' + parseInt(value[1]);

		if (value[0] >= 0 && value[1] >= 0) {
			$(code + '-value-from').innerHTML = parseInt(1 * value[0])+' &euro;';
			$(code + '-value-to').innerHTML = parseInt(1 * value[1])+' &euro;';
		}
		$(code + '-value').innerHTML = htmlvalue;
	};

	s1.draw = function(event) {
		var pointer = [ Event.pointerX(event), Event.pointerY(event) ];
		var offsets = Position.cumulativeOffset(this.track);
		pointer[0] -= this.offsetX + offsets[0];
		pointer[1] -= this.offsetY + offsets[1];
		this.event = event;

		var value = this.translateToValue(this.isVertical() ? pointer[1]
				: pointer[0]);

		if (isNaN(value))
			return false;

		this.setValue(value);

		if (this.initialized && this.options.onSlide)
			this.options.onSlide(this.values.length > 1 ? this.values
					: this.value, this);
	};

	var htmlvalue = parseInt(s1.values[0]) + ' - ' + parseInt(s1.values[1]);

	$(code + '-value-from').innerHTML = parseInt(s1.values[0])+' &euro;';
	$(code + '-value-to').innerHTML = parseInt(s1.values[1])+' &euro;';
	$(code + '-value').innerHTML = htmlvalue;
}

// Category Navitaion
navigationOpenFilters = {};
navigation_eval_js = null;

document.observe("dom:loaded", function() {

	ganLoadForPlain();

});

document.onreadystatechange = ganLoadForPlain;

function ganLoadForPlain() {
	mainNav("gan_nav_left", {
		"show_delay" : "100",
		"hide_delay" : "100"
	});
	mainNav("gan_nav_top", {
		"show_delay" : "100",
		"hide_delay" : "100"
	});
	mainNav("gan_nav_right", {
		"show_delay" : "100",
		"hide_delay" : "100"
	});
}

function showNavigationNote(id, control) {
	var arr = $(control).cumulativeOffset();
	$(id).style.left = arr[0] + 'px';
	$(id).style.top = arr[1] + 'px';
	$(id).style.display = 'block';
}

function hideNavigationNote() {
	$$('.filter-note-content').each(function(e) {
		e.style.display = 'none';
	});
}

function navigationOpenFilter(request_var) {
	var id = 'advancednavigation-filter-content-' + request_var;
	if ($(id).style.display == 'none') {
		$(id).style.display = 'block';
		if (navigation_eval_js)
			eval(navigation_eval_js);
		navigationOpenFilters[request_var + '_is_open'] = true;
	} else {
		$(id).style.display = 'none';
		navigationOpenFilters[request_var + '_is_open'] = false;
	}
}
