$(function(){
    var timeoutId = null;
    // Gracefull degradation
    $('.hideByJS').hide();
    // Link class="blank" in una nuova finestra
    $('a.blank').attr('target','_blank');
    // Gestione commenti
    // @require 'jquery-rating'
    $('.quick_comments .user_message').hide();
    $('.quick_comments .product-id').each(function() {
        var prod_id = $(this).val();
        if (typeof ($.fn.rating) == 'function') {
          $('.prodotto-' + prod_id + ' div.vote input:radio').rating({
            cancel: 'Rimuovi il voto',
            currentValue: $('.prodotto-' + prod_id +' div.vote input:radio[@name="vote[' + prod_id + '"]"][@checked]').val()
          });
        }
        $('.quick_comments .prodotto-' + prod_id + ' .buttons input.submit').click(function (e) {
            e.preventDefault();
            var data = new Object();
            data['comments-text[' + prod_id + ']'] = $('.quick_comments .prodotto-' + prod_id + ' .textarea textarea').val();
            data['vote[' + prod_id + ']'] = $('.quick_comments .prodotto-' + prod_id + ' input[@name="vote[' + prod_id + '"]"').val();
            if (data['comments-text[' + prod_id + ']'].length == 0) return;
              $('.quick_comments .prodotto-' + prod_id + ' .buttons input.submit')
                .val('Invio del commento in corso...')
                .attr('readOnly', true).attr('disabled', true);
            $.post('/utenti/commenti.html', data, function (data, textStatus) {
                if (textStatus != 'success') {
                    $('.quick_comments .user_message').html('Impossibile commentare il prodotto!');
                } else {
                    if ($('.quick_comments .item').length - 1 == 0) {
                      clearTimeout(timeoutId);
                      $('.quick_comments .user_message').html('Grazie per i commenti '
                        + 'che hai scritto. Se vuoi avere un sommario dei prodotti commentati '
                        + 'o commentare altri prodotti acquistati, vai '
                        + 'nell\'<a href="/utenti/commenti.html">Area Commenti</a>');
                      $('.quick_comments .user_message').slideDown("slow");
                    } else {
                      $('.quick_comments .user_message').html('Il commento è stato aggiunto con successo!');
                      $('.quick_comments .user_message').slideDown("slow");
                      clearTimeout(timeoutId);
                      timeoutId = setTimeout(function() {
                        $('.quick_comments .user_message').slideUp("slow").empty();
                      }, 4000);
                    }
                    $('.quick_comments .prodotto-' + prod_id).parent().fadeOut("slow", function() {
                      $('.quick_comments .prodotto-' + prod_id).parent().remove();
                    });
                }
            });
        });
        $('.quick_comments .prodotto-' + prod_id + ' .textarea textarea').keyup(function (e) {
            $message = $(this).parent().parent().find('.message');
            var max = $message.find('.max').text();
            var counter = $message.find('.counter');
            var inserted_chars = $(this).val().length;
            var style = 'red';
            if (inserted_chars >= max) {
              style = 'green';
            }
            counter.html('<span class="' + style + '">Hai inserito ' + inserted_chars + ' caratteri.</span>');
            e.preventDefault();
        });
    });
});
// OnLoad: Se la descrizione di una categoria è troppo lunga la divide e mostra il link per continuare la lettura
$(function () {
	var $c = $("div#categoryDescriptionContainer");
	if ($c.hasClass('noBorder'))
		return;
    var $cTitle = $("div#categoryDescriptionContainer h2");
    var $cText = $("div#categoryDescription");
	if ($c.length == 0) return;
	// Tolgo la proprietà che imposta uno stile apposito x chi non ha JS abilitato
	$c.removeClass('noJS');
	// Calcola l'altezza normale del box
	$c.orgHeight = $cText.innerHeight() + $cTitle.height();
	$c.minHeight = $c.height();
    if ($c.minHeight >= $c.orgHeight) {
        $("div#categoryDescriptionContainer a.continue").remove();
        return;
    }
	// C'è il link x continuare la lettura?
	var $a = $("div#categoryDescriptionContainer a.continue");
	if ($a.length == 1) {
		// Sì, determino gli handler x espandere e collassare il box
		$a.click(function(e){
			if ($c.collapsed) {
				// Collassato, dobbiamo espanderlo:
				// Elimino il blocco che nascondeva (abbassava) il testo e i '...'
				$a.prev().remove();
				$a.prev().remove();
				// Aggiungo la classe al link che indica lo stato (così cambia l'icona)
				$(this).addClass('collapse');
				// Porto il box all'altezza completa
				$c.animate({height: $c.orgHeight},'slow');
				// Imposto come espanso
				$c.collapsed = false;
			} else {
				// Uno span che mi servirà solo x calcolare l'altezza al punto dove dividere il testo
				// e a nascondere il testo + prossimo impostando un margin
				var $tmpSpan = $('<span> </span>');
				// Mi preparo x calcolare l'altezza dove dividere
				$tmpSpan.css({
					display: "block",
					margin: 0
				});
				$a.before($tmpSpan);
				// Calcolo l'altezza
				var imgbottom = 0;
				var height = $c.minHeight;
				// Riporto al normale (invisibile visto che vuoto) lo span
				$tmpSpan.css('display','inline');
				// Nascondo l'eccesso
				$c.css('overflow','hidden');
				// Rimuovo la classe che mostrava l'icona x collassare
				$(this).removeClass('collapse');
				// Aggiungo i '...' al testo (e nascondo finchè non collasso del tutto)
				//$tmpSpan.before("<span>...</span>").prev().hide();
				// Porto il box a collassarsi
				$c.animate({height: height+10},'slow','',function(){
					// Al completamento dell'animazione imposto lo span di prima come blocco e gli assegno un margine
					// in modo da nascondere il testo che segue. Poi mostro i puntini (.prev()) che prima avevo nascosto
					$tmpSpan.css({marginBottom: 500,display: 'block'}).prev().show();
				});
				// Imposto come collassato
				$c.collapsed = true;
			}
			e.preventDefault();
		});
		
		// Collasso
		$c.collapsed = false;
		$a.click();
	}
	
});

