$(document).ready(function(){
	
	debug 		= false;
	var step	= 1;
	
	var cake	= new Cake();
	cake.init();
	
	$("a[prop=form][value=circle]").addClass("current");
	$("a[prop=weight][value=2]").addClass("current");
	$("a[prop=impregnation][value=default]").addClass("current");
	
	
	if (debug)
	{
		$("input[name=telephone]").val("123456");
		$("input[name=password]").val("123456");
	}
	
	/*
	
		Cake object
		
		
	*/
	
	function Cake() 
	{
		this.defaults	= {
			form		: 'circle',
			weight		: 2,
			impregnation: 'default', /* коржи, пропитка */
			interlayer	: false, /* прослойка (склейка) */
			filling		: false, /* наполнение */
			coating		: false, /* обмазка */
			decor		: false /* декор */
		};
		
		/* Closure for this */
		var my = this;
		
		/* 
		
		Для хранения количественного показателя опции
		используется дополнительный массив prop_quantity
		
		*/
		this.prop_quantity = { };
		
		
		/* Initiate */
		this.init = function (options)
		{
			/* Evaluate options */
			for(var name in my.defaults) 
			{
				this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : my.defaults[name];
			}
		};
		
		
		/* set property */
		this.setProperty = function (prop, value, quantity)
		{
			if (!quantity) quantity = 1;
			
			if (prop !== undefined && value !== undefined) 
			{
				this[prop] = value;
				eval ("my.prop_quantity[prop] = { '"+value+"' : "+quantity+" };");
			}
			
			// log
			if (debug) 
			{
				_debug = my.display_config('debug');
				$("#description div.center_bg").html('<p style="text-align: left;"><table>' + _debug + '</table></p>');
			}
			// render
			
			my.render();
		};
		
		
		/* add property */
		this.addProperty = function (prop, value, quantity)
		{
			if (prop !== undefined && value !== undefined) 
			{
				if (debug) console.log('addProperty('+prop+', '+value+', '+quantity+')');
				if (!quantity) var quantity = 1;
				var old_value 	= String (my[prop]);
				var els 		= old_value.split(',');
				var new_value;
				
				if (old_value != 'false')
				{
					// проверяем наличие такого значения
					var has = false;
					for (i in els) 
					{
						if (els[i] == value) 
						{
							has = true;
							break;
						}
					}
					if (has == false) 
					{
						new_value = old_value + ',' + value;
					}
					else 
						new_value = old_value;
				}
				else new_value = value;
				
				
				// количество
				quantity = Number(quantity);
				eval ("var new_quantity = {'"+value+"' : "+quantity+" };");
				if (my.prop_quantity[prop] === undefined) 
				{
					my.prop_quantity[prop] = new_quantity;
				}
				else 
				{
					var old_quantity = my.prop_quantity[prop];
					old_quantity[value] = quantity;
					my.prop_quantity[prop] = old_quantity;
				}
				
				this[prop] = new_value;
				
				this.render();
			}
		}
		
		/* remove property */
		this.removeProperty = function (prop, value)
		{
			if (debug) console.log("removeProperty("+prop+", "+value+")");
			if (prop !== undefined && value !== undefined) 
			{
				
				var old_value 	= String (this[prop]);
				var els 		= old_value.split(',');
				var del_from;
				
				
				for (i in els) 
				{
					if (els[i] == value)
					{
						del_from = i;
					}
				}
								
				els.splice(del_from, 1);
				
				// удаляем из массива количеств
				for (var z in my.prop_quantity)
				{
					if (z == prop) 
					{
						var arr = my.prop_quantity[z];
						for (var y in arr)
						{
							if (y == value) 
							{
								delete(arr[y]);
							}
						}
					}
				}
				
				
				if (els.length > 0) this[prop] = els.join(',');
				else this[prop] = false;
				
				my.render();
				
			}
		}
		
		
		
		// 
		//	Возвращаем количество опций (массив[paramName][paramValue])
		//
		this.get_quantity = function (paramName, paramValue)
		{
			if (my.prop_quantity[paramName] !== undefined) 
			{
				return my.prop_quantity[paramName][paramValue];
			}
			else return 0;
		}
		
		// Показываем текущую конфигурацию торта
		// mode:
		//		tab - в виде строки таблицы
		//		input - в виде инпутов
		//		debug - в виде строки таблицы (оригинальные значения)
		// return html
		this.display_config = function (mode)
		{
			var _r = '';
			var _prop;
			var _val;
			var _quant;
			for (prop in this)
			{
				var val = this[prop];
				var _val = '';
				var _val_arr = new Array();
				
				if (prop == 'form' || prop == 'weight' || prop == 'impregnation' || prop == 'interlayer' || prop == 'filling' || prop == 'coating' || prop == 'decor' || prop == 'text' || prop == 'cost') 
				{
					if (prop !== undefined)
					{
						
						
						// количество опций
						_quant = my.get_quantity(prop, val);
						
						switch (prop)
						{
							case 'form' :
								_prop = 'Форма';
								break;
								
							case 'weight' :
								_prop = 'Вес';
								break;
								
							case 'impregnation' :
								_prop = 'Коржи, пропитка';
								break;
								
							case 'interlayer' :
								_prop = 'Склейка';
								break;
								
							case 'filling' :
								_prop = 'Начинка';
								break;
								
							case 'coating' :
								_prop = 'Обмазка';
								break;
								
							case 'decor' :
								_prop = 'Украшение';
								break;
								
							case 'text' :
								_prop = 'Наносимый текст';
								break;
								
							default:
								_prop = prop;
								break;
						}
						
						// перевод значений на русский
						switch (val)
						{
							case 'undefined' :
								_val = '<не определено>';
								break;
								
							case '' :
								_val = '<не указано>';
								break;
								
							case false :
								_val = '<не выбрано>';
								break;
								
							default :
								// если есть запятая значит обрабатываем как массив
								val = String(val);
								
								var vals = val.split(',');
																	
								for (i in vals)
								{
									var v = vals[i];
									if (options_rus[prop+'_'+v]) 
									{
										_val_arr[i] = options_rus[prop+'_' + v] ;
										// количество опций
										_quant = my.get_quantity(prop, v);
										if (_quant > 1) _val_arr[i] += ' ('+_quant+' шт.)';
									}
									else _val_arr[i] = v;
								}
								
								_val = _val_arr.join(', ');
								
								break;
						}
						
						
						if (mode == 'tab') _r += '<tr><td>'+_prop+':</td><td>'+_val+'</td><!--td>'+_quant+'</td--></tr>';
						else if (mode == 'input') _r += '<input type="hidden" name="cake_config['+_prop+']" value="'+_val+'" />';
						else if (mode == 'debug') _r += '<tr><td>'+prop+':</td><td>'+val+'</td></tr>';
					}
				}
			}
			
			if (_r !== undefined) return _r;
		}
		
		
		/* multi layers */
		this.multi_layers = function (layer, prop, value)
		{
			if (debug) console.log('multi_layers('+layer+', '+prop+', '+value+')');
			var obj = $(layer);
			var options = String(value);
			var els 	= options.split(',');
			var img_full_path;
			var val;
			
			$(obj).empty();
			
			for (i in els)
			{
				val = els[i];
				if (cake_images[prop][val][this.form]) img_full_path = image_path + cake_images[prop][val][this.form];
				else if (cake_images[prop][val]['default']) img_full_path = image_path + cake_images[prop][val]['default'];
				$(obj).append('<div class="cake-layer" style="background: url('+img_full_path+') no-repeat"></div>');
			}
		}
		
		
		/* render cake */
		this.render = function ()
		{
			if (debug) console.log('render()');
			
			$("div.cake div").css("background", "none");
			for (prop in my)
			{
				if (prop == 'form' || prop == 'impregnation' || prop == 'interlayer' || prop == 'filling' || prop == 'coating' || prop == 'decor') 
				{
					var val 			= this[prop];
					var img_full_path	= '';
					
					if (val != false) 
					{
						
						//console.log('cake_images['+prop+']['+val+'][default]');
						
						switch (prop)
						{
							case 'decor':
								if (cake_images[prop][val][this.form]) img_full_path = image_path + cake_images[prop][val][this.form];
								else if (cake_images[prop][val]['default']) img_full_path = image_path + cake_images[prop][val]['default'];
								$("div.cake div."+prop+ " div").css("background", 'url("'+ img_full_path + '") no-repeat');
								break;
							
							case 'filling':								
								// так как может быть одновременно несколько наполнений создаем несколько слоев
								this.multi_layers('div.cake-layer.filling', 'filling', val);
								break;
								
							case 'impregnation':								
								// так как может быть одновременно несколько наполнений создаем несколько слоев
								this.multi_layers('div.cake-layer.impregnation', 'impregnation', val);
								break;
							
							default:
								if (cake_images[prop][val][this.form]) img_full_path = image_path + cake_images[prop][val][this.form];
								else if (cake_images[prop][val]['default']) img_full_path = image_path + cake_images[prop][val]['default'];
								$("div.cake div."+prop+ "").css("background", 'url("'+ img_full_path + '") no-repeat');
								break;
						}
					}
				}
			}
		};
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/****************************************************************************
	
		Actions 
		
	*/
	
	
	
	
	// Панель управления количеством
	$("div.count_panel input[name=item_count]").change(function(){
		change_quantity($(this));
	});
	$("div.iframe li.additionally a").click(function(e){
		//alert (e);
		e.preventDefault();
	});
	
	// изменение количества
	function change_quantity(o){
		var v = $(o).val();
		var a = $(o).closest("li").find("a[quantity]");
		$(a).attr("quantity", v);
		
		if (v >= 1) cake.addProperty($(a).attr("prop"), $(a).attr("value"), v);
		else cake.removeProperty($(a).attr("prop"), $(a).attr("value"));
		
		//console.log('checkStep('+step+')');
		checkStep(step);
	}
	
	// нажатие на "-" или "+"
	$("input[type=button].decrease, input[type=button].increase").click(function(e){
		e.preventDefault();
		var c; // class
		var v;
		var overall = 0;
		var menu_option = $(this).closest("li.main-level").find("a[open]");
		
		if ($(this).hasClass("decrease")) c = "decrease";
		if ($(this).hasClass("increase")) c = "increase";
		
		$("li.visible input[name=item_count]").each (function(){
			overall += Number ($(this).val() );
		});
		
		switch (c)
		{
			case "decrease" :
				var o = $(this).next();
				var v = $(o).val();
				if (overall <= 0) return;
				if (v <= 0) return;
				v--;
				overall--;
				break;
				
			case "increase" :
				var o = $(this).prev();
				var v = $(o).val();
				if (overall >= 3)
				{
					alert ("К сожалению, максимально возможно только три коржа...");
					return;
				}
				v++;
				overall++;
				break;
		}
		$(o).val(v);	
		
		
		// вкл./выкл. опцию в главном меню, в зависимости от общего кол-ва выпадающмх опций
		if (overall >= 1) $(menu_option).addClass("current");
		else $(menu_option).removeClass("current");
		
		change_quantity(o);
	});	
	
	
	
	
	
	// Предупреждение что не выбраны обязательные опции на данном шаге
	$("div.nav a.next").hover(function () {
		if ($(this).hasClass('disabled') === true) 
		{
			//alert ('Не выбраны обязательные опции на данном шаге!');
			$("#infoblock").show().find('div').html('Прежде чем перейти дальше, нужно выбрать одну из обязательных опций в левом и правом меню!');
			/*$("li.main-level.required:visible a:not(.current)").each(function(){
				$(this).css('border', '1px dashed red');
				$(this).css('margin', '0px');
			});*/
		}
	}, 
	function () {
		$('#infoblock').hide().find('div').html('');
		/*$("li.main-level.required:visible a:not(.current)").each(function(){
			$(this).css('border', 'none');
			$(this).css('margin', '1px');
		});*/
    });
	
	
	
	// Показываем слои под обмазкой и начинкой
	$("#left_icons li[step=2] a").hover(function () {
		$("#cake div.filling").fadeOut('slow');
	});
	$("li[step=2] a, #left_icons li[step=3]").hover(function () {
		$("#cake div.coating").fadeOut('slow');
	}, 
	function () {
		//$("#cake div.coating").delay('1000').fadeIn('fast');
    });
	
	$("li[step=3] a[prop=coating]").click(function(){
		$("#cake div.coating").show();
	});
	
	// Ввод текста
	$("textarea[name=words_on_cake]").bind('keydown keypress keyup', function(){
		var _len = $(this).val().length;
		var _max = 50
		if (_len > _max) $(this).val($(this).val().substr(0,_max));
		else $("#words_on_cake div p").html("<p>Текст на плитке шоколада (еще свободно " + (_max - _len) + " символов)</p>");
		cake.setProperty('text', $(this).val());
	}).keyup();
	
	
	// Навигация
	$("ul.steps a").click(function(e){
		e.preventDefault();
		if (debug)
		{
			step = $(this).attr("step");
			active_step = $("ul.steps a.select").attr("step");
			
			if (active_step == step) return;
		
			doStep(step);
		}
		
	});
	
	
	// назад - вперед
	$("div.nav a").click(function(e){
		e.preventDefault();
		var action = $(this).attr("action");
		var cur_step = $("ul.steps a.select").attr("step");
		
		if($(this).hasClass("disabled")) return;
		
		switch(action)
		{
			case 'next':
				if (cur_step == 6) return;
				step++;
				break;
				
			case 'prev':
				if (cur_step == 1) return;
				step--;
				break;
		}
		doStep(step);
	});
	
	
	// Убираем обмазку и украшения при смене формы
	$("#left_icons li[step=1] a:not(.current)").click(function(){
		cake.setProperty('coating', false);
		cake.setProperty('decor', false);
		$("li[step=4] a").removeClass("current");
		$("#right_icons li[step=3] a.current").removeClass("current");
		$("ul.decor_list li").removeClass("current");
	});
	
	
	// Опции
	$("#left_icons a, #right_icons a").click(function(e){
		e.preventDefault();
		
		
		var step 	= $(this).parent().attr("step");
		var _open 	= $(this).attr("open");
		var addit	= $(this).attr("additionally"); // additionally
		var prop 	= $(this).attr("prop");
		var value 	= $(this).attr("value");
		var quantity= $(this).attr("quantity");
		
		// показываем обмазку (если вдруг она была убрана)
		//if (cake.coating != false) $("#cake div.coating").delay('800').fadeIn('slow');
		
		// Мультивыбор (несколько дополнительных опций)
		if (addit == 'true') 
		{
			// "выключаем" выбранное из дополнительных
			if ($(this).hasClass("current"))
			{
				if (step == 1) return;
				$(this).removeClass("current");
				cake.removeProperty(prop, value);
				checkStep(step);
				return;
			}
			else 
			{
				$(this).addClass("current");
				cake.addProperty(prop, value);
			}
		}
		else 
		{
			// если опция не является поп-апом, то выделяем
			if (step !== undefined && _open === undefined)
			{
				//$(this).parent().parent().find("li[step="+step+"] a[additionally!='true']").removeClass("current");
				$(this).parent().parent().find("li[step="+step+"] a").removeClass("current");
				$(this).addClass("current");
			}
			else 
			{
				//checkStep(step);
				return;
			}
			
			if (prop && value) 
			{
				cake.setProperty(prop, value, quantity);
			}
		}
		
		checkStep(step);
		countCost();
	});
	
	
	// Дополнительные опции (всплывающее окно)
	$("a[open]").click(function(e){
		e.preventDefault();
		var title = $(this).attr("title");
		var obj = $(this).attr("open");
		
		$(this).closest("ul").find("a").removeClass("pressed");
		$(this).addClass("pressed");
		$("div.iframe").hide();
		$(obj).fadeIn();
		$(obj).find("p.iframe_title").html(title);
	});
	$('div.iframe ul.decor_list li').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	}); 
	
	// Выбор Дополнительные опции 
	$("ul.decor_list a").click(function(e){
		e.preventDefault();
		
		// если щелкаем по мультиопциям, то не выбираем опцию
		if ($(this).parent().hasClass("additionally") === true) return;
		
		var prop = $(this).attr("prop");
		var value = $(this).attr("value");
		var quantity= $(this).attr("quantity");
				
		// снимаем активность с опциий
		var main_ul = $(this).closest("li.main-level").closest("ul");
		$(main_ul).find("li.visible ul.decor_list li").removeClass("current");
		$(main_ul).find("li.visible a").removeClass("current");
		
		$(this).closest("li").addClass("current");
		$(this).addClass("current");
		
		
		// выделяем в меню
		var iframe = $(this).closest("div.iframe");
		$(iframe).parent().find('a[open]').addClass("current");
		countCost();
		
		if (prop && value) 
		{
			cake.setProperty(prop, value, quantity);
		}
		
		$(iframe).fadeOut('slow');
		$(iframe).closest("ul").find("a").removeClass("pressed");
		
		checkStep(step);
		
	});
	// закрыть окно
	$("div.iframe_close").click(function(){
		$(this).parent().fadeOut('fast');
		$(this).closest("ul").find("a").removeClass("pressed");
	});
	// дополнительная кнопка "ок" для опций с количеством
	$("div.iframe").each(function(i){
		var has_countable = $(this).find("li.additionally").length;
		if (has_countable > 0) 
		{
			//$("div.iframe_close").hide();
			$(this).find("ul.decor_list").before('<input type="button" value=" Подтвердить количество " class="iframe_close_btn button" />');
		}
	});
	$("input.iframe_close_btn").click(function(){ 
		$("div.iframe_close").click(); 
		$("div.iframe_close").show();
	});
	
	
	// масштаб 
	$("a[prop=weight]").click(function(){
		var i = $("#weight_scale img");
		var cake = $("#cake");
		switch ($(this).attr("value"))
		{
			case '6' :
				$(i).css("width", "150px").css("height", "133px");
				break;
				
			case '4' :
				$(i).css("width", "200px").css("height", "177px");
				break;
				
			case '2' :
			default :
				$(i).css("width", "250px").css("height", "221px");
				break;
				
				
		}
	});
	
	doStep(step);
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*
	
		Functions
		
	*/
	
	// Подсчитываем стоимость выбранных опций
	function countCost()
	{
		var summa = 0;
		var weight = Number (cake.weight);
		var cost;
		var collect = $("a.current[cost]");
		$(collect).each(function(i){
			cost = Number ($(this).attr("cost"));
			summa += cost;
		});
		if (debug) 
		{
			console.log(cake.prop_quantity);
			console.log(summa + '*' + weight);
		}
		$("#cost span").text(summa * weight);
	}
	
	
	
	
	// Проверяем выбраны ли required опции на данном шаге
	function checkStep(step)
	{
		if (step == 5 || step == 6) return;
		if (debug) { $("div.nav a.next").removeClass("disabled"); return; }
		
		// проверяем левую колонку
		var left = false;
		var o = $("#left_icons li.required:visible");
		
		if (o.length > 0) 
		{
			$(o).find("a:first").each(function(i){
				if ($(this).hasClass("current"))
					left = true;
			});
		}
		else left = true;
		
		// проверяем правую колонку
		var right = false;
		var o = $("#right_icons li.required:visible");
		if (o.length > 0) 
		{
			$(o).find("a:first").each(function(i){
				if ($(this).hasClass("current"))
					right = true;
			});
		}
		else right = true;
		
		//console.log(left + ' || ' + right);
		
		if (left && right) $("div.nav a.next").removeClass("disabled");
		else $("div.nav a.next").addClass("disabled");
	}
	
	// Делаем шаг
	function doStep (step) 
	{
		$("ul.steps a").each(function(){
			$(this).removeClass("select");
		});
		$("ul.steps a[step="+step+"]").addClass("select");
		
		$("div.nav a.prev").removeClass("disabled");
		
		// название колонки
		$("div.col_header").hide();
		$("div.col_header[step="+step+"]").show();
		
		// пункты меню
		$("#left_icons li.main-level, #right_icons li.main-level").removeClass("visible"); // убираем все пункты 
		$("#left_icons li[step="+step+"].main-level, #right_icons li[step="+step+"].main-level").addClass("visible");
		
		// размещение пунктов меню по колонкам
		$("#left_icons, #right_icons, div.col_header").css("width", "100px");
		$("div.right #right_icons, div.right div.col_header").css("float", "right");
		$("#right_icons").css("width", "110px");
		var menu_L_count = $("#left_icons li[step="+step+"]").length;
		var menu_R_count = $("#right_icons li[step="+step+"]").length;
		if (menu_L_count > 6) 
		{
			$("#left_icons, div.left div.col_header").css("width", "200px");
		}
		if (menu_R_count > 6) 
		{
			$("#right_icons, div.right div.col_header").css("width", "200px");
		}
		
		
		
		countCost();
		$("#order_form").hide();
		
		
		switch (step)
		{
			case 1 :
			default:
				$("#cake div.coating").fadeIn('slow');	
				$("#cake div.filling").fadeIn('slow');			
				$("div.nav a.prev").addClass("disabled");
				$("#weight_scale").fadeIn('slow');	
				break;
				
			case 2 :
				$("#cake div.coating").fadeIn('slow');
				$("#cake div.filling").fadeIn('slow');
				/**/
				$("#weight_scale").fadeOut('slow');	
				$("div.pInfoGood").hide();
				$("div.pInfoError").hide();
				//$("#cake div.filling div.cake-layer").fadeOut('slow');	
				break;
				
			case 3 :
				$("#cake div.coating").fadeIn('slow');
				$("#cake div.filling").fadeIn('slow');
				//$("#cake div.filling div.cake-layer").fadeIn('slow');
				break;
				
			case 4 :
				$("#cake div.coating").fadeIn('slow');
				
				// убираем украшения, невозможные в этой форме 
				$("li[step=4] ul.decor_list").closest("li[step="+step+"]").addClass("visible");
				$("li[step=4] ul.decor_list li").addClass('visible');
				$("li[step=4] ul.decor_list a[form!="+cake.form+"]").closest("li").removeClass('visible');
				$("li[step=4] ul.decor_list").each(function(i)
				{
					var len = $(this).find("li.visible").length;
					if (len == 0) $(this).closest("li").removeClass("visible");
				}); 
				
				
				$("#words_on_cake").fadeOut('fast');
				break;
				
			case 5 :
				$("#cake div.coating").fadeIn('slow');
				$("#words_on_cake").fadeIn('slow');
				$("#words_on_cake textarea").focus();
				$("div.nav a.next").removeClass("disabled").show();
				$("#cost").hide();
				$("#weight_scale").fadeOut('slow');	
				break;
				
			case 6 :
				$("#words_on_cake").fadeOut('fast');
				$("div.nav a.next").addClass("disabled").hide();
				$("#cost").show();
				$("#weight_scale").fadeIn('slow');	
				
				// форма заказа
				var cost = $("#cost span").text();
				$("#order_form").show();
				$("#cake_options").html('<table>' + cake.display_config('tab') + '</table>');
				$("#cake_options_hidden1, #cake_options_hidden2").html(cake.display_config('input') + '<input type=hidden name=cost value="'+ cost +'"><input type=hidden name=overall_cost value="'+ cost +'">');

				

				$("#order_form").appendTo("#description div.center_bg");
				countOverallCost();
				
				break;
		}		
		$("#description div.center_bg p").html(description[step]);
		
		cake.render();
		checkStep(step);
		if (debug) console.log(cake);
	}
	
	
	// сохраняем данные по картинке торта
	function save_cake_img()
	{
		var cake_img_coating = get_clear_filename($("div.cake-layer.coating").css("background-image"));
		var cake_img_decor = get_clear_filename($("div.cake-layer.decor div").css("background-image"));
		if (cake_img_coating !== undefined && cake_img_decor !== undefined) 
			$("#cake_options_hidden1, #cake_options_hidden2").append('<input type="hidden" name=cake_img[coating] value="'+cake_img_coating+'" /><input type="hidden" name=cake_img[decor] value="'+cake_img_decor+'" />');
	}
	
	// Возвращаем "очищенный" путь файла из "background: url(path_to_file)"
	function get_clear_filename(file)
	{
		if (!file || file == 'none') return;
		var res		= file.substr(0, file.lastIndexOf('.') + 4 );
		var start 	= res.search(/\/files\//);
		var result	= res.substr(start );
		return result;
	}
	
	
	
	
});
