// CONTROLLO CHE NON SIA PIU' GRANDE DELL'AREA EDITABILE
	function checkBoundariesOverflow(){
		if (sideShown == "fronte") {
			var wLimit = ($("#frontEditor .boundaries").width());
			var hLimit = ($("#frontEditor .boundaries").height());
		} else {
			var wLimit = ($("#rearEditor .boundaries").width());
			var hLimit = ($("#rearEditor .boundaries").height());
		}
		$(".frontOverlay, .frontOverlay img, .rearOverlay, .rearOverlay img").each(function(){
			if ($(this).width() > wLimit) $(this).css("width", wLimit);
			if ($(this).height() > hLimit) $(this).css("height", hLimit);
		})
	}

// PRODOTTI:
	// carico il MODELLO DAL PRODOTTO
		function modelByProduct(elem, ctx){
			$("#frontEditor").css({ background: "url("+ $(elem).data('model').frontModelURL +")" })
			$("#frontEditor .boundaries").css({ display: "block", left: $(elem).data('model').frontBoundaries.x, top: $(elem).data('model').frontBoundaries.y, width: $(elem).data('model').frontBoundaries.w, height: $(elem).data('model').frontBoundaries.h })
			$("#rearEditor").css({ background: "url("+ $(elem).data('model').rearModelURL +")" })
			$("#rearEditor .boundaries").css({ display: "block", left: $(elem).data('model').rearBoundaries.x, top: $(elem).data('model').rearBoundaries.y, width: $(elem).data('model').rearBoundaries.w, height: $(elem).data('model').rearBoundaries.h })
			// sblocco gli altri tab per aggiunta motivi e del testo
				$("#addOnWrapper, #editorWrapper").data('disabled.tabs', [])
			// carico taglie e colori
				showSizeColor($(elem).data('model').pid, ctx, 0)
			// deseleziono tutti e segno il SELECTED
				$('#addOnProducts img').css({ border: '2px solid #ddd', cursor: 'pointer' })
				$('#addOnProducts img').data('selected',false)
				$(elem).data('selected',true)
				$(elem).css({ border: '2px solid #555', cursor: 'default' })
			// memorizzo la luminosita' del modello (chiaro o scuro)
				$("#editorWrapper").data('luminosity', $(elem).data('model').luminosity)
			// ripulisco il modello da immagini non compatibili (chiare/scure)
				cleanImgOnModel()
			// mostro il pulsante SALVA
				$('#saveButton').fadeIn();
			// mostro l'upload se mi trovo nel secondo tab e il prodotto selezionato e' chiaro
				if ( addOnShown == 'immagini' && $("#editorWrapper").data('luminosity') == 'light' || ctx == 2) {
					$('#upload').slideDown()
				} else if ( $("#editorWrapper").data('luminosity') == 'dark' && ctx != 2) { 
					$('#upload').hide()
				}
		};
	// include TAGLIE E COLORI
		function showSizeColor(pid, ctx, cid){
			$.ajax({
				url: "tse-tagliecolori.php"
				, data: {pid: pid, ctx: ctx, cid: cid}
				, success: function(html){
					$("#taglieColori").html(html)
				}
			})
		}


// ACCORDION ELENCO IMMAGINI/PRODOTTI
	function tseCatAccordion(){	
		if ( $(this).next().is(":hidden") ){
			$(this)
				.css({ backgroundImage: 'url(/images/freccia-giu.gif)'})
				.next()
					.show()
					.find('img[luminosity]')
						.css({ width: '100px', height: '100px' })
				// COLORI DELLE IMMAGINI in cluetip
					.next().cluetip({
						local: true
						, showTitle: false
						, activation: 'click'
						, sticky: true
						, closePosition: 'top'
						, closeText: '<div class="closeTip"/>'
						, width: 400
						, attribute: 'rel'
						, cursor: 'pointer'
					});
		} else {
			$(this)
				.css({ backgroundImage: 'url(/images/freccia-dx.gif)'})
				.next()
					.hide()
		}
	}
	

