DEBUG = 0;

//// Categories menu

function _create_stop_handler(func) {
		function _handler(ev) {
				ev = new Event(ev);
				ev.stop();
				func(ev);
		}
		return _handler;
}

/******** Slider (category menu) ************************************/

var config_fade = false;
var config_steps = 20;
var config_slide_in_duration = 800;
var config_slide_out_duration = 400;
var config_fade_duration = 333;

var last_opened_box = null;

function _slide_fx(box, slide_in_or_out) {
		// slide in/out a .box
		var right = box.getElement(".right");
		if (!right.fx) {
				right.slide_fx = new Fx.Slide(right, {
								'mode':'horizontal', 'transition':'expo:out', 'fps':30});
				right.tween_fx = new Fx.Tween(right, {
								'transition':'sine:out', 'fps':18,
								'duration':config_fade_duration});
				right.slide_fx.wrapper.setStyle("float", "left"); // that's the trick
		}
		if (slide_in_or_out=="in") {
				box.addClass("opened");
				right.slide_fx.cancel();
				right.slide_fx.hide();
				right.slide_fx.options.duration = config_slide_in_duration;

				if (last_opened_box && last_opened_box!=box)
						right.slide_fx.slideIn();
				else
						right.slide_fx.slideIn();

				if (config_fade) {
						right.tween_fx.set("opacity", 0);
						right.tween_fx.start("opacity", 1);
				}
		} else if (slide_in_or_out=="out") {
				right.slide_fx.cancel();
				right.slide_fx.show();
				right.slide_fx.options.delay = 0;
				right.slide_fx.options.duration = config_slide_out_duration;
				right.slide_fx.slideOut();
				if (config_fade)
						right.tween_fx.start("opacity", 0);
				right.onComplete = function () { box.removeClass("opened"); };
		}
}
function _slide_vanilla(box, slide_in_or_out) {
		// simple version
		if (slide_in_or_out=="in")
				box.addClass("opened");
		else if (slide_in_or_out=="out")
				box.removeClass("opened");
}
_slide = _slide_fx;
//_slide = _slide_vanilla;

function _init_slider(box) {
		/// init the category menu with sliders, etc.
		function _scroll_to(box, element) {
				var coordinates = element.getCoordinates(box);
				var scollable = box.getElement(".subcategory");
				var size = scollable.getSize();
				var scroll_size = scollable.getScrollSize();
				var y = coordinates.top - size.y / 2;
				if (y<0) y = 0;
				box.slider.set(y*config_steps/(scroll_size.y - size.y));
		}

		// adds the scollbar to the .box
		var right = box.getElement(".right");
		var scollable = box.getElement(".subcategory");
		var size = scollable.getSize();
		var scroll_size = scollable.getScrollSize();
		function _on_change(p) {
				scollable.scrollTo(0, p*(scroll_size.y - size.y)/config_steps);
		}
		if (!box.slider) {
				var slider = new Element("div", {'class':'slider'});
				var knob = new Element("div", {'class':'knob'});
				knob.injectInside(slider);
				slider.injectInside(box);
				box.slider = new Slider(slider, knob, 
																	{'mode':'vertical', 
																	 'wheel':true,
																	 'steps':config_steps});
		} else {
				box.getElement(".knob").setStyle("display", "block");
		}
		box.slider.set(0);
		box.slider.removeEvents("change");
		box.slider.addEvent("change",  _on_change);

		// goodies
		right.addEvent("mousewheel", box.slider.scrolledElement.bindWithEvent(box.slider));
		var active_sub = box.getElement(".active_sub");
		if (active_sub)
				_scroll_to(box, active_sub);
		
}

function _hide_slider(box) {
		// hides the slider (comp. issues -> css not enugh)
		if (box && box.slider) {
				box.getElement(".knob").setStyle("display", "none");
		}
}

function _category_menu_posthandler() {
		// handler called when ajax suceeds
		var this_box = this.getParent(".box");
		if (this_box!=last_opened_box) {
				//$$("#submenu .box").each(function(box) { box.removeClass("opened"); });
				if (last_opened_box) {
						_slide(last_opened_box, "out");
				}
				_slide(this_box, "in");
		}
		_hide_slider(last_opened_box);
		_init_slider(this_box);
		last_opened_box = this_box;
}

function _activate_submenu(a) {
		// deals with .active styles
		$$('#submenu LI.top_category').each(function(li) { li.removeClass("active"); });
		var li = a.getParent();
		li.addClass("active");
		a.blur(); // avoids ff dotted box
}

