$(document).ready(function() {
	$().mousemove(function(e){
	      mousex = e.pageX;
		  mousey = e.pageY;
	   }); 

	
	$("*[@id^=addtocart]").click(function(){
		add_to_cart($(this).attr('id').replace(/\D/g,''));
		return false;
	})
	
	$(":checkbox[@id^=compare]").click(function(){
		var cid = $(this).attr('id').replace(/compare/,'');
		$('#compare_block').load('/shop_compare_block.php?lang=' + $("body").attr("lang") + '&id=' + cid + (this.checked ? '' : '&delete=1'));
	})
	
	$("#order_recount").click(reload_cart)

	function reload_cart()
	{
		$("#cart_table").load("/shop_cart_table.php?lang=" + $("body").attr("lang"),$("#order_form").serializeArray(),function(){
			$("#cart_block").load("/shop_cart_block.php?lang=" + $("body").attr("lang"));
			$("#cart_sum").load("/shop_cart_sum.php?lang=" + $("body").attr("lang"));
			$(":text[@name^=q_]").keyup(function(){if(new RegExp('^[0-9]+$','g').test($(this).val())) reload_cart()})
		});

		if($(":checkbox[@name^=d]").length == $(":checkbox[@name^=d]:checked").length) $("#cart_options").hide();
	}
	
	$(":text[@name^=q_]").keyup(function(){if(new RegExp('^[0-9]+$','g').test($(this).val())) reload_cart()})
	
	$('#orderphys').click(function(){
		$('#ordercontent').load('/shop_order_form.php?order_type=phys&lang=' + $("body").attr("lang"),function(){$(this).show();init()});
	})

	$('#orderjur').click(function(){
		$('#ordercontent').load('/shop_order_form.php?order_type=jur&lang=' + $("body").attr("lang"),function(){$(this).show();init()});
	})

	$.get('/forms_messages.php?lang=' + $('body').attr('lang'),function(data){
		$(data).appendTo('body');
	})
	
	$("form.pollform").submit(function(){
		url_str = "id=" + $(this).attr('pollid') + "&variant=" + $(":checked",this).val() + "&lang=" + $('body').attr('lang');
		$("#poll" + $(this).attr('pollid')).load("/poll.php?" + url_str);
		return false;
	});
	
	$("a[@id^=th_]").click(function(){
		var preg_array = /^th_(\d+)_(\d+)_(\d+)$/.exec($(this).attr('id'));
		if(preg_array)
		{
			var res_id = preg_array[1];
			var res_width = preg_array[2];
			var res_height = preg_array[3];
			open_modal_window('/open_image.php?file=' + res_id,res_width,res_height);
		}
		return false;
	})

	$('a[id^=sitemaplink]').click(function(){
		var divid = $(this).attr('id').replace(/\D/g,'');
		var sitemap_div = $('#sitemap' + divid);
		var img = $(this).find('img');
		var img_src = img.attr('src');
		if(!sitemap_div.is(':hidden'))
		{
			sitemap_div.hide();
			$('<br id=temp_br'+divid+'>').insertAfter(sitemap_div);
			var new_src = img_src.replace(/minus/g,'plus');
			img.attr('src',new_src);
		}
		else
		{
			sitemap_div.show();
			$('#temp_br'+divid).hide();
			var new_src = img_src.replace(/plus/g,'minus');
			img.attr('src',new_src);
		}
		return false;
	})
	
	init();
	reevent_comments();
});


function reevent_comments()
{
	$('#comments *[@id^=quote]').click(function(){
		var cid = 'comment' + $(this).attr('id').replace(/\D/g,'');
		var str = $('#' + cid).html();
		str = str.replace(/<(blockquote)>.*<\/\1>/ig,'');
		str = '[QUOTE]' + str + '[/QUOTE]';
 		if(typeof(tinyMCE) == 'object') tinyMCE.execInstanceCommand('comment','mceInsertContent',false,str);
		return false;
	})
}

function reload_captcha(elID)
{
	jq = !elID ? $("img[@src*=code.jpg]") : $("img[@src*=code.jpg]",$("#"+elID));
	jq.each(function(){
		var new_src = $(this).attr('src').replace(/\?.*$/g,'') + '?' + Math.random();
		$(this).attr('src',new_src);
	})
}


function show_need_message(obj,message)
{
	return $('<div class=needmessage needdiv=1>' + message + '</div>').insertAfter($(obj)).hide().fadeIn(600);
}

function show_message(msgText,msgPos)
{
	if(!msgPos) msgPos = 'center';
	var ajax_message = $("<div id=ajaxmessage style='display:none'>" + msgText + "</div>").appendTo('body').css('position','absolute');
	ajax_message.css('left',($(document).scrollLeft() + ($(window).width() - ajax_message.width()) / 2));
	ajax_message.css('top',($(document).scrollTop() + ($(window).height() - ajax_message.height()) / 2));
	return ajax_message;
}

function show_menu(i)
{
	$('#submenu'+i).is(":hidden") ? $('#submenu'+i).show() : $('#submenu'+i).hide();
}

function add_to_cart(n)
{
	if(!$(":text[@name=q_" + n + "]").size()) $("<input type=hidden name=q_" + n + " value=1>").appendTo('body');
	var f = $("select[@name^=prop_"+n+"_],:text[@name=q_" + n + "]").serializeArray();
	$("#cart_block").load('/shop_cart_block.php?lang=' + $('body').attr('lang'),f,function(){
		var sm = show_message($("#cart_added_text").val(),'center').fadeIn(200);
		setTimeout(function(){sm.fadeOut(600,function(){$(this).remove()})},1000);
	});
}

