﻿var uploaded = true;

//////// FUNCTIONS /////////

function refresh()
{
	$.post(root + "ajax/refresh.php");
}

function renderLoadingOverlay(msg)
{
	dg = $("#gal_dialog");
	dg.css({"display": "block"});
	
	cont = '<div id="gal_dialog_loading" class="gal_dialog_content">';
	cont += '<div class="header">' + msg + '</div>';		
	cont += '</div>';
	
	$("body").append(cont);

	if ($.browser.msie)
		dg.css({"height": $("body").height()});
}

function renderLoadingOverlaySized(msg, width)
{
	dg = $("#gal_dialog");
	dg.css({"display": "block"});
	dg.css({"background-color": "#000000"});
	
	cont = '<div id="gal_dialog_loading" class="gal_dialog_content" style="width: 550px; font-size: 14px; left: 350px;">';
	cont += '<div class="header">' + msg + '</div>';		
	cont += '</div>';
	
	$("body").append(cont);
	
	if ($.browser.msie)
		dg.css({"height": $("body").height()});
}

function removeLoadingOverlay()
{
	$("#gal_dialog_loading").remove();
	$("#gal_dialog").css({"display": "none"});
}

function startGalDialog(msg)
{
	dg = $("#gal_dialog");
	dg.css({"display": "block"});
	
	cont = '<div id="gal_dialog_cont">';
	cont += '<div class="header">' + msg + '<span id="gal_dialog_close"></span><div class="clear"><!-- --></div></div><div id="gal_dialog_body"></div>';		
	cont += '</div>';
	
	$("body").append(cont);
	if ($.browser.msie)
		dg.css({"height": $("body").height()});
}

function removeGalDialog()
{
	$("#gal_dialog").css({"display": "none"});
	$("#gal_dialog_cont").remove();
}

function loadImage(i, data)
{
	divHtml = $("#img-00").html();
	divHtml = divHtml.replace("#$#", i);
	divHtml = divHtml.replace("#$#", i);
	div = "<div class='photos' id='img-" + i + "'>" + divHtml + "</div>";
	
	if (i == 0)
		last = $("#img-00");
	else
	{
		lastIndex = parseInt(i) - 1;
		last = $("#img-" + lastIndex);
	}
	$(div).insertAfter(last);
	
	$("#img-" + i + " .special_copy_agreement").fadeIn();
	$("img-" + i + " .image_filename").html(data.data[i].real_name);
	$("#img-" + i + " .choose_sample").attr("title", i);
	$("#img-" + i + " .image_format").html(data.default_size);
//	$("#count_files").html(data.files);
//	$("#current_image_number").html(i+1);
	$("#img-" + i + " .image_price").html(data.default_price + 'лв.');
	$("#img-" + i + " .image_new_name").val(data.data[i].name);
	$("#img-" + i + " .image_size").html(data.data[i].size + ", " + data.data[i].filesize + ' Mb');
	$("#img-" + i + " .additional_sizes").html("<tr><td>Формат</td><td>Копия</td><td>Цена</td></tr>");
	
	if (data.type == "gifts" || data.type == "crystals" || data.type == "albums" || data.type == "frames2")
	{
		$("#gifts_real_img").attr("src", root + 'orders/order' + data.order + '/thumb/' + data.data[i].name);
		$("#main_size_copies").val(data.data[i].sizes.qt);
	}
	else
	{
		$("#img-" + i + " .main_size_copies").val(data.data[i].sizes[data.default_size]);
		$("#img-" + i + " .main_size_copies").attr("alt", data.default_size);
	}
		
	
	if (data.type == "gifts" || data.type == "calendars" || data.type == "frames" || data.type == "crystals" || data.type == "albums" || data.type == "frames2")
	{
		if (data.data[i].sample)
			$("#order_samples_image img ").attr("src", root + "samples/" + data.data[i].sample.type +"/thumb/" + data.data[i].sample.file);
		else
			$("#order_samples_image img ").attr("src", root + "images/order-welcome3-" + data.type + ".gif");
	}
	
//	if (data.data[i].frame == "fill")
//	{
		$("#img-" + i + " .frame_fill").attr("checked", "checked");
//	}
//	else
//		$("#img-" + i + " .frame_fit").attr("checked", "checked");
	
	if (data.add_sizes[data.data[i].name])
		$.each(data.add_sizes[data.data[i].name], function(key, val) {
			$("#img-" + i + " .additional_sizes").append('<tr><td>' + val.name + '</td><td><input type="text" alt="' + val.name.replace("/", "_") + '" class="sizes_input2" name="add_size" value="' + val.quantity + '" /></td><td>' + val.price + '</td></tr>');
		});
								
	$("#img-" + i + " .image_fit").attr("src", root + 'orders/order' + data.order + '/thumb/' + data.data[i].name);
	$("#img-" + i + " .image_fit").css({
		'position': 'absolute', 
		'top': (((100 - data.frames[data.data[i].name].r.height)/2)+1) + 'px',
		'left': ((100 - data.frames[data.data[i].name].r.width)/2) + 'px',
		'width': data.frames[data.data[i].name].r.width + 'px',
		'height': data.frames[data.data[i].name].r.height + 'px'});
		
	$("#img-" + i + " .image_fill").attr("src", root + 'orders/order' + data.order + '/thumb/' + data.data[i].name);							 
	$("#img-" + i + " .image_fill").css({
		'position': 'absolute', 
		'top': (((100 - data.frames[data.data[i].name].t.height)/2)+1) + 'px',
		'left': ((100 - data.frames[data.data[i].name].t.width)/2) + 'px',
		'width': data.frames[data.data[i].name].t.width + 'px',
		'height': data.frames[data.data[i].name].t.height + 'px'});
		
	$("#img-" + i + " .image_border").css({
		'margin': '0px', 
		'border': '1px solid red', 
		'display': 'block',	
		'background-color': '#fff',	
		'position': 'absolute', 
		'top': ((100 - data.frames[data.data[i].name].b.height)/2) + 'px',
		'left': (((100 - data.frames[data.data[i].name].b.width)/2)-1) + 'px',
		'width': data.frames[data.data[i].name].b.width + 'px',
		'height': data.frames[data.data[i].name].b.height + 'px'});
	$("#img-" + i + " .image_border_fill").css('background-color', 'transparent');
}

$(function(){
	/////////////////////// MSG za kristalite
	if ($.browser.opera)
		$("#copy-agreement").css({"border": "1px solid grey"});
	
	$("#crystals_btn").mouseover(function(){
		$("#crystals_msg").fadeIn();
	});
	
	$("#crystals_btn").mouseout(function(){
		$("#crystals_msg").fadeOut();
	});
	
	$(".del").click( function(){
		return confirm("Сигурни ли сте, че искате да продължите с изтриването?");
	});
	
	$(".del_photo").click( function(){
		if (confirm("Сигурни ли сте, че искате да продължите с изтриването?"))
		{			
			$("#delete_photo").val($(this).attr("title"));
			$("#delete_photo_submit").click();
			return false;
		}
		else
			return false;
	});
	
	$(".sizes_input").change( function(){
		name = $(this).attr("name");
		qt = $(this).val();
		data = name.split("-");
		
		$.post(root + "ajax/change_quantity.php", {"action":"change_additional", "id":data[2], "size":data[1], "quantity":qt}, function(data){
			$(this).val(data);
		});
	});

	$("#custom_quantity").change( function(){		
		qt = $(this).val();
		if (isNaN(qt))
			$(this).val("1");
		if (qt < 1)
			$(this).val("1");
		price = $("#custom_single_price").html();
		price = price.substring(0, price.length-3);
		files = $("#custom_max_files").html();
		
		$.post(root + "ajax/change_custom_price.php", {"action":"change_custom_price", "quantity":qt, "price":price, "files":files}, function(data){
			$("#custom_whole_price").html(data);
		});
	});
	
	$(".frame_radio").click(function(){
		name = $(this).attr("name");		
		data = name.split("-");
		val = $(this).val();
		
		$.post(root + "ajax/change_frame.php", {"id":data[1], "value":val});
	});
	
	$(".operator_radio").click(function(){
		val = $(this).val();
		
		$.post(root + "ajax/change_operator.php", {"value":val});
	});
	
	$(".paper_radio").click(function(){
		val = $(this).val();
		
		$.post(root + "ajax/change_paper.php", {"value":val}, function(){
			if (val == "glanc")
				$(".image_paper").html("ГЛАНЦ");
			else
				$(".image_paper").html("МАТ");
		});
	});
	
	$("#step2_submit").click(function(){
		$.getJSON(root + "ajax/check_quantities.php", function(data){
			
			if(data.error == "true")
			{
				$(".error").remove();				
				$("#order_more").before('<div class="error"><p>Трябва да зададете най-малко 1 копие, за поне един размер, за следните файлове: ' + data.files + '</p></div>');
				return false;
			}
			else
				$("form[name='order_step_2']").submit();
		}, "json");
		
		
	});
	
	$(".order_more").click(function(){
		sub = $("#order_type").val();
		window.location = root + "order/step1/" + sub + "/";
	});
	
	$("#order_deny_hover").click(function(){
		window.location = root + "order/delete/";		
	});
	
	$("#order_deny").click(function(){
		window.location = root + "order/delete/";		
	});
	
//////////////////// NEW ORDER ///////////////////////////
	
	$("#control-send").click(function(){
		qt = $("#all-count").val();
		format = $(".frame_radio_all:checked").val();
		size = $(".img-1 .main_size_copies").attr("alt");
		
		if (qt <= 0)
		{
			alert("Трябва да въведете размер по-голям или равен на 1");
			$("#all-count").val("1");
		}
		else
		{
			$.post(root + "ajax/change_all_photos.php", {"frame": format, "qt": qt, "size": size}, function(data){
				$(".main_size_copies").val(qt);
				$(".frame_" + format).attr("checked", "checked");
			});
		}
	});
	
	$(".frame_radio_all").click(function(){
		format = $(this).attr("id").replace("frame_", "").replace("_all", "");
		
		$.post(root + "ajax/change_all_photos.php", {"action": "frame", "frame": format}, function(data){
			$(".frame_" + format).attr("checked", "checked");
		});
	});
	
	$("#all-count").keyup(function(e){
		qt = $(this).val();
		size = $(".img-1 .main_size_copies").attr("alt");
		
		if ((qt <= 0 || isNaN(qt)) && (qt != ''))
		{
			alert("Трябва да въведете размер по-голям или равен на 1");
			$("#all-count").val($("#default-size").val());
		}
		else
		{
			$.post(root + "ajax/change_all_photos.php", {"action": "sizes", "qt": qt, "size": size}, function(data){
				if (qt != '')
				{
					$(".main_size_copies").val(qt);
					$("#default-size").val(qt);
				}
			});
		}
	});
	
	$("#all-count").change(function(){
		qt = $(this).val();
		size = $(".img-1 .main_size_copies").attr("alt");
		
		if (qt == '')
		{
			alert("Трябва да въведете размер по-голям или равен на 1");
			$("#all-count").val($("#default-size").val());
		}
	});
	
	$(".banner_gifts").click(function (){
		$("#banner_container").attr("src", root + "images/gifts_prices.jpg");
		$("#dialog_").dialog('option', 'title', 'Подаръци и сувенири:');
		$("#dialog_").dialog('option', 'position', 'top');
		$('#dialog_').dialog('option', 'modal', true);
		$("#dialog_").dialog('open');
		
		return false;
	});
	
	$(".banner_crystals").click(function (){
		$("#banner_container").attr("src", root + "images/crystals_prices.jpg");
		$("#dialog_").dialog('option', 'title', 'Подаръци и сувенири:');
		$("#dialog_").dialog('option', 'position', 'top');
		$('#dialog_').dialog('option', 'modal', true);
		$("#dialog_").dialog('open');
		
		return false;
	});
	
	$("#dialog_").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 1000
	});
	
	$("#accordion").accordion({ 
		autoHeight: true,
		fillSpace: true

	});
	
	$('#accordion a').click(function() {
		return false;
	});
	
	$('#accordion .ui-accordion-header span').click(function() {
		return false;
	});
	
	$('#accordion .next_step_hover').live('click', function() {
		
		if ($(this).attr("id") != "next_step_4")
		{			
			if ($(this).attr("id") != "first_step_btn")
			{
				setTimeout($(this).attr("disabled", "enabled"), 1000);
			}
			else
			{
				if (($("input:radio[name=copy_type]:checked").val() == 2) && ($("#copy-agreement:checked").val() != 2))
				{
					alert('Не сте отбелязали, че сте прочели условията за копиране.');
					return false;
				}
				if ($(this).attr("disabled"))
					return false;
			}
			
			$(this).parents(".acc_content").hide('slow').next().next('.acc_content').toggle("slow");
			$(this).parents(".acc_content").prev().removeClass('ui-accordion-header ui-helper-reset ui-state-active ui-corner-top');
			$(this).parents(".acc_content").prev().children("span").removeClass('ui-icon ui-icon-triangle-1-s');
			$(this).parents(".acc_content").prev().children("span").addClass('ui-icon ui-icon-triangle-1-e');
			$(this).parents(".acc_content").prev().addClass('ui-accordion-header ui-helper-reset ui-state-default ui-corner-all');
		}
		
		$(this).attr("disabled", "disabled");
		
		return false;
	});
	
