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



/* ********************************************************************************
					PRENDO VALORI DALLA QUERY STRING
******************************************************************************** */
function getParameterByName(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
};



/* ********************************************************************************
						JGROWL - NOTICE, WARNING, ERROR
******************************************************************************** */
function showNotice(text, title){ $.jGrowl(text, { header: title, theme: 'notice' }) };
function showWarning(text, title){ $.jGrowl(text, { header: title, sticky: true, theme: 'warning' }) };
function showError(text, title){ $.jGrowl(text, { header: title, sticky: true, theme: 'error' }) };


/* ********************************************************************************
								RESET DEFAULT
		RIPOPOLO I CAMPI VUOTI CON IL VALORE DI DEFAULT (cancellato al submit)
******************************************************************************** */
function resetDefault(formId){
	if (!formId) formId = '';
	$(formId + ' [emptyIf]').each(function(){
		if ( $(this).val() == '' ){
			$(this).val($(this).attr('emptyIf'));
		}
	})
};



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



/* ********************************************************************************
			SVUOTO IL CAMPO SE CON ATTRIBUTO 'EMPTYIF' AL SUBMIT
******************************************************************************** */
function emptyDefaultFields() {
	$('*').find("[emptyIf]").each(function() { // per ogni campo
		if ($(this).val() == $(this).attr('emptyIf')) { // se ha il testo di default
			$(this).val(''); // lo svuoto
		};
	});
};