// OnLoad: espandi/nascondi per descrizione prodotto
$(function () {
	var $c = $("div#bookDescriptionContainer");
    var $cText = $("div#bookDescriptionBox");
	if ($c.length == 0) return;
	$c.removeClass('noJS');
	// Calcola l'altezza normale del box
	$c.minHeight = $c.height();
    if ($c.minHeight >= $cText.innerHeight()) {
        $("div#bookDescriptionContainer a.continue").remove();
		$c.css('min-height',$cText.innerHeight());
		$c.css('height',$cText.innerHeight());
		if ($cText.text().trim() == 0) {
			$c.css('display','none');
		}
        return;
    }

	// C'è il link x continuare la lettura?
	var $a = $("div#bookDescriptionContainer a.continue");
	if ($a.length == 1) {
		// Sì, determino gli handler x espandere e collassare il box
		$a.click(function(e){
			if ($c.collapsed) {
				// Collassato, dobbiamo espanderlo:
				// Elimino il blocco che nascondeva (abbassava) il testo e i '...'
				$a.prev().remove();
				$a.prev().remove();
				// Aggiungo la classe al link che indica lo stato (così cambia l'icona)
				$(this).addClass('collapse');
				// Porto il box all'altezza completa
				$c.animate({height: $cText.innerHeight()},'slow');
				// Imposto come espanso
				$c.collapsed = false;
			} else {
				// Uno span che mi servirà solo x calcolare l'altezza al punto dove dividere il testo
				// e a nascondere il testo + prossimo impostando un margin
				var $tmpSpan = $('<span> </span>');
				// Mi preparo x calcolare l'altezza dove dividere
				$tmpSpan.css({
					display: "block",
					margin: 0
				});
				$a.before($tmpSpan);
				// Calcolo l'altezza
				var imgbottom = 0;
				var height = $c.minHeight;
				// Riporto al normale (invisibile visto che vuoto) lo span
				$tmpSpan.css('display','inline');
				// Nascondo l'eccesso
				$c.css('overflow','hidden');
				// Rimuovo la classe che mostrava l'icona x collassare
				$(this).removeClass('collapse');
				// Aggiungo i '...' al testo (e nascondo finchè non collasso del tutto)
				//$tmpSpan.before("<span>...</span>").prev().hide();
				// Porto il box a collassarsi
				$c.animate({height: height+10},'slow','',function(){
					// Al completamento dell'animazione imposto lo span di prima come blocco e gli assegno un margine
					// in modo da nascondere il testo che segue. Poi mostro i puntini (.prev()) che prima avevo nascosto
					$tmpSpan.css({marginBottom: 500,display: 'block'}).prev().show();
				});
				// Imposto come collassato
				$c.collapsed = true;
			}
			e.preventDefault();
		});
		
		// Collasso
		$c.collapsed = false;
		$a.click();
	}
	
});

// OnLoad: Gestisce il link "Mostra tutti i reparti"
$(function(){
	var $l = $("div#showAllCategories a");
	
	if($l.length == 0) return;
	
	$l.originalText = $l.text();
	
	$l.toggle(function(e){
		$('div#currentCategory').slideUp('fast');
		$l.text('Mostra il reparto corrente');
		$l.addClass('thisCategory');
		e.preventDefault();
	},function(e){
		$('div#currentCategory').slideDown('fast');
		$l.text($l.originalText);
		$l.removeClass('thisCategory');
		e.preventDefault();
	});
});

// OnLoad: Gestisce la casella di ricerca
$(function(){
	var $s = $('form.search input[@name=q]');
	$s.orgText = $s.val();
	$s.focus(function(){
		if($s.val() == $s.orgText)
			$s.val('');
	});
	$s.blur(function(){
		if($s.val() == '')
			$s.val($s.orgText);
	});
});