function _category_menu_handler(ev) {
		function _get_slug(a) {
				var m = a.href.match("/category/([^/]*)");
				if (m)
						return m[1];
		}
		ev = new Event(ev);
		ev.stop();
		var slug =_get_slug(this);
		var box = this.getParent(".box");
		var destination = box.getElement(".right");
		var url = "/navigation/subcategories/ajax/?category_slug="+slug;
		_activate_submenu(this);
		new Request.HTML({
						'update':destination, 
						'onComplete':_category_menu_posthandler.bind(this)}).get(url);
}

function init_category_menu() {
		$$("#submenu LI.top_category A").each(function (el) {
						el.addEvent("click", _category_menu_handler);
				});
}

/****** Cart ********************************************************/
var config_tooltip_offset_y = 60,
    config_tooltip_offset_x = -150;

function set_cart_total(total) {
		if (!total) {
				$('cart-frame').addClass("empty");
				$('cart-total').set("text", "");
		} else {
				$('cart-frame').removeClass("empty");
				$('cart-total').set("text", total);
		}
}

var current_topbar_tooltip = null;

function _close_tooltip() {
		if (current_topbar_tooltip) {
				var tooltip = current_topbar_tooltip;
				//current_topbar_tooltip.dispose();
				current_topbar_tooltip.set("tween", {
								'duration':300, 'fps':24, 'transition':'expo:in',
  							'onComplete':function() { tooltip.dispose(); }});
				current_topbar_tooltip.tween("opacity", 0);
				current_topbar_tooltip = null;
		} 
}

function _extract_tooltip(frame) {
		function _position_tip(tip, handle) {
				var handle_coords = handle.getCoordinates();
				var top = handle_coords.top + config_tooltip_offset_y;
				tip.setStyles({
								'top':top,
								'left':handle_coords.left + config_tooltip_offset_x
						});
				tip.set("tween", {'duration':300, 'fps':24, 'transition':'expo:in'});
				tip.tween("opacity", 0, 1);
				tip.setStyle("opacity", 0);
				tip.injectInside(document.body);
				current_topbar_tooltip = tip;
		}
		function _install_handlers(tip) {
				var close_button = tip.getElement(".close-tip-button");
				var show_cart_button = tip.getElement(".show-cart-close-tip-button");
				if (close_button)
						close_button.addEvent("click", 
																	_create_stop_handler(_close_tooltip));
				if (show_cart_button) {
						show_cart_button.addEvent("click", 
																			_create_stop_handler(
																					function(ev) {
																							show_frame("cart-frame");
																					}));
				}
		}
		var tip = frame.getElement(".topbar-tooltip");
		if (!tip) return;
		if (_get_current_frame()) { // no need for the tip
				tip.dispose();
		} else {
				// get rid of the old one
				if (current_topbar_tooltip) 
						current_topbar_tooltip.dispose();
				var handle = frame.getElement(".btn-box");
				_position_tip(tip, handle);
				_install_handlers(tip);
		}
}

EMPTY_TOKEN = "<!--empty-->";

function _update_cart(data) {
		if (data==EMPTY_TOKEN) {
				var frame = $('cart').getParent(".frame");
				$('cart').empty();
				set_cart_total(false);
				hide_frame(frame);
		}
		else if (data) {
				$('cart').innerHTML = data;
				var frame = $('cart').getParent(".frame");
				adjust_frame(frame); // if needed
				set_cart_total($('cart_total_hidden').get("text"));
				_extract_tooltip(frame);
		} 
		init_cart_quantity_buttons();
		init_cart_update_button();
}

function init_cart_quantity_buttons() {
		function _init_cart_quantity_buttons(li) {
				var inp = li.getElement("input");
				function _add(n) {
						var val = parseInt(inp.value);
						val = val + n;
						if (!val || val<0) val = 0;
						inp.value = val;
				}
				var plus_button = li.getElement(".top");
				var minus_button = li.getElement(".bottom");
				var trash_button = li.getElement(".trash");
				if (!plus_button || !minus_button) return;
				plus_button.addEvent("click", function (ev) { new Event(ev).stop(); this.blur(); _add(1); });
				minus_button.addEvent("click", function (ev) { new Event(ev).stop(); this.blur(); _add(-1);});				
				if (trash_button)
						trash_button.addEvent("click", function (ev) { new Event(ev).stop(); this.blur(); inp.value = "0";});				
		}
		$$("LI.cart_item").each(_init_cart_quantity_buttons);
}

function init_cart_update_button() {
		var form = $('cart_update_form');
		if (!form) return;
		form.addEvent("submit", function (ev) {
						ev = new Event(ev);
						ev.stop();
						this.set("send", {
										'method':'post', 
										'onComplete':_update_cart});
						this.send();
						
				});
}


