var accordionicons = {
	header: "ui-icon-folder-collapsed",
	headerSelected: "ui-icon-folder-open"
};

$(document).ready(function () {
	$("#dialog-info").dialog({
		modal: true,
		autoOpen: false,
		draggable: true,
		width: 650
	});
	
	clearCart();
	
	$("#catalog").load("ajax/getinfo.php?action=tree", function () {
		prepareCategoriesTree(3);
	});
	
	$("#search-form").ajaxForm({
			success: function (responseText, statusText, xhr, $form) {
				$("#catalog").remove();
				
				var catalogWrapper = $("#catalog-wrapper");
				$("<div id='catalog'></div>").appendTo(catalogWrapper);
				$("#catalog").html(responseText);
				
				if ($("#searchinput").val() != "") {
					prepareCategoriesTree(0);
				} else {
					prepareCategoriesTree(3);
				}
			}
	});
	
	$("#clean-search-btn").click(function () {
		$("#searchinput").val("");

		$("#catalog").remove();
		
		var catalogWrapper = $("#catalog-wrapper");
		$("<div id='catalog'></div>").appendTo(catalogWrapper);
		
		$("#catalog").load("ajax/getinfo.php?action=tree", function () {
			prepareCategoriesTree(3);
			//showCategory(cat);
		});
	});
	
	changeTitleLoad("");
	
	//$("#btn-title-mislistas").click(showLists);
	$("#btn-title-save a").click(saveList);
	$("#btn-title-send a").click(sendList);
	$("#btn-title-clear a").click(clearList);
	
	
	refreshUserStatus();
	
	$(".datepicker").datepicker({minDate: new Date()});
});

function makeCartZebra() {
	$("#cart li").alternate();
}

function changeTitleLoad(title) {
	var changeTitleRegion = $("#cart-title-region");
	
	$(".control", changeTitleRegion).hide();
	setCartTitle(title);
	
	/*$(".btn-accept", changeTitleRegion).click(function () {
		$("#cart-title-region .control").hide();
		$("#cart-title-text").show();
		
		var newTitle = $("#cart-title").val();
		setCartTitle(newTitle);
	});
	
	$(".btn-cancel", changeTitleRegion).click(function () {
		$("#cart-title-region .control").hide();
		$("#cart-title-text").show();
		
		var title = $("#cart-title-text").text();
		setCartTitle(title);
	});
	
	$("#cart-title-text").click(function () {
		$("#cart-title-text").hide();
		$("#cart-title-region .control").show();
	}); */
}

function setCartTitle(title) {
	if (title.indexOf("sin nombre") == 0) {
		title = "";
	}
	$("#cart-title").val(title);
	if (title == "") {
		title = "sin nombre";
	}
	$("#cart-title-text").html(title);
}

function getCartTitle() {
	return $("#cart-title").val();
}

function addProductToCart(id, name, price, cantToAdd, cats) {
	
	$("#cart .placeholder").remove();
	
	var elems = $("#cart ol li");
	var found = false;
	
	for (i = 0; i < elems.length; i++) {
		if ($(elems[i]).data("id") == id) {
			var cant = $("input.cant", elems[i]).val();
			
			cant = cant * 1 + cantToAdd * 1;
			
			$("input.cant", elems[i]).val(cant);
			
			found = true;
		}
	}
	
	if (!found) {
		var cartList = $("#cart ol");
		var prodBox = getCartElement(id, name, price, cantToAdd, cats);
				
		var newCartRow = $("<li></li>");
		
		$(newCartRow).data("id", id);
		$(newCartRow).data("name", name);
		$(newCartRow).data("price", price);
				
		$(prodBox).appendTo(newCartRow);
		$(newCartRow).appendTo(cartList);
	}
	
	//var cartTotal = $("#cart-total").text();
	//cartTotal = cartTotal * 1 + price * 1;
	//$("#cart-total").text(cartTotal);
	
	refreshCart();	
}