// OnLoad: Gestisce la casella x l'iscrizione alla newsletter
$(function(){
	var $s = $('div#newsletter form input[@name=email]');
	$s.orgText = $s.val();
	$s.focus(function(){
		if($s.val() == $s.orgText)
			$s.val('');
	});
	$s.blur(function(){
		if($s.val() == '')
			$s.val($s.orgText);
	});
});

//OnLoad: Tracking newsletters
$(function(){
	category = getUrlParameter('cat');
	action = getUrlParameter('act');
	label = getUrlParameter('lbl');
	
	if (category != "" && action != "") {
		if (typeof(pageTracker)!='undefined') {
			pageTracker._trackEvent(category, action, label);
		}
	}
});

// OnLoad: Libro del mese
$(function(){
    jq132("#bestSellers div.scrollable").scrollable({
        vertical:true,
        size: 1
    // use mousewheel plugin
    }).circular().autoscroll({autoplay: true});
});

//OnLoad: Santo del giorno
$(function(){
    $.get(json_ws_url + 'json/brocardodata.json',
    {},
        function(data) {
            $("#brocardodata").empty();
            $("#brocardodata").append(data);
            $("#brocardodata").show();
        },
        'html'
        );
});

//OnLoad: Frase del giorno
$(function(){
    $.get(json_ws_url + 'json/phrase_of_the_day.json',
        {},
        function(data) {
        	$("#phrase_of_the_day").empty();
            $("#phrase_of_the_day").append(data);
            $('#phrase_of_the_day').show();
        },
        'html'
    );
});

//OnLoad: Barra laterale
$(function() {
    if ($('#side').find('div').length == 0) {
        $('#side').hide();
        $.get(json_ws_url + 'json/sidebar.json',
            {},
            function (data) {
                    $("#side").append(data);
                    $('#side').fadeIn(2000);
            },
            'html'
        );
    }
});

//Onload check for admin cookie
$(function(){
	c_name = "LOGGED_IN_ADMIN";
	if (document.cookie.length == 0)
		return;
	c_start = document.cookie.indexOf(c_name + "=");
	if (c_start == -1)
		return;
	if (typeof(admin_request) != 'undefined') {
		admin_request();
		return;
	}
	$.getScript(theme_url + 'javascript/adminForm.js', function(){
		admin_request();
	});
});

// My Functions:

/**
 * Returns a sequence of siblings elements next to the specified element
 */
function nextSiblings($elem){
	var next = $elem.get(0).nextSibling;
	if(next != null){
		var $seq = $(next);
		$seq = $seq.add(nextSiblings($seq).get());
		return $seq;
	}else{
		return $("#nulllllllllll");
	}
}

/**
 * Get category for google events from url
 */
function getCategory() {
	var category = '';
	if (location.href.indexOf('cart.html') != -1) {
		category = 'Carrello';
	} else if (location.href.indexOf('/reparti/') != -1 &&
		location.href.indexOf('_recensiti') != -1) {
		category = 'Recensiti';
	} else if (location.href.indexOf('/reparti/') != -1 &&
		location.href.indexOf('_commentati') != -1) {
		category = 'Commentati';
	} else if ((location.href.indexOf('/reparti/') != -1 &&
		location.href.indexOf('uservoice') != -1) ||
		location.href.indexOf('la_voce_ai_lettori.html') != -1) {
		category = 'Commentati o Recensiti';
	} else if (location.href.indexOf('/reparti/libri/libri_scontati') != -1 ||
		location.href.indexOf('/reparti/cd/cd_scontati') != -1 ||
		location.href.indexOf('/reparti/dvd/dvd_scontati') != -1 ||
		location.href.indexOf('/reparti/varie/varie_scontati') != -1 ) {
		category = 'Offerte';
	} else if (location.href.indexOf('/libri/novita') != -1) {
		category = 'Novità';
	} else if (location.href.indexOf('_di/autore/') != -1) {
		category = 'Autore';
	} else if (location.href.indexOf('/libri/editore') != -1) {
		category = 'Editore';
	} else if (location.href.indexOf('/reparti/') != -1) {
		category = 'Categoria';
	} else if (location.href.indexOf('/libri/') != -1 ||
		location.href.indexOf('/cd/') != -1 ||
		location.href.indexOf('/spartiti/') != -1 ||
		location.href.indexOf('/dvd/') != -1 ||
		location.href.indexOf('/varie/') != -1) {
		category = 'Prodotto';
	} else {
		category = 'Home page';
	}

	return category;
}

/**
 * Parse url parameters
 */
function getUrlParameter( 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 results[1];
};

/* utilities */
function checkRadio(inputname){
  var valueSelected = '';
  $('input[name='+ inputname +']').each(function (i){
    if(this.checked){
      valueSelected = this.value;
    }
  });
  return valueSelected;
}

function fetchSelect(inputname){
  var valueSelected = '';
  $('select[name='+ inputname +'] option').each(function (i){
    if(this.selected){
      valueSelected = this.value;
    }
  });
  return valueSelected;
}