///////////////// BUTTON HOVERS ///////////////////////////////////////////////
	
	$(".next_step").mouseover(function (){
		$(this).attr('class', 'next_step_hover ie6_first_btn');
	});
	
	$(".next_step_hover").live('mouseout', function (){
		$(this).attr('class', 'next_step ie6_first_btn');
	});
	
	$(".next_step_last").mouseover(function (){
		$(this).attr('class', 'next_step_last_hover ie6_first_btn');
	});
	
	$(".next_step_last_hover").live('mouseout', function (){
		$(this).attr('class', 'next_step_last ie6_first_btn');
	});
	
	$(".finish_cart").mouseover(function (){
		$(this).attr('class', 'finish_cart_hover');
	});
	
	$(".finish_cart_hover").live('mouseout', function (){
		$(this).attr('class', 'finish_cart');
	});
	
	$(".last_cart").mouseover(function (){
		$(this).attr('class', 'last_cart_hover');
	});
	
	$(".last_cart_hover").live('mouseout', function (){
		$(this).attr('class', 'last_cart');
	});
	
	$(".finish_step").mouseover(function (){
		$(this).attr('class', 'finish_step_hover');
	});
	
	$(".finish_step_hover").live('mouseout', function (){
		$(this).attr('class', 'finish_step');
	});
	
	$(".start_new_order").mouseover(function (){
		$(this).attr('class', 'start_new_order_hover big_button');
	});
	
	$(".start_new_order_hover").live('mouseout', function (){
		$(this).attr('class', 'start_new_order big_button');
	});
	
	$(".copy_from_gal").mouseover(function(){
		$(this).css({"background-color": "#F7F7F7"});
	});
	
	$(".copy_from_gal").mouseout(function(){
		$(this).css({"background-color": "#EDE8E9"});
	});
	
	$("#terms_of_use_link").live("click", function(){
		$("#terms_of_use").toggle();
		
		return false;
	});
	
	$("#terms_of_use_link").click(function(){
		$("#terms_of_use p").css({"width": "430px"});
		$("#terms_of_use").toggle();
		
		return false;
	});
	
	$('.acc_content').css({"height": "auto"});
	
	$(".copy_from_gal").click(function(){
		$("#main_flash_container").fadeOut("fast", function(){
			$("#main_java_container").fadeOut("fast", function(){
				$(this).parent().parent().load(root + "ajax/order_gallery.php", { 'action': "get_albums"});
			});
		});
		$("#main_java_container").fadeOut();		
	});
	
	$(".order_albums_item").live("click", function(){
		if (!$(this).hasClass("order_images_item"))
		{
			id = $(this).attr("id").replace("album_", "");
			$("#main_order_gallery_container").load(root + "ajax/order_gallery.php", { 'action': "get_images", "id": id});
		}
		
		return false;
	});
	
	$("#order_gal_copy_images").live("click", function(){
		renderLoadingOverlay('Копиране');
		$(".order_images_item").each(function(id, item){
			if ($(this).children("p").children("input").attr("checked"))
			{
				image = $(this).children("p").children("input").val();
				$.post(root + "ajax/order_gallery_copy.php", { 'action': "copy", "image": image, "album": $("#order_gal_album_id").val()}, function(data){
	//				alert(data);
					if (!data.success)
					{
						alert("Възникна проблем при копирането на файловете. Моля опитайте пак.");
						removeLoadingOverlay();
						return false;
					}
				}, "json");
			}
		});
		removeLoadingOverlay();
		
		copy = $("input:radio[name=copy_type]:checked").val();
		size = $("input:radio[name=size]:checked").val();
		
		if (copy == 1)
		{
			$("#image_container").load(root + "ajax/order_queries.php", { 'action': "load_gallery", "copy": copy, "size": size },function(){
				$("#image_container").fadeIn();
			});
		}
		else
		{
			$.post(root + "ajax/order_queries.php", { 'action': "load_gallery", "copy": copy, "size": size }, function(data){
				$("#image_container").data("images", data);
				$("#image_container").data("show", 0);
				$("#image_container").data("qty", {});
				loadImage(0, $("#image_container").data("images"));
				$("#image_container").fadeIn();
				
				for (var i in data.files)
				{
					loadImage(i, $("#image_container").data("images"));
				}
//				if (data.files > 1)
//				{
//					$("#next_file img").mouseover(function(){
//						$(this).attr("src", root + 'images/next-img.gif');
//					});
//					$("#next_file img").mouseout(function(){
//						$(this).attr("src", root + 'images/next-img-grey.gif');
//					});
//
//					$("#previous_file img").mouseover(function(){
//						$(this).attr("src", root + 'images/prev-img.gif');
//					});
//					$("#previous_file img").mouseout(function(){
//						$(this).attr("src", root + 'images/prev-img-grey.gif');
//					});
//
//					$("#previous_file img").bind("click", function(){
//						show = $("#image_container").data("show");
//						files = $("#image_container").data("images").files;
//
//						if (show > 0)
//						{
//							loadImage(show - 1, $("#image_container").data("images"));
//							$("#image_container").data("show", show - 1);
//						}
//						else
//						{
//							loadImage(files - 1, $("#image_container").data("images"));
//							$("#image_container").data("show", files - 1);
//						}
//					});
//
//					$("#next_file img").bind("click", function(){
//						show = $("#image_container").data("show");
//						files = $("#image_container").data("images").files;
//
//						if ((show + 1) < files)
//						{
//							loadImage(show + 1, $("#image_container").data("images"));
//							$("#image_container").data("show", show + 1);
//						}
//						else
//						{
//							loadImage(0, $("#image_container").data("images"));
//							$("#image_container").data("show", 0);
//						}
//					});
//				}
		    }, "json");
		}

		$('#accordion .next_step_hover').trigger("click");
	});
	
	$("#order_gal_back_album").live("click", function(){
		$("#order_albums_container").load(root + "ajax/order_gallery.php", { 'action': "get_albums"});
	});
	
	var orderGalCheck = function()
	{
		$(this).toggle(function(){
			$("#order_albums_content").children(".order_images_item").each(function(){			
				$(this).children("p").children("input[type='checkbox']").attr("checked", true);
			});
		}, function(){
			$("#order_albums_content").children(".order_images_item").each(function(){			
				$(this).children("p").children("input[type='checkbox']").attr("checked", false);
			});
		});
	};
	
	var destroyGalCheck = function() { 
		 $(this).unbind('toggle').unbind('click'); 
	}; 
	
	$("#order_gal_checkall_image").livequery(orderGalCheck, destroyGalCheck);
	
