// F1 front-end/back-end toggle
	if (document.all) {
		document.onhelp = function() {
			location.href = 'admin/auth/index';
			return false;
		}
	} else {
		document.onkeydown = function (evt) {
			if (evt.keyCode == '112') {
				location.href = 'admin/auth/index';
				return false;
			}
		}
	}

$(document).ready(function(){

	$('#brand_select').change(function() {
	//	$('#productList').hide('slow');
			location.href = $(this).attr('url') + $(this).attr('value');	
	//	$.ajax({
	//		type: "POST",
	//		url: $(this).attr('url'),
	//		data: "bid=" + $(this).attr('value') + "&authenticity_token=" + $(this).attr('token'),
	//		success: function(html) {
	//			$('#productList').html(html);	
	//			$('#productList').show('slow');
	//		}
	//	});
	});			

	$('.toCart').click(function() {
		var pid = $(this).attr('id');
		var qty = $("#qty" + pid).val();

		if(isInteger(qty)) {

			$.ajax({
				type: "GET",
				url: "/cart/product_add/" + pid,
				data: "qty=" + qty,
				success: function(html) {
					var result = $.json.decode(html);
					if(result.res == 'ok') {
						$.ajax({
							type: "GET",
							url: "/cart/summary",
							success: function(h_tml) {
								$('#cartSummary').html(h_tml);
								$.facebox('<div class="alert">Prodotto aggiunto al <a href="/cart/view">CARRELLO</a></div>');
								setTimeout("$.facebox.close()", 3000)
							}
						});
					} else {
						alert(result.msg);
					}
				}
			});
		} else {
			alert("Non hai inserito un numero");
		}
	});

	$('.buttonUpdateCart').click(function() {
		var pid = $(this).attr('id');
		var qty = $("#qty" + pid).val();

		if(isInteger(qty)) {
			if(qty != "0") {			
				$.ajax({
					type: "GET",
					url: "/cart/product_add/" + pid,
					data: "qty=" + qty,
					success: function(html) {
						var result = $.json.decode(html);
						if(result.res == 'ok') {
							$('#price_cart').html("&euro; " + result.total_cart);
							$('#total_row' + pid).html("&euro; " + result.total_row);
							$.ajax({
								type: "GET",
								url: "/cart/summary",
								success: function(h_tml) {
									$('#cartSummary').html(h_tml);
								}
							});
							$.ajax({
								type: "GET",
								url: "/cart/check",
								success: function(h_tml) {
									$('#cartCheck').html(h_tml);
								}
							});
						} else {
							alert(result.msg);
						}
					}
				});
			} else {
				alert('Inserire un numero diverso da zero');
			}
		}
	});

	$('.buttonRemoveCart').click(function() {
		var pid = $(this).attr('id');

		if(isInteger(pid)) {
		
			$.ajax({
				type: "GET",
				url: "/cart/product_remove/" + pid,
				success: function(html) {
					var result = $.json.decode(html);
					if(result.res == 'ok') {
						if (result.total_cart == '0,00') {
							location.href = '/cart/step1';
						} else {
							$('#price_cart').html("&euro; " + result.total_cart);
							$.ajax({
								type: "GET",
								url: "/cart/summary",
								success: function(h_tml) {
									$('#cartSummary').html(h_tml);
								}
							});
							$.ajax({
								type: "GET",
								url: "/cart/check",
								success: function(h_tml) {
									$('#cartCheck').html(h_tml);
								}
							});
							$("#row" + pid).fadeOut(1000, function() {
								$(this).remove();
							});
						}
					} else {
						alert(result.msg);
					}
				}
			});
		} else {
			alert("Non hai inserito un numero");
		}
	});

	$('#lines_order_select').change(function() {
		//alert("?sort_order=" + $(this).attr('value'));
		location.href = "?sort_order=" + $(this).attr('value');
	});

	$('#brands_filter_select').change(function() {
		location.href = "?filter_brand=" + $(this).attr('value');
	});

	$('#is_company').change(function() {
		if($(this).attr('value') == 'true') {
			if($('#user_company_name').size() != 0) {
				$('#user_company_name').attr("disabled", false);
				$('#user_vat_code').attr("disabled", false);
			} else {
				$('#order_company_name').attr("disabled", false);
				$('#order_vat_code').attr("disabled", false);		
			}
		} else {
			if($('#user_company_name').size() != 0) {
				$('#user_company_name').attr("value", '');
				$('#user_vat_code').attr("value", '');
				$('#user_company_name').attr("disabled", true);
				$('#user_vat_code').attr("disabled", true);
			} else {
				$('#order_company_name').attr("value", '');
				$('#order_vat_code').attr("value", '');
				$('#order_company_name').attr("disabled", true);
				$('#order_vat_code').attr("disabled", true);		
			}
		}
	});

	// WIZARD (tabs)
		// mi trovo nella pagina giusta se esiste una variabile impostata nel template
		if ( typeof(clickTab) != 'undefined' ){
			// INIZIALIZZO IL PLUGIN
				var wizard = $("#tabsWizard", $('#wizard')).tabs($(".stepContent", $('#wizard')), {api: true, effect: 'fade'})
			// CLICCO SUL TAB COME DA VAR NEL TEMPLATE
				wizard.click(clickTab);
			// AL CLICK SU UN TAB
				wizard.onBeforeClick(function(index){
					// se ho cliccato sul secondo tab e non ho confermato il carrello...
					// ... oppure ...
					// ho cliccato il terzo tab ma non l'ho selezionato dalla variabile nel template...
					if (( index == 1 && !isCartConfirmed || index == 2 && clickTab != 2 )) {
						// avvisa l'utente
						if ( index == 1 ) {
							$.facebox('<div class="alert">Per passare allo STEP 2 e\' necessario confermare gli acquisti cliccando sul pulsante a fine pagina.</div>')
						} else if ( index == 2 ) {
							$.facebox('<div class="alert">Per passare allo STEP 3 e\' necessario confermare l\'ordine cliccando sul pulsante a fine pagina.</div>')
						}
						// blocca tutto e non aprire il tab cliccato
						return false;
					}
				})
			// PULSANTE "CONFERMA ACQUISTI" NEL PRIMO TAB
				$('#goTo1').click(function(){
					// il carrello e' ora confermato
						isCartConfirmed = true;
					// passo il contenuto del campo note (primo step) ad un campo hidden della form (secondo step)
						$('#order_order_notes').val($('#order_notes').val())
					// vado al secondo tab
						wizard.click(1)
				})
		}
		

	// CART SLIDE
	$('#cartButton').toggle(
		function(){
			$('#cartOverlay').slideDown();
			$(this).css({ backgroundImage: 'url(/images/cart-ico-selected.gif)'});
		},
		function(){
			$('#cartOverlay').slideUp();
			$(this).css({ backgroundImage: 'url(/images/cart-ico.gif)'});
		}
	);

	// TABS HOME
	$('#tabsHome').tabs('#tabsHomeContent > a', {
		current: 'selected'
		, event: 'mouseover'
		, tabs: 'div'
	})
	
	// SCROLLABLE HOME (promozioni)
	$('#promoScrollable').scrollable({
		items: '#promoItems'
		, size: 3
		, prevPage: '#promoPrev'
		, nextPage: '#promoNext'
	})
	

	// PNG FIX
	$('img[src*=.png]').ifixpng();
		
		
	// CREO I CANVAS VUOTI
	$(".box, .barranav, #cartOverlay").backgroundCanvas();

		// HELPER FUNCTION TO DRAW BACKGROUND FOR CONVIENIENCE
		function DrawBackground(){
			// Paints on the background canvas with the PaintFunction you must provide!
			$(".box, #cartOverlay").backgroundCanvasPaint(gradient1);
			$(".barranav").backgroundCanvasPaint(gradient2);
		}

		// DRAW THE BACKGROUND ON LOAD AND RESIZE
		$(window).load(function () { DrawBackground(); });
		$(window).resize(function() { DrawBackground(); });

		// GRADIENT1
		function gradient1(context, width, height, canvas, $canvas, $canvasDiv, $content, $element) {
			var options = { x:0, height: height, width: width, radius: 10 };
			// COLORE RIEMPIMENTO A TINTA UNITA, VIENE RIMPIAZZATO DALL'EVENTUALE SFUMATURA
			context.fillStyle = "#bbb";
			$.canvasPaint.roundedRect(context,options);
			// DRAW THE GRADIENT FILLED INNER RECTANGLE
			var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 10);
			backgroundGradient.addColorStop(0 ,'#ddd');
			backgroundGradient.addColorStop(1, '#fff');
			options.border = 1;
			context.fillStyle = backgroundGradient;
			$.canvasPaint.roundedRect(context,options);
		}
		// GRADIENT2
		function gradient2(context, width, height, canvas, $canvas, $canvasDiv, $content, $element) {
			var options = { x:0, height: height, width: width, radius: 10 };
			// COLORE RIEMPIMENTO A TINTA UNITA, VIENE RIMPIAZZATO DALL'EVENTUALE SFUMATURA
			context.fillStyle = "#eee";
			$.canvasPaint.roundedRect(context,options);
			// DRAW THE GRADIENT FILLED INNER RECTANGLE
			var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 10);
			backgroundGradient.addColorStop(0 ,'#ddd');
			backgroundGradient.addColorStop(1, '#f5f5f5');
			options.border = 1;
			context.fillStyle = backgroundGradient;
			$.canvasPaint.roundedRect(context,options);
		}

	//UNIFORMO L'ALTEZZA DI DUE COLONNE
	$('.content').height() > $('#colSx').height() ? $('#colSx').height($('.content').height()) : $('.content').height($('#colSx').height())

	// FACEBOX
	$("a[rel*='facebox']").facebox();
	
	// CAPTCHA: ELIMINO BORDO
	$("#simple_captcha").children().andSelf().css({
		border: "0" 
	});
	
	// TOOLTIP generico
	$('a.tipTrigger').tooltip();
	// TOOLTIP form
	$('form.showTip :input').tooltip();
	
	// SVUOTO I CAMPI INPUT AL CLICK
		//AREA RISERVATA USERNAME E PASSWORD
		$("input[name='login']").focus(function(){
			$("input[name='login'][value*='username']").val("");
		});	
		$("input[name='password']").focus(function(){
			$("input[name='password'][value*='scrivipass']").val("");
		});	
		//RICERCA PER NOME PRODOTTO
		$("input[name='q']").focus(function(){
			$("input[name='q'][value*='inserisci']").val("");
		});	
		//FIDELITY CARD
		$("input[name='fidelity']").focus(function(){
			$("input[name='fidelity'][value*='numero carta']").val("");
		});			
});

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

