var pag_prev = 'Prev';
var pag_next = 'Next';

jQuery.fn.isDefined = function(c) {
	try {
		return (typeof(eval(c)) == "undefined") ?  false : typeof(eval(c));
	} catch (e) {
		return false;
	}	
};

function Validate() {};
	Validate.init = function(submit_form, form_fields) {
		var req = form_fields;
		$('#' + submit_form).submit(function() {
			// console.log(req);
			// console.log(this);
			return Validate.checkFields(req);
		});
	}
	Validate.asRadio = function(item) {
		if($('*[name="' +item.id+ '"][checked]').length)
			return true;
		else
			return false;
	}
	Validate.asNotEmpty = function(item) {
		if($('#' +item.id).val() == '')
			return false;
		else
			return true;
	}
	Validate.asEmail = function(item) {
		var emailCheck = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,6})$/i;
		if(!emailCheck.test($('#' +item.id).val()))
			return false;
		else
			return true;
	}
	Validate.asPositive = function(item) {
		if($('#' +item.id).val() == '' || $('#' +item.id).val() <= 0)
			return false;
		else
			return true;
	}
	Validate.asChecked = function(item) {
		if($('#' +item.id).attr('checked')) {
			return true;
		} else {
			return false;
		}
	}
	Validate.checkFields = function(req) {
		$('#msg-box').hide().html('');
		var error = false;
		$(req).each(function(key, item) {
			item.is_ok = false;
			$('#' +item.id+ '_tr').removeClass('error');
			if(item.type == 'email')
				item.is_ok = Validate.asEmail(item);
			else if(item.type == 'positive')
				item.is_ok = Validate.asPositive(item);
			else if(item.type == 'radio')
				item.is_ok = Validate.asRadio(item);
			else if(item.type == 'check')
				item.is_ok = Validate.asChecked(item);
			else
				item.is_ok = Validate.asNotEmpty(item);
			if(!item.is_ok) {
				$('#' +item.id+ '_tr').addClass('error');
				$('#msg-box').append(' ' +item.msg);
				error = true;
			}
		});
		if (error) {			
			$('#msg-box').html('<p class="heading">' + _var.validate_error + '</p>' + $('#msg-box').html());
			$('#msg-box').removeClass('msg-ok').addClass('msg-error').show();			
			setTimeout(function() { $('.msg-ok').fadeOut('slow'); $('.msg-error').fadeOut('slow'); }, 3000);
			return false;
		} else {
			return true;
		}
	}

var productVotes = {	
	init: function() {
		if ($().isDefined('_var.vote_product_id'))
		{	
			if (parseInt($('#vcnt').html(), 10) <= 0)
			{
				$('.current_ratings').hide();
			} else {
				$('.current_ratings').show();
			}
			productVotes.getVotes();
			if ($().isDefined('_var.voting_disables')) {
				$('#form_votes').remove();
				$('#votes_info_2').fadeIn('slow');
			} else {
				productVotes.bindEvents();
			}
		}
		else
		{
			$('#view_votes').remove();
		}			
	},
	bindEvents: function() {
		$('#form_votes').submit(function(){
			productVotes.sendVote();
			$('#form_votes').hide('slow', function() {
				$('#votes_info').fadeIn('slow');
				productVotes.getVotes();
				$('.rating').fadeOut().fadeIn();
				$('#vcnt').fadeOut().fadeIn();
			});				
			return false;
		});
	},
	getVotes: function() {
		var votes = '&do=getvotes&p_id=' + _var.vote_product_id;			
		$.post(_var.votes_url, votes, function(msg) {
			if (!msg.average || !msg.votes) {
				$('.rating').html('0');
				$('#vcnt').html('0');
			} else {						
				$('.rating').html(msg.average);
				$('#vcnt').html(msg.votes);
			}
		}, 'json');						
	},
	sendVote: function() {
		var votes = $('#form_votes :checked').serialize();
			votes += '&do=vote&p_id=' + _var.vote_product_id;
		
		$.post(_var.votes_url, votes, '', 'json');
	}
};