//	$(".order_gal_image_select").live("click", function(){
//		if ($(this).attr("checked"))
//			$(this).attr("checked", "");
//		else
//			$(this).attr("checked", "checked");
//	});
	
	$(".sizes_input2").livequery("change", function(){
//		image = $("#current_image_number").html() - 1;
		image = $(this).parents(".photos").attr("id").replace("img-", "");
		val = parseInt($(this).val());
		size = $(this).attr("alt");
		t = $(this).parents(".photos");
		
		if ((val < 0) || (isNaN(val)))
		{
			$(this).val(0);
			val = 0;
		}
		
		$.post(root + "ajax/order_queries.php", { 'action': "change_size", "image": image, "val": val, "size": size }, function(data){
			if (data.length > 0)
				alert('Възникна проблем при смяна на количеството.');
			else
			{
				sum = 0;
				t.find(".sizes_input2").each(function(i){
					sum += parseInt($(this).val());
				});				
				
				if (sum <= 0)
				{
					alert('Минималният брой копия за всяка снимка е 1.');
					qty = $("#image_container").data("qty");
					qty[image+1] = 1;
					$("#image_container").data("qty", qty);
				}
				else
				{
					qty = $("#image_container").data("qty");
					qty[image+1] = 0;
					$("#image_container").data("qty", qty);
				}
				
			}
		}, "json");
		
		return false;
	});
	
	$(".del_photo2").click(function (){
		t = $(this).parents(".photos");
		if (confirm("Сигурни ли сте, че искате да изтриете тази снимка?"))
		{
			del = t.attr("id").replace("img-", "");
			
			$.post(root + "ajax/order_queries.php", { 'action': "delete_image", "deleted_file": del }, function(){				
				t.fadeOut("fast", function(){
					window.location.href = window.location.href;
				});
			});
		}
		else
			return false;
	});
	
	$("#custom_quantity").livequery("change", function(){		
		val = parseInt($(this).val());		
		
		if ((val < 0) || (isNaN(val)))
		{
			$(this).val(0);
			val = 0;
		}
		
		if (val == 0)
		{
			$(this).css({"border": "1px solid #E8AB1B"});			
			$("#image_container").data("custom_qty", 1);
			alert('Минималният брой копия за всяка снимка е 1.');
		}
		else
		{			
			$("#image_container").data("custom_qty", 0);
			$(this).css({"border": "1px solid #000000"});
			$.post(root + "ajax/order_queries.php", { 'action': "change_size_custom", "val": val}, function(data){
				if (data.length > 0)
					$("#custom_whole_price").html(data + ' лв.');
				else
					alert('Възникна проблем при смяна на количеството.');
			});
		}
	});
	
	$(".custom_frame").live("click", function(){
		val = $(this).val();
		
		$.post(root + "ajax/order_queries.php", { 'action': "change_frame_custom", "val": val });
	});
	
	$(".frame_radio2").live("click", function(){
		image = $(this).parents('.photos').attr("id").replace("img-", "");

		val = $(this).val();	
		
		$.post(root + "ajax/order_queries.php", { 'action': "change_frame", "image": image, "val": val }, function(){
			$("#image_container").data("images", data_);
		});
	});
	
	$("#next_step_3").click(function () {
		copy = $("input:radio[name=copy_type]:checked").val();
		paper = $("input:radio[name=paper_radio]:checked").val();
		
		if (copy == 1)
		{
			if ($("#image_container").data("custom_qty") == 1)
			{
				alert('Избрали сте брой копия по-малък от 1.');
				return false;
			}
		}
		else
		{
			images = '';
			qty = $("#image_container").data("qty");
			
			$.each(qty, function(key, qt) {
				if (qt > 0)
				images += ' ' + key + ',';
			});
			
			if (images.length > 0)
			{
				alert('Избрали сте брой копия по-малък от 1 за снимки с номера:' + images.substring(0, images.length - 1));
				return false;
			}
		}
		
		val = $("input:radio[name=ship]:checked").val();
///////////////// Доставката се определя от пазарската количка ////////////////////////////////////////////////////////
			$.post(root + "ajax/order_queries.php", { 'action': "ready_final_step", "val": val, "paper": paper}, function(){
///////////////// Преминаваме към пазарската количка ///////////////////////////////////////////////////////////

				$.post(root + "ajax/order_queries.php", {"action": "finish_order"}, function(){
					window.onbeforeunload = function() {
						window.event.cancelBubble = true;
						window.event.cancelBubble = '';
						if (!$.browser.msie)
							if (e.stopPropagation) {
								e.stopPropagation();
								e.preventDefault();
							}
					};
/*	
					address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
					new_address = window.location.href.replace(address[4] + "/", "");
					new_address = new_address.replace(address[5] + "/", "");
					new_address = new_address.replace(address[3] + "/", "");
*/
					window.location = root + "cart/add/";
				});
			});
	});
	
	$("#order_register").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 500,
		title: 'Регистрация на нов потребител:',
		position: 'top',
		modal: true,
		stack: true,
		beforeclose: function() {
			$('#order_register').dialog('option', 'modal', false);
		}
	});
	
	$("#order_user_address").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 500,
		title: 'Регистрация на нов потребител:',
		position: 'top',
		modal: true,
		stack: true,
		beforeclose: function() {
			$('#order_user_address').dialog('option', 'modal', false);
		}
	});
	
	$("#order_link_register").live("click", function (){
		$("#order_register table").css({
			"font-size": "14px"
		});
		
		$("#order_register input[type='password'], input[type='text']").css({
			"width": "157px",
			"height": "21px",
			"background": "url('" + root + "images/reg-input-bg.gif') no-repeat center",
			"border": "0px solid black"
		});					
		
		$("#order_register input[type='text']").css({
			"background": "url('" + root + "images/reg-input-bg.gif') no-repeat center"
		});
		
		$("#order_register #order_user_reg").css({
			"display": "none"
		});
		
		$("#order_user_login").css({
			"display": "none"
		});
		
		$("#order_register textarea").css({
			"border": "1px solid #8D8B78",
			"width": "157px"
		});
		
		$("#order_register .star").css({
			"color": "red"
		});
		
		$("#order_register input[type='button']").css({
			"background": "url('" + root + "images/reg-submit.gif') no-repeat",
			"width": "124px",
			"height": "23px",	
			"margin-top": "10px",
			"cursor": "hand",
			"cursor": "pointer"
		});		
		
		$("#order_register input[type='button']").mouseover(function(){
			$(this).css({
				"background": "url('" + root + "images/reg-submit-hover.gif') no-repeat"
			});
		});
		
		$("#order_register input[type='button']").mouseout(function(){
			$(this).css({
				"background": "url('" + root + "images/reg-submit.gif') no-repeat"
			});
		});
		$('#order_register').dialog( 'moveToTop' );
		$('#order_register').dialog('option', 'modal', true);
		$("#order_register").dialog('open');
		
		
		return false;
	});
	
	$("#order_register form").submit(function(){
		return false;
	});
	
	$("#order_reg_submit").click(function (){
		user = $("#order_register input[name='username']").val();
		pass = $("#order_register input[name='password']").val();
		pass2 = $("#order_register input[name='password2']").val();
		email = $("#order_register input[name='email']").val();
		from = $("#order_register input[name='reference']").val();
		capt = $("#order_register input[name='code']").val();
		terms = $("#order_register input[name='terms']:checked").val();
		$("#order_register #order_user_reg").fadeOut('fast');
		
		$.post(root + "ajax/order_queries.php", { 
			"action": "register", 
			"username": user, 
			"password": pass,
			"password2": pass2,
			"email": email,
			"terms": terms,
			"code": capt,
			"reference": from
			}, 
			function(data){
				if (data.error == "1")
				{
					error = '';
					$.each(data.msg, function(key, qt) {
						error += '<p>' + qt + '</p>';
					});
					
					$("#order_register #order_user_reg").attr("class", "error");
					$("#order_register #order_user_reg").html(error).fadeIn("slow");
				}
				else
				{
					$("#order_user_login").attr("class", "msg");
					$("#order_user_login").html("<p>Вие се регистрирахте успешно.</p>").fadeIn("slow");
					$("#order_login_user").val(user);
					$("#order_login_pass").val(pass);
					$("#order_register").dialog("close");
				}
			}, "json");
	});
	
	$("#order_login_form input[name='order_login']").live("click", function (){
		user = $("#order_login_form input[name='username']").val();
		pass = $("#order_login_form input[name='password']").val();
		
		$.post(root + "ajax/order_queries.php", { 
			"action": "login", 
			"username": user, 
			"password": pass
			}, 
			function(data){
				if (data.logged == "1")
				{					
					$("#order_user_login").attr("class", "msg");
					$("#order_user_login").html("<p>Вие влязохте в акаунта си успешно.</p>").fadeIn("slow");
					$("#login").html('<a href="http://www.facebook.com/snimkitevi/" ><img alt="facebook" src="'+ root + 'images/facebook.jpg" /></a><br/><br/>' + data.user_panel);
					$("#cart_addition").fadeIn();
					$("#order_user_login_cont").fadeOut();
					$("#first_cart").fadeIn();
					
				}
				else
				{
					$("#order_user_login").attr("class", "error");
					$("#order_user_login").html("<p>Грешно потребителско име или парола.</p>").fadeIn("slow");
				}				
			}, "json");
	});
	
	$("#order_login_form input[name='order_gal_login']").live("click", function (){
		user = $("#order_login_form input[name='username']").val();
		pass = $("#order_login_form input[name='password']").val();
		
		$.post(root + "ajax/order_queries.php", { 
			"action": "login", 
			"username": user, 
			"password": pass
			}, 
			function(data){
				if (data.logged == "1")
				{					
					$("#order_user_login").attr("class", "msg");
					$("#order_user_login").html("<p>Вие влязохте в акаунта си успешно.</p>").fadeIn("slow");
					$("#login").html('<a href="http://www.facebook.com/snimkitevi/" ><img alt="facebook" src="'+ root + 'images/facebook.jpg" /></a><br/><br/>' + data.user_panel);
					$("#main_order_gallery_container").load(root + "ajax/order_gallery.php", { 'action': "get_albums"});
					
				}
				else
				{
					$("#order_user_login").attr("class", "error");
					$("#order_user_login").html("<p>Грешно потребителско име или парола.</p>").fadeIn("slow");
				}				
			}, "json");
	});
	
	$("#order_set_address").live("click", function() {		
		$("#order_user_address").dialog('option', 'title', 'Адреси за доставка:');
		$("#order_user_address").dialog('option', 'position', 'top');
		$('#order_user_address').dialog('option', 'buttons', { "Затвори": function() { $(this).dialog("close"); }, "Изпрати": 
			function() 
			{
				$("#error_dialog").fadeOut("fast");
				$("#msg_dialog").fadeOut("fast");
				
				name = $("input[name='name']").val();
				city = $("input[name='city']").val();
				region = $("select[name='region']").val();
				gsm = $("input[name='gsm']").val();
				streetType = $("select[name='streetType']").val();
				address = $("input[name='address']").val();
				streetNo = $("input[name='streetNo']").val();
				quarterName = $("input[name='quarterName']").val();
				postcode = $("input[name='postcode']").val();
				
				$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery", "add": true, "name": name, "city": city, "region": region, "gsm": gsm, "streetType": streetType, "address": address, "streetNo": streetNo, "quarterName": quarterName, "postcode": postcode});
				
			}
		});		

		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery"});
		$('#order_user_address').dialog('option', 'modal', true);
		$("#order_user_address").dialog('open');
		
		return false;
	});
	
	$("#load_java_link").click( function() {
		$("#main_flash_container").fadeOut("fast", function(){
			$("#main_java_container").fadeIn();
		});		
		
		return false;
	});
	
	$("#load_flash_link").click( function() {
		$("#main_java_container").fadeOut("fast", function(){
			$("#main_flash_container").fadeIn();
		});		
		
		return false;
	});
	
	$(".choose_delivery_address").live("click", function(){
		address_id = $(this).attr("name").replace("address-", "");val = $(this).attr("alt").replace("address-", "");
		
		$("#order_user_address").dialog('option', 'title', 'Адреси за доставка:');
		$("#order_user_address").dialog('option', 'position', 'top');		
		$('#order_user_address').dialog('option', 'buttons', { "Затвори": function() { $(this).dialog("close"); }, "Промени": 
			function() 
			{
				$("#error_dialog").fadeOut("fast");
				$("#msg_dialog").fadeOut("fast");
				
				name = $("input[name='name']").val();
				city = $("input[name='city']").val();
				region = $("select[name='region']").val();
				gsm = $("input[name='gsm']").val();
				streetType = $("select[name='streetType']").val();
				address = $("input[name='address']").val();
				streetNo = $("input[name='streetNo']").val();
				quarterName = $("input[name='quarterName']").val();
				postcode = $("input[name='postcode']").val();				
				
				$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery", "change": true, "name": name, "city": city, "region": region, "gsm": gsm, "streetType": streetType, "address": address, "streetNo": streetNo, "quarterName": quarterName, "postcode": postcode, "address_id": address_id});
				$('#order_user_address').dialog('option', 'buttons', { "Затвори": function() { $(this).dialog("close"); }, "Изпрати": 
					function() 
					{
						$("#error_dialog").fadeOut("fast");
						$("#msg_dialog").fadeOut("fast");
						
						name = $("input[name='name']").val();
						city = $("input[name='city']").val();
						region = $("select[name='region']").val();
						gsm = $("input[name='gsm']").val();
						streetType = $("select[name='streetType']").val();
						address = $("input[name='address']").val();
						streetNo = $("input[name='streetNo']").val();
						quarterName = $("input[name='quarterName']").val();
						postcode = $("input[name='postcode']").val();		
						
						$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery", "add": true, "name": name, "city": city, "region": region, "gsm": gsm, "streetType": streetType, "address": address, "streetNo": streetNo, "quarterName": quarterName, "postcode": postcode});
						
					}
				});
			}
		});		

		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery", "address_id": address_id});
		
		$("#order_user_address").dialog('open');
		
		return false;
	});
	
	$(".activate_delivery_address").live("click", function(){
		address_id = $(this).attr("name").replace("address-", "");
		
		$("#user_address_info").html("Зареждане на новия адрес...");
		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery", "address_id": address_id, "activate": true}, function() {
			$("#user_address_info").load(root + "ajax/order_queries.php", {"action": "get_active_address"});
		});		
		
		return false;
	});
	
	$(".delete_delivery_address").live("click", function(){
		address_id = $(this).attr("name").replace("address-", "");
		
		if (confirm("Сигурни ли сте, че искате да изтриете адреса?"))
			$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_delivery", "address_id": address_id, "delete": true}, function() {
				$("#user_address_info").load(root + "ajax/order_queries.php", {"action": "get_active_address"});
			});
		
		return false;
	});
	
	$("#order_personal_data_form").livequery("submit", function(){
		return false;
	});
	
	$("#shipment_dest").livequery("change", function(){
		dest = $("#ship_type").val();
		type = $(".shopping_cart_shipping:checked").val();
		
		if (dest == 0)
		{
			if ($(this).val() == 0)
			{
				$("#user_address_info").fadeIn("fast");
				$.post(root + "ajax/order_queries.php", {"action": "change_delivery_price", "type": type, "val": "1"});
			}
			else
			{
				$("#user_address_info").fadeOut("fast");
				$.post(root + "ajax/order_queries.php", {"action": "change_delivery_price", "type": type, "val": "2", "id": $(this).val()});
			}
			
			$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": 0},function(data){
				$("#cart_final_price").html(data.sum + " лв.");
				$("#cart_delivery").html(data.delivery + " лв.");
			}, "json");
		}
		else
		{
			val = $("#shipment_dest").val();
			$("#studio_info").load(root + "ajax/order_queries.php", {"action": "change_studio", "type": type, "val": val}, function(){
				$("#studio_info p").css({
					"font-size": "13px"
				});
				$("#studio_info").css({
					"font-size": "13px"
				});
			});
		}
			
	});
	
	$(".order_invoice").live("click", function(){		
		if ($(".order_invoice:checked").val() == 1)
		{
			$("#user_invoice_info").load(root + "ajax/order_queries.php", {"action": "get_active_invoice", "invoice": "1"});
			$("#user_invoice_info").fadeIn("fast");
		}
		else
		{
			$("#user_invoice_info").fadeOut("fast");
			$.post(root + "ajax/order_queries.php", {"action": "get_active_invoice", "invoice": "0"});
		}
	});
	
	$("#order_set_invoice").livequery("click", function(){
		$("#order_user_address").dialog('option', 'title', 'Адреси за фактура: ');
		$("#order_user_address").dialog('option', 'position', 'top');
		$('#order_user_address').dialog('option', 'buttons', { "Затвори": function() { $(this).dialog("close"); }, "Изпрати": 
			function() 
			{
				$("#error_dialog").fadeOut("fast");
				$("#msg_dialog").fadeOut("fast");
				
				firm = $("input[name='firm']").val();
				mol = $("input[name='mol']").val();
				number = $("input[name='number']").val();
				bulstat = $("input[name='bulstat']").val();
				phone = $("input[name='phone']").val();
				city = $("input[name='city']").val();
				region = $("select[name='region']").val();
				gsm = $("input[name='gsm']").val();
				address = $("input[name='address']").val();
				postcode = $("input[name='postcode']").val();				
				
				$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice", "add": true, "firm": firm, "bulstat": bulstat, "phone": phone, "mol": mol, "number": number, "city": city, "region": region, "gsm": gsm, "address": address, "postcode": postcode});
				
			}
		});		

		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice"});
		$('#order_user_address').dialog('option', 'modal', true);
		$("#order_user_address").dialog('open');
		return false;
	});
	
	$(".choose_invoice_address").live("click", function(){
		address_id = $(this).attr("name").replace("address-", "");
		
		$("#order_user_address").dialog('option', 'title', 'Адреси за фактура: ');
		$("#order_user_address").dialog('option', 'position', 'top');
		$('#order_user_address').dialog('option', 'buttons', { "Затвори": function() { $(this).dialog("close"); }, "Промени": 
			function() 
			{
				$("#error_dialog").fadeOut("fast");
				$("#msg_dialog").fadeOut("fast");
				
				firm = $("input[name='firm']").val();
				mol = $("input[name='mol']").val();
				number = $("input[name='number']").val();
				bulstat = $("input[name='bulstat']").val();
				phone = $("input[name='phone']").val();
				city = $("input[name='city']").val();
				region = $("select[name='region']").val();
				gsm = $("input[name='gsm']").val();
				address = $("input[name='address']").val();
				postcode = $("input[name='postcode']").val();				
				
				$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice", "change": true, "firm": firm, "bulstat": bulstat, "phone": phone, "mol": mol, "number": number, "city": city, "region": region, "gsm": gsm, "address": address, "postcode": postcode, "address_id": address_id});
				$('#order_user_address').dialog('option', 'buttons', { "Затвори": function() { $(this).dialog("close"); }, "Изпрати": 
					function() 
					{
					firm = $("input[name='firm']").val();
					mol = $("input[name='mol']").val();
					number = $("input[name='number']").val();
					bulstat = $("input[name='bulstat']").val();
					phone = $("input[name='phone']").val();
					city = $("input[name='city']").val();
					region = $("select[name='region']").val();
					gsm = $("input[name='gsm']").val();
					address = $("input[name='address']").val();
					postcode = $("input[name='postcode']").val();				
					
					$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice", "add": true, "firm": firm, "bulstat": bulstat, "phone": phone, "mol": mol, "number": number, "city": city, "region": region, "gsm": gsm, "address": address, "postcode": postcode});
						
					}
				});
			}
		});		

		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice", "address_id": address_id});
		
		$("#order_user_address").dialog('open');
		
		return false;
	});	
	
	$(".activate_invoice_address").live("click", function(){
		address_id = $(this).attr("name").replace("address-", "");val = $(this).attr("alt").replace("address-", "");
		
		$("#user_invoice_info").html("Зареждане на новия адрес...");
		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice", "address_id": address_id, "activate": true}, function(){
			$("#user_invoice_info").load(root + "ajax/order_queries.php", {"action": "get_active_invoice"});
		});
		
		return false;
	});
	
	$(".delete_invoice_address").live("click", function(){
		address_id = $(this).attr("name").replace("address-", "");val = $(this).attr("alt").replace("address-", "");		
		
		if (confirm("Сигурни ли сте, че искате да изтриете адреса?"))
			$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "user_invoice", "address_id": address_id, "delete": true}, function(){
				$("#user_invoice_info").load(root + "ajax/order_queries.php", {"action": "get_active_invoice"});
			});
		
		return false;
	});
	
	$(".payment-item").live("click", function(){
		type = $(".payment-item:checked").val();
		
//		if (type != 3)		//ePay
//		{
//			if ($("#paypal-warning").is(":visible"))
//				$("#paypal-warning").fadeOut();
//		}
//		
//		if (type == 3)
//		{
//			$("#paypal-warning").fadeIn();
//		}
			
		$.post(root + "ajax/order_queries.php", {"action": "switch_payment", "type": type}, function(data_){
			$("#payment_vendor").html(data_);
			ship = $(".shopping_cart_shipping:checked").val();
			if (ship == '02')		//ePay
			{
				$.post(root + "ajax/count_standart.php", {}, function(dt){
					if (dt > 50)
					{
						$.post(root + "ajax/order_queries.php", {"action": "change_payment_price", "type": type}, function(rt){
							$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": "1"},function(data){
								$("#cart_final_price").html(data.sum + " лв.");
								$("#cart_delivery").html(data.delivery + " лв.");
								$.post(root + "ajax/order_queries.php", {"action": "switch_payment", "type": type}, function(data2){
									$("#payment_vendor").html(data2);
								});
							}, "json");
						});
					}
				});
			}
		}, "text");
	});
	

	$("#order_samples_show").click(function(){
		$("#order_samples_list").toggle();
	});
	
	$("#order_samples_list").ready(function(){
		type = $("#order_samples_hidden").val();
		
		if (!isNaN(type))
		{
			$.post(root + "ajax/order_queries.php", {"action":"get_samples", "type": type}, function(data){
					html = "";
					info = "";
					
					for (i=0; i<3; ++i)
					{
						if (data.count > i + 1)
						{
							if (data.samples[i].price > 0)
								price = "Цена: " + data.samples[i].price/100 + " лв.<br/>";
							else
								price = "";
							
							style = "";
							if (data.samples[i].size == 1)
								style = "style='margin-top: 5px;'";
							else
								style = "style='margin-top: 0px;'";
							
							html += "<a href='#' id='sample_id_" + i + "' class='order_samples_a'><img " + style + " src='" + root + "samples/" + data.folder + "/thumb/" + data.samples[i].file + "'/></a>";
							info += "<p class='order_samples_info'>" + price + data.samples[i].info + "</p>";
						
						}
						
					}
					
					info += "<div class='clear'><!-- --></div>";
					html += "<div class='clear'><!-- --></div>";				
					
					$("#order_samples_cont").html(html + info);
					$("#order_samples_cont").data("samples", data);
					$("#order_samples_cont").data("current", 2);
					
					for (i=0; i<3; ++i)
					{
						$("#sample_id_" + i).data("samples", data.samples[i]);
						$("#sample_id_" + i).data("folder", data.folder);
					}
				
			}, "json");
		}
	});
	
	$("#order_samples_left").click(function(){
		data = $("#order_samples_cont").data("samples");
		current = parseInt($("#order_samples_cont").data("current"));
		html = "";
		info = "";
		
		if (current > 2)
		{
			current = current - 1;
			for (i=0; i<3; ++i)
			{
				if (data.count > i + 1)
				{
					if (data.samples[(current-2) + i].price > 0)
						price = "Цена: " + data.samples[(current-2) + i].price/100 + " лв.<br/>";
					else
						price = "";
					
					style = "";
					if (data.samples[(current-2) + i].size == 1)
						style = "style='margin-top: 5px;'";
					else
						style = "style='margin-top: 0px;'";
					
					html += "<a href='#' id='sample_id_" + i + "' class='order_samples_a'><img " + style + " src='" + root + "samples/" + data.folder + "/thumb/" + data.samples[(current-2) + i].file + "'/></a>";
					info += "<p class='order_samples_info'>" + price + data.samples[(current-2) + i].info + "</p>";
				}			
			}
			
			info += "<div class='clear'><!-- --></div>";
			html += "<div class='clear'><!-- --></div>";				
			
			$("#order_samples_cont").html(html + info);
			$("#order_samples_cont").data("current", current);
			
			for (i=0; i<3; ++i)
			{
				$("#sample_id_" + i).data("samples", data.samples[(current-2) + i]);
				$("#sample_id_" + i).data("folder", data.folder);
			}
		}
	});
	
	$("#sample-preview-close").live("click", function(){
		$(this).parent().parent().click();
	})
	
	$(".product-preview").click(function(){
		id = $(this).attr("data-id");
		$(".sample-preview").remove();
		$("body").append("<div class='sample-preview'></div>");
		$(".sample-preview").css({
			"top": $(document).scrollTop(),
			"left": "180px"
		}).load(root + 'ajax/custom_orders/product_preview.php', {"action": "get_views", "id": id}, function(){
			;
		}).fadeIn().bind("click", function(){
			$(this).fadeOut().remove();
		}).find(".sample-preview-image").live("mouseenter", function(e){
			$("#samples-preview-canvas").html("<img src='" + $(this).find("img").attr("src").replace("thumb/", "") + "'/>");
			t = e.pageX - $(this).offset().top;
			l = e.pageY - $(this).offset().left;

			$(this).find(".preview-box").fadeIn(100).css({
				"top": (t - ($(this).height()/2)) + "px",
				"left": (l - ($(this).width()/2)) + "px"
			});
		}).live("mouseleave", function(){
			$(this).find(".preview-box").css("display", "none");
		}).live("mousemove", function(e){
			box = $(this).find(".preview-box");
			viewCanvas = $("#samples-preview-canvas");
			img = $(this).find("img")
			
			wd = img.width();
			hg = img.height();
			ot = img.offset().top;
			ol = img.offset().left;
			
			l = e.pageX - ol;
			t = e.pageY - ot;
			
			box.css({
				width: wd*(viewCanvas.width()/viewCanvas.find("img").first().width()),
				height: hg*(viewCanvas.height()/viewCanvas.find("img").first().height())
			});
			
			if (e.pageX > (ol + wd) || e.pageX < ol || e.pageY > (ot + hg) || e.pageY < ot)
				$(this).mouseleave();
			
			
			boxLeft = l - (box.width()/2);
			boxTop = t - (box.height()/2);
			
			if (boxLeft <= 0)
				boxLeft = 0;
				
			if (boxLeft >= (wd - box.width() - 2))
				boxLeft = wd - box.width() - 2;
				
			if (boxTop <= 0)
				boxTop = 0;
				
			if (boxTop >= (hg - box.height() - 2))
				boxTop = hg - box.height() - 2;
			
			box.css({
				"top": boxTop + "px",
				"left": boxLeft + "px"
			});
			
			viewCanvas.find("img").css({
				"top": (-boxTop*(viewCanvas.find("img").first().height()/hg)) + "px",
				"left": (-boxLeft*(viewCanvas.find("img").first().width()/wd)) + "px"
			});
			
			// console.log(() +'-'+ lp)
		});
		
		return false;
	});
	
	$("#order_samples_right").click(function(){
		data = $("#order_samples_cont").data("samples");
		current = $("#order_samples_cont").data("current");
		html = "";
		info = "";		
		if (parseInt(data.count) > current + 1)
		{
			for (i=0; i<3; ++i)
			{
				if (data.count > i + 1)
				{
					if (data.samples[(current-1) + i].price > 0)
						price = "Цена: " + data.samples[(current-1) + i].price/100 + " лв.<br/>";
					else
						price = "";
					
					style = "";
					if (data.samples[(current-1) + i].size == 1)
						style = "style='margin-top: 5px;'";
					else
						style = "style='margin-top: 0px;'";
					
					html += "<a href='#' id='sample_id_" + i + "' class='order_samples_a'><img " + style + " src='" + root + "samples/" + data.folder + "/thumb/" + data.samples[(current-1) + i].file + "'/></a>";
					info += "<p class='order_samples_info'>" + price + data.samples[(current-1) + i].info + "</p>";
				
				}
				
			}
			
			info += "<div class='clear'><!-- --></div>";
			html += "<div class='clear'><!-- --></div>";				
			
			$("#order_samples_cont").html(html + info);
			$("#order_samples_cont").data("current", current + 1);
			
			for (i=0; i<3; ++i)
			{
				$("#sample_id_" + i).data("samples", data.samples[(current-1) + i]);
				$("#sample_id_" + i).data("folder", data.folder);
			}
		}
	});
	
	$(".order_samples_a").live("click", function(){
		data = $(this).data("samples");
		folder = $(this).data("folder");
		image = $("#product_id").val();
		
		if (data.image == 1)
		{
			$("#product_flash").fadeIn("fast");
			uploaded = false;
		}
		else
		{
			$("#product_flash").fadeOut("fast");
			uploaded = true;
		}
		
		$.post(root + "ajax/order_queries.php", {"action": "set_sample_product", "image": image, "sample": data.id, "file": data.info}, function(data_){
			$("#product_price").html(data_);
			$("#product_image_hold").attr("src", root + "samples/" + folder + "/thumb/" + data.file);
		}, "text");

		return false;
	});
	
	window.onbeforeunload = function (e)
	{
		address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
		if ((address[3] == "order" || address[3] == "gifts") && address[4] == "start")
		{
			return "Ако презаредите или напуснете страницата, ще загубите текущата си поръчка. Ако искате да го направите натиснете Ok.";
		}
		
	};
	
	$(".order_product_cont").mouseover(function(){
		$(this).css({
			"border": "1px solid #E0A80B"
		});
	});
	
	$(".order_product_cont").mouseout(function(){
		$(this).css({
			"border": "1px solid #c5c5c5",
			"cursor": "hand",
			"cursor": "pointer"
		});
	});
	
	$(".order_product_cont").click(function(){
		product = $(this).children("img").attr("alt");
		$("#selected-product").val(product);
		
		data = '';
		
		if ($("#customSet").val() == 1)
		{
			return;
		}
		
		$.post(root + "ajax/order_queries.php", {"action": "get_product_overview", "product": product}, function(data){
			if (data.error == 0)
			{
				$("#product_image_hold").attr("src", root + "samples/" + data.folder + "/thumb/" + data.file);
				$("#product_image_hold").attr("alt", data.info);
				$("#product_name_hold").html(data.info);
				$("#product_price").html(data.price);
				$("#product_qty").val(data.qty);
				$("#has-custom-preview").val(data.pages);
				// alert(data.pages);
				
				if (data.image == 1)
				{
					$("#product_flash").fadeIn("fast");
				}
				else
					uploaded = true;
				
				if (!$("#step1_hidden_button").attr("disabled"))
				{
					$("#step1_hidden_button").click();
					$("#step1_hidden_button").attr("disabled", "disabled");
				}
				
				$("#product_id").val(product);
			}
		}, "json");
		
	});
	
	$("#custom-order-wrap .custom-sample-image").live("click", function(){
		$(this).parent().fadeOut();
		sample = "<br/>чаша: " + $("#custom-sample-name").val() + "<br/>мостра:" + $(this).children("img").attr("alt").replace(".", "").replace("jpg", "");
		$.post(root + "ajax/order_queries.php", {"action": "get_product_overview", "product": $("#selected-product").val(), "sample": sample}, function(data){
			if (data.error == 0)
			{
				$("#product_image_hold").attr("src", root + "samples/" + data.folder + "/thumb/" + data.file);
				$("#product_image_hold").attr("alt", data.info);
				$("#product_name_hold").html(data.info);
				$("#product_price").html(data.price);
				$("#product_qty").val(data.qty);
				
				if (data.image == 1)
				{
					$("#product_flash").fadeIn("fast");
				}
				else
					uploaded = true;
				
				if (!$("#step1_hidden_button").attr("disabled"))
				{
					$("#step1_hidden_button").click();
					$("#step1_hidden_button").attr("disabled", "disabled");
				}
				
				$("#product_id").val(product);
			}
		}, "json");
	});
	
	$("#custom-order-wrap #bcards-submit").live("click", function(){
		$(this).parent().fadeOut();
		sample = "<br/>Мостра:" + $("#custom-sample-name").val() + "<br/>";
		sample += "<br/>Име: " + $("#bc-name").val() + "<br/>";
		sample += "Длъжност: " + $("#bc-title").val() + "<br/>";
		sample += "Телефон: " + $("#bc-phone").val() + "<br/>";
		sample += "Адрес: " + $("#bc-address").val() + "<br/>";
		sample += "Фирма: " + $("#bc-firm").val() + "<br/>";
		sample += "Сайт: " + $("#bc-site").val() + "<br/>";
		sample += "E-mail: " + $("#bc-email").val() + "<br/>";
		
		$.post(root + "ajax/order_queries.php", {"action": "get_product_overview", "product": $("#selected-product").val(), "sample": sample}, function(data){
			if (data.error == 0)
			{
				$("#product_image_hold").attr("src", root + "samples/" + data.folder + "/thumb/" + data.file);
				$("#product_image_hold").attr("alt", data.info);
				$("#product_name_hold").html(data.info);
				$("#product_price").html(data.price);
				$("#product_qty").val(data.qty);
				
				if (data.image == 1)
				{
					$("#product_flash").fadeIn("fast");
				}
				else
					uploaded = true;
				
				if (!$("#step1_hidden_button").attr("disabled"))
				{
					$("#step1_hidden_button").click();
					$("#step1_hidden_button").attr("disabled", "disabled");
				}
				
				$("#product_id").val(product);
			}
		}, "json");
	});
		
	$("#product_qty").change(function(){
		val = $(this).val();
		id = $("#product_id").val();
		
		if (isNaN(val) || val < 1)
		{
			$(this).css({
				"border": "1px solid #E0410B"
			});
		}
		else
		{
			$.post(root + "ajax/order_queries.php", {"action": "change_product_qty", "qty": val, "product": id}, function(data){
				$("#product_qty").css({
					"border": "1px solid #c5c5c5"
				});
				$("#product_price").html(data);
			}, "text");
		}
	});
	
	$("#next_step_3_prod").click(function(){
		if (!uploaded)
		{
			alert("Не сте качили файл.");
			return false;
		}
		else if ($("#product_qty").val() <= 0 || isNaN($("#product_qty").val()))
		{
			alert("Трябва да изберете количество по-голямо от 0.");			
			return false;
		}		
		else
		{			
			$.post(root + "ajax/order_queries.php", { 'action': "ready_final_step", "val": 0, "paper": "mat", "type": "product"}, function(){
				$.post(root + "ajax/order_queries.php", {"action": "finish_order"}, function(){

					window.onbeforeunload = function() {
						window.event.cancelBubble = true;
						window.event.cancelBubble = '';
						if (!$.browser.msie)
							if (e.stopPropagation) {
								e.stopPropagation();
								e.preventDefault();
							}
					};
				
					address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
					new_address = window.location.href.replace(address[4] + "/", "");
					new_address = new_address.replace(address[5] + "/", "");
					new_address = new_address.replace(address[3] + "/", "");
					
					if ($("#has-custom-preview").val() > 0)
						window.location = new_address + "gifts/preview_calendar/";
					else
						window.location = new_address + "cart/add/";
				});
			});
		}
	});
	
	$(".order_gifts_discounts").click(function(){
		id = $(this).attr("id").replace("gifts_discount_", "");
		startGalDialog("Отстъпки:");
		
		$("#gal_dialog_body").html("Зареждане...");		
		$("#gal_dialog_body").load(root + "ajax/order_discounts.php", {"action": "get_discounts", "id": id}, function(data){
			if (data == "<p>За поръчка на големи количества се свържете с нас, за да уточним възможностите за отстъпка.</p>")
			{
				$("#gal_dialog_body").css({"height": "100px"});
				$("#gal_dialog_cont").css({
					"height": "100px",
					"min-height": "100px"
				});
			}
		}, "text");
		
		return false;
	});
	