// NASCONDO LE IMMAGINI NON COMPATIBILI CON IL COLORE DEL MODELLO
	function markByLuminosity(){
		var modelLum = $("#editorWrapper").data('luminosity');
		$('#addOnImages img[luminosity]').each(function(){
			if ( modelLum == 'dark' && $(this).attr('luminosity') == 'light' ){	
				$(this)
					.css({ border: '1px dotted #bbb' })
					.click(function(){
						$.facebox('<h3>Questa immagine non può essere stampata sul prodotto selezionato, si prega di selezionarne un\'altra.</h3>');
						return false
					})
			} else {
				$(this)
					.css({ border: '1px solid #888' })
					.click(function(){
						imageOnModel($(this))
				})
			}
		 })
	}


// RIPULISCO IL MODELLO DA IMMAGINI NON COMPATIBILI (chiare/scure)
	function cleanImgOnModel(){
		var modelLum = $("#editorWrapper").data('luminosity');
		if ( modelLum == 'dark' && $('.frontOverlay img, .rearOverlay img').filter('[luminosity="light"]').size() > 0 ) {
			if ( confirm('Una o più immagini che hai aggiunto all\'Editor potrebbero non essere stampabili su questo prodotto. "OK" per rimuoverle, "ANNULLA" per lasciarle.') ){
				$('.frontOverlay img, .rearOverlay img').filter('[luminosity="light"]').parent().remove()
			} else {
				return false
			}
		}
	}


// IMMAGINE su modello

	// CREO LA NUOVA IMMAGINE DA SOVRAPPORRE AL MODELLO
		function imageOnModel(elem){
			$('<img />')
				.attr({
					id: ( $(elem).attr('id') + '-cloned' )
					, type: $(elem).attr('type')
					, src: $(elem).attr('editorsize')
					, luminosity: $(elem).attr('luminosity')
				})
				.appendTo(thumbWrapper)
				.wrap('<div class="'+ thumbClass +'" style="position: absolute"></div>') // ... la wrappo
				.load(function(){
					dragResizeRemove();
					checkBoundariesOverflow();
				})
		};



// TESTO

	// SVUOTO L'INPUT AL CLICK
		function emptyInput(){
			if ($(this).val() == "Scrivi qui il testo..."){
				$(this).val("")
			}
		}
	
	// FONT
		function selectFont(){
			// deseleziono tutti
			$("#tseFont div").removeClass("selected")
			// seleziono quello scelto
			$(this).addClass("selected")
		}
		
	// FONT COLOR
		function updateFontColor(){
			$("#tseFontColor").css({
				background: $("#tseFontColor option:selected").css("backgroundColor")
				, color: $("#tseFontColor option:selected").css("color")
				, border: "1px solid"
			});
		}
	// CREO L'IMG CON IL TESTO
		function imgFromTxt(){
			tseCarattere = $("#tseFont .selected img").attr("alt");
			userText = $("#tseTextInput").val();
			// creo l'immagine con il testo...
			txtImg = '<img type="txt" src="/images/txt.php?png&text='+ userText +'&color='+ $("#tseFontColor").val() +'&font='+ tseCarattere +'&size='+ $("#tseFontSize").val() +'" alt="'+ userText +'">';
			// ... la sposto nell'editor e la wrappo
			$(txtImg)
				.appendTo(thumbWrapper)
				.wrap('<div class="'+ thumbClass +'" style="position: absolute" />')
				.load(function(){
					dragResizeRemove();
					checkBoundariesOverflow();
				})
		};


// DRAG, RESIZE, REMOVE - immagini e testo
	function dragResizeRemove(){
		$(".frontOverlay, .rearOverlay")
			// drag
			.draggable({
				containment: "parent"
			})
			// resize
			.resizable({
				containment: "parent"
				, start: function(){ $(this).find('img').css({width: "100%", height: "100%"}) }
			})
			// REMOVE
			.append('<div class="removeOverlay" />')
			// all'hover sul frontOverlay mostro la X
			.hover(
				function(){
					$(this).find(".removeOverlay").show();
					$(this).find(".ui-resizable-handle").show()
				}
				, function(){
					$(this).find(".removeOverlay").hide();
					$(this).find(".ui-resizable-handle").hide()
				}
			)
			.find(".removeOverlay")
				.click(function(){
					$(this).parent().fadeOut("fast", function(){$(this).remove()})
				})
	}