var productCompare = {
	comparables: 0,
	init: function() {
		productCompare.getCompareCount();
		productCompare.bindEvents();
	},
	bindEvents: function() {
		$('.add_cmp').click(function(){
			var cmp_id = $(this).attr('href').split('#')[1];
			productCompare.addCompare(cmp_id, 1);
			return false;
		});
		$('.remove_cmp').click(function(){
			var cmp_id = $(this).attr('href').split('#')[1];
			productCompare.removeCompare(cmp_id, 1);
			return false;
		});
		$('.click_cmp').click(function(){
			var prevId = parseInt($(this).prev().val(), 10);
			if (prevId > 0 && ($(this).prev().attr('checked') !== true || $(this).prev().attr('checked') == undefined))
			{
				productCompare.addCompare(prevId, false, true, $(this).attr('href'));
				return false;
			}
		});
		$('.check_cmp').click(function(){		
			productCompare.getCompareCount();
			var cmp_id = $(this).val();
			if ($(this).attr('checked') && $(this).attr('checked') != undefined)
			{
				if (productCompare.comparables >= 4) {
					if (confirm(_var.compare_full_alert_msg)) {
						productCompare.addCompare(cmp_id, false);
					} else {
						return false;
					}
				} else {
					productCompare.addCompare(cmp_id, false);
				}
			}
			else
			{
				productCompare.removeCompare(cmp_id, false);
			}									
		});		
	},
	getCompareCount: function() {
		$.post(_var.compare_url, {"do": "count"}, function(msg) {
			productCompare.comparables = eval('(' + msg + ')').comparables;			
		});
	},
	addCompare: function(cmp_id, refresh_box, no_count, redirect_url) {
		$.post(_var.compare_url, {"do": "add", "pid": cmp_id}, function(msg) {	
			if (refresh_box == 1)
			{
				productCompare.fetchComparables(cmp_id);
			}
			if (no_count != true)
			{
				productCompare.getCompareCount();
			}		
			if (redirect_url)
			{
				window.location = redirect_url;
			}
		}, 'json');	
	},
	removeCompare: function(cmp_id, refresh_box) {
		$.post(_var.compare_url, {"do": "remove", "pid": cmp_id}, function(msg) {
			if (refresh_box == 1)
			{
				productCompare.fetchComparables(cmp_id);
			}
			productCompare.getCompareCount();
		}, 'json');	
	},
	fetchComparables: function(cmp_id) {
		$.post(_var.compare_url, {"do": "view", "pid": cmp_id}, function(msg) {
			$('.cmp_box').slideUp('slow', function(){
				$('.cmp_box').html(msg).slideDown('slow');
				productCompare.bindEvents();
			});
		});	
	}
};

$(document).ready(function(){ 

	productVotes.init();
	productCompare.init();

	$('#adv_clear_form').click(function(){
		$('#price_min').val('');
		$('#price_max').val('');
		$('.features_list').each(function(){
			$(this).removeAttr('checked');
			this.checked = false;			
		});
	});

	if ($().isDefined('_var.validate_error'))
	{
		Validate.init('form_comments', new Array(
				{id: 'author_id', msg: _var.validate_error_author},			
				{id: 'comment_id', msg: _var.validate_error_comment}
			)		
		);
		
		/* {id: 'email_id', msg: _var.validate_error_email, type: 'email'}, */

		setTimeout(function() { $('.msg-ok').fadeOut('slow'); $('.msg-error').fadeOut('slow'); }, 5000);

		dynPagingLI($('#comments_list'), _var.comments_paginate_count, 1);	
		
		var pag_prev = _var.comments_paginate_prev;
		var pag_next = _var.comments_paginate_next;
	}

	var lastCaptchaCache = $.cookie('capchaDataCache');
	if (lastCaptchaCache == 1)
	{
		$('#author_id').val($.cookie('capchaDataCache_auth'));
		$('#email_id').val($.cookie('capchaDataCache_emil'));
		$('#comment_id').val($.cookie('capchaDataCache_cont'));
		$.cookie('capchaDataCache_auth', null);
		$.cookie('capchaDataCache_emil', null);
		$.cookie('capchaDataCache_cont', null);
	}

	$('.captcha-txt A').click(function(){
		$.cookie('capchaDataCache', '1');
		$.cookie('capchaDataCache_auth', $('#author_id').val());
		$.cookie('capchaDataCache_emil', $('#email_id').val());
		$.cookie('capchaDataCache_cont', $('#comment_id').val());	
	});

/*

	if ($().isDefined('_var.show_product_features'))
	{
		$('H3.expandable').each(function(i,a){
			$('A', a).click(function(){
				if($(this).hasClass('open')){
					$(this).removeClass('open');
					$($('A', a).attr('href')).addClass('hidden');
				} else {
					$(this).addClass('open');
					$($('A', a).attr('href')).removeClass('hidden');
				}
				return false;
			});
			if(!$('A', a).hasClass('open')){
				$($('A', a).attr('href')).addClass('hidden');
			}
		});
	}
*/
	

	if ($().isDefined('_var.group_product_brands'))
	{
		$('H2.expandable').each(function(i,a){
			$('A', a).click(function(){
				if($(this).hasClass('open')){
					$(this).removeClass('open');
					$($('A', a).attr('href')).addClass('hidden');
				} else {
					$(this).addClass('open');
					$($('A', a).attr('href')).removeClass('hidden');
				}
				return false;
			});
			if(!$('A', a).hasClass('open')){
				$($('A', a).attr('href')).addClass('hidden');
			}
		});
	}

	// Products sorting 
	$('.jssortby').click(function(){
		reSort();
	});
	
	$('#quick_search').submit(function() {
		reSort();
		return false;
	});
	
	$('#tiny_search').submit(function() {
		window.location = this.action + '&kw=' + $('#kw').val();
		return false;
	});
});