////////////////////////////////// SHOPPING CART FUNCTIONS //////////////////
	
	$("#shopping_cart").ready(function(){
		if ($("#logged").val() != true)
		{
			$("#cart_addition").fadeOut();
			$("#order_user_login_cont").load(root + "ajax/order_queries.php", {'action': "get_login"}, function(){
				$("#order_user_login_cont input[type='password'], input[type='text']").css({
					"width": "157px",
					"height": "21px",
					"background": "url('" + root + "images/reg-input-bg.gif') no-repeat center",
					"border": "0px solid black"
				});
			}).fadeIn();
			
			$("#first_cart").fadeOut();
		}
		else
		{
			$("#cart_addition").fadeIn();
		}
	});
	
	$(".cart_order_info").click(function(){
		id = $(this).parents("tr").attr("id").replace("order_", "");
		
		$("#order_user_address").dialog('option', 'title', 'Информация за продукт ');
		$('#order_user_address').dialog('moveToTop');
		$("#order_user_address").dialog('option', 'width', '700px');
		$("#order_user_address").html("Зареждане...");
		$('#order_user_address').dialog('option', 'buttons', { "Затвори": function(){ $(this).dialog("close"); }});
		$("#order_user_address").load(root + "ajax/order_queries.php", {"action": "order_details", "id": id});
		$('#order_user_address').dialog('option', 'modal', true);
		$("#order_user_address").dialog('open');
		
		return false;
	});
	
	$(".cart_order_delete").toggle(function(){
		$(".shopping_cart_shipping:checked").click();
		id = $(this).parents("tr").attr("id").replace("order_", "");
		
		$.post(root + "ajax/order_queries.php", {"action": "cart_delete_order", "order": id}, function(data){
			if (data.success)
			{
				$(".suborder_" + id).css({"background-color": "#ffffff"});
				$("#order_" + id + " td").fadeTo("fast", 0.3);
				$(".suborder_" + id).fadeTo("fast", 0.3);
				$("#order_" + id + " .cart_order_delete").attr("src", root + "images/ico-undo.png");
				$("#order_" + id + " .cart_order_delete").attr("alt", "Възстановяване");
				$("#cart_price").html(data.prices.price + " лв.");
				$("#cart_discount").html(data.prices.discount + " лв.");
				$("#cart_final_price").html(data.prices.sum + " лв.");
				$("#cart_delivery").html(data.delivery + " лв.");
			}
			else
				alert("Възникна проблем при изтриването на поръчката. Моля опитайте пак и ако проблема моля свържете се с нас.");
		}, "json");
	},
	function(){
		$(".shopping_cart_shipping:checked").click();
		id = $(this).parents("tr").attr("id").replace("order_", "");
		$.post(root + "ajax/order_queries.php", {"action": "undo_delete_order", "order": id}, function(data){
			if (data.success)
			{
				$(".suborder_" + id).css({"background-color": "#F5F5F5"});
				$("#order_" + id + " td").fadeTo("fast", 1.0, function(){
					if ($.browser.msie)
						this.style.removeAttribute('filter');
				});
				$(".suborder_" + id).fadeTo("fast", 1.0, function(){
					if ($.browser.msie)
						this.style.removeAttribute('filter');
				});
				$("#order_" + id + " .cart_order_delete").attr("src", root + "images/ico-delete.gif");
				$("#order_" + id + " .cart_order_delete").attr("alt", "Изтриване");				
				$("#cart_price").html(data.prices.price + " лв.");
				$("#cart_discount").html(data.prices.discount + " лв.");
				$("#cart_final_price").html(data.prices.sum + " лв.");
				$("#cart_delivery").html(data.delivery + " лв.");
				last_delete = 0;
			}
			else
				alert("Възникна проблем при възстановяването на поръчката.");
		}, "json");
	});
	
	$("#start_new_order").click(function(){
		address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
		new_address = window.location.href.replace(address[4] + "/", "");
		new_address = new_address.replace(address[3] + "/", "");
		window.location = new_address + "order/index/";
		
		return false;
	});
	
	$(".shopping_cart_shipping").click(function(){
		val = $(".shopping_cart_shipping:checked").val();
		
		$("#payment_list").fadeIn();
		$("#ship_price_info").html("Зареждане..");
		
		payment_ = '';
		payment_ += '<input type="radio" class="payment-item" name="payment" id="payment_list_get" value="1"><label for="payment">При получаване</label><br/>';			
		payment_ += '<input type="radio" class="payment-item" value="2" name="payment"><label for="payment">ePay</label><br/>';
		payment_ += '<input type="radio" class="payment-item" value="3" name="payment"><label for="payment">PayPal</label><br/>';
		
//		if ($("#username-test").val() == "greg")
			payment_ += '<input type="radio" class="payment-item" value="4" name="payment"><label for="payment">EasyPay/B-Pay</label><br/>';
		
		if (val == '01')
		{
			$("#ship_price_info").load(root + "ajax/order_queries.php", {"action": "get_shipment_addresses", "type": 0, "add": 2},function(){
				$(this).append('<p>Цена за доставка до офис на Speedy: 2.50 лв.</p>');
				el = $(this);
				$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": val},function(data){
					$("#cart_final_price").html(data.sum + " лв.");
					$("#cart_delivery").html(data.delivery + " лв.");
					$("#payment_list").html('');
					$("#payment_list").append(payment_);

					el.append('<p>Телефон за контакт: <input type="text" id="user_phone" value="' + data.tel + '" /><span style="color: red;">*</span></p>');
					el.append('<p>Лице за контакт: <input style="margin: 3px 0px 0px 23px;" type="text" id="user_name" value="' + data.name + '" /><span style="color: red;">*</span></p>');
				}, "json");
			});
		}
		else if (val == '03')
		{
			$("#ship_price_info").load(root + "ajax/order_queries.php", {"action": "get_shipment_addresses", "type": 0, "add": 3},function(){
				$(this).append('<p>Цена за доставка Speedy до адрес: 2.90 лв.</p>');
				el = $(this);
				$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": val},function(data){
					$("#cart_final_price").html(data.sum + " лв.");
					$("#cart_delivery").html(data.delivery + " лв.");
					$("#payment_list").html('');
					$("#payment_list").append(payment_);
					
					el.append('<p>Телефон за контакт: <input type="text" id="user_phone" value="' + data.tel + '" /><span style="color: red;">*</span></p>');
					el.append('<p>Лице за контакт: <input style="margin: 3px 0px 0px 23px;" type="text" id="user_name" value="' + data.name + '" /><span style="color: red;">*</span></p>');
				}, "json");
			});
		}
		else if (val == '02')
		{
			$("#ship_price_info").load(root + "ajax/order_queries.php", {"action": "get_shipment_addresses", "type": 0, "add": 1},function(){
				$(this).append('<p>Цена за доставка до адрес: 2.20 лв.</p>');
				$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": val},function(data){
					$("#cart_final_price").html(data.sum + " лв.");
					$("#cart_delivery").html(data.delivery + " лв.");
					$("#payment_list").html('');
					$("#payment_list").append(payment_);
				}, "json");
			});
		}
		else if (val == '1')
		{
			$("#ship_price_info").load(root + "ajax/order_queries.php", {"action": "get_shipment_addresses", "type": val},function(){
				$(this).append('<div id="studio_info"></div>');
				$(this).append('<p>Цена за доставка: 0.00 лв.</p>');
				$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": val},function(data){
					$("#cart_final_price").html(data.sum + " лв.");
					$("#cart_delivery").html(data.delivery + " лв.");
					$("#payment_list").html('');
					$("#payment_list").append(payment_);
				}, "json");
			});
		}
		else if (val == 2)
		{
			$("#ship_price_info").load(root + "ajax/order_queries.php", {"action": "get_shipment_addresses", "type": val},function(){
				$(this).append('<p>Цена за доставка:</p><p style="color: #ED002B">до адрес: 2.50 лв. само за формати 9/13, 10/15 и 13/18 и не повече от 500 снимки.</p><p> При поръчка на повече снимки се изпращат като отделна доставка.</p><p><span style="color: #ED002B">Плащане само през ePay.</span> Доставка до 5 работни дни.</p>');
				$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": val},function(data){
					$("#cart_final_price").html(data.sum + " лв.");
					$("#cart_delivery").html(data.delivery + " лв.");				
					$("#payment_list").html('');
					
					payment_ = '<option value="0">Начин на плащане</option><option value="2">ePay</option>';
					$("#payment_list").append(payment_);
				}, "json");
			});		
			
		}
		else if (val == -1)
		{
			$("#ship_price_info").fadeOut("fast");
			$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": -1},function(data){
				$("#cart_final_price").html(data.sum + " лв.");
				$("#cart_delivery").html(data.delivery + " лв.");
			}, "json");
			
			return false;
		}