/* ********************************************************************************
***********************************************************************************
***********************************************************************************
								DOCUMENT READY
***********************************************************************************
***********************************************************************************
******************************************************************************** */
$(document).ready(function(){



	if($(".showNotice").length == 1) { showNotice( $(".showNotice").html(), "Informazione" ); };
	if($(".showWarning").length == 1) { showWarning( $(".showWarning").html(), "Attenzione" ); };
	if($(".showError").length == 1) { showError( $(".showError").html(), "Problema" ); };


	/* ********************************************************************************
									ALL'INVIO DI OGNI FORM
	******************************************************************************** */
	$('form').live('submit', function(){
		emptyDefaultFields(); // SVUOTO I CAMPI CON VALORE DI DEFAULT
		$('*').removeClass('errorField'); // RIPULISCO I CAMPI CON LO STILE DELL'ERRORE
	});



	/* ********************************************************************************
										COLORBOX
	******************************************************************************** */
	// DEFAULT: carico il contenuto via ajax (n.b.: la pagina chiamata non deve essere una pagina completa di tag html, head, ecc.)
	$('a[class~=colorbox]').live('click', function() {$.fn.colorbox({ href: $(this).attr('href'), open:true }); return false; });

	// APPLICATO AI PULSANTI
	// nascondo anche gli iframe visto che alcuni banner in essi contenuti vengono sovrapposti
	$(':button[class~=colorbox]').click(function(){ $.colorbox({ href: $(this).attr('href') }) });

	// IFRAME (in colorbox): apro una pag esterna completa di tag html, head, ecc.
	$('[class~="cBoxIframe"]').colorbox({iframe: true, width: '1050px', height: '90%' });

	// INLINE: apre un elemento (il cui ID è definito nell'href con #) contenuto nella pagina del chiamante
	$('.showDiv').colorbox({ inline: true, href: function(){ return $(this).attr('href') } });



	/* ********************************************************************************
										TOOLTIP
	******************************************************************************** */
	// piccolo nero
	$('.tip[title]').tooltip({ effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	perPaccoTip = $('#perPacco').tooltip({ effect: 'slide', predelay: 100, delay: 0, api: true });
	perCartoneTip = $('#perCartone').tooltip({ effect: 'slide', predelay: 100, delay: 0, api: true });

	// grande nero
	$('.tip2[title]').tooltip({ tipClass: 'tooltip2', effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	// piccolo bianco
	$('.tip3[title]').tooltip({ tipClass: 'tooltip3', effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	// grande bianco
	$('.tip4[title]').tooltip({ tipClass: 'tooltip4', effect: 'slide', predelay: 100, delay: 0 }).dynamic();



	/* ********************************************************************************
					SVUOTO IL CAMPO SE CON ATTRIBUTO 'EMPTYIF'
	******************************************************************************** */
	// AL FOCUS...
	$(':text[emptyIf], textarea[emptyIf]')
		.live('focusin', function(){
			if ( $(this).val() == $(this).attr('emptyIf') ){
				$(this).val('')
			}
		})
		.live('focusout', function(){
			if ( $.trim($(this).val()) == '' ){
				$(this).val($(this).attr('emptyIf'));
			}
		})
	;



	/* ********************************************************************************
										TABS
	******************************************************************************** */
	$('.tabColSx > .tabs').tabs('.tabColSx > .panes > div', {tabs: 'a', effect: 'fade'});
	dxTabs = $('.tabColDx > .tabs').tabs('.tabColDx > .panes > div', {tabs: 'a', effect: 'fade', api: true});
	//areaRiservataTabsApi = $('#areaRiservataTabs').tabs('#areaRiservataPanes > div', {tabs: 'a[class!=disabled]', api: true, history: true});



	/* ********************************************************************************
										DROPDOWN
	******************************************************************************** */
	var hoverIntentConfig = {
		over:
			function(){
				$('.dropDownTrigger').removeClass('selected'); // spengo i pulsanti
				$('.dropDownWrapper')
					.stop(false,true) // interrompo eventuali altre animazioni non completate
					.hide() // nascondo tutti i wrapper
					.filter('[rel='+ $(this).attr("rel") +']') // trovo il corrispondente da aprire (che abbia lo stesso 'rel' del trigger) e...
                        .slideDown('fast', function(){ // lo mostro
							$(this).mouseleave(function(){ // imposto la chiusura al mouseout
								$(this).slideUp('fast');
								$('.dropDownTrigger[class~=selected]').removeClass('selected');
							});
                        });
				$(this).addClass('selected'); // ... accendo il relativo pulsante
			}
		, out: function(){}
		, interval: 100
	};
	$('.dropDownTrigger').hoverIntent(hoverIntentConfig);



	/* ********************************************************************************
										PRODOTTO
	******************************************************************************** */
	/* AL CLICK SULLA THUMB DEL PRODOTTO CAMBIO LA DETAIL */
	$('#prodThumbs > div > img').live('click', function(){
		$('#detailPic')
			.attr({ src: $(this).attr('detail') })
			.parent()
				.attr({ href: $(this).attr('zoom') })
	});
	/* CYCLE FOTO */
	$('#prodThumbs').cycle({ 
		fx:			'scrollHorz' 
		, speed:	'fast' 
		, timeout:	0 
		, prev:		'#prodPrev'
		, next:		'#prodNext'
	});
	/* CYCLE COLORI */
	$('#colorThumbs').cycle({ 
		fx:			'scrollHorz' 
		, speed:	'fast' 
		, timeout:	0 
		, prev:		'#colorPrev'
		, next:		'#colorNext'
	});
	/* CYCLE CORRELATI */
	$('#relatedThumbs').cycle({ 
		fx:			'scrollHorz' 
		, speed:	'fast' 
		, timeout:	0 
		, prev:		'#relatedPrev'
		, next:		'#relatedNext'
	});



	/* ********************************************************************************
										FILTRI
	******************************************************************************** */
	// "ALTRI..."
	$('a.altri').click(function(){
		var $cliccato = $(this);
		$('#expandedResults').slideUp(function(){ // chiudo il contenitore eventualmente aperto
			$(this).empty(); // svuoto il contenitore che ospiterà gli "altri" link
			$('a.altri').show(); // mostro tutti i link "altri" e...
			$cliccato.hide(); // nascondo quello cliccato
			$('a.altri').parent().css({ background: '#eee' }); // ripristino lo sfondo di tutte le colonne e...
			$cliccato.parent().css({ background: '#f9f9f9' }); // ... coloro quello della colonna del link cliccato
			$('a.altri').parent().css({ borderBottom: '1px solid #ccc'}); // rimetto i bordi inferiori a tutte le colonne
			$cliccato.parent().css({ borderBottom: '0'}); // levo il bordo inferiore alla colonna del link cliccato

			$('#expandedResults').attr('rel', $cliccato.parent().attr('rel')); // copio il rel per le url

			$('#expandedResults')
				.append($cliccato.nextAll('.otherResult').clone(true)) // copio tutti i link nascosti nel nuovo contenitore
				.slideDown() // mostro il contenitore
				.find('a:not(:last)') // trovo i link
					.after(' &nbsp; &middot; &nbsp; ') // li separo
			;
		});
	});
	// SELEZIONATI
	$('#filtri a:not([class]), a.otherResult') // TUTTI I FILTRI ATTIVABILI
		.live('click', function(){
			var filter_label = '';
			filter_label = $(this).parent().attr('rel');
			if (location.search != null && location.search.length > 0) {
				if(location.search.match($(this).parent().attr('rel'))) {
					var qs = location.search.split("&");
					var new_qs = new Array();
					for(i=0;i<qs.length; i++) {
						var tmp = qs[i].split('=');
						new_qs.push(qs[i]);
					};

					new_qs.push( filter_label + '[]=' + $(this).attr('rel') );

					qs = new_qs.join('&');
					if(qs.substring(1,0) == '?') {
						location.href = location.href.split("?")[0] + qs;
					} else {
						location.href = location.href.split("?")[0] + '?' + qs;
					};

				} else {
					location.href += '&' + filter_label + '[]=' + $(this).attr('rel');
				};
			} else {
				location.href += '?' + filter_label + '[]=' + $(this).attr('rel');
			};
		});
	$('#selectedFilters a').live('click', function(){ // AL CLICK SU UN FILTRO SELEZIONATO
		$(this).fadeOut('fast', function(){ // LO SFUMO
			$(this).remove(); // LO ELIMINO DAL DOM
			var qs = location.search.split("&");
			var new_qs = new Array();
			for(i=0;i<qs.length; i++) {
				var tmp = qs[i].split('=');
				if(tmp[1] == $(this).attr('rel') ) {
					// new_qs.push( $(this).parent().attr('rel') + '=' + $(this).attr('rel') );
				} else {
					new_qs.push(qs[i]);
				}
			}
			qs = new_qs.join('&');
			if(qs.substring(1,0) == '?') {
				location.href = location.href.split("?")[0] + qs;
			} else {
				if(qs.length > 0)
					location.href = location.href.split("?")[0] + '?' + qs;
				else
					location.href = location.href.split("?")[0];
			}
		});
	});



	/* ********************************************************************************
							CARRELLO: AGGIORNO Q.TA' PRODOTTO
	******************************************************************************** */
	$('.stepTable :text[id^="qty"]') // input quantità
		.focus(function(){ // al focus
			$('.updateCartLink').css({ visibility: 'hidden' });
			$(this)
				.next() // link 'aggiorna'
					.css({ visibility: 'visible' }) // lo mostro
					.unbind()
					.click(function(){ // al click
						updateCart($(this).prev()); // aggiorno il carrello via ajax
					});
		})
		.keypress(function (e) { // disabilito il tasto 'enter'
			if (e.which == 13){ return false; };
		});

	function updateCart(elem) {
		var pid = elem.attr('rel');
		var qty = $("#qty" + pid).val();
		var codArt = $("#qty" + pid).attr('codart');
		if(isInteger(qty)) {
			if(qty != "0") {
				$.ajax({
					type: "GET",
					url: "/cart/product_add/" + pid,
					data: "qty=" + qty + "&is_cart=true",
					dataType: 'json',
					success: function(result) {
						if(result.res == 'ok') {
							$('#totalRow'+ pid +'').text(result.total_row); // aggiorno l'importo

							$('span[codart='+codArt+']').text(result.unit_price); // aggiorno il prezzo unitario per tutti gli articoli con lo stesso codArt

							$("#totalCart, #layoutTotalCart").html(result.total_cart);
							$('.dropDownWrapper[rel=cart] .dropDownContent').html(result.cartList);


							showNotice('Carrello aggiornato.');
						} else {
							showWarning(result.msg, 'ATTENZIONE');
						}
					}
				});
			} else {
				showError('Inserire un numero diverso da zero','ERRORE');
			}
		}
	};



	/* ********************************************************************************
							CARRELLO: RIMOZIONE ARTICOLO
	******************************************************************************** */
	$('.stepTable img[src*=erase]:not("[kit]")') // pulsante 'X'
		.css({ cursor: 'pointer' })
		.click(function(){
			pid = $(this).attr('pid');
			$(this)
				.closest('tr')
					.fadeOut(function(){
						removeFromCart(pid);
					});
		});
	function removeFromCart(pid) {
		$.ajax({
			type: "GET",
			url: "/cart/product_remove/" + pid,
			dataType: 'json',
			success: function(result) {
				if(result.res == 'ok') {
					$("#totalCart, #layoutTotalCart").html(result.total_cart);
					$('.dropDownWrapper[rel=cart] .dropDownContent').html(result.cartList);

					if(result.product_cnt == '0') {
						location.reload();
					}

					showNotice('Articolo eliminato');
				} else {
					showWarning(result.msg, 'ATTENZIONE');
				}
			}
		});
	};



	/* ********************************************************************************
							VALIDAZIONE CHECKBOX PRIVACY
	******************************************************************************** */
	/*
	$('form').submit(function(){
		if ( $(':checkbox.privacy').is(':not(:checked)') ){
			showError('E\' necessario accettare l\'informativa sulla privacy.', 'Attenzione');
			return false;
		}
	});
	*/


	/* ********************************************************************************
									BEHAVIORAL STYLING
	******************************************************************************** */

	$('a.altri').show();
	
	$('.sorting a').append('<i />');

	// ICONE ATTRIBUTI PRODOTTO (novità, promo, stock)
	$('a.thumb[ico=novita]').append('<img src="/images/ico_novita.png" class="ico">');
	$('a.thumb[ico=promo]').append('<img src="/images/ico_promo.png" class="ico">');
	$('a.thumb[ico=stock]').append('<img src="/images/ico_stock.png" class="ico">');

	// ICONTE ATTRIBUTI PRODOTTO in correlati
	$('a.correlati[ico=novita]').append('<img src="/images/ico_novita.png" class="ico">');
	$('a.correlati[ico=promo]').append('<img src="/images/ico_promo.png" class="ico">');
	$('a.correlati[ico=stock]').append('<img src="/images/ico_stock.png" class="ico">');


	/* ********************************************************************************
									FOOTER DI SVILUPPO
	******************************************************************************** */
	$('body').css({ marginBottom: '32px' });
	$('#devFooter')
		.find('a')
			.each(function(){
				if ( $(this).attr('href').indexOf(location.pathname) != -1 ){
					$(this).addClass('selected');
				};
			})
			.end()
		.find('#chiudi')
			.click(function() {
				$('#devFooter').show();
				$('body').css('marginBottom','0');
			});
	
	/*
	*
	*/
	$("#articoloChangeColor").live('click', function() {
		$.ajax({
			url:'/frontend/articolo_change_color/' + $(this).attr('rel')
			, dataType: 'json'
			, success: function(result) {
				if(result.res == 'ok') {
					$("#picsWrapper").html(result.picsWrapper);
					$("#articoloColorCart").html(result.enterQty);
					$("#articoloDescrizione").html(result.descs);
					perPaccoTip.getTip().find('b').html(result.pezzi_pacco);
					perCartoneTip.getTip().find('b').html(result.pezzi_cartone);
				} else {
					showWarning(result.msg);
				};
				/* reinizializzo tooltip e cycle */
				$('#prodThumbs').cycle({ 
					fx:			'scrollHorz' 
					, speed:	'fast' 
					, timeout:	0 
					, prev:		'#prodPrev'
					, next:		'#prodNext'
				});
				$('.tip[title]').tooltip({ effect: 'slide', predelay: 100, delay: 0 });
			}
		});
	});

	/*
	*
	*/
	$("form#search").live('submit', function() {
		if( $("form#search > input").val().length < 3 ) {
			showWarning('Inserire almeno 3 caratteri', '');
			resetDefault("#search");
			return false;
		}
	});



	/* ********************************************************************************
						AGGIUNGO PRODOTTO AL CARRELLO (SE TAGLIA UNICA)
	******************************************************************************** */
	$('.toCart').live('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,
				dataType: 'json',
				beforeSend: function() {
					if ($('#qty'+pid).val().length >= 6){
						showWarning('La quantita\' non puo\' superare un valore a 6 cifre!', 'Attenzione');
						return false;
					}
				},
				success: function(result) {
					if(result.res == 'ok') {
						$("#layoutTotalCart").html(result.total_cart);
						$('.dropDownWrapper[rel=cart] .dropDownContent').html(result.cartList);
						showNotice('Prodotto aggiunto al <a href="/cart/step1" style="color: #fff">carrello</a>', '');
					} else {
						showWarning(result.msg, 'Attenzione');
					}
				}
			});
		} else {
			showWarning('Inserire solo numeri', 'Attenzione');
		}
	});



	/* ********************************************************************************
						AGGIUNGO PRODOTTO AL CARRELLO (SE PIU' TAGLIE)
	******************************************************************************** */
	$('.toCartAll').live('click', function() {
		/* per ogni taglia */
		$(this).closest('tr').find(':text').each(function(i, elem){
			
			var pid = $(this).attr('id');
			var qty = $(this).val();
			if (isInteger(qty) && qty != 0) {
				$.ajax({
					type: "GET",
					url: "/cart/product_add/" + pid,
					data: "qty=" + qty,
					dataType: 'json',
					beforeSend: function() {
						if ($('#'+pid).val().length >= 6){
							showWarning('La quantita\' non puo\' superare un valore a 6 cifre!', 'Attenzione');
							return false;
						}
					},
					success: function(result) {
						if(result.res == 'ok') {
							$("#layoutTotalCart").html(result.total_cart);
							$('.dropDownWrapper[rel=cart] .dropDownContent').html(result.cartList);
							showNotice('aggiunta correttamente al <a href="/cart/step1" style="color: #fff">carrello</a>', (i+1) + '&deg; quantit&agrave; inserita');
						} else {
							showWarning(result.msg, (i+1) + '&deg; quantit&agrave; inserita');
						}
					}
				});
			} else if ( qty != 0 ){
				showError('Valore non valido, inserire solo numeri.', (i+1) + '&deg; quantit&agrave; inserita');
			};
		
		});
	});


	$("#step2Form").live('submit', function() {
		$.ajax({ url: "/cart/ajax_step2_submit"
		, dataType: 'json'
		, data: $(this).serialize()
		, beforeSend: function() {
			$(".formError").remove();
			$("#step2FormSubmit").attr('disabled', 'disabled');
		}
		, success: function(result) {
			if(result.res == "ok") {
				location.href = "/cart/step3"
			} else {

				if(result.form_error != null) {
					showWarning("Bisogna riempire tutti i campi della form", "Attenzione");
					$.each(result.form_error, function(index, value) {
						var txt = "#ordini_" + value[0];
						$(txt).parent().prepend("<div class='formError'>" + value[1] + "</div>");
					});
				} else {
					showWarning(result.msg);
				}
			}	
			$("#step2FormSubmit").removeAttr('disabled');
		}
		});
		return false;
	});

	// FOTO SCROLLABLE DETTAGLIO PRODOTTO
	$('#fotoScrollable').scrollable({
		size: 3
		, prev: '#fotoPrev'
		, next: '#fotoNext'
		, keyboard: true
		, circular: true
	}).autoscroll({ autoplay: true });	

});