// SALVATAGGIO TSE
	function saveTse(customimageurl){

		//CREO L'OGGETTO VUOTO E LA SUA STRUTTURA
			tse = {};
			$('#addOnProducts img').each(function(){
				if ($(this).data("selected") == true) {
					tse.product = $(this).attr('id')
				}
			});
			tse.front = { image: new Array(), model: new Array(), boundaries: new Array() };
			tse.rear = { image: new Array(), model: new Array(), boundaries: new Array() };

		// FRONTE
			// MOTIVI E TESTO
				$(".frontOverlay")
					.each(function(){
						var datiOggetto = {
							w: $(this).width()
							, h: $(this).height()
							, x: $(this).css("left")
							, y: $(this).css("top")
							, id: $(this).find('img').attr("id")
							, src: $(this).find('img').attr("src")
							, type: $(this).find('img').attr("type")
							, luminosity: $(this).find('img').attr("luminosity")
						};
						tse.front.image.push(datiOggetto);
					})
			// MODELLO
				tse.front.model = { image: $("#frontEditor").css("backgroundImage") }
				tse.front.boundaries = { 
					x: $("#frontEditor .boundaries").css('left')
					, y: $("#frontEditor .boundaries").css('top')
					, w: $("#frontEditor .boundaries").css('width')
					, h: $("#frontEditor .boundaries").css('height')
				}

		// RETRO
			// MOTIVI E TESTO
				$(".rearOverlay")
					.each(function(){
						datiOggetto = {
							w: $(this).width()
							, h: $(this).height()
							, x: $(this).css("left")
							, y: $(this).css("top")
							, id: $(this).find('img').attr("id")
							, src: $(this).find('img').attr("src")
							, type: $(this).find('img').attr("type")
							, luminosity: $(this).find('img').attr("luminosity")
						};
						tse.rear.image.push(datiOggetto);
					});
			// MODELLO
				tse.rear.model = { image: $("#rearEditor").css("backgroundImage") };
				tse.rear.boundaries = { 
					x: $("#rearEditor .boundaries").css('left')
					, y: $("#rearEditor .boundaries").css('top')
					, w: $("#rearEditor .boundaries").css('width')
					, h: $("#rearEditor .boundaries").css('height')
				}
		
			return tse;
	}

// SALVATAGGIO CARRELLO
	function saveCart(){
		cart = new Array();
		$("#inputs :text")
			.each(function() {
				if (isInteger($(this).val())) {
					var datiOggetto = {
						name: $(this).attr('name')
						, val: parseInt($(this).val())
					}
					cart.push(datiOggetto)
				}
			});
		return cart;
	}


// ADD TO CART
	function addToCart(pid, ctx, cid){
		$.ajax({
			url: "tse-cart.php?update=1&pid=" + pid + "&ctx=" + ctx + "&cid=" + cid
			, type: "POST"
			, data: { tse: $.json.encode(saveTse()), cart: $.json.encode(saveCart()) }
			, beforeSend: function(){
				// suggerisci richiesta preventivo
				if ( $('#totale').text() > 1 && ctx != 2){
					$.facebox('<h3>Hai aggiunto diverse quantità al carrello, ti suggeriamo di chiedere un preventivo.</h3>')
				}
			}
			, success: function(){
				showSizeColor(pid, ctx, cid)
			}
		})
		};


// TSE TO JSON
	function tseToJson(idx){
		$.ajax({
			type: "POST"
			, url: "/json.php"
			, data: {tse: $.json.encode(saveTse()), ctx: idx}
		})
	}