//		else if (val == 3)
//		{
//			$("#ship_price_info").load(root + "ajax/order_queries.php", {"action": "get_shipment_addresses", "type": val},function(){
//				$(this).append('<p>Цена за доставка:</p><p style="color: #ED002B">до адрес: 2.50 лв. само за формати 9/13, 10/15 и 13/18 и не повече от 500 снимки.</p><p> При поръчка на повече снимки се изпращат като отделна доставка.</p><p><span style="color: #ED002B">Плащане само през ePay.</span> Доставка до 5 работни дни.</p>');
//				$.post(root + "ajax/order_queries.php", {"action": "get_cart_prices", "type": val},function(data){
//					$("#cart_final_price").html(data.sum + " лв.");
//					$("#cart_delivery").html(data.delivery + " лв.");				
//					$("#payment_list").html('');
//					
//					payment_ = '<option value="0">Начин на плащане</option><option value="2">ePay</option>';
//					$("#payment_list").append(payment_);
//				}, "json");
//			});		
//			
//		}
		$("#ship_price_info").fadeIn("slow");		
	});
	
	$("#first_cart").click(function(){
		shipping = $(".shopping_cart_shipping:checked").val();
		
		$.post(root + "ajax/order_queries.php", {"action": "check_addresses"}, function(data){
			studio = $("#shipment_dest").val();
			pay = $(".payment-item:checked").val();	

			$.post(root + "ajax/order_queries.php", {"action": "check_cart_qt"}, function(data_){
				if (data_.empty)
				{
					alert("Пазарската количка е празна. За да продължите трябва да има добавен поне един продукт.");
				}
				else
				{
					if (studio == "-2")
					{
						alert("Не сте избрали студио, където да получите снимките си.");				
						return false;
					}
					else if (studio == "-3")
					{
						alert("Не сте избрали офис на Speedy.");				
						return false;
					}
					else if (data.invoice == 1 && $(".order_invoice:checked").val() == 1)
					{
						alert('Отбелязали сте, че желаете да получите фактура, но не сте въвели активен адрес. Моля въведете адрес преди да продължите.');
						return false;
					}
					else if (data.delivery == 1)
					{
						alert('Отбелязали сте, че желаете да получите снимките си на избран от Вас адрес, но не сте въвели активен адрес. Моля въведете адрес преди да продължите.');
						return false;
					}
					else if (pay == undefined)
					{
						alert('Не сте избрали начин на плащане.');
						return false;
					}
					
					if (!data.logged)
					{
						alert("За да продължите трябва да сте влезнали в акаунта си.");
						return false;
					}					
					
					if (shipping == '01' || shipping == '03')
					{
						if ($("#user_phone").val().length > 0)
						{
							if (isNaN($("#user_phone").val()))
							{
								alert("Не сте въвели телефон.");
								return false;
							}
						}
						else
						{
							alert("Не сте въвели телефон.");
							return false;
						}
						
						if ($("#user_name").val().length <= 0)
						{
							alert("Не сте въвели лице за контакт.");
							return false;							
						}

					}
					
					if (shipping == undefined)
					{
						alert("Не сте избрали начин на доставка.");
						return false;
					}
					else
					{
						renderLoadingOverlaySized("Обработване на поръчката. Моля изчакайте.");
						
						if ($(".payment-item:checked").val() == 2)
						{
							add_info = "[тел: " + $("#user_phone").val() + " | име: " + $("#user_name").val() + "]" + $("#order_additional_info").val();

							$.post(root + "ajax/order_queries.php", {"action": "add_info", "info": add_info}, function(){
								$.post(root + "ajax/order_queries.php", {"action": "destroy_cart"}, function(){
									$("#epay_form").submit();
								});
							});
						}
						else if ($(".payment-item:checked").val() == 3)
						{
							add_info = "[тел: " + $("#user_phone").val() + " | име: " + $("#user_name").val() + "]" + $("#order_additional_info").val();
							

							$.post(root + "ajax/order_queries.php", {"action": "add_info", "info": add_info}, function(){
//								alert($("#paypal_form").html());
//								$("#paypal_form").submit();
								$.post(root + "ajax/order_queries.php", {"action": "destroy_cart"}, function(){
									$("#paypal_form").submit();
								});
							});
						}
						else if ($(".payment-item:checked").val() == 4)
						{
							add_info = "[тел: " + $("#user_phone").val() + " | име: " + $("#user_name").val() + "]" + $("#order_additional_info").val();
							

							$.post(root + "ajax/order_queries.php", {"action": "add_info", "info": add_info}, function(){
								$.post(root + "ajax/order_queries.php", {"action": "easypay"}, function(){
									address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
									new_address = window.location.href.replace(address[4] + "/", "");
									new_address = new_address.replace(address[3] + "/", "");
									window.location = new_address + "cart/finish/";
								});
							});
						}
						else
						{
							add_info = "[тел: " + $("#user_phone").val() + " | име: " + $("#user_name").val() + "]" + $("#order_additional_info").val();
							$.post(root + "ajax/order_queries.php", {"action": "add_info", "info": add_info}, function(){
								address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
								new_address = window.location.href.replace(address[4] + "/", "");
								new_address = new_address.replace(address[3] + "/", "");
								window.location = new_address + "cart/finish/";
							});					
						}
						return false;
					}
				}
			}, "json");					
			
		}, "json");	
	});
	
	var hoverParent = null;
	
	// $(".product_image_hover_zoom").click(function(){
		// cont = $(this).parent("div");
		// hoverParent = cont;