function updateCartTotall() {
	var total = 0;

	if ($("#cart ol li div.cart-prod-info").length > 0) {
		var elems = $("#cart ol li");
		for (i = 0; i < elems.length; i++) {
			var cant = $("input.cant", elems[i]).val();
				
			cant = cant * 1 * $(elems[i]).data("price");
			
			total += cant;
		}
	}
	
	$("#cart-total").text(total);
}


function prepareCategoriesTree(catSelected) {
	// activo las c�maras si salen
	
	$("#catalog").accordion({
		icons: accordionicons,
		autoHeight: false,
		collapsible: true
	});
	
	var cam = $(".tree-cat-" + catSelected);
	var activeIndex = 0;
	
	if (cam.length > 0) {
		activeIndex = $(cam).prevAll(".ui-accordion-header").length;
	}
	
	if (activeIndex > 0) {
		$("#catalog").accordion( "activate", activeIndex);
	}
	
	$("#catalog li").draggable({
		appendTo: "#cart",
		helper: "clone"
	});
	
	//pJT_init("#catalog a.info");
	prepareInfo("#catalog a.info");
	
	$(document).triggerHandler("tree-ready");
}

function checkCartHeight() {
	var cant = $("#cart li").length;
/*	var lh = 250;
	var rh = 250; 
	*/
	var lh = 140;
	var rh = 140; 

	
	if (cant != 0) {
		rh = (cant)* $("#cart li").height();
	}
	
	if (rh < lh) {
		rh = lh;
	}
	
	$("#cart ol").height(rh);
	$("#cart").height(rh + 40);
}

function prepareInfo(sel) {
	$(sel).each(function () {
		$(this).click(function () {
			var url = $(this).attr("href");
			
			getInfo(url);
			
			return false;
		});
	});
}

function showInfo(id) {
	var url = "paginas/ficha_prod.php?id=" + id;
	getInfo(url);
}

function getInfo(urlContent) {
	$("#prod-text").load(urlContent, function () {
		$("#dialog-info").dialog("open");
	});
}

function getCartElement(id, name, price, cant, cats) {
	var html = "<div class='cart-prod-info'>";
	
	html += "<div class='section-img section'><img src='images/prods/thumb/" + id +".jpg' border='0' /></div>";
	html += "<div class='section-center section'>";
	
	html += "<a class='prod-name' href='javascript:showInfo(" + id + ")'>" + name + "</a> <br />";
	html += "<span class='cats'>" + cats + "</span>";
	
	
	html += "</div>";
	
	html += "<div class='section-right section'><span class='prod-price'>" + price + " &euro;/d&iacute;a</div>";

	html += "<div class='section section-cant'><input type='text' class='cant' value='" + cant + "' name='cart[" + id + "]' />";
	

	html += "<a href='#' class='remove-btn'><img src='images/trash.png' border='0' /></a></span></div>";
	
	html += "</div>";
	
	var baseProdInfo = $(html);
	
	$(".remove-btn", baseProdInfo).click(removeProduct);
	$(".cant", baseProdInfo).change(refreshCart);
	

	
	//$().appendTo(baseProdInfo);
	//$().html(price + "").appendTo(baseProdInfo);
	//$("<input type='hidden' class='prod-id' name='cart[]' value='" + id +"' />").appendTo(baseProdInfo);
	
	//$(".prod-name", baseProdInfo).append("<br /><table><tr><td width='300px'></td><td><a href='javascript:showInfo(" + id + ")'>+info</a></td></tr></table>");
	
	//var removeBtn = $("").click(removeProduct);
	
	//$(removeBtn).appendTo(baseProdInfo);
	
	return baseProdInfo;
}