// RICOSTRUISCO IL MODELLO CON GLI ADD-ON
	function rebuild(risposta, allowEdit){
		// FRONT
			// IMMAGINI E TESTO
				$.each(risposta.front.image, function(){
					$("<img />")
						.attr({ src: this.src, id: this.id, type: this.type, luminosity: this.luminosity })
						.appendTo("#frontEditor .boundaries")
						.wrap('<div class="frontOverlay" style="position: absolute" />')
						.parent()
							.css({ width: this.w + 'px', height: this.h + 'px', left: this.x, top: this.y })
							.find('img')
								.css({ width: this.w + 'px', height: this.h + 'px' })
				})
			// MODELLO
				$("#frontEditor").css({ background: risposta.front.model.image })
			// BOUNDARIES
				$("#frontEditor .boundaries").css({
					left: risposta.front.boundaries.x
					, top: risposta.front.boundaries.y
					, width: risposta.front.boundaries.w
					, height: risposta.front.boundaries.h
					, display: 'block'
				})
		// REAR
			// IMMAGINI E TESTO
				$.each(risposta.rear.image, function(){
					$("<img />")
						.attr({ src: this.src, id: this.id, type: this.type })
						.appendTo("#rearEditor .boundaries")
						.wrap('<div class="rearOverlay" style="position: absolute" />')
						.parent()
							.css({ width: this.w + 'px', height: this.h + 'px', left: this.x, top: this.y })
							.find('img')
								.css({ width: this.w + 'px', height: this.h + 'px' })
				})
			// MODELLO
				$("#rearEditor").css({ background: risposta.rear.model.image });
			// BOUNDARIES
				$("#rearEditor .boundaries").css({
					left: risposta.rear.boundaries.x
					, top: risposta.rear.boundaries.y
					, width: risposta.rear.boundaries.w
					, height: risposta.rear.boundaries.h
					, display: 'block'
				})
	// CONSENTO O MENO L'EDITING (dipende dal contesto)
		if (allowEdit == 'allowEdit') {
			dragResizeRemove();
		}
		checkBoundariesOverflow();
	// SBLOCCO TUTTI I TAB
		$("#addOnWrapper, #editorWrapper").data('disabled.tabs', [])
}


// FUNZIONI DI SUPPORTO
	function isInteger (s) {
		var i;

		if (isEmpty(s))
			if (isInteger.arguments.length == 1)
				return 0;
			else
				return (isInteger.arguments[1] == true);

		for (i = 0; i < s.length; i++) {
			var c = s.charAt(i);
			if (!isDigit(c)) return false;
		}
		return true;
	}
	function isEmpty(s) {
		return ((s == null) || (s.length == 0))
	}
	function isDigit (c) {
		return ((c >= "0") && (c <= "9"))
	}


// COLORE: al click aggiorno il modello e le disponibilita'
	function modelByColor(elem, ctx){
		$("#frontEditor").css({ background: "url("+ $(elem).data('model').frontModelURL +")" })
		$("#frontEditor .boundaries").css({ display: "block", left: $(elem).data('model').frontBoundaries.x, top: $(elem).data('model').frontBoundaries.y, width: $(elem).data('model').frontBoundaries.w, height: $(elem).data('model').frontBoundaries.h })
		$("#rearEditor").css({ background: "url("+ $(elem).data('model').rearModelURL +")" })
		$("#rearEditor .boundaries").css({ display: "block", left: $(elem).data('model').rearBoundaries.x, top: $(elem).data('model').rearBoundaries.y, width: $(elem).data('model').rearBoundaries.w, height: $(elem).data('model').rearBoundaries.h })
		updateAvailability($(elem).data('model').pid, $(elem).data('model').cid, ctx )
		// memorizzo la luminosita' del modello (chiaro o scuro)
			$("#editorWrapper").data('luminosity', $(elem).data('model').luminosity)
		// ripulisco il modello da immagini non compatibili (chiare/scure)
			cleanImgOnModel()
		// mostro il pulsante SALVA
			$('#saveButton').fadeIn();
		// ricarico il secondo tab
			$("#addOnWrapper").tabs( 'load' , 1 )
		// mostro l'upload se mi trovo nel secondo tab e il prodotto selezionato e' chiaro oppure sono in promo
			if ( addOnShown == 'immagini' && $("#editorWrapper").data('luminosity') == 'light' || ctx == 2) {
				$('#upload').slideDown()
			} else if ( $("#editorWrapper").data('luminosity') == 'dark' && ctx != 2) { 
				$('#upload').hide()
			}
	};