// 		
		// $("#product_big_image").html("<img alt='" + cont.children(".product_p_info").html() + "' src='" + cont.children("img").attr("src").replace("thumb", "thumb_big") + "' />");
// 		
		// if (cont.position().left < 400)
			// $("#product_big_image").css({"position": "absolute", "left": cont.position().left, "top": cont.position().top});
		// else
			// $("#product_big_image").css({"position": "absolute", "left": cont.position().left - 80, "top": cont.position().top});
// 		
		// $("#product_big_image").fadeIn("fast");
// 		
		// return false;		
	// });
	
	$("#product_big_image").mouseout(function(){
		$(this).fadeOut("fast");
	});
	
	$("#product_big_image").click(function(){
		hoverParent.click();
	});
	
	$("#last_cart").click(function(){
//		$.post(root + "ajax/order_queries.php", {"action": "add_delivery"}, function(){
				address = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
				new_address = window.location.href.replace(address[4] + "/", "");
				new_address = new_address.replace(address[3] + "/", "");
				window.location = new_address + "order/finish/";
				return false;
//		});		
	});
	
	//////////////// IMAGES STRIP /////////////////////////////////////////////////////////
	
	
	
	$("#calendars-new-finish").click(function(){
		months = $("#calendar-data").attr("data-pages");
			
		$.post(root + "ajax/custom_orders/check_all_months.php", {"months": months}, function(data){
			if (data == -1)
				alert("Не сте попълнили снимките за всички страници");
			else
			{
				window.location = root + "cart/add/";
			}
		});
		
		return false;
	});
	
	//////////////// USER ORDERS INFORMATION //////////////////////////////////////////////
	
	$(".order_info").toggle(function(){
		id = $(this).attr("id").replace("order_info_", "");
		$(".suborder_" + id).fadeIn();
		$(".order_" + id).fadeIn();
		return false;
	},
	function(){
		id = $(this).attr("id").replace("order_info_", "");
		$(".suborder_" + id).fadeOut();
		$(".order_" + id).fadeOut("fast");
		return false;
	});
	
	$(".order_info").click(function(){return false;});
	
	