function removeProduct() {
	var idToRemove = $(this).siblings(".prod-id").val();
	
	var row = $(this).parents("li").get(0);
	var price = $(row).data("price");
	
	var cartTotal = $("#cart-total").text();
	cartTotal = cartTotal * 1 - price * 1;
	$("#cart-total").text(cartTotal);
	
	$(row).remove();
	
	refreshCart();
	
	return false;
}

function refreshCart() {
	
	makeCartZebra();
	
	updateCartTotall();
	
	checkCartHeight();
	
}

function clearCart() {
	$("#cart ol").remove();
	
	$("#cart .ui-widget-content").html("<ol><li class='placeholder'>" + TEXT_PLACEHOLDER + "</li></ol>");
	
	$("#cart ol").droppable({
		activeClass: "ui-state-default",
		hoverClass: "ui-state-hover",
		accept: ":not(.ui-sortable-helper)",
		drop: function(event, ui) {
			var prodId = $(".prodid", ui.draggable).val();
			var priceText = $(".price", ui.draggable).text();
			var prodName = $(".prod-name", ui.draggable).text();
			
			var priceValue = $(".prodprice", ui.draggable).val();
			var cats = $(".prodcats", ui.draggable).val();

			addProductToCart(prodId, prodName, priceValue, 1, cats);
			
			/*var newCartRow = $("<li></li>");
			
			$(prodBox).appendTo(newCartRow);
			$(newCartRow).appendTo(this);*/
		}
	}).sortable({
		items: "li:not(.placeholder)",
		axis: 'y',
		sort: function() {
			// gets added unintentionally by droppable interacting with sortable
			// using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
			$(this).removeClass("ui-state-default");
		},
		update: function () {
			makeCartZebra();
		}
	});
	
	changeTitleLoad("");
	
	refreshCart();
	
	$("#cartid").val(-1);
	
}

function addSugestion(id, name, price, cats) {
	cats = Base64.decode(cats);
	addProductToCart(id, name, price, 1, cats);
}

function showList() {
	$("#my-lists").load("paginas/mis_listas.php", function () {
		$("#cart-form").hide();
		$("#my-lists").show();
	});
}

function showCart() {
	$("#my-lists").hide();
	$("#cart-form").show();
}

function saveList() {
	/*if (getCartTitle() == "") {
		notifyMsg(MSG_LIST_ERROR_NO_NAME);
	} else 
	*/
	if ($("#cart .cart-prod-info").length == 0) {
		notifyMsg(MSG_LIST_ERROR_NO_PRODS);
	} else {
		$("#cart-title-name").val(getCartTitle());
		
		$("#cart-title-dlg").dialog("option", "buttons", {
			"Aceptar": function () {
				$("#cart-title-dlg").dialog("close");
				
				setCartTitle($("#cart-title-name").val());
			
				if (!userSessionExists()) {
					$("#dialog-save").dialog("open");
				} else {
					saveListAjax("");
				}				
			}
		});
		
		$("#cart-title-dlg").dialog("open");
	}

	return false;
}



// --------------------------------- formulario de envio


function checkLength(o,n,min,max) {

	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("El campo " + n + " debe tener entre "+min+" y "+max+" caracteres.");
		return false;
	} else {
		return true;
	}

}

function checkRegexp(o,regexp,n) {

	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('ui-state-error');
		updateTips(n);
		return false;
	} else {
		return true;
	}

}

function updateTips(t) {
	var tips = $(".validateTips");
	
	tips
		.text(t)
		.addClass('ui-state-highlight');
	setTimeout(function() {
		tips.removeClass('ui-state-highlight', 1500);
	}, 500);
}

