function set_cookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function get_cookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var path = document.location.pathname;
if ( path.charAt(path.length-1) != '/' ) path = path+'/';

var epos = document.location.pathname.indexOf('/',1) == -1 ? document.location.pathname.length : document.location.pathname.indexOf('/',1)-1;
var section = document.location.pathname.substr(1, epos );	

$(document).ready(init);

var ajaxRes = new Array();
var catStatus = new Array();
var catHrefs = new Array();

function init(){
	//updateCart();
	
	$('.main-title').click(function(){
		
		var $el = $($(this).attr('rel'));
		if (!$el.length)
			return;

		if ($el.is(':visible')) {
			$el.hide();
			$(this).removeClass('main-title-opened').addClass('main-title-closed');
		}
		else {
			$el.show();
			$(this).removeClass('main-title-closed').addClass('main-title-opened');
		}
		
		return false;
	});
	
	var $see_also = $('#see_also');
	if ($see_also.length) {
		
		var $pages = $('.see-also-pages a');
		$('.see-also-pages a').click(function(){
			
			$pages.removeClass('see-also-page-active');
			$(this).addClass('see-also-page-active');
			
			var page = $(this).attr('see-also:page');
			$.ajax({
				url: $see_also.attr('see-also:url')+'?page='+page
			})
			.success(function(data){
				$see_also.empty().html(data);
			});
			
			return false;
		})
		.eq(0).click();
	}
	
	var buf = get_cookie('compare');
	if (buf){
		$('.compare-link').attr('href', '/comparer/'+buf);
		buf = buf.split(',');
		
		for (var i = 0; i < buf.length; i++)
			$('.compare-check[rel="'+buf[i]+'"]').attr('checked', true);
	}
	
	$('.compare-check').live('change', function(){
		var buf = get_cookie('compare');
		
		if (!buf)
			buf = [];
		else
			buf = buf.split(',');
		
		var id = $(this).attr('rel');
		var index = $.inArray(id, buf);
		if (index > -1)
			buf = buf.slice(0, index).concat(buf.slice(index+1));
		else
			buf.push($(this).attr('rel'));
		
		var ids = buf.join(',');
		set_cookie('compare', ids, 30);
		$('.compare-link').attr('href', '/comparer/'+ids);
	});
	
	$('.compare-link').live('click', function(){
		var buf = get_cookie('compare');
		if (!buf)
			buf = [];
		else
			buf = buf.split(',');
		
		if (buf.length < 2) {
			$(this).parent().find('.buyed-message').show();
			return false;
		}
	});
	
	$('.buyed-message-close').live('click', function(){
		
		$(this).parent().parent().hide();
		
		return false;
	});	

	$("#menu a").hover(
		function(){
			$(this).parent().prev("th").addClass("rc");
			$(this).parent().next("th").addClass("lc");
		},
		function(){
			$(this).parent().prev("th").removeClass("rc");
			$(this).parent().next("th").removeClass("lc");
		}
	);
	
	$("a.add2cart").live('click', product2cart);
	
	$(".raiting a").hover (
        function () {   
            //$(this).addClass("selected");
			$(".raiting a").removeClass("selected");
            var level = $(this).attr("rel");            
            $(".raiting a").each( function () { if ( (1*$(this).attr("rel")) <= level ) $(this).addClass("selected"); } );
        },
        function () {
            $(".raiting a").removeClass("selected");
			var level = $(".raiting").attr("id");			
			$(".raiting a").each( function () { if ( (1*$(this).attr("rel")) <= level ) $(this).addClass("selected"); } );
        }
    );
	
	$(".raiting a").click( function() {
			$.get("/ajax/index.php", { 'action': 'vote', 'product_id':$(this).parent().attr("rel"), 'vote': $(this).attr("rel") }, function (data) {
					
					if ( $("answer",data).attr('type') == 'error' ) {
						switch ( $("answer",data).attr('subtype') ) {
						case '1':
							$("#answer-type-1").fadeIn("slow", function () { setTimeout('$("#answer-type-1").fadeOut()',1500); });
							break;
						case '2':
							$("#answer-type-2").fadeIn("slow", function () { setTimeout('$("#answer-type-2").fadeOut()',1500); });
							break;
						case '0':
							$("#answer-type-0").fadeIn("slow", function () { setTimeout('$("#answer-type-0").fadeOut()',1500); });
							break;
						}
					}
					else if ( $("answer",data).attr('type') == 'done' ) {
						$("#answer-type-3").fadeIn("slow", function () { setTimeout('$("#answer-type-3").fadeOut()',1500); });						
					}
				}
			);
			
			return false;
		}
	);
	
	if ( $("div.raiting") ) {
		//#updateRaiting();
	}
	
	
	$("#login input").click (
		function() {
			if ( $(this).attr("value") == 'Ваш email' || $(this).attr("value") == 'пароль' ) { $(this).attr("value",''); }			
		}
	);
	$("#login input").blur (
		function() {
			if ( $(this).attr("name") == 'email' && $(this).attr("value") == '' ) { $(this).attr("value",'Ваш email'); }
			if ( $(this).attr("name") == 'password' && $(this).attr("value") == '' ) { $(this).attr("value",'пароль'); }			
		}
	);
	
	$("table.params tr:nth-child(odd)").addClass("white");
	
	$("#submenu .level0").click( function() {		
		
		if ( !$(this).attr("rel") ) {
			return true;
		}
		
		var pid = $(this).attr("rel");
		
		if ( catStatus[pid] ) {
			$("#pid-"+pid).hide();
			
			$(this).parent().next("div.item").removeClass("first");
			$(this).parent().prev("div.item").removeClass("last");
			
			$(this).parent().removeClass("selected");
			//$("img.title", this).attr('src', $("img.title", this).attr('src').replace('selected','default'));		
			
			var src = $("img.title", this).attr('rel').replace('s','');
			$("img.title", this).replaceWith('<img src="/images/submenu/titles/default/'+src+'.png" class="title" rel="s'+src+'">');
		}
		else {		
			catHrefs[pid] = $(this).attr("href");
			$(this).parent().addClass("selected");
			
			/*alert($("img.title", this).attr('src'));
			$("img.title", this).attr('src', $("img.title", this).attr('src').replace('default','selected'));*/
			var src = $("img.title", this).attr('rel').replace('s','');
			//alert(src);
			$("img.title", this).replaceWith('<img src="/images/submenu/titles/selected/'+src+'.png" class="title" rel="s'+src+'">');
			
			$(this).parent().prev("div.item").addClass("last");			
			$(this).parent().next("div.item").addClass("first");

			if ( !ajaxRes[pid]) {
				$("#pid-"+pid).text('Загрузка...');
				$("#pid-"+pid).load("/ajax/catalogue-menu.php", { 'pid': pid }, onAjaxSuccess);				
			}
			else 
				$("#pid-"+pid).show();
		}
		
		catStatus[pid] = !catStatus[pid];	
		
		return false;
	});

	$("#submenu .level0").each ( function () {
		var href = $(this).attr("href").replace('http://'+document.domain,'');
		
		if ( path.indexOf(href) == 0 ) {
			$(this).click();	
		}
	});

	$("#filters a").click(onFilterClick);
	$("#filters a").each ( function () {
		var href = $(this).attr("href").replace('http://'+document.domain,'');
		
		if ( path.indexOf(href) == 0 ) {
			$(this).click();	
		}
	});

	$("#voting a").click (function() {		
		if ( !$("#voting input[name='vote']:checked").attr('value') ) {
			$("#voting-error-vote").fadeIn("slow", function () { setTimeout('$("#voting-error-vote").fadeOut()',1500); });			
			return false;
		}
		$.get("/ajax/index.php", { 'action': 'voting', 'voting': $("#voting").attr("rel"), 'vote': $("#voting input[name='vote']:checked").attr('value') }, function (data) {			
			$("#voting input[name='vote']:checked").attr('checked','');
			if ( $("answer",data).attr('type') == 'done' ) $("#voting-done").fadeIn("slow", function () { setTimeout('$("#voting-done").fadeOut(); $("#voting").hide(); $("#voting-results").show()',1500); });
			if ( $("answer",data).attr('type') == 'error' ) $("#voting-error").fadeIn("slow", function () { setTimeout('$("#voting-error").fadeOut(); $("#voting").hide(); $("#voting-results").show()',1500); });
			if ( $("answer",data).attr('type') == 'error-vote' ) $("#voting-error-vote").fadeIn("slow", function () { setTimeout('$("#voting-error-vote").fadeOut()',1500); });
		});
		return false;
	});
	
	//if ( path == '/' ) {
		updateVoting();
	//}
	
}

function onFilterClick( e ) {
	var pid = $(this).attr("rel");
	var is_filter = false;
	if ( /filter-/.test(pid) ) {
		pid = pid.replace('filter-','');
		is_filter = true;
	}	
	
	if ( catStatus[pid] ) {
		$("#pid-"+pid).css("display","none");
		$(this).parent().removeClass('selected');
	}
	else {			
		if ( ajaxRes[pid] ) {	
			$("#pid-"+pid).css("display","block");
		}
		else {
			$('<ul id="pid-'+pid+'"></ul>').insertAfter(this);
			$("#pid-"+pid).html('<li>Загрузка...</li>');
			
			if ( is_filter ) { 				
				$("#pid-"+pid).load("/ajax/index.php", { 'action':'get-filters', 'filter': pid }, function (data) {					
					ajaxRes[$(this).attr("id").replace('pid-','')] = data;
					/*$("a", "#pid-"+$(this).attr("id").replace('pid-','')).click( function() {						
						$.get("/ajax/index.php", { 'action':'get-filter-data', 'filter': $(this).attr('rel'), 'cat-name': encodeURI($(this).text()) }, function (data) {
							alert(data);
						});
						return false;
					});*/
				});
			}
			else
				$("#pid-"+pid).load("/ajax/index.php", { 'action':'get-subcats', 'pid': pid }, function (data) {
					ajaxRes[$(this).attr("id").replace('pid-','')] = data;
				});
		}
		$(this).parent().addClass('selected');
	}
	catStatus[pid] = !catStatus[pid];

	return false;
}