/////////////////// GALLERY /////////////////////////////////////////////////////////
	
	$("#gallery .menu_item").mouseover(function(){
		$(this).css({"background-color": "#F7F7F7"});
	});
	
	$("#gallery .menu_item").mouseout(function(){
		$(this).css({"background-color": "#EDE8E9"});
	});
	
	$(".copy_from_gal").live('mouseover', function(){
		$(this).css({"background-color": "#F7F7F7"});
	});
	
	$(".copy_from_gal").live('mouseout', function(){
		$(this).css({"background-color": "#EDE8E9"});
	});
	
	$("#gal_dialog_body .dialog_buttons").live('mouseover', function(){
		$(this).css({"background-color": "#F7F7F7"});
	});
	
	$("#gal_dialog_body .dialog_buttons").live('mouseout', function(){
		$(this).css({"background-color": "#EDE8E9"});
	});
	
	$("#gal_checkall_album").toggle(function(){
		$("#gal_albums").children(".gal_albums_item").each(function(){			
			$(this).children("p").children("input[type='checkbox']").attr("checked", true);
		});
	}, function(){
		$("#gal_albums").children(".gal_albums_item").each(function(){			
			$(this).children("p").children("input[type='checkbox']").attr("checked", false);
		});
	});
	
	$("#gal_add_album").click(function(){
		startGalDialog("Добавяне на албум:");
		
		$("#gal_dialog_body").html("Зареждане...");
		
		$("#gal_dialog_body").load(root + "ajax/gal_albums.php", {"action": "add_form_load"});
	});
	
	$("#gal_dialog_close").live('click', function(){
		removeGalDialog();
	});
	
	$("#gal_dialog_cancel").live("click", function(){
		$("#gal_dialog_close").click();
	});
	
	$("#gal_dialog_album_create").live("click", function(){
		name = $("#album_name").val();
		
		if (name.length <= 0)
		{
			alert("Въведете име с повече от 1 символ.");
			return false;
		}
		
		place = $("#album_place").val();
		desc = $("#album_desc").val();
		folder = $("#album_folder:checked").val();
		
		$.post(root + "ajax/gal_albums.php", {"action": "create_album", "name": name, "place": place, "desc": desc, "folder": folder}, function(data){
			if (data.success)
			{
				album = "<div class='gal_albums_item' id='album_" + data.id + "' style='background: url(\"" + root + "images/gallery/" + folder + "\") center no-repeat;'>";
				album += "<p><input type='checkbox' name='gal_album_select' class='gal_album_select' value='" + data.id + "' /><span>" + data.date + " г.</span></p>";
				album += "<div class='album_thumb'><div>Натисни тук</div></div>";				
				album += "<p>" + name + "</p>";
				album += "</div>";
				album += "<div class='clear'><!-- --></div>";
				
				$("#gal_albums div:last").remove();
				
				if ($("#gal_albums").children(".gal_albums_item").size() <= 0)
					$("#gal_albums").html("");
				
				
				$("#gal_albums").append(album);
				$("#gal_dialog_close").click();
			}
			else
				alert("Възникна проблем при създаването на Вашия албум.");
		}, "json");		
	});
	
	var selected_albums = new Array();
	var selected_images = new Array();
	
	
	$("#gal_del_album").click(function(){
		renderLoadingOverlay("Изтриване...");
		var i = 0;
		selected_albums = [];
		
		$(".gal_album_select:checked").each(function()
		{
			val = $(this).val();
			if (val > 0)
			{
				selected_albums[i] = val;
				++i;
			}
		});
		
		if (selected_albums.length > 0)
		{			
			$.post(root + "ajax/gal_albums.php", {"action": "delete_albums", "ids[]": selected_albums}, function(data){
				if (data.success)
				{
					len = selected_albums.length;
					
					for (i=0;i<len;++i)
					{
						$("#album_" + selected_albums[i]).remove();
						if ($("#gal_albums").children(".gal_albums_item").size() <= 0)
							$("#gal_albums").html("Няма създадени албуми.");
					}
					
					removeLoadingOverlay();
				}
				else
				{
					removeLoadingOverlay();
					alert("Изтриването е неуспешно");
				}
			}, "json");
		}
		else
			removeLoadingOverlay();
	});
	
	$(".gal_albums_item").live("mouseover", function(){
		$(this).css({"border": "1px solid #4F4D4D"});
	});
	
	$(".gal_albums_item").live("mouseout", function(){
		$(this).css({"border": "1px solid #c5c5c5"});
	});
	
	$(".album_thumb").live("click", function(){
		id = $(this).parent(".gal_albums_item").attr("id").replace("album_", "");
		
		if ($(this).parent(".gal_albums_item").attr("id").substr(0, 1) == "a")
			window.location = window.location.href + "album-" + id + "/";			
		
		return false;
	});
	
	$("#gal_edit_album").click(function(){
		startGalDialog("Редактриране на албум:");
		id = $("#album_id").val();
		
		$("#gal_dialog_body").html("Зареждане...");		
		$("#gal_dialog_body").load(root + "ajax/gal_albums.php", {"action": "edit_form_load", "id": id});
	});
	
	$("#gal_dialog_album_edit").live("click", function(){
		id = $("#album_id").val();
		name = $("#album_name").val();
		place = $("#album_place").val();
		desc = $("#album_desc").val();
		folder = $("#album_folder:checked").val();
		
		$.post(root + "ajax/gal_albums.php", {"action": "edit", "id": id, "name": name, "place": place, "desc": desc, "folder": folder}, function(data){
			if (data.success)
			{
				$("#titles_name").html("Албум: " + name);
				$("#titles_place").html("<span>Място: " + place + "</span>");
				$("#gal_dialog_close").click();
			}
		}, "json");
	});
	
	$("#gal_private_album").click(function(){
		album = $("#album_id").val();
		
		if ($(this).val() == 1)
		{
			$(this).val("0");
		}
		else
		{
			$(this).val("1");
		}
		
		val = $(this).val();
		
		if (val == 1)
			val = 0;
		else
			val = 1;
		
		$.post(root + "ajax/gal_albums.php", {"action": "public", "id": album, "val": val});
	});
	
////////////////////////// GALLERY IMAGES ////////////////////////////////////////////////////
	
	$("#gal_add_image").click(function(){
		startGalDialog("Добавяне на снимки:");		
		$("#gal_dialog_body").html("Зареждане...");
		
		$("#gal_dialog_body").load(root + "ajax/gal_images.php", {"action": "add_form_load", "private": $("#gal_private_album").val()});
	});
	
	$(".image_name").live("click", function(){
		if ($(this).html().indexOf("<input") != 0)
			$(this).html("<input type='text' class='gal_image_name' maxlength='60' id='gal_image_name_" + $(this).parents("div").attr("id").replace("image_", "") + "' value='" + $(this).html() + "' />");
		
		$(this).children("input").focus();
	});
	
	$(".image_name_title").click(function(){
		if ($(this).html().indexOf("<input") != 0)
			$(this).html("<input type='text' class='gal_image_name' maxlength='60' id='gal_image_name_" + $(this).attr("id").replace("image_name_", "") + "' value='" + $(this).html() + "' />");
		
		$(this).children("input").focus();
	});
	
	$(".gal_image_name").livequery("keypress", function(event){
		if (event.keyCode == "13")
		{
			id = $(this).attr("id").replace("gal_image_name_", "");
			name = $(this).val();
			
			$.post(root + "ajax/gal_images.php", {"action": "change_name", "id": id, "name": name}, function(data){
				if (data.success)
				{
					$("#gal_image_name_" + id).parent(".image_name").html(data.name);
					$("#gal_image_name_" + id).parent(".image_name_title").html(data.name);
				}
				else
					alert(data);
			}, "json");
		}
	});
	
	$(".gal_image_name").livequery("blur", function(){
		id = $(this).attr("id").replace("gal_image_name_", "");
		name = $(this).val();
		
		$.post(root + "ajax/gal_images.php", {"action": "change_name", "id": id, "name": name}, function(data){
			if (data.success)
			{
				$("#gal_image_name_" + id).parent(".image_name").html(data.name);
				$("#gal_image_name_" + id).parent(".image_name_title").html(data.name);
			}
			else
				alert(data);
		}, "json");
		
		return false;
	});
	
	$("#gal_del_image").click(function(){
		renderLoadingOverlay("Изтриване...");
		var i = 0;
		selected_images = [];
		$(".gal_image_select:checked").each(function(){
			val = $(this).val();
			id = $(this).parents(".gal_albums_item").attr("id").replace("image_", "");
			
			if (val.length > 0)
			{				
				selected_images[i] = val + "||" + id + "||" + $("#album_id").val();				
				++i;
			}
		});

		if (selected_images.length > 0)
		{
			$.post(root + "ajax/gal_images.php", {"action": "delete_images", "ids[]": selected_images}, function(data){
				if (data.success)
				{
					len = selected_images.length;
					
					for (i=0;i<len;++i)
					{
						tp = selected_images[i].split("||", 2);
						$("#image_" + tp[1]).remove();
						
						if ($("#gal_albums").children(".gal_albums_item").size() <= 0)
							$("#gal_albums").html("Няма създадени албуми.");
					}					
					removeLoadingOverlay();
				}
				else
				{
					removeLoadingOverlay();
					alert("Изтриването е неуспешно");
				}
			}, "json");
		}
		else
			removeLoadingOverlay();
	});
	
	$(".gal_image img").live("click", function(){
		id = $(this).parent().parent(".gal_image_item").attr("id").replace("image_", "");
		albumID = $("#album_id").val();
		
		window.location = window.location.href + id + "/";
	});
	
	$(".gal_image_search img").live("click", function(){
		url = $(this).attr("src").replace("thumb/", "").replace("album_", "album-");
		url = url.substr(0, url.lastIndexOf("/"));
		url = url + "/" + $(this).attr("alt") + "/";
		window.location = url;
	});
	
	$("#gal_set_image").click(function(){
		file = $("#gal_image_large_img img").attr("alt");
		id = $("#album_id").val();
		
		$(".gal_albums_msg").fadeOut();
		
		$.post(root + "ajax/gal_albums.php", {"action": "set_thumb", "file": file, "id": id}, function(data){
			if (data == "failed")
			{
				$("#gal_albums_error").html("Промяната на заглавна снимка на албума е неуспешна, моля опитайте пак.");
				$("#gal_albums_error").fadeIn();
			}
			else
			{
				$("#gal_albums_msg").html("Промяната на заглавна снимка на албума е успешна.");
				$("#gal_albums_msg").fadeIn();
			}
		});
	});
	
	$("#gal_keywords a").click(function(){
		id = $(this).attr("id").replace("gal_keywords_", "");
		
		startGalDialog("Добавяне на ключови думи:");
		
		$("#gal_dialog_body").html("Зареждане...");		
		$("#gal_dialog_body").load(root + "ajax/gal_images.php", {"action": "keywords_form_load", "id": id});
		
		return false;
	});
	
	$("#gal_image_keywords_add").live("click", function(){
		id = $("#gal_image_id").val();
		keywords = $("#image_keywords").val();

		$.post(root + "ajax/gal_images.php", {"action": "add_keywords", "id": id, "keywords": keywords}, function(data){
			if (data.success)
			{
				if (keywords != " ")
				{
					keywords = keywords.replace(" ", ", ");
					
					if ($("#gal_keywords span").html().length > 0)
						$("#gal_keywords span").append(", ");
					$("#gal_keywords span").append(keywords);
				}
				removeGalDialog();
			}
			else
			{
				alert("false");
			}
		}, "json");
	});
	
	$("#gal_set_profile_image").click(function(){
		file = $("#gal_image_large_img img").attr("alt");
		id = $("#album_id").val();
		
		$(".gal_albums_msg").fadeOut();
		
		$.post(root + "ajax/gal_images.php", {"action": "set_profile", "file": file, "id": id}, function(data){
			if (data == "failed")
			{
				$("#gal_albums_error").html("Промяната на заглавна снимка на профила е неуспешна, моля опитайте пак.");
				$("#gal_albums_error").fadeIn();
			}
			else
			{
				$("#gal_albums_msg").html("Промяната на заглавна снимка на профила е успешна.");
				$("#gal_albums_msg").fadeIn();
			}
		});
	});
	