// AGGIORNO Q.TA E TAGLIE ALLA SCELTA DEL COLORE
	function updateAvailability(pid, cid, ctx){
		$.ajax({
			url: "tse-tagliecolori.php"
			, data: { pid: pid, cid: cid, ctx: ctx }
			, success: function(html){
				$("#taglieColori").html(html)
			}
		})
	}


// AGGIORNO IL TOTALE QTA durante la digitazione
	function updateQty(){
		somma = 0;
		$("#inputs :text").each(function(){
			if (isInteger($(this).val()))
				somma += parseInt($(this).val());
			$("#totale")
				.text(somma)
				.css({ "font-weight" : "bold" , "font-size" : "120%" })
		})
	};



// UPLOAD
	function ajaxFileUpload(){
		$.ajaxFileUpload({
			url:'tse-image.php',
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status){
				if(typeof(data.err) != 'undefined'){
					if(data.err != ''){
						// messaggio di errore
							$.facebox('<h3>'+ data.err +'</h3>')
					} else {
						// creo l'immagine e...
							var tmp = $('<img />')
								.attr({
									id: 'usr' + data.iid
									, type: 'usrimg'
									, editorsize: data.url
									, luminosity: 'dark'
								})
						// ... la mostro nell'editor
							imageOnModel(tmp);
						// messaggio di conferma
							$.facebox('<h3>'+ data.msg +'</h3>')
					}
				}
			},
			error: function (data, status, e){
				alert(e);
			}
		})
		return false;
	}

/* *********************************************************
************************************************************
					AL DOCUMENT READY
************************************************************
********************************************************** */
$(function(){
	
	// AJAX LOADER
	$('body')
		.append('<img id="loading" src="/images/ajax-loader.gif">')
		.find('#loading')
			.hide()
			.css({
				position: "fixed"
				, left: ( $(window).width() / 2  - 110 ) + 'px'
				, top: ( $(window).height() / 2 - 9 ) + 'px'
				, zIndex: 1000
				, opacity: 1
			})
	$(document).ajaxSend(function(){ $('#loading').show() })
	$(document).ajaxComplete(function(){ $('#loading').fadeOut('fast') })
	

	// TABS
		// MODELLO
			sideShown = '';
			$("#editorWrapper").tabs({
				event: 'click'
				, cache: true
				// memorizzo in "sideShown" il tab attivo
				, show: function(event, ui){
					sideShown = ui.tab.innerHTML;
					// definisco il contesto (fronte o retro)
					if (sideShown == "fronte") {
						thumbWrapper = "#frontEditor .boundaries";
						thumbClass = "frontOverlay";
					} else if (sideShown == "retro") {
						thumbWrapper = "#rearEditor .boundaries";
						thumbClass = "rearOverlay";
					}
				}
				, disabled: [1]
			});
		// ADD-ON
			$("#addOnWrapper").tabs({
				event: 'click'
				, cache: true
				// memorizzo in "addOnShown" il tab attivo
					, show: function(event, ui){
						$('.cluetip-default').hide();
						addOnShown = ui.tab.innerHTML;
						// mostro l'upload se mi trovo nel secondo tab e il prodotto selezionato e' chiaro
							if ( addOnShown == 'immagini' && $("#editorWrapper").data('luminosity') == 'light') {
								$('#upload').slideDown()
								// ricarico il secondo tab
									$("#addOnWrapper").tabs( 'load' , 1 )
							} else {
								$('#upload').hide()
							}
					}
					, disabled: [1,2]
			});
	

});

