$(document).ready(function() {

	if ($('body#page-store').length == 0) $.matchPanels(); // match panel heights unless we are in store page
	$('#lang-changer').change(function() { this.form.submit() }); // make language changer submit form

	// LINKS
	$('#wrapper #header h1').click(function() { window.location = $(this).find('a').attr('href'); });
	$('div.item').each(function() {
		// find first anchor and get its action
		var href = $(this).find('a:first').attr('href');
		// make the parent div.item clicable to same target
		if (href && href.substring(0,7) != 'http://') $(this).css('cursor', 'pointer').click(function() { window.location = href } );
	});
	$('div.controls li.print').click(function () { window.print() });
	
	// NAV
	$('#nav ul li.more').mouseenter(function() {
		clearTimeout($(this).data('timeoutId'));
		$(this).find('ul').fadeIn();
	}).mouseleave(function(){
		var bla = this;
		var timeoutId = setTimeout(function() {
			$(bla).find("ul").fadeOut();
		}, 650);
		$(bla).data('timeoutId', timeoutId);
	});

	// MODAL WINDOWS for panel (add) buttons
	$('div#panel div.box.buttons ul li a[class^=add]').colorbox({ opacity: 0.5 });

	// HOMEPAGE CATEGORIES
	$('div#content div#picker div#catexpand ul').mouseenter(function() {
		var slug = $(this).attr('id');
		$('div#content div#picker').removeClass().addClass($(this).attr('class'));
		$.ajax({
			type: "GET",
			cache: false,
			dataType: 'json',
			url: base_url+'category/'+slug+'/groups',
			success: function(msg) {
				if (msg && msg.result == 1)
				{
					// no good, too tired now, TODO:
					var groups = '<h2>Products</h2><h3>'+msg.name+'</h3><ul>';
					$.each(msg.groups, function(i, group){
						groups += '<li><a href="'+base_url+'group/'+i+'">' + group +'</a></li>';
					});
					groups += '</ul>';
					$('div#content div#picker div#catoverlay').fadeIn('slow').html(groups);
				}
				else {}
			}
		});
	});
	$('div#content div#picker').hover(false, function() { $(this).find('div#catoverlay').fadeOut('slow') });

	// REVIEW
	$('div#content div.box div.reviews ul li a[class!=reply]').click(function() {
		// first make sure we fetch a.more element
		var el = $(this).hasClass('more') ? $(this) : $(this).parent().siblings('a.more');
		// now lets toggle it, get his sibling div.review-body, toggle that too,
		// and toggle the class 'opened' for the parent li
		el.toggle().siblings('div.review-body').slideToggle('fast').parent('li').toggleClass('opened');
		return false;
	});

	// STAR RATING
	$("#star-rating").children().not(":radio").hide();
	$('#star-rating').stars({
		cancelValue: 999,
		cancelShow: false,
		oneVoteOnly: true,
		callback: function(ui, type, value)
		{
			$.post(base_url+$('#star-rating').attr('rel')+'/rate', {rate: value}, function(msg)
			{
				if (msg.result == 0)
				{
					alert('You can only vote once');
				}
			}, "json");
		}
	});

	// TABS (IN GROUPS)
	$('div.widget.tabs ul.tabs li a').click(
		function(e) {
			var el = $(e.target);
			var rel = el.attr('rel');
			if ( ! rel) return true;
			$('div.widget.tabs ul.tabs li').removeClass('active');
			$('div.widget.tabs div.widget-body').addClass('hide');
			$('#'+rel).removeClass('hide');
			el.parent('li').addClass('active');
			return false;
		}
	);

	// POLL AJAX
	$('form#user-poll').submit(
		function() {
			var action = $(this).attr('action');
			if (action == base_url+'polls') return true;
			var vars = $(this).serialize();
			$.ajax({
				type: "POST",
				cache: false,
				dataType: 'json',
				url: action,
				data: vars,
				success: function(msg) {
					$('form#user-poll').attr('action', base_url+'polls').find('fieldset').html(msg.view);
				}
			});
			return false;
		}
	);

	// COMMENT AJAX
	$('div#content div.box div.reviews h3 a').click(function () {
		$.get($(this).attr('href'), function(data) {
			$('div#content div.box div.reviews div.review-write').toggle().html(data).find('form[class!=login]').submit(
				function() {
					var action = $(this).attr('action');
					var vars = $(this).serialize();
					$.ajax({
						type: "POST",
						cache: false,
						dataType: 'json',
						url: action,
						data: vars,
						success: function(msg) {
							if (msg && msg.result == 1)
							{
								if (msg.unregistered)
								{
									$('div#content div.box div.reviews div.review-write').html('<p>'+msg.view+'</p><br />');
								}
								else
								{
									$('div.body.reviews ul').prepend(msg.view);
									$('div#content div.box div.reviews ul li:first-child a.more')
										.toggle().siblings('div.review-body').slideToggle('fast').parent('li').toggleClass('opened');
									$('div#content div.box div.reviews div.review-write').slideUp('normal');
								}
							}
							else
							{
								if (msg && msg.errors)
								{
									var errors = '';
									$.each(msg.errors, function(i, error){
										errors += error+"\n";
									});
									alert(errors);
								}
							}
						}
					});
					return false;
				}
			);
			// if form login opened, handle input helpers
			$('div.review-write form.login input').enableHelper({'img': base_url+'media/img/layout/txt_password.gif'});
		});
		return false;
	});
	
	// SCROLL TO REVIEWS
	$('div.inner div.widget div.widget-body, div.controls ul').localScroll();
	$('a#review-write-link, div.controls ul li.write').click(function () { $('div#content div.box div.reviews h3 a').trigger('click') });
	
	$("#signin_menu").signinMenu(); // login box
	$('form.quicksearch input.q, #panel input, div#signin_menu input, div.box.login input')
		.enableHelper({'img': base_url+'media/img/layout/txt_password.gif'}); // input helpers
	
});