function check_mail(str)
{
	if(str == '') return true;
	var reg = /\s/g;
	str = str.replace(reg,'');
	var mails = str.split(",");
	var reg2 = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@[a-zA-Z0-9_\.-]+\.[a-zA-Z]{2,4}$/;
	for(i = 0;i < mails.length;i++) if(!reg2.test(mails[i])) return false;
	return true;
} 

function open_modal_window(file,modal_width,modal_height,func)
{
	$("#modal").remove();
	var modal = $('<div id=modal style="display: none">Загрузка...</div>').appendTo('body');
	modal.css('position','absolute').width(modal_width).height(modal_height);
	var left_coord = parseInt($(document).scrollLeft() + ($(window).width() - modal_width) / 2);
	var top_coord = parseInt($(document).scrollTop() + ($(window).height() - modal_height) / 2);
	if(left_coord < 0) left_coord = 0;
	if(top_coord < 0) top_coord = 0;
	modal.css('left',left_coord).css('top',top_coord);
	var reg = new RegExp('^/','g');
	modal.load(file,function(){
		$("#modalimage").parents('a').click(function(){return false})
		$("body,#modalimage").click(function(){$("#modal").fadeOut(250,function(){$(this).remove()})})
		modal.fadeIn(250).draggable();
	});
}

function close_order_form()
{
	$('#cart_table,#cart_options').remove();
	$('#cart_block').load('/shop_cart_block.php');
}

function init()
{
	$("form[validate]").submit(function(){
			var submit_form = true;
			var form_id = $(this).attr('id');
			if(!form_id) form_id = $(this).attr('id','form' + document.uniqueID).attr('id');
			$(this).find("div[needdiv]").remove();
			$(this).find(':input[need]').each(function(){
				if($(this).val() == '' && !$("div[needdiv]").length)
				{
					var need_message = show_need_message(this,$("div[@fmessage=fill]").html());
					$(this).bind("keydown",function(){need_message.remove()})
					submit_form = false;
					if($(this).is(":visible")) $(this).focus();
					return false;
				}
			});
			$(this).find(':input[mail]').each(function(){
				if($(this).val() && !check_mail($(this).val()) && !$("div[needdiv]").length)
				{
					var need_message = show_need_message(this,$("div[@fmessage=mail]").html());
					$(this).bind("keydown",function(){need_message.remove()})
					submit_form = false;
					this.focus();
					return false;
				}
			});
			$(this).find(':input[minlength],:password[minlength]').each(function(){
				var val_length = $(this).val().length;
				var min_length = parseInt($(this).attr('minlength'));
				if(val_length < min_length && !$("div[needdiv]").length)
				{
					var need_message = show_need_message(this,$("div[@fmessage=min]").html().replace(/#n#/g,min_length));
					$(this).bind("keydown",function(){need_message.remove()})
					submit_form = false;
					this.focus();
					return false;
				}
			});
			$(this).find(':file[exts]').each(function(){
				var exts = $(this).attr('exts').split(' ');
				var file_name = $(this).val();
				if(file_name)
				{
					var ext = '';
					var valid_ext = false;
					if(preg = new RegExp('\.([a-zA-Z]+)$','g').exec(file_name)) ext = preg[1];
					for(i = 0;i < exts.length; i++)
					{
						if(ext == exts[i])
						{
							valid_ext = true;
							break;
						}
					}
					if(!valid_ext && !$("div[needdiv]").length)
					{
						var message = $("div[@fmessage=fileext]").html();
						message = message.replace('#formats#',exts.join(','));
						var need_message = show_need_message(this,message);
						$(this).bind("keydown",function(){need_message.remove()})
						submit_form = false;
						if($(this).is(":visible")) $(this).focus();
						return false;
					}
				}
			});
						
			var pss = $(this).find(':password[password]');
			if(pss.length && submit_form)
			{
				var pss_val = $(this).find(':password[password]:first').val();
				pss.each(function(){
					if($(this).val() != pss_val && !$("div[needdiv]").length)
					{
						var need_message = show_need_message(this,$("div[@fmessage=pwds]").html());
						$(this).bind("keydown",function(){need_message.remove()})
						submit_form = false;
						this.focus();
						return false;
					}
				})
			}
			if(submit_form)
			{
				$(this).find(':file').each(function(){
					if($(this).val())
					{
						$("#" + form_id).attr('direct','1');
						if($("#" + form_id).attr('action').indexOf('forms_handler.php') != -1) $("#" + form_id).attr('action','');
						return;
					}
				})
				if(!$(this).is("[@direct=1]"))
				{
					var is_order_form = $(this).attr('action').indexOf('shop_order_send.php') != -1;
					var sending = show_message($("div[@fmessage=send]").html(),'center');
					if(this.method == 'get') $("#" + form_id + "_result").load($(this).attr('action'),function(){sending.remove();reload_captcha(form_id)});
					else
					{ 
						var serialize = "#" + form_id + (is_order_form ? ',#order_form' : '');
						var to = $(this).attr('action');
						$("#" + form_id + "_result").load(to,$(serialize).serializeArray(),function(){
							sending.remove();
							reload_captcha(form_id);
							reevent_comments();
							$('#comments textarea').val('');
							if(typeof(tinyMCE) == 'object') tinyMCE.execInstanceCommand('comment','mceSetContent',false,'');
							if($(this).find('#form_message_ok,.success').size()) $("#" + form_id).remove();
							if(is_order_form) close_order_form();
						});
					}
				}
				else return true;
			}
			return false;
	})

}