// ajax for content (cart related)
function init_cart_add_ajax() {
		function _init_cart_add_ajax(form) {
				form.addEvent("submit", function (ev) {
								ev = new Event(ev);
								ev.stop();
								this.set("send", {
												'url':this.action+"ajax/", 'method':'post', 
												'onComplete':_update_cart});
								this.send();
														
						});
		}
		$$("FORM.add_cart_ajax").each(_init_cart_add_ajax);
}

function init_quantity_buttons() {
		function _init_quantity_buttons(form) {
				function _add(n) {
						var val = parseInt(form['quantity'].value);
						val = val + n;
						if (!val || val<0) val = 0;
						form['quantity'].value = val;
				}
				var plus_button = form.getElement(".top-lnk");
				var minus_button = form.getElement(".bottom-lnk");
				if (!plus_button || !minus_button) return;
				plus_button.addEvent("click", function (ev) { new Event(ev).stop(); this.blur(); _add(1);});
				minus_button.addEvent("click", function (ev) { new Event(ev).stop(); this.blur(); _add(-1);});
		}
		$$("form").each(_init_quantity_buttons);
}

/******* Top bar frames *********************************************/

var topbar_current_frame = null;
function _get_current_frame() {
		return $(Cookie.read('topbar_current_frame'));
		//return topbar_current_frame;
}
function _set_current_frame(frame) {
		Cookie.write('topbar_current_frame', frame && frame.id, {
						'path':'/'
				});
		$$('#topbar .frame').each(function (frame) {
				frame.addClass("closed");
				});
		if (frame)
				frame.removeClass("closed");
		//topbar_current_frame = frame;
}

function adjust_frame(frame) {
		// resize the frame (when ajax conte eg.)
		var current_frame = _get_current_frame();
		if (frame && current_frame==frame) {
				frame.fx.show();
		}
}


function _track_frame_event(show_or_hide, frame) {
                try {
                                var name = frame.id || frame;
                                pageTracker._trackEvent("Topbar", show_or_hide+"("+name+")");
                } catch(e) {
                                // ignore errors
                }
}

function show_frame(frame) {
		frame = $(frame);
		if (!frame) return;
		if (frame.hasClass("empty")) {
				hide_frame(frame);
				_set_current_frame(null);
				return
		}
		_close_tooltip(); // special hook
		var current_frame = _get_current_frame();
		if (current_frame==frame && frame) {
				adjust_frame(frame);
				_set_current_frame(frame);
				return
		}
		if (current_frame)
				hide_frame(current_frame);
		frame.fx.slideIn();
		_set_current_frame(frame);
		_track_frame_event("show", frame);
}

function hide_frame(frame) {
		frame = $(frame);
		var current_frame = _get_current_frame();
		if (current_frame!=frame) return;		
		if (Browser.Engine.trident5) // unexplained ie7 bug
				frame.fx.hide();
		else
				frame.fx.slideOut();
		_set_current_frame(null);
		_track_frame_event("hide", frame);
}

function toggle_frame(frame) {
		if (!frame) return;
		var current_frame = _get_current_frame();
		_close_tooltip(); // special hook
		frame = $(frame);
		if (current_frame==frame) {
				hide_frame(frame);
		} else {
				show_frame(frame);
		}
}

var _topbar_top = 0;
function _init_topbar_absolute_hack() {
		var fx = new Fx.Scroll(window);
		function _fix_topbar_absolute() {
				var scroll = window.getScroll();
				if (_topbar_top!= scroll.y) {
						$$('#topbar .frame').each(function (frame) {
										//document.title = ""+frame.getStyle("top")+":"+scroll.y;
										frame.setStyle("top", scroll.y);
								});
						$$('.topbar-tooltip').each(function (tip) {
										tip.setStyle("top", scroll.y + config_tooltip_offset_y + 13);
								});

						_topbar_top = scroll.y;
				}
		}
		_fix_topbar_absolute.periodical(100);
}

function init_topbar(refresh) {
		var topbar = $('topbar');
		var frames = topbar.getElements(".frame");
		function frame_toggle_handler(ev) {
				ev = new Event(ev);
				ev.stop();
				this.blur();
				toggle_frame(this.frame);				
		}		
		function _init_frame(frame) {
				var frame_content = frame.getElement(".frame-content");
				frame.fx = new Fx.Slide(frame_content, {'mode':'vertical', 'fps':12});
				if (!refresh) frame.fx.hide();
				var toggles = frame.getElements(".frame-toggle");
				toggles.each(function(a) { 
								a.frame = frame; 
								a.addEvent("click", frame_toggle_handler); 
						});
		}
		frames.each(_init_frame);
		if (!refresh) topbar.setStyle("display", "block");
		if (!refresh && _get_current_frame())
				show_frame(_get_current_frame());

		if (Browser.Engine.trident4) {
				_init_topbar_absolute_hack();
		}
}