// matches grid panels to be same size
jQuery.matchPanels = function() {
	// match content & panel heights, first find the margin
	var h_margin = $('#wrapper #panel').height() - $('#wrapper #content').height();
	// now grab the box we need to enlarge, last box in #content or #panel
	var lastbox = $('#wrapper #'+(h_margin > 0 ? 'content' : 'panel')+' div.box:last-child '+(h_margin > 0 ? 'div.inner' : ''));
	// add the marginal height
	lastbox.height(Math.abs(h_margin) + lastbox.height());
};

// input helpers (toggling default value on inputs)
jQuery.fn.enableHelper = function(settings) {
	var config = {'color': '', 'img': ''};
	if (settings) $.extend(config, settings);
	this.each(
		function() {
			var el = $(this);
			var type = el.attr('type');
			switch (type)
			{
				case 'text':
					el
					.data('txt', el.val())
					.data('color', el.css('color'))
					.focus(
						function() {
							var el = $(this);
							if (el.val() == el.data('txt')) el.val('');
							if (config.color) el.css('color', el.data('color'));
						})
					.blur(
						function() {
							var el = $(this);
							if (el.val() == '') el.val(el.data('txt'));
							if (config.color) el.css('color', config.color);
						});
					break;
				case 'password':
					el
					.css('background-image', 'url('+config.img+')').css('background-repeat', 'no-repeat')
					.data('img', config.img)
					.focus(
						function() {
							$(this).css('background-image', 'none');
						})
					.blur(
						function () {
							var el = $(this);
							if ( ! el.val()) el.css('background-image', 'url('+el.data('img')+')');
						});
					
					break;
			}
		});
	return this;
};

// signin hover menu
jQuery.fn.signinMenu=function(){
	return this.each(function() {
		var menu = $(this);
		var flag = true;
		$(".signin").bind("click focus",
			function(e) {
				e.preventDefault();
				if (!flag) return;
				flag = false;
				setTimeout(function() { flag = true }, 500);
				var link = $(this);
				var offset = link.offset();
				menu.css({top:Math.floor(offset.top + link.height() + 1), left: (offset.left + 13) - menu.width() + link.width()});
				link.toggleClass("menu-open");
				menu.toggle();
				if (link.hasClass("menu-open"))
				{
					//setTimeout(function() { $("#username").focus() }, 50);
				}else{
					//$("#header input.q:eq(0)").focus();
				}
			}
		);
		menu.mouseup(function() { return false });
		$(document).mouseup(function(e) {
			//if($(e.target).parent("menu.signin").length==0) {
			if ($(e.target).parents('div:first').attr('id') !== 'header') {
				$(".signin").removeClass("menu-open");
				menu.hide();
			}
		});
	})
};