var Config = {
	_baseURL: 'http://www.glassato.com/',
	getBaseURL: function(){
			return this._baseURL;
		}
};

var preloadImage = new Image();
preloadImage.src= Config.getBaseURL() + "media/images/ajax-loader.gif";

function visualizza_figli(idDiv){
	return false;
}

function visualizza_figli_root(idDiv, aObj){
	$("#dizionari-root a[id!=" + aObj.id + "]").css('display', 'none');
	$("#" + idDiv).css('display', 'block');
	return false;
}

function nascondi_ramo(idDiv){
	$("#" + idDiv).css('display', 'none');
	$("#dizionari-root a").css('display', 'block');
}

/**
 *  Attiva il plugin history   
*/
function activate_history(){
	$("a:not([class^=standalone])").click(function(){
		$("#scroll-content").html(preloadImage);				
		var hash = this.href;
		hash = hash.replace(Config.getBaseURL(), '');
		hash = encodeURI(hash.replace(/^.*#/, ''));
		// moves to a new page. 
		// pageload is called at once. 
		$.history.load(hash);
		return false;
	});
}
/**
*  Funzioni delle thumbs   
*/
function cambia_img(url_img){
	$(".img-ingrandita img").attr('src', url_img);
}

function cambia_img_dettaglio_orologio(overlay_id, url_img){
	$(".img-ingrandita img").attr('src', url_img);
	$(".img-ingrandita img").attr('rel', "#" + overlay_id);
	$(".overlay img").attr('src', url_img);
	$(".overlay").attr('id', overlay_id);
	$("img[rel]").overlay();
}

function cambia_img_dettaglio_marca(overlay_id, url_img){
	$(".img-ingrandita img").attr('src', url_img);
	$(".img-ingrandita img").attr('rel', "#" + overlay_id);
	$(".overlay img").attr('src', url_img);
	$(".overlay").attr('id', overlay_id);
	$("img[rel]").overlay();
}

function cambia_img_dettaglio_news(url_img){
	$(".img-ingrandita img").attr('src', url_img);
}

/**
*  Dichiarazione variabili globali   
*/
var contentOuterWidth = 0;
var scrollHandleWidth = 0;
var scrollbarWidth = 0;
var contentScrollWidth = 0;

var timerLeft; // usato nello scroll laterale globale
var timerRight; // usato nello scroll laterale globale
var timerUp; // usato nello scroll della descrizione di una marca 
var timerDown; // usato nello scroll della descrizione di una marca


/**
 *  Inizializza la galleria   
*/
function initGalleria(){
	$("#handle_scroll_right").mouseover(
		function(ev){
			scrollRight();
		}
	);
	
	$("#handle_scroll_right").mouseout(
		function(ev){
			clearTimeout(timerRight);
		}
	);

	$("#handle_scroll_left").mouseover(
		function(ev){
			scrollLeft();
		}
	);
	
	$("#handle_scroll_left").mouseout(
		function(ev){
			clearTimeout(timerLeft);
		}
	);
	
}

function scrollLeft(){
	$("#scroll-content").scrollLeft($("#scroll-content").scrollLeft() - 10);
	$("#scroll-handle").css("left", $("#scroll-content").scrollLeft() * 436 / (document.getElementById("scroll-content").scrollWidth - $("#scroll-content").outerWidth()));
	timerLeft = setTimeout("scrollLeft()",10);
}

function scrollRight(){
	$("#scroll-content").scrollLeft($("#scroll-content").scrollLeft() + 10);
	$("#scroll-handle").css("left", $("#scroll-content").scrollLeft() * 436 / (document.getElementById("scroll-content").scrollWidth - $("#scroll-content").outerWidth()))
	timerRight = setTimeout("scrollRight()",10);
}


function scrollUp(el){
	$("#dettaglio-marca .testo-descrizione-marca").scrollTop($("#dettaglio-marca .testo-descrizione-marca").scrollTop() - 1);
	timerUp = setTimeout("scrollUp()",10);
}

function scrollDown(){
	$("#dettaglio-marca .testo-descrizione-marca").scrollTop($("#dettaglio-marca .testo-descrizione-marca").scrollTop() + 1);
	timerDown = setTimeout("scrollDown()",10);
}

function initScrollMarca(){
	var contentScrollHeight = 0;
	try {
		contentScrollHeight = document.getElementById("testo-descrizione-marca").scrollHeight;
	}
	catch(ex){ }
	
	if (contentScrollHeight > $("#dettaglio-marca .testo-descrizione-marca").innerHeight()){
		$("#scroll-up").mouseover(function(ev)
		{
			scrollUp();
		}
		);
		$("#scroll-down").mouseover(function(ev)
			{
				scrollDown();
			}
		);
	
		$("#scroll-up").mouseout(function(ev)
			{
				clearTimeout(timerUp);
			}
		);
		$("#scroll-down").mouseout(function(ev)
			{
				clearTimeout(timerDown);
			}
		);
	} else {
		$("#scroll-down").css("display", "none");
		$("#scroll-up").css("display", "none");
	}
}
  
/* FUNZIONE DI CARICAMENTO DINAMICO DI JAVASCRIPT E CSS */
function loadjscssfile(filename, filetype){
	if (filetype=="js"){ //if filename is a external JavaScript file
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype=="css"){ //if filename is an external CSS file
		var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
	}
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);

}

/* INIZIALIZZA GLI OVERLAY */
function initOverlay(){
	loadjscssfile(Config.getBaseURL() + 'media/css/overlay-minimal.css', 'css');
	$.getScript(Config.getBaseURL() + 'media/js/jquery.tools.min.js',
		function(){
			$("img[rel]").overlay({
				top:0
			});
			//$("button[rel]").click(function(){ console.log("riuscito") });
			$("button[rel]").overlay({
				top:0
			});
			
			$("span[rel]").overlay({
				top:0
			});
		}
	);
}

/* INIZIALIZZA LA RICERCA SEMPLICE */
function initRicercaSemplice(){
	loadjscssfile(Config.getBaseURL() + 'media/css/customselect.css', 'css');
	loadjscssfile(Config.getBaseURL() + 'media/js/jquery_ui/css/dot-luv/jquery-ui-1.7.1.custom.css', 'css');
	
	$.getScript(Config.getBaseURL() + 'media/js/jquery.customselect.js', 
		function(){
			$.getScript(Config.getBaseURL() + 'media/js/jquery.scrollTo-min.js',
				function(){
					$.getScript(Config.getBaseURL() + 'media/js/jquery_ui/development-bundle/ui/ui.slider.js', 
						function(){
							$("#select_marca").SelectCustomizer();
							$("#select_collezione").SelectCustomizer();
							$("#select_tipologia_orologio").SelectCustomizer();
							$("#select_condizione_orologio").SelectCustomizer();
							$("#select_genere").SelectCustomizer();
							$("#select_tipologia_movimento").SelectCustomizer();
							$("#select_figli_tipologia_movimento").SelectCustomizer();
							$(function(){
								$("#select_tipologia_movimento_options .selectitems").mouseup(function(){
									var contSelTip = document.getElementById("container_select_figli_tipologia_movimento");
									contSelTip.innerHTML = "";
									if($(this).attr("title") == "meccanico"){
										var sel = document.createElement("select"); // id generato da select customizer
										sel.setAttribute("class", "selectitems");
										sel.setAttribute("name", "figli_tipologia_movimento");
										sel.setAttribute("id", "select_figli_tipologia_movimento");
										sel.setAttribute("title", "Tipologia movimento");
						
										var option1 = document.createElement("option");
										option1.setAttribute("value", "manuale");
										option1.innerHTML = "Manuale";
										
										var option2 = document.createElement("option");
										option2.setAttribute("value", "automatico");
										option2.innerHTML = "Automatico";
						
										sel.appendChild(option1);
										sel.appendChild(option2);
						
										contSelTip.appendChild(sel);
										$("#select_figli_tipologia_movimento").SelectCustomizer();
									}	
									else if($(this).attr("title") == "quarzo"){
										var sel = document.createElement("select"); // id generato da select customizer
										sel.setAttribute("class", "selectitems");
										sel.setAttribute("name", "figli_tipologia_movimento");
										sel.setAttribute("id", "select_figli_tipologia_movimento");
										sel.setAttribute("title", "Tipologia movimento");
						
										var option1 = document.createElement("option");
										option1.setAttribute("value", "analogico");
										option1.innerHTML = "Analogico";
										
										var option2 = document.createElement("option");
										option2.setAttribute("value", "digitale");
										option2.innerHTML = "Digitale";
						
										var option3 = document.createElement("option");
										option3.setAttribute("value", "anadigitale");
										option3.innerHTML = "Anadigitale";
						
										sel.appendChild(option1);
										sel.appendChild(option2);
										sel.appendChild(option3);
						
										contSelTip.appendChild(sel);
										$("#select_figli_tipologia_movimento").SelectCustomizer();
									}
									else{
									}
								});
								$("#select_marca_options .selectitems").mouseup(function(){
									$.ajax({
										  url: Config.getBaseURL() +  "collezione/get_colleziones_by_marca/" + $(this).attr('title'),
										  cache: false,
										  type: "POST",
										  dataType: "json",
										  success: function(res){
											var contSel = document.getElementById("container_select_collezione");
											contSel.innerHTML = "";
										  	var sel = document.createElement("select"); // id generato da select customizer
											sel.setAttribute("class", "selectitems");
											sel.setAttribute("name", "collezione");
											sel.setAttribute("id", "select_collezione");
											sel.setAttribute("title", "Collezione");
						
											var option = document.createElement("option");
											option.setAttribute("value", -1);
											option.innerHTML = "Nessuna";
											sel.appendChild(option);
										  	for(var i = 0; i < res.length; i++){
												option = document.createElement("option")
										  		option.setAttribute("value", res[i].id);
												option.innerHTML = res[i].nome;
										  		sel.appendChild(option);
											}
											contSel.appendChild(sel);
											$("#select_collezione").SelectCustomizer();
										  }
										});
								})
							
								$("#slider-range").slider({
									range: true,
									min: 100,
									max: 200000,
									values: [800, 1000],
									step:100,
									slide: function(event, ui) {
										ui.values[0] = ui.values[1] * 4 / 5;
										$("#amount").html("$" + ui.values[0] + " - $" + ui.values[1]);
										$("#min_price").val(ui.values[0]);
										$("#max_price").val(ui.values[1]);
									}
								});
								$("#amount").html("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1));
								
							});
						}
					);
				}
			);
		}
	);
}

function selezionaTipologiaMovimento(){
	var contSelTip = $("#container_select_figli_tipologia_movimento");
	contSelTip.html("");
	var valFigli = $("#val_figli_tipologia_movimento").val();
	if($("#select_tipologia_movimento").val() == "meccanico"){
		var sel = document.createElement("select"); // id generato da select customizer
		sel.setAttribute("class", "selectitems");
		sel.setAttribute("name", "figli_tipologia_movimento");
		sel.setAttribute("id", "select_figli_tipologia_movimento");
		sel.setAttribute("title", "Tipologia movimento");

		var option1 = document.createElement("option");
		option1.setAttribute("value", "manuale");
		option1.innerHTML = "Manuale";
		if(valFigli == "manuale")
			option1.setAttribute("selected", "selected");
		
		var option2 = document.createElement("option");
		option2.setAttribute("value", "automatico");
		option2.innerHTML = "Automatico";
		if(valFigli == "automatico")
			option2.setAttribute("selected", "selected");

		sel.appendChild(option1);
		sel.appendChild(option2);

		contSelTip.append(sel);
	}	
	else if($("#select_tipologia_movimento").val() == "quarzo"){
		var sel = document.createElement("select"); // id generato da select customizer
		sel.setAttribute("class", "selectitems");
		sel.setAttribute("name", "figli_tipologia_movimento");
		sel.setAttribute("id", "select_figli_tipologia_movimento");
		sel.setAttribute("title", "Tipologia movimento");

		var option1 = document.createElement("option");
		option1.setAttribute("value", "analogico");
		option1.innerHTML = "Analogico";
		if(valFigli == "analogico")
			option1.setAttribute("selected", "selected");
		
		var option2 = document.createElement("option");
		option2.setAttribute("value", "digitale");
		option2.innerHTML = "Digitale";
		if(valFigli == "digitale")
			option3.setAttribute("selected", "selected");

		var option3 = document.createElement("option");
		option3.setAttribute("value", "anadigitale");
		option3.innerHTML = "Anadigitale";
		if(valFigli == "anadigitale")
			option3.setAttribute("selected", "selected");

		sel.appendChild(option1);
		sel.appendChild(option2);
		sel.appendChild(option3);

		contSelTip.append(sel);
	}
}

function selezionaCollezione(){
	var valColl = $("#val_collezione").val();
	$.ajax({
	  url: Config.getBaseURL() +  "collezione/get_colleziones_by_marca/" + $("#select_marca").val(),
	  cache: false,
	  type: "POST",
	  dataType: "json",
	  success: function(res){
		var contSel = $("#container_select_collezione");
		contSel.html("");
	  	var sel = document.createElement("select"); // id generato da select customizer
		sel.setAttribute("class", "selectitems");
		sel.setAttribute("name", "collezione");
		sel.setAttribute("id", "select_collezione");
		sel.setAttribute("title", "Collezione");

		var option = document.createElement("option");
		option.setAttribute("value", -1);
		option.innerHTML = "Nessuna";
		sel.appendChild(option);
	  	for(var i = 0; i < res.length; i++){
			option = document.createElement("option")
	  		option.setAttribute("value", res[i].id);
			if(valColl == res[i].id)
				option.setAttribute("selected", "selected");
			option.innerHTML = res[i].nome;
	  		sel.appendChild(option);
		}
		contSel.append(sel);
	  }
	});
}
/* INIZIALIZZA IL RIEPILOGO DELLA RICERCA EFFETTUATA */
function initSliderRicerca(){
	$(function(){
		$("#handle-slider").click(function(){
			if($("#handle-slider").attr('rel') == 'closed'){
				$("#handle-slider").attr('rel', 'opened');
				$("#form-ricerca-slider").fadeIn("slow");
			}
			else{
				$("#handle-slider").attr('rel', 'closed');
				$("#form-ricerca-slider").fadeOut("slow");
			}
    	});
		
		$("#select_tipologia_movimento option").mouseup(function(){
			selezionaTipologiaMovimento();
		});
		
		selezionaTipologiaMovimento();
		$("#select_marca").change(function(){
			selezionaCollezione();
		});
		if($("#select_marca").val() > 0){
			selezionaCollezione();
		}
	});
}

var collezioneCaricata = false;
function initSliderRicercaDefault(){
	$("#link-ricerca-default").click(function(){
		if($("#link-ricerca-default").attr('rel') == 'closed'){
			$("#select_tipologia_movimento option").mouseup(function(){
				selezionaTipologiaMovimento();
			});
			$("#select_marca").change(function(){
				selezionaCollezione();
			});
			if($("#select_marca").val() > 0){
				if (!collezioneCaricata) {
					selezionaCollezione();
					collezioneCaricata = true;
				}
			}
			$("#link-ricerca-default").attr('rel', 'opened');
			$("#form-ricerca-slider").fadeIn("slow");
			
		}
		else{
			$("#link-ricerca-default").attr('rel', 'closed');
			$("#form-ricerca-slider").fadeOut("slow");
		}
		return false;
	});
	selezionaTipologiaMovimento();
}

function initDizionarioTermini(){
	initOverlay();
}

/* CARICA DINAMICAMENTE IL CONTENUTO */
function pageload(hash) {
		// hash doesn't contain the first # character.
		$("#scroll-content").empty();
		$("#other-views").empty();
		$("#statusbar").empty();
		var divLoading = document.createElement("div");
		divLoading.className = "div-loading";
		var inCaricamento = document.createElement("div");
		inCaricamento.innerHTML = i18n.in_caricamento;
		divLoading.appendChild(preloadImage);
		divLoading.appendChild(inCaricamento);
		$("#scroll-content").html(divLoading);
		if(hash) {			
			// restore ajax loaded state
			$("#scroll-content").load(Config.getBaseURL() + hash + " #scroll-content > *", "", 
				function(responseText, textStatus, XMLHttpRequest){
					$("#scroll-content a:not([class^=standalone])").click(function(){
						var hash = this.href;
						hash = hash.replace(Config.getBaseURL(), '');
						hash = encodeURI(hash.replace(/^.*#/, ''));
						$.history.load(hash);
						return false;
					});
					
					controlloBarraScorrimento();
					$(function(){
						$("a.to_statusbar").mouseover(function(){ $("#statusbar").html(this.title) });
						$("a.to_statusbar").mouseout(function(){ $("#statusbar").html("") });
					});
				}
			);
			$("#other-views").load(Config.getBaseURL() + hash + " #other-views > *", "",
				function(responseText, textStatus, XMLHttpRequest){
					$("#other-views a:not([class^=standalone])").click(function(){
						var hash = this.href;
						hash = hash.replace(Config.getBaseURL(), '');
						hash = encodeURI(hash.replace(/^.*#/, ''));
						$.history.load(hash);
						return false;
					});
					initGalleria();
					if(hash.match("marca/dettaglio") != null
						|| hash.match("collezione/dettaglio/") != null)
						initScrollMarca();
					if(hash.match("ricerca_orologi/semplice") != null)
						initRicercaSemplice();
					if(hash.match("ricerca_orologi/risultato_ricerca_semplice") != null)
						initSliderRicerca();
					if(hash.match("orologio/dettaglio/") != null 
						|| hash.match("dizionario_termini")
						|| hash.match("collezione/dettaglio/") != null)
						initOverlay();
					if(hash.match("dizionario_termini/alfabetico") != null 
						|| hash.match("dizionario_termini/voce_dizionario")
						|| hash.match("dizionario_termini")
						)
						initDizionarioTermini();

					controlloBarraScorrimento();
					$(function(){
						$("a.to_statusbar").mouseover(function(){ $("#statusbar").html(this.title) });
						$("a.to_statusbar").mouseout(function(){ $("#statusbar").html("") });
					});
				}
			);
		} else {
			// start page
			$("#scroll-content").load(window.location + " #scroll-content > *", "", 
				function(responseText, textStatus, XMLHttpRequest){
					$("#scroll-content a:not([class^=standalone])").click(function(){
						var hash = this.href;
						hash = hash.replace(Config.getBaseURL(), '');
						hash = encodeURI(hash.replace(/^.*#/, ''));
						$.history.load(hash);
						
						return false;
					});
					
					controlloBarraScorrimento();
					$(function(){
						$("a.to_statusbar").mouseover(function(){ $("#statusbar").html(this.title) });
						$("a.to_statusbar").mouseout(function(){ $("#statusbar").html("") });
					});
				});

			$("#other-views").load(window.location + " #other-views > *", "",
				function(responseText, textStatus, XMLHttpRequest){
					$("#other-views a:not([class^=standalone])").click(function(){
						var hash = this.href;
						hash = hash.replace(Config.getBaseURL(), '');
						hash = encodeURI(hash.replace(/^.*#/, ''));
						$.history.load(hash);
						return false;
					});
					initGalleria();
					var wl = window.location.toString();
					if(wl.match("marca/dettaglio") != null
						|| hash.match("collezione/dettaglio/") != null)
						initScrollMarca();
					if(wl.match("ricerca_orologi/semplice") != null)
						initRicercaSemplice();
					if (wl.match("ricerca_orologi/risultato_ricerca_semplice") != null)
						initSliderRicerca();
					if(wl.match("orologio/dettaglio/") != null 
						|| hash.match("dizionario_termini"))
						initOverlay();
					if(wl.match("dizionario_termini/alfabetico") != null 
						|| wl.match("dizionario_termini/voce_dizionario")
						|| wl.match("dizionario_termini")
						)
						initDizionarioTermini();
					controlloBarraScorrimento();
					$(function(){
						$("a.to_statusbar").mouseover(function(){ $("#statusbar").html(this.title); });
						$("a.to_statusbar").mouseout(function(){ $("#statusbar").html(""); });
					});
				}
			);
		}
					
		$("#scroll-content").scrollLeft(0);
		$("#scroll-handle").css("left", "0px");
		controlloBarraScorrimento();
	}

function controlloBarraScorrimento(){
	contentOuterWidth = $("#scroll-content").outerWidth();
    scrollHandleWidth = $("#scroll-handle").width();
    scrollbarWidth = $("#scrollbar").width() - scrollHandleWidth;
    contentScrollWidth = document.getElementById("scroll-content").scrollWidth;
    if(contentScrollWidth > contentOuterWidth) {
		$("#scrollbar").css('display', 'block');
		$("html").css('overflow-x', 'hidden');
	}
	else{
		$("#scrollbar").css('display', 'none');
	}
}
  $(function() {
  				$(".app-opener").click(function () {
				  if ($("#app-list").is(":hidden")) {
				    $("#app-list").slideDown("slow");
				  } else {
				    $("#app-list").slideUp();
				  }
				});
				$("#app-list div ul li a").click(function(){
					$("#app-list").slideUp();
				});
				$("#link-ricerca-default").click(function(){
				if($("#link-ricerca-default").attr('rel') == 'closed'){
					$("#select_tipologia_movimento option").mouseup(function(){
						selezionaTipologiaMovimento();
					});
					$("#select_marca").change(function(){
						selezionaCollezione();
					});
					if($("#select_marca").val() > 0){
						if (!collezioneCaricata) {
							selezionaCollezione();
							collezioneCaricata = true;
						}
					}
					$("#link-ricerca-default").attr('rel', 'opened');
					$("#form-ricerca-slider").fadeIn("slow");
					$("#close-icon").click(function(){
						$("#link-ricerca-default").attr('rel', 'closed');
						$("#form-ricerca-slider").fadeOut("slow");
					});
				}
				else{
					$("#link-ricerca-default").attr('rel', 'closed');
					$("#form-ricerca-slider").fadeOut("slow");
				}
				return false;
			});
			selezionaTipologiaMovimento();
			    
  				controlloBarraScorrimento();
				$("#scroll-content").scrollLeft(0);
			    $("#scroll-handle").draggable({
					axis: 'x', 
					containment: 'parent',
					start: function(event, ui){
						contentOuterWidth = $("#scroll-content").outerWidth();
						scrollHandleWidth = $("#scroll-handle").width();
						scrollbarWidth = $("#scrollbar").width() - scrollHandleWidth;
						contentScrollWidth = document.getElementById("scroll-content").scrollWidth;
					},
					drag: function(event, ui){
					    var position = ui.position;
					    $("#scroll-content").scrollLeft(position.left * (contentScrollWidth - contentOuterWidth) / scrollbarWidth); 
					}
			    });
			$.history.init(pageload);
			activate_history();
			$("a.to_statusbar").mouseover(function(){ $("#statusbar").html(this.title) });
			$("a.to_statusbar").mouseout(function(){ $("#statusbar").html("") });
			var hash = location.href;
			hash = hash.replace(Config.getBaseURL(), '');
			hash = encodeURI(hash.replace(/^.*#/, ''));
			
			
			if(hash.match("ricerca_orologi/semplice") != null)
				initRicercaSemplice();
			if (hash.match("ricerca_orologi/risultato_ricerca_semplice") != null) {
				initSliderRicerca();
				
			}
			if (hash.match("orologio/dettaglio/") != null ||
			hash.match(Config.getBaseURL() + "dizionario_termini") ||
			hash.match("collezione/dettaglio/") != null			) {
				initOverlay();
			}
			if(hash.match("marca/dettaglio") != null ||
			hash.match("collezione/dettaglio/") != null){
				initScrollMarca();	
			}
				
			if(hash.match("dizionario_termini/alfabetico") != null 
						|| hash.match("dizionario_termini/voce_dizionario")
						|| hash.match("dizionario_termini")
				)
						initDizionarioTermini();
			
  });

  $(window).resize(function(){
    contentOuterWidth = $("#scroll-content").outerWidth();
    scrollHandleWidth = $("#scroll-handle").width();
    scrollbarWidth = $("#scrollbar").width() - scrollHandleWidth;
    contentScrollWidth = document.getElementById("scroll-content").scrollWidth;
    if(contentScrollWidth > contentOuterWidth){
	$("#scrollbar").css('display', 'block');
	$("html").css('overflow-x', 'hidden');
	}
  });