$(function() {

	
	$("#dialog-save").dialog({
		modal: true,
		autoOpen: false,
		width: 660,
		height: 505,
		buttons: {
			'Guardar': function() {

		var 
		name = $("#new-user-name"),
		email = $("#new-user-email"),
		pass = $("#new-user-password"),
		pass2 = $("#new-user-password2"),
		
		regEmail = $("#reg-user-email"),
		regPass = $("#reg-user-password");
		
		
		allFields = $([]).add(email).add(pass).add(pass2).add(name).add(regEmail).add(regPass);
				
		
		var bValid = true;
				allFields.removeClass('ui-state-error');
		
		if ($("#is-registered-user")[0].checked) {
			bValid = bValid && checkLength(regEmail,"email",6,80);
			bValid = bValid && checkRegexp(regEmail,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. user@server.com");
		} else {
			bValid = bValid && checkLength(name,"nombre",1,80);
			bValid = bValid && checkLength(email,"email",6,80);
			bValid = bValid && checkLength(pass,"clave",3,15);
			
			if (pass.val() != pass2.val()) {
				bValid = false;
				
				pass.addClass('ui-state-error');
				updateTips(MSG_PASS_DONTMATCH);
			}
			
//				bValid = bValid && checkLength(password,"password",5,16);
		
//				bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
				// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. user@server.com");
//				bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
				
		}		
				if (bValid) {
					$(this).dialog('close');
					
					var urlp = $("#save-list-auth").formSerialize();
					
					saveListAjax(urlp);
				}
				
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			//allFields.val('').removeClass('ui-state-error');
		},
		open: function (event, ui) {
			/*var title = getCartTitle();
			$("#save-list-name").val(title);*/
		}
	});	
	
	
	$("#dialog-modal-msg").dialog({
		modal: true,
		autoOpen: false,
		buttons: {
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	});
	
	
	$("#dialog-send").dialog({
		modal: true,
		autoOpen: false,
		width: 475,
		buttons: {
		'Enviar': function() {

			$(this).dialog('close');
			
			var listId = $("#cartid").val();
			
			var urlAction = "ajax/doaction.php?action=send_list&cartid=" + listId + "&" + $("#send-list-form").formSerialize();
				
				/*
				 * 
				 * 
				 * 
				 * $("#cart-form").ajaxSubmit({
		url: urlBuilt,
		type: "POST",
		success: function (resp) {
			notifyMsg(resp);
		}
	});	
				 */
			
			
			$("#cart-form").ajaxSubmit({
						url: urlAction,
						type: "POST",
						success: function (resp) {
							
							notifyMsg(resp);
							
							// clearCart();
							
						}
					});
					
			
					
				},
				Cancel: function() {
					$(this).dialog('close');
				}
				}
	});
	
});

function saveListAjax(urlp) {
	var urlBuilt = 'ajax/save_list.php';
	
	if (urlp != '') {
		urlBuilt += '?' + urlp
	}
	
	$("#cart-form").ajaxSubmit({
		url: urlBuilt,
		type: "POST",
		success: function (resp) {
			
			if (resp.indexOf("|") > 0) {
				var cartid = resp.substr(0, resp.indexOf("|"));
				$("#cartid").val(cartid);
				resp = resp.substr(resp.indexOf("|") + 1);
			}
		
			refreshUserStatus();
			
			// notifyMsg(resp);
		}
	});	
}

function notifyMsg(text) {
	$("#modal-msg").html(text);
	
	$("#dialog-modal-msg").dialog("open");
}

function showCategory(cat) {
	var catalogObj = $("#catalog");
	
	if ($(".tree-cat-" + cat, catalogObj).length > 0) {
		
		var index = $(".tree-cat-" + cat, catalogObj).prevAll(".ui-accordion-header").length;
		
		if (!$(".tree-cat-" + cat, catalogObj).hasClass("ui-state-active")) {
		$("#catalog").accordion( "activate", index);
		}
	} else {
		$("#catalog").remove();
		$("#searchinput").val("");
		
		var catalogWrapper = $("#catalog-wrapper");
		$("<div id='catalog'></div>").appendTo(catalogWrapper);
		
		$("#catalog").load("ajax/getinfo.php?action=tree", function () {
			prepareCategoriesTree(cat);
			//showCategory(cat);
		});
	}
	
	return false;
}