////////////// GALERY INDEX ///////////////////////////////////////////////
	
	$("#gal_search_btn").click(function(){
		type = $("#gal_search_type").val();
		keywords = $("#gal_search_text").val();
//		keywords = keywords.trim();
//		keywords = ltrim(rtrim(keywords, ' '), ' ');
		
		$("#gal_albums").html("Търсене...");
		
		if (keywords.replace(" ", "") == "")
			return false;
		
		$.post(root + "ajax/gal_index.php", {"action": "search", "type": type, "keywords": keywords}, function(data){
			$("#gal_search_title").html("Резултати за: " + keywords);

			if (data.count > 0)
			{
				$("#gal_albums").html("");				
				$.each(data.results, function(index, result){
					if (type == 1)
					{
						album  = "<div class='gal_albums_item gal_image_item' id='image_" + result.id + "'>";
						album += "<p></p>";
						album += "<div class='clear'><!-- --></div>";
						album += "<p class='gal_image_search'><img src='" + root + "ajax/gal_get_image.php?user=" + result.user + "&album=" + result.album_id + "&thumb=thumb&image=" + result.file + "'  alt='" + result.id + "' /></p>";
						
						if (result.name == "Натиснете, за да смените името" )
							result.name = "";
						album += "<p><span class='image_name'>" + result.name + "</span></p>";
						
						
						album += "</div>";
					}
					else if (type == 2)
					{
						album = "<div class='gal_albums_item' id='album_" + result.id + "' style='background: url(\"" + root + "images/gallery/" + result.folder + "\") center no-repeat;'>";
						album += "<p><span>" + result.date + " г.</span></p>";
						album += "<div class='album_thumb_search'><img src='" + root + "ajax/gal_get_image.php?user=" + result.user + "&album=" + result.id + "&thumb=thumbs&image=" + result.thumb + "' alt='" + result.date + "' style='margin-top: 50px;' /></div>";				
						album += "<p>" + result.name + "</p>";
						album += "</div>";
					}
					else
					{
						album = "<div class='gal_albums_item' id='album_" + result.id + "' >";
						if (!result.image)
							album += "<div class='album_thumb_user'><img alt=" + result.username + " src='" + root + "images/noimg.png' style='margin-top: 50px;' /></div>";
						else
						{
							imageData = result.image.split("||");
							album += "<div class='album_thumb_user'><img alt=" + result.username + " src='" + root + "ajax/gal_get_image.php?user=" + result.username + "&album=" + imageData[0] + "&thumb=thumbs&image=" + imageData[1] + "' style='margin-top: 50px;' /></div>";
						}
						album += "<p>" + result.username + "</p>";
						album += "</div>";
					}
					
					$("#gal_albums").append(album);
				});
				
				album = "<div class='clear'><!-- --></div>";						
				$("#gal_albums").append(album);				
			}
			else
			{				
				$("#gal_albums").html("Няма открити резултати..");
			}
			
		}, "json");
	});
	
	$(".album_thumb_search").live("click", function(){
		src = $(this).children("img").attr("src");
		src = src.replace(src.substr(src.indexOf("thumb")), "");
		src = src.replace("album_", "album-");
		window.location = root + 'galle';
	});
	
	$(".album_thumb_user").live("click", function(){
		username = $(this).children("img").attr("alt");
		url = root + 'gallery/' + username + '/';
		window.location = url;
	});
	
	$("#gal_top_links_tags").click(function(){
		$("#gal_search_text").fadeOut();
		$("#gal_search_type").fadeOut();
		$("#gal_search_btn").fadeOut();
		
		$(".gal_top_links").css({"font-weight": "normal"});
		$("#gal_search_title").html("Ключови думи:");
		$("#gal_albums").html('');
		$(this).css({"font-weight": "bold"});
		
		$.post(root + "ajax/gal_index.php", {"action": "last_tags"}, function(data){
			$.each(data, function(index, tag){
				w = tag.weight;
				if (w > 500)
					weight = 220;
				if (w > 250 && w <= 500)
					weight = 210;
				if (w > 100 & w <= 250)
					weight = 200;
				if (w > 50 && w <= 100)
					weight = 190;
				if (w > 25 && w <= 50)
					weight = 180;
				if (w > 10 && w <= 25)
					weight = 170;
				if (w > 5 && w <= 10)
					weight = 160;
				if (w > 2 && w <= 5)
					weight = 130;
				if (w <= 2)
					weight = 100;
				
				$("#gal_albums").append(" <a href='#' class='gal_tags_link' style='color: #000000; font-size:" + weight + "%;'>" + tag.tag + "</a> ");
			});
		}, "json");
		
		return false;
	});
	
	$(".gal_tags_link").livequery("mouseover", function(){
		$(this).css({"text-decoration": "underline"});
	});
	
	$(".gal_tags_link").livequery("mouseout", function(){
		$(this).css({"text-decoration": "none"});
	});
	
	$(".gal_tags_link").live("click", function(){
		tag = $(this).html();
		
		$("#gal_search_text").fadeIn();
		$("#gal_search_type").fadeIn();
		$("#gal_search_btn").fadeIn();
		$("#gal_search_text").val(tag);
		$("#gal_search_title").html("Резултати за: " + tag);		
		$("#gal_search_btn").click();
		
		return false;
	});
	
	$("#gal_top_links_users").click(function(){
		$("#gal_search_text").fadeOut();
		$("#gal_search_type").fadeOut();
		$("#gal_search_btn").fadeOut();
		
		letters = new Array('0', '1', '2', '3', '4', '5', '6', '7',
							'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
							'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
							'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 
							'W', 'X', 'Y', 'Z');
		
		len = letters.length;
		let = '';
		
		for (i=0; i<len; ++i)
			let += ' <a href="#" class="gal_letters_links" style="color: #000000; font-weight: bold;">' + letters[i] + '</a> ';
		
		$(".gal_top_links").css({"font-weight": "normal"});
		$("#gal_search_title").html("Потребители: ");
		$("#gal_albums").html('<p class="gal_search_letters">' + let + '</p><br/>');
		$(this).css({"font-weight": "bold"});
		
		$.post(root + "ajax/gal_index.php", {"action": "last_users"}, function(data){
			$.each(data, function(index, user){
				if (!user.image)
				{
					img = "<a href='" + root + "gallery/" + user.username + "/' class='gal_users_link'><img alt=" + user.username + " src='" + root + "images/ico-no-avatar.png'/></a>";
				}
				else
				{
					image = user.image.split("||");
					img = "<a href='" + root + "gallery/" + user.username + "/' class='gal_users_link'><img alt='" + user.id + "' src='" + root + "ajax/gal_get_image.php?user=" + user.username + "&album=" + image[0] + "&thumb=thumbs&image=" + image[1] + "' /></a>";
				}

				userBox = "<div class='gal_search_user_box'>";
				userBox += img;
				userBox += "<p><a href='" + root + "gallery/" + user.username + "/' class='gal_users_link'>" + user.username + "</a><br/>";
				
				if (user.name)
					userBox += "<span>" + user.name + "</span><br/>";
				
				userBox += "<span>Снимки: " + user.images + "</span><br/>";
				userBox += "<span>Албуми: " + user.albums + "</span>";
				
				userBox += "</p><div class='clear'></div></div>";
				$("#gal_albums").append(userBox);
			});
		}, "json");
		
		return false;
	});
	
	$(".gal_search_user_box").livequery("mouseover", function(){
		$(this).css({
			"border": "1px solid #CF968F"
		});
	});
	
	$(".gal_search_user_box").livequery("mouseout", function(){
		$(this).css({"border": "1px solid #c5c5c5"});
	});
	
	$(".gal_letters_links").livequery("mouseover", function(){
		$(this).css({"text-decoration": "underline"});
	});
	
	$(".gal_letters_links").livequery("mouseout", function(){
		$(this).css({"text-decoration": "none"});
	});
	
	$(".gal_letters_links").live("click", function(){
		renderLoadingOverlay("Зареждане...");
		letters = new Array('0', '1', '2', '3', '4', '5', '6', '7',
				'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
				'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
				'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 
				'W', 'X', 'Y', 'Z');

		len = letters.length;
		let = '';
		
		for (i=0; i<len; ++i)
		let += ' <a href="#" class="gal_letters_links" style="color: #000000; font-weight: bold;">' + letters[i] + '</a> ';

		$("#gal_albums").html('<p class="gal_search_letters">' + let + '</p><br/>');
		$.post(root + "ajax/gal_index.php", {"action": "get_users", "letter": $(this).html()}, function(data){
			removeLoadingOverlay();
			$.each(data, function(index, user){
				if (!user.image)
				{
					img = "<a href='" + root + "gallery/" + user.username + "/' class='gal_users_link'><img alt=" + user.username + " src='" + root + "images/ico-no-avatar.png'/></a>";
				}
				else
				{
					image = user.image.split("||");
					img = "<a href='" + root + "gallery/" + user.username + "/' class='gal_users_link'><img alt='" + user.id + "' src='" + root + "ajax/gal_get_image.php?user=" + user.username + "&album=" + image[0] + "&thumb=thumbs&image=" + image[1] + "' /></a>";
				}

				userBox = "<div class='gal_search_user_box'>";
				userBox += img;
				userBox += "<p><a href='" + root + "gallery/" + user.username + "/' class='gal_users_link'>" + user.username + "</a><br/>";
				
				if (user.name)
					userBox += "<span>" + user.name + "</span><br/>";
				
				userBox += "<span>Снимки: " + user.images + "</span><br/>";
				userBox += "<span>Албуми: " + user.albums + "</span>";
				
				userBox += "</p><div class='clear'></div></div>";
				$("#gal_albums").append(userBox);
			});
		}, "json");
		
		return false;
	});
	
////////////////////////////// GALLERY EFFECTS //////////////////////////////////////
	
	$(".image_tools").click(function(){
		fx = $(this).attr("id");
		fx = fx.replace("fx-", "");
		user = $("#image_username").val();
		album =	$("#image_album").val();
		thumb = $("#image_thumb").val();
		file = $("#image_name").val();
		
		if (fx == "cancel")
			$("#gal_big_image").attr("src", $("#original_image").val());
		else
			$("#gal_big_image").attr("src", root + "ajax/photo_edit.php?effect=" + fx + "&user=" + user + "&album=" + album + "&thumb=" + thumb + "&image=" + file);
		
		$("#applied_effect").val(fx);
	});
	
	$(".image_tools").mouseover(function(){
		$(this).css({"font-weight": "bold"});
	});
	
	$(".image_tools_save").mouseover(function(){
		$(this).css({"color": "#3C8C04"});
	});
	
	$(".image_tools, .image_tools_save").mouseout(function(){
		$(this).css({"font-weight": "normal", "color": "#000000"});
	});
	
	$("#image_save").click(function(){
		renderLoadingOverlay("Зареждане");
		fx = $("#applied_effect").val();
		user = $("#image_username").val();
		album =	$("#image_album").val();
		thumb = $("#image_thumb").val();
		file = $("#image_name").val();
		priv = $("#image_private").val();
		
		$.get(root + "ajax/photo_edit.php", {"effect":fx, "user": user, "album": album, "thumb": thumb, "image": file, "save": "save", "private": priv}, function(data){
			removeLoadingOverlay();
			alert(data);			
		});
		
		$("#applied_effect").val(fx);
	});
	
	$("#image_save_overwrite").click(function(){
		renderLoadingOverlay("Зареждане");
		fx = $("#applied_effect").val();
		user = $("#image_username").val();
		album =	$("#image_album").val();
		thumb = $("#image_thumb").val();
		file = $("#image_name").val();
		priv = $("#image_private").val();
		
		$.get(root + "ajax/photo_edit.php", {"effect":fx, "user": user, "album": album, "thumb": thumb, "image": file, "save": "overwrite", "private": priv}, function(data){
			removeLoadingOverlay();
			alert(data);			
		});
		
		$("#applied_effect").val(fx);
	});
});