function reSort() {
	var sort = $('form input[@name=sortby]:checked').val();
	var kw = $('#kw').val();
	if (kw == $('#search_string_default').val()) { kw = ''; }
	var query = _var.url_me + '&kw=' + kw + '&sort=' + sort;
	// console.log(query);
	window.location = query;
}


jQuery.fn.sort = function() {
	return this.pushStack( jQuery.makeArray( [].sort.apply( this, arguments ) ) );
}; 

dynPagingLI = function(tbl, per_page, active, ret) {
	/*	Kui uus tõlkesüsteem JS jaoks kunagi valmis saab, on vaja see (ja ka kõik muud scriptid) üle käia	*/
	var lbl = ["&laquo; "+(pag_prev!==undefined ? pag_prev : "Previous"), (pag_next!==undefined ? pag_next : "Next")+" &raquo"];
	tbl = $(tbl);
	active = active===undefined || parseInt(active)===0 || !is_numeric(active) ? 1 : active;
	per_page = per_page===undefined || parseInt(per_page)===0 || !is_numeric(per_page) ? 30 : per_page;
	var count = $("li", tbl).size();
	if (count<per_page) {
		return;
	}
	var clickFunc = function(e) {
		var tbl = e.data.tbl;
		var ul = $(this).parent().parent();
		var count = $('a', ul).size();
		var p;
		if (e.data.special!==undefined) {
			if (this.className == 'disabled') {
				return;
			}
			p = parseInt($('a.active', ul).text()) + parseInt(e.data.special);
		} else {
			p = parseInt($(this).text());
		}
		var per_page = e.data.p;
		$('a', ul).removeClass('active');
		$('a:eq('+p+')', ul).addClass('active');
		$('li', tbl).addClass('hidden').filter('li:gt('+((p-1)*per_page-1)+')').filter("li:lt("+per_page+")").removeClass('hidden');
		$('a', ul).removeClass('disabled');
		if (p<2) {
			$('a:first', ul).addClass('disabled');
		} else if (p+1>count-2) {
			$('a:last', ul).addClass('disabled');
		}
	};
	var ul = dom.ce('ul').addClass('pages clear');
	for (var i=0; i<=count; i++) {
		if (i%per_page==0) {
			ul.append(dom.ce('li').append(dom.ce('a')
				.attr('href', 'javascript:void(0)')
				.text(i/per_page+1)
				.bind('click', {p: per_page, tbl:tbl}, clickFunc)));
		}
	} 
	ul.prepend(dom.ce('li').append(dom.ce('a', 'disabled', lbl[0]).attr('href', 'javascript:void(0)').bind('click', {p: per_page, tbl:tbl, special:-1}, clickFunc)));
	ul.append(dom.ce('li').append(dom.ce('a', '', lbl[1]).attr('href', 'javascript:void(0)').bind('click', {p: per_page, tbl:tbl, special:1}, clickFunc)));
	$('li:eq('+(active)+')>a', ul).click();

	if (ret===undefined) {
		$(tbl).after(ul);		
	} else {
		return ul;
	}
};eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('j.5=u(9,a,2){6(h a!=\'v\'){2=2||{};6(a===m){a=\'\';2.3=-1}4 3=\'\';6(2.3&&(h 2.3==\'n\'||2.3.k)){4 7;6(h 2.3==\'n\'){7=w C();7.B(7.z()+(2.3*A*o*o*E))}l{7=2.3}3=\'; 3=\'+7.k()}4 8=2.8?\'; 8=\'+2.8:\'\';4 b=2.b?\'; b=\'+2.b:\'\';4 c=2.c?\'; c\':\'\';d.5=[9,\'=\',q(a),3,8,b,c].t(\'\')}l{4 g=m;6(d.5&&d.5!=\'\'){4 e=d.5.x(\';\');D(4 i=0;i<e.f;i++){4 5=j.r(e[i]);6(5.p(0,9.f+1)==(9+\'=\')){g=y(5.p(9.f+1));s}}}F g}};',42,42,'||options|expires|var|cookie|if|date|path|name|value|domain|secure|document|cookies|length|cookieValue|typeof||jQuery|toUTCString|else|null|number|60|substring|encodeURIComponent|trim|break|join|function|undefined|new|split|decodeURIComponent|getTime|24|setTime|Date|for|1000|return'.split('|'),0,{}))