function onAjaxSuccess(data) {	
	ajaxRes[$(this).attr("id").replace('pid-','')] = data;
	$("#"+$(this).attr("id")+" a").each ( function () { 
		var href = $(this).attr("href").replace('http://'+document.domain,'');
	
		if ( path.indexOf(href) == 0 ) {
			$(this).addClass("selected");	
		}
	});	
}

function product2cart(e) {
	var prod_id = $(this).attr("rel");	
	var count = $("#count_"+prod_id).attr("value");
	var $buyed = $(this).parent().find('.buyed-message');
	
	if ( !count )
		count = 1;
	
	var url = "/cart/add/"+prod_id+"/"+count+"/";
	
	$.ajax({
		url: url,
		dataType: 'json'
	})
	.success(function(data){
		$buyed.show();
		
		$('#all_count').text(data.count);
		$('#all_cost').text(data.cost);
		
		setTimeout(function(){ $buyed.hide(); }, 3000);
	})
	
	//try { console.log(url) } catch(e) {} 
	//document.location = url;
	/*var win = window.open('/cart/add/'+prod_id+'/'+count+'/',
		'add2cart',
		"scrollbars=0, resizable=0, titlebar=0, height=1, width=1, left="+(screen.width/2-750/2)+", top=20");*/
	
	return false;
}

function updateCart() {
	$.get("/ajax/cart.php", {}, onUpdateCart);
	setTimeout('updateCart()',3000);
	/*if ( !(/MSIE/.test(navigator.userAgent)) )
		return;*/
		
	if ( $("html").width() % 2 != 0 ) { $("#menu .right").css("right", "-40px"); }
}

function updateVoting() {
	$.get("/ajax/index.php", { 'action':'voting-results', 'voting': $("#voting-results").attr("rel") }, function(data) {
	
		for(i=1; i<=$("#voting-results .bar").length; i++) {
			var res = 232 - (232 * $("answer", data).attr("res"+i) / 100);
			$("#voting-results .bar[rel='res"+i+"'] span").text(' - '+$("answer", data).attr("res"+i+"")+'%');
			$("#voting-results .bar[rel='res"+i+"']").css('background-position', '-'+res+'px top');
		}
	});
	setTimeout('updateVoting()', 30000);
}

function updateRaiting () {
	$.get("/ajax/index.php", { 'action':'getraiting', 'product_id': $("div.raiting").attr("rel") }, function(data) {
			var raiting = $("answer", data).attr("raiting");			
						
			$(".raiting .value").hide();
			$(".raiting .value[rel='"+raiting+"']").show();
			$(".raiting .value[rel='"+raiting+"'] .votes-count").text(" ("+$("answer", data).attr("count")+")");
			$(".raiting").attr("id", raiting);
			
			$(".raiting a").each( function () { if ( (1*$(this).attr("rel")) <= raiting ) $(this).addClass("selected"); } );
		}		
	);
	setTimeout('updateRaiting()',3000);
}

function onUpdateCart( data ) {	
	$("#all_count").text($("cart",data).attr('all_count'));
	$("#all_cost").text($("cart",data).attr('all_cost'));
}

function sendForm( name ) {
	try {
		var n = document.forms[name].length;		
		
		var i = 0;
		while ( i < n ) {		
			if ( document.forms[name].elements[i].value == '' && document.forms[name].elements[i].className != 'nrq' ) {
				alert('Не все поля заполнены');
				
				document.forms[name].elements[i].focus();
				return false;
			}
		
			i++;
		}
		document.forms[name].submit();		
	}
	catch ( ex ) {
		alert(ex);
	}
}

function clearForm( name ) {
	try {
		var n = document.forms[name].length;		
		
		var i = 0;
		while ( i < n ) {		
			document.forms[name].elements[i].value = '';				
			i++;
		}		
	}
	catch ( ex ) {
		alert(ex);
	}
}

function checkForm ( name ) {
	var res = true;
	$("#"+name+" input, #"+name+" textarea").each(
		function () {			
			
			if ( $(this).hasClass("required") && $(this).val() == '' ) {
				res = false;
				$("#"+name+" .inline-message.required").show();
			}
			if ( $(this).hasClass("email") && $(this).val() != '' ) {								
				var emailTest = '^[_\\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z_-]+\\.)+[a-z]{2,4}$';
				var regex = new RegExp(emailTest);
				if ( !regex.test( $(this).val() ) ) {
					res = false;
					$("#"+name+" .inline-message.email").show();
				}
			}
		}
	);
	setTimeout("$('#"+name+" .inline-message').fadeOut();",5000);
	return res;
}

function popupWindow( url, w, h ) {
	var win = window.open(
		url,
		'PopupWindow',
		"scrollbars=1, resizable=1, titlebar=1, height="+h+", width="+w+", left="+(screen.width/2-w/2)+", top=20");	
}