/***** tabs ************************************************************/

function _init_tabs(div) {
		var buttons = div.getElements(".tab-button");
		var panes = div.getElements(".tab-pane");
		function _doit(button) {
				var i = buttons.indexOf(button);
				panes.each(function(el) { el.removeClass("shown"); });
				buttons.each(function(el) { $(el.parentNode).removeClass("selected"); });
				$(panes[i]).addClass("shown");
				$(buttons[i].parentNode).addClass("selected");
		}
		for (var i=0;i<buttons.length;i++) {
				buttons[i].addEvent("click", function(ev) { ev = new Event(ev); ev.stop(); _doit(this); });
		}
}
function init_tabs() {
		$$("DIV.with-tabs").each(_init_tabs);
}


/***** goodies *********************************************************/

function init_emailthis() {
		$$(".emailthis-container").each(function (div) {
						var form = div.getElement(".emailthis-form");
						var toggle = div.getElement(".emailthis-link");
						toggle.addEvent("click", function (ev) {
										ev = new Event(ev);
										ev.stop();
										form.toggleClass("shown");
								});
						form.addEvent("submit", function (ev) {
										ev = new Event(ev);
										ev.stop();
										this.set("send", {'onComplete': function(data) {
																if (data=="OK") {
																		form.removeClass("shown");
																		form.removeClass("errors");
																}
																else
																		form.addClass("errors");
														}});
										this.send();
								});
				});
}

function init_copy_address_trick() {
		function _init_copy_address_trick(form) {
				function _toggle_inputs() {
						var flag = this.checked;
						form.getElements("input, select").each(function(inp) {
										if (!inp.name.match(/ship_.*/)) return;
										inp.disabled = flag;
										if (flag)
												$(inp.parentNode).addClass("disabled");
										else
												$(inp.parentNode).removeClass("disabled");
								});
				}
				if (!form['copy_address']) return;
				var checkbox = $(form['copy_address']);
				if (checkbox) {
						checkbox.addEvent("click", _toggle_inputs);
						_toggle_inputs.bind(checkbox)();
				}
		}
		$$("form").each(_init_copy_address_trick);
}

function init_autolabels() {
		function _set_input_default(input, initial_text) {
				if (!input || (input.value && input.value!=initial_text)) return;
				input.addEvent("focus", function () { if (this.value == initial_text) this.value = ''; this.removeClass("inactive"); });
				input.addEvent("blur", function () { if (this.value == '') { this.value = initial_text; this.addClass("inactive");}});
				input.value = initial_text;
				input.addClass("inactive");
				function _reset() {
						if (input.value==initial_text) {
								input.value = '';
						}
				}
				$(input.form).addEvent("submit", _reset);
		}
		$$("INPUT.autolabel, TEXTAREA.autolabel").each(function(input) {
						var label = input.title;
						input.title = '';
						_set_input_default(input, label);
				});
}

function init_fancy_select() {
   $$('.n2Select').each(function(el){  
					 //new n2Select(el);  
					 new MavSelectBox(el);  
			 });
}


function init_sitemap() {
		function _init_sitemap_toggle(div) {
				var h3 = div.getElement("h3");
				h3.addEvent("click", _create_stop_handler(function (ev) {
										div.toggleClass("shown");
								}));
		}
		$$('.box_sitemap .category').each(_init_sitemap_toggle);
}

function init_search_ajax() {
		$$('.search_ajax').each(function (a) {
						a.addEvent("click", _create_stop_handler(function(ev) {
												show_frame("search-frame");
										}));
				});
}


function fix_ie6() {
		$$("IMG.ie6_png2gif").each(function(img) {
						img.src = img.src.replace("png", "gif");
				});
}

/******** MAIN ******************************************************/

var init_complete = false;
window.addEvent("domready", function () {
				if (DEBUG)
						document.title = "INIT start";
				init_topbar();
				init_category_menu();
				init_cart_add_ajax();
				init_search_ajax();
				init_quantity_buttons();
				init_cart_quantity_buttons();
				init_cart_update_button();
				init_copy_address_trick();
				init_autolabels();
				//init_fancy_select();
				init_tabs();
				init_emailthis();
				init_sitemap();
				init_complete = true;
				if (Browser.Engine.trident4)
						fix_ie6();
				if (DEBUG)
						document.title = "INIT DONE";
		});
