/* COMMON.JS */


// Funzione che si occupa della GESTIONE AJAX
var myRequest = null;

function CreateXmlHttpReq(handler) {
  var xmlhttp = null;
  try {
    xmlhttp = new XMLHttpRequest();
  } catch(e) {
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  xmlhttp.onreadystatechange = handler;
  return xmlhttp;
}


// Funzione che si occupa del CAMBIO PAGINA
function changePage(frm, caller, numpage) {
	
  c = false;
	
  if (frm == 'changepage_' + caller) {
  	document.getElementById('n_page').setAttribute("value", numpage);
	c = true;
  }
  
  try {
	if (c)
  		document.getElementById(frm).submit();
  } catch(e) {
  	alert("Si è verificato un errore Javascript durante l'invio dei dati\n\n" + e.description);
    return false;
  }
}


// Funzione che si occupa della RICERCA ALL'INTERNO DI UN ARGOMENTO
function searchArgomento(frm, caller) {
	
  c = false;
  
  page =caller.substring(caller.lastIndexOf('_')+1);
  
  if (document.getElementById('fld_argomento_'+page).value == "")
  	alert("Attenzione. Non hai indicato alcun criterio di ricerca.");
  else { 
	  if (frm == 'search_' + caller)
		c = true;
	  
	  try {
		if (c)
			document.getElementById(frm).submit();
	  } catch(e) {
		alert("Si \u00E8 verificato un errore Javascript durante l'invio dei dati\n\n" + e.description);
		return false;
	  }
  }
}


// Funzione che si occupa di lanciare la form di RICERCA
function searchProd(type) {  
  if (type != "") {
  	if (type == 'search_header') {
		var prod = document.getElementById('search_input').value;
		var kind = document.getElementById('search_type').value;
	} else if (type == 'search_footer') {
		var prod = document.getElementById('search_input_footer').value;
		var kind = document.getElementById('search_type_footer').value;
	}

	if (prod == "")
		alert("Attenzione. Non hai indicato alcun criterio di ricerca.");
	else {
		
		// Formatto il titolo della pagina
		page = pageCreate(prod);
		if (kind == 'G')
			page = "ricerca-"+page+".php";
		else if (kind == 'L')
			page = "ricerca-libri-"+page+".php";
		else if (kind == 'R')
			page = "ricerca-remainders-"+page+".php";
		else if (kind == 'S')
			page = "ricerca-superofferte-"+page+".php";
		else if (kind == 'P')
			page = "ricerca-pacchi-di-libri-"+page+".php";
			
		url = document.getElementById('url').value;
		ids = document.getElementById('ids').value;
	
		document.getElementById(type).setAttribute('action',url+page+'?t='+ids);
		
		try {
			document.getElementById(type).submit();
		} catch(e) {
			alert("Si \u00E8 verificato un errore Javascript durante l'invio dei dati\n\n" + e.description);
			return false;
		}
	}
  }
}

// Funzione che si occupa di lanciare la form di RICERCA AVANZATA
function advancedSearch() {
	ean = document.getElementById('adv_ean').value;
	titolo = document.getElementById('adv_titolo').value;
	editore = document.getElementById('adv_editore').value;
	collana = document.getElementById('adv_collana').value;
	autore = document.getElementById('adv_autore').value;
	argomento = document.getElementById('adv_argomento').value;
	area = document.getElementById('adv_area').value;
	data = document.getElementById('adv_data').value;
	prezzomin = document.getElementById('adv_prezzomin').value;
	prezzomax = document.getElementById('adv_prezzomax').value;
	
	ids = document.getElementById('ids').value;
	url = document.getElementById('url').value;
	
	if ((ean == "") && (titolo == "") && (editore == "") && (collana == "") && (autore == "") && (argomento == "") && (area == "") && (data == "") && (prezzomin == "") && (prezzomax == ""))
		alert("Attenzione. Non hai indicato alcun criterio di ricerca avanzata.")
	else {
		
		if (area == "")
			page = "avanzata-ricerca.php";
		else if (area == "S")
			page = "avanzata-superofferte.php";
		else if (area == "R")
			page = "avanzata-remainders.php";
		else if (area == "C")
			page = "avanzata-remainders-consigliati.php";
		else if (area == "L")
			page = "avanzata-libri.php";
		else if (area == "P")
			page = "avanzata-pacchi-di-libri.php";
		
		document.getElementById('avanzata_ricerca').setAttribute('action',url+page+"?t="+ids);
		
		try {
			document.getElementById('avanzata_ricerca').submit();
		} catch(e) {
			alert("Si \u00E8 verificato un errore Javascript durante l'invio dei dati\n\n" + e.description);
			return false;
		}
	}
}

// Funzione che cambia il colore del bordo dell'input search
function colorSearch(block, type, color, ie) {
	
	// Controllo per browser Explorer
	if (ie == 'T')
		className = "className";
	else 
		className = "class";
	
	// Header
	if (block == 'header') {
		if (type == 'f')
			document.getElementById('search_focus').value = 't';
		else if (type == 'b')
			document.getElementById('search_focus').value = 'f';
		else if (type == 'm')
			document.getElementById('search_over').value = 't';
		else if (type == 'o')
			document.getElementById('search_over').value = 'f';
		
		if (color == 'b') {
			l = 'search_left_blu';
			c = 'search_center_blu';
			r = 'search_right_blu';
		} else if ((color == 'g') && (document.getElementById('search_focus').value == 'f') && (document.getElementById('search_over').value == 'f'))  {
			l = 'search_left';
			c = 'search_center';
			r = 'search_right';
		} 
		
		document.getElementById('search_left').setAttribute(className, l);
		document.getElementById('search_center').setAttribute(className, c);
		document.getElementById('search_right').setAttribute(className, r);
	
	// Footer
	} else if (block == 'footer') {
		if (type == 'f')
			document.getElementById('search_focus_footer').value = 't';
		else if (type == 'b')
			document.getElementById('search_focus_footer').value = 'f';
		else if (type == 'm')
			document.getElementById('search_over_footer').value = 't';
		else if (type == 'o')
			document.getElementById('search_over_footer').value = 'f';
		
		if (color == 'b') {
			l = 'search_left_footer_blu';
			c = 'search_center_footer_blu';
			r = 'search_right_footer_blu';
		} else if ((color == 'g') && (document.getElementById('search_focus_footer').value == 'f') && (document.getElementById('search_over_footer').value == 'f'))  {
			l = 'search_left_footer';
			c = 'search_center_footer';
			r = 'search_right_footer';
		} 
		
		document.getElementById('search_left_footer').setAttribute(className, l);
		document.getElementById('search_center_footer').setAttribute(className, c);
		document.getElementById('search_right_footer').setAttribute(className, r);
	}
}
	

// Funzione che cambia il colore del bordo della select list
function colorSearchType(color, block, browser) {
	
	// Controllo per browser Explorer
	if (browser == 'IE')
		className = "className";
	else 
		className = "class";
	
	// Header
	if (block == 'header') {
		
		b = 'search_type_blu';
		g = 'search_type';
	
		if (color == 'b')
			document.getElementById('search_type_container').setAttribute(className, b);
		else if (color == 'g')
			document.getElementById('search_type_container').setAttribute(className, g);
	
	// Footer
	} else if (block == 'footer') {
		b = 'search_type_footer_blu';
		g = 'search_type_footer';
			
		
		if (color == 'b')
			document.getElementById('search_type_container_footer').setAttribute(className, b);
		else if (color == 'g')
			document.getElementById('search_type_container_footer').setAttribute(className, g);
	}
}

// Funzione che setta correttamente le variabili di sessione
function callSetSession(handler,params) {
	path = document.getElementById('url').value;
	myRequest = CreateXmlHttpReq(handler);
	myRequest.open("POST", path+"functions/session.php", true);
	myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	myRequest.setRequestHeader("Content-length", params.length);
	myRequest.setRequestHeader("Connection", "close");
	myRequest.send(params);
}

function handlerSession(){
	 if (myRequest.readyState == 4 && myRequest.status == 200) {
		var r = myRequest.responseText;

		if (r != "") {
			if (r.indexOf('gotoscheda') != -1) {
				var subdir = r.substr(r.indexOf("****")+4, 1);
				if (subdir == 'L')
					dir = 'libri';
				else if (subdir == 'R')
					dir = 'remainders';
				else if (subdir == 'S')
					dir = 'superofferte';
				else if (subdir == 'P')
					dir = 'pacchi-di-libri';
					
				var namepage = r.substring(r.indexOf("&&&&")+4, r.indexOf('$$$$'));
				var idoggetto = r.substr(r.indexOf("$$$$")+4, 13);	
				var autore = r.substr(r.indexOf(">>>>")+4);
				
				
				var url = document.getElementById('url').value;
				var ids = document.getElementById('ids').value;
				window.location.href = url+dir+"/"+idoggetto+"/"+autore+"/"+namepage+'.php?t='+ids;
			} else if (r.indexOf('clearcarrello') != -1) {

				redirect = r.substr(13, 1);
				if (redirect == 'N')
					page = 'index.php';
				else if (redirect == '1')
					page = 'ordine.php';
				else if (redirect == '2')
					page = 'i-miei-dati.php';
				else if (redirect == '3')
					page = 'gestione_ordini.php';
				var url = document.getElementById('url').value;
				var ids = document.getElementById('ids').value;
				window.parent.location.href = url+page+'?t='+ids;

			} else if (r.indexOf('updatecarrello') != -1) {
				var r_arr = r.split(',');
				return r_arr[1];
			} else if (r.indexOf('loadcarrello') != -1){
				var r_arr = this.responseText.split(',');
				var basket_qty = r_arr[1];
				var basket_view = parent.document.getElementById('carrello_qty');
				basket_view.innerHTML = basket_qty;
				parent.myLightWindow.deactivate();
			}else {
				switch (r) {
					case 'carrello':
						var url = document.getElementById('url').value;
						var ids = document.getElementById('ids').value;
						window.location.href = url+'carrello.php?t='+ids;
						break;	
					
					case 'logout':
						window.location.href = window.location;
						break;
					
					case 'contatti':
						document.getElementById('form_contatti').submit();
						break;
					
					case 'registrati':
						document.getElementById('form_registrati').submit();
						break;
						
					case 'b2b':
						document.getElementById('form_b2b').submit();
						break;
						
					case 'delcarrello':
						if (document.getElementById('label_empty') != null) {
							Effect.Fade('label_empty',{duration: 1.2});
						}
						break;	
					
					case 'pagacontrassegno':
						var url = document.getElementById('url').value;
						var ids = document.getElementById('ids').value;
						window.location.href = url+'conferma_ordine.php?t='+ids;
						break;
					
					case 'loadcarrello':
						var url = document.getElementById('url').value;
						var ids = document.getElementById('ids').value;
						window.parent.location.href = url+'carrello.php'+'?t='+ids;
						break;
					
					case 'increaseordine':
						var url = document.getElementById('url').value;
						var ids = document.getElementById('ids').value;
						window.parent.location.href = url+'carrello.php'+'?t='+ids;
						break;
					
					case 'nuovoordine':
						var url = document.getElementById('url').value;
						var ids = document.getElementById('ids').value;
						window.parent.location.href = url+'carrello.php'+'?t='+ids;
						break;
						
					default:
						break;
				}
			}
		}
	 }
}

// Funzione che nasconde le celle della tabella Menù Argomenti Libri
function hideArgomentiLibri(max_id) {
	for (i=1; i<=max_id; i++) 
		if (document.getElementById('td_arg_libro_'+i) != null)
			document.getElementById('td_arg_libro_'+i).style.display = 'none';
}
	
	
// Funzione che apre a scorrimento il div degli argomenti Libri
function viewMenuArgomentiLibri(max_id) {
	var show_argomenti_libri = document.getElementById('show_argomenti_libri');
	
	if (show_argomenti_libri.value == "n") {
		for (i=1; i<=max_id; i++) {
			if (document.getElementById('td_arg_libro_'+i) != null) {
				document.getElementById('td_arg_libro_'+i).style.display = 'table-cell';
				new Effect.BlindDown('arg_libro_'+i, { duration: 0.9 });
			}
		}
		var vedi_libri = document.getElementById('vedi_altro_libri').innerHTML;
		vedi_libri = vedi_libri.replace('Visualizza altri', 'Nascondi');
		document.getElementById('vedi_altro_libri').innerHTML = vedi_libri;
		
		document.getElementById('show_argomenti_libri').value = "s";
	} else if (show_argomenti_libri.value == "s") {
		for (i=1; i<=max_id; i++)
			if (document.getElementById('td_arg_libro_'+i) != null) 
				new Effect.BlindUp('arg_libro_'+i, { duration: 0.9 });
		
		setTimeout("hideArgomentiLibri("+max_id+")", 1000);		
		
		var vedi_libri = document.getElementById('vedi_altro_libri').innerHTML;
		vedi_libri = vedi_libri.replace('Nascondi', 'Visualizza altri');
		document.getElementById('vedi_altro_libri').innerHTML = vedi_libri;	
		document.getElementById('show_argomenti_libri').value = "n";
	}
		
	// Aggiorno la variabile di sessione
	params = "page=home&item=show_argomenti_libri&value="+document.getElementById('show_argomenti_libri').value;
	callSetSession(handlerSession, params);
}


// Funzione che nasconde le celle della tabella Menù Argomenti Dvd
function hideArgomentiDvd(max_id) {
	for (i=1; i<=max_id; i++) 
		if (document.getElementById('td_arg_dvd_'+i) != null)
			document.getElementById('td_arg_dvd_'+i).style.display = 'none';
}


// Funzione che apre a scorrimento il div degli argomenti Dvd
function viewMenuArgomentiDvd(max_id) {
	var show_argomenti_dvd= document.getElementById('show_argomenti_dvd');
	
	if (show_argomenti_dvd.value == "n") {
		for (i=1; i<=max_id; i++) {
			if (document.getElementById('td_arg_dvd_'+i) != null) {
				document.getElementById('td_arg_dvd_'+i).style.display = 'table-cell';
				new Effect.BlindDown('arg_dvd_'+i, { duration: 0.9 });
			}
		}
		var vedi_dvd = document.getElementById('vedi_altro_dvd').innerHTML;
		vedi_dvd = vedi_dvd.replace('Visualizza altri', 'Nascondi');
		document.getElementById('vedi_altro_dvd').innerHTML = vedi_dvd;
		
		document.getElementById('show_argomenti_dvd').value = "s";
	} else if (show_argomenti_dvd.value == "s") {
		for (i=1; i<=max_id; i++)
			if (document.getElementById('td_arg_dvd_'+i) != null) 
				new Effect.BlindUp('arg_dvd_'+i, { duration: 0.9 });
		
		setTimeout("hideArgomentiDvd("+max_id+")", 1000);		
		
		var vedi_dvd = document.getElementById('vedi_altro_dvd').innerHTML;
		vedi_dvd = vedi_dvd.replace('Nascondi', 'Visualizza altri');
		document.getElementById('vedi_altro_dvd').innerHTML = vedi_dvd;	
		document.getElementById('show_argomenti_dvd').value = "n";
	}
	
	// Aggiorno la variabile di sessione
	params = "page=home&item=show_argomenti_dvd&value="+document.getElementById('show_argomenti_dvd').value;
	callSetSession(handlerSession, params)	
}

// Funzione che visualizza/nasconde il div relativo alle info sulle spedizioni
function viewSpedizioni() {
	ctrl = document.getElementById('flag');
	if (ctrl.value == "v") {
		new Effect.BlindUp('blocco');
		ctrl.setAttribute("value", "h");
	} else {
		new Effect.BlindDown('blocco');
		ctrl.setAttribute("value", "v");
	}
}


function viewRegistra() {
		ctrl = document.getElementById('flag');
		document.getElementById('blocco-info1').style.display = 'block';
		document.getElementById('blocco-info2').style.display = 'none';
		ctrl.setAttribute("value", "h");
		document.getElementById('tipo_elemento').innerHTML = 'PRIVATO';
		document.getElementById('pulsante_reg_privato').style.display = 'none';
		document.getElementById('pulsante_reg_azienda').style.display = 'block';
}

function viewRegistra2() {
		ctrl = document.getElementById('flag');
		document.getElementById('blocco-info1').style.display = 'none';
		document.getElementById('blocco-info2').style.display = 'block';
		ctrl.setAttribute("value", "v");
		document.getElementById('tipo_elemento').innerHTML = 'AZIENDA';
		document.getElementById('pulsante_reg_azienda').style.display = 'none';
		document.getElementById('pulsante_reg_privato').style.display = 'block';	
}


// Funzione che lancia la richiesta per costi
function SearchCosti(nazione){
	params = "nazione="+escape(nazione);
  	callSearchCosti(handlerCosti,params)	
}

function callSearchCosti(handler,params) {
	url = document.getElementById('url').value;
	myRequest = CreateXmlHttpReq(handler);
	myRequest.open("POST", url+"functions/searchCosti.php", true);
	myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	myRequest.setRequestHeader("Content-length", params.length);
	myRequest.setRequestHeader("Connection", "close");
	myRequest.send(params);
}

function handlerCosti(){
	 if (myRequest.readyState == 4 && myRequest.status == 200) {
			var r = myRequest.responseText;
			document.getElementById('dettagli').innerHTML=r;
	 }
}


//Funzione per il recupero dei dati personali
function viewRecuperoDati() {
	ctrl = document.getElementById('flag_dati_personali');
	if (ctrl.value == "v") {
		new Effect.BlindUp('blocco_dati_personali');
		ctrl.setAttribute("value", "h");
	} else {
		new Effect.BlindDown('blocco_dati_personali');
		ctrl.setAttribute("value", "v");
		document.getElementById('email_recupero').value = "";
	}
}



// Funzione che effettua l'inserimento di un prodotto all'interno del carrello
function addToBasket(type, id, qta) {
	params = "page=carrello&item="+type+"&value="+id+"&qta="+qta;
	callSetSession(handlerSession, params);
}





// Funzione che forza la logout
function doLogout() {
	params = "page=dologout";
	callSetSession(handlerSession, params);
}


// Funzione che elimina gli elementi non più esistenti
function deleteElemsFromBasket(values) {
	// Aggiorno la variabile di sessione
	params = "page=delcarrello&value="+values;
	callSetSession(handlerSession, params);
}
	

// Funzione che nasconde il div di avvertimento di cambio prezzo
function priceChanged() {
	if (document.getElementById('label_empty_c') != null) {
		Effect.Fade('label_empty_c',{duration: 1.2});
	}
}

// Funzione che nasconde il div di avvertimento di disponibilità limitata
function tooMuchQta() {
	if (document.getElementById('label_empty_m') != null) {
		Effect.Fade('label_empty_m',{duration: 1.2});
	}
}


// Funzione che replica l'effetto Blink
function blinkText(color, id) {	
	if (document.getElementById(id) != undefined) {
		var text = document.getElementById(id);
		if (text.style.color == "rgb(255, 255, 255)")
			text.style.color = color;
		else
			text.style.color = "#ffffff";
	}
}


// Funzione che invia la mail dei contatti
function sendContatti() {
	params = "page=contatti";
	callSetSession(handlerSession, params);
}

//Funzione che invia la mail dei contatti
function sendRegistrati() {
	params = "page=registrati";
	callSetSession(handlerSession, params);
}

// Funzione che invia la mail del B2B
function sendB2B() {
	params = "page=b2b";
	callSetSession(handlerSession, params);
}


function viewLegendaOrdine() {
	ctrl = document.getElementById('flag_come');
	if (ctrl.value == "v") {
		new Effect.BlindUp('blocco');
		ctrl.setAttribute("value", "h");
	} else {
		new Effect.BlindDown('blocco');
		ctrl.setAttribute("value", "v");
	}
}

function viewLegendaCC() {
	ctrl = document.getElementById('flag_cc');
	if (ctrl.value == "v") {
		new Effect.BlindUp('blocco_cc');
		ctrl.setAttribute("value", "h");
	} else {
		new Effect.BlindDown('blocco_cc');
		ctrl.setAttribute("value", "v");
	}
}


function viewLegendaCO(type) {
	
	if (type == 1) {
		ctrl = document.getElementById('flag_come1');
		other = document.getElementById('flag_come2');
		blocco = 'blocco1';
		other_blocco = 'blocco2';
	} else if (type == 2) {
		ctrl = document.getElementById('flag_come2');
		other = document.getElementById('flag_come1');
		blocco = 'blocco2';
		other_blocco = 'blocco1';
	}
	
	if (ctrl.value == "v") {
		new Effect.BlindUp(blocco);
		ctrl.setAttribute("value", "h");
	} else {
		
		if (other.value == 'v') {
			new Effect.BlindUp(other_blocco);
			other.setAttribute("value", "h");
		}
		
		new Effect.BlindDown(blocco);
		ctrl.setAttribute("value", "v");
	}
}

function viewLegendaRegistra(type) {
	if (type == 'p') {
		ctrl = document.getElementById('flag_come_p');
		other = document.getElementById('flag_come_a');
		blocco = 'blocco_legenda_p';
		other_blocco = 'blocco_legenda_a';
	} else if (type == 'a') {
		ctrl = document.getElementById('flag_come_a');
		other = document.getElementById('flag_come_p');
		blocco = 'blocco_legenda_a';
		other_blocco = 'blocco_legenda_p';
	}
	
	if (ctrl.value == "v") {
		new Effect.BlindUp(blocco);
		ctrl.setAttribute("value", "h");
	} else {
		
		if (other.value == 'v') {
			new Effect.BlindUp(other_blocco);
			other.setAttribute("value", "h");
		}
		
		new Effect.BlindDown(blocco);
		ctrl.setAttribute("value", "v");
	}
}


function viewLegendaMieiDati() {
	ctrl = document.getElementById('flag_come');
	if (ctrl.value == "v") {
		new Effect.BlindUp('blocco_legenda');
		ctrl.setAttribute("value", "h");
	} else {
		new Effect.BlindDown('blocco_legenda');
		ctrl.setAttribute("value", "v");
	}
}

// Funzione che visualizza il pannello con i dati relativi alla Spedizione Bartolini
function checkSpedizione() {
	ctrl = document.getElementById('flag_spedizione');
	if (ctrl.value == "h") {
		new Effect.BlindDown('blocco_spedizione1');
		if (document.getElementById('blocco_spedizione2') != undefined)
			new Effect.BlindDown('blocco_spedizione2');
		ctrl.setAttribute("value", "v");
	} else if (ctrl.value == "v") {
		new Effect.BlindUp('blocco_spedizione1');
		if (document.getElementById('blocco_spedizione2') != undefined)
			new Effect.BlindUp('blocco_spedizione2');
		ctrl.setAttribute("value", "h");
	}
}

// Funzione che apre il popup con la richiesta di mantenere o meno il carrello
function openCarrello(url) {
	myLightWindow.activateWindow({
		href: url, 
		title: '',
		loadingAnimation: true,
		type: 'external',
		width: 400, 
		height: 300
	});
}

// Funzione che esegue i redirect dopo aver eseguito la login
function redirectLogin(carrello, redirect, url, ids) {
	if (carrello == 0) {
		if (redirect == 1) 
			window.location= url + 'ordine.php?t='+ids;
		else if (redirect == 2)
			window.location= url + 'i-miei-dati.php?t='+ids;
		else if (redirect == 3)
			window.location= url + 'gestione_ordini.php?t='+ids;
	} else if ((carrello == 1) && (redirect != "")) {
		url = url+'functions/saveCarrello.php?redirect='+redirect+'&ids='+ids;
		setTimeout('openCarrello(\''+url+'\')', 50);
	}
}



// Funzione che ripulisce la tabella di Appoggio Carrello
function clearCarrello(redirect) {
	params = "page=clearcarrello&value="+redirect;
	callSetSession(handlerSession, params);
}

// Funzione che ricarica gli elementi della tabella Appoggio Carrello
function loadCarrello(redirect) {
	params = "page=loadcarrello&value="+redirect;
	callSetSession(handlerSession, params);
}

// Funzione che permette di inserire nuovi prodotti nell'ordine
function increaseOrdine(num_ord) {
	params = "page=increaseordine&value="+num_ord;
	callSetSession(handlerSession, params);
}

/**
 * tagtip - http://www.tagtaxa.com/projects/tagtip/index.php
 * Per l'alert che l'oggetto è stato aggiunto al carrello.
 */

var Tagtip = Class.create({
	initialize: function(trigger, content, options) {
		this.options = $H({
			ajax: null,
			ajaxRefresh: true,
			align: 'topMiddle',
			hideDelay: .5,
         hideTrigger: 'mouseout',
			offsetx: 0,
			offsety: 8,
			parent: null,
			showDelay: .5,
         showTrigger: 'mouseover',
         style: 'default',
         target: null,
         title: null
      });
		this.options.update(options);

		this.ajax = this.options.get('ajax');
		this.ajaxRefresh = this.options.get('ajaxRefresh');
		this.align = this.options.get('align');
		this.appearEffect = null;
		this.container = null;
		this.hideEffect = null;
		this.hideDelay = this.options.get('hideDelay') * 1000;
		this.hideDelayTimer = null;
		this.hideTrigger = this.options.get('hideTrigger');
		this.offsetx = this.options.get('offsetx');
		this.offsety = this.options.get('offsety');
		this.parent = this.options.get('parent');
		this.showDelay = this.options.get('showDelay') * 1000;
		this.showDelayTimer = null;
		this.shown = false;
		this.showTrigger = this.options.get('showTrigger');
		this.style = this.options.get('style');
		this.target = this.options.get('target');

		if ($(content) != undefined)
         this.text = $(content).innerHTML;
      else
         this.text = content;
		this.tipFetched = false; // is tip content already fetched via ajax
		this.title = this.options.get('title');
		this.trigger = $(trigger);

		this.buildTip();
		this.addObservers();
  	},

  	buildTip: function() {
  		container = new Element('div', { 'class': 'tagtip ' + this.style });
  		content = new Element('div', { 'class': 'content' });

  		if (this.title) {
  			title = new Element('div', { 'class': 'title' });
  			title.update(this.title);
  			container.insert(title);
  		}

  		container.insert(content);
  		if (this.parent)
  			$(this.parent).insert(container);
  		else
  			document.body.insert(container);

  		this.container = container;
  		this.content = content;

  		this.container.setStyle({display: 'none'});

  		if (this.text) {
  			this.content.update(this.text);
  		} else {
  			this.content.update('');
  		}
  	},

	addObservers: function() {
		this.trigger.observe(this.showTrigger, this.showDelayed.bindAsEventListener(this, "trigger"));
		this.trigger.observe(this.hideTrigger, this.hideDelayed.bindAsEventListener(this));
		this.container.observe(this.showTrigger, this.showDelayed.bindAsEventListener(this));
		this.container.observe(this.hideTrigger, this.hideDelayed.bindAsEventListener(this));
	},

	showDelayed: function(event, whoCalled) {
  		if (this.hideDelayTimer) clearTimeout(this.hideDelayTimer);
  		clearTimeout(this.showDelayTimer);
    	if (this.shown) {
			if (whoCalled=="trigger")
				this.hideDelayed();
		} else
			this.showDelayTimer = setTimeout(this.showMenu.bind(this), this.showDelay);
	},

  	showMenu: function(event) {
  		if (this.hideEffect)
  			this.hideEffect.cancel();

		// reset position
		this.container.setStyle({
			position: "absolute",
		   display: 'block'
		});

		// set target
		if (this.target) target = this.target;
		else target = this.trigger;

		// align
		if (this.align=='topLeft') {
			tipPosX = 0;
			tipPosY = -(this.container.getHeight() + this.offsety);
		}
		if (this.align=='topMiddle') {
			tipPosX =  this.trigger.getWidth()/2 - this.container.getWidth()/2;
			tipPosY = -(this.container.getHeight() + this.offsety);
		}
		if (this.align=='topRight') {
			tipPosX = this.trigger.getWidth()/2 - this.container.getWidth()/2 + (this.trigger.getWidth()/2 - this.container.getWidth()/2);
			tipPosY = -(this.container.getHeight() + this.offsety);
		}
		if (this.align=='rightTop') {
			tipPosX =  this.trigger.getWidth() + this.offsetx;
			tipPosY = this.trigger.getHeight()/2 - this.container.getHeight()/2 - (this.trigger.getHeight()/2 - this.container.getHeight()/2);
		}
		if (this.align=='rightMiddle') {
			tipPosX =  this.trigger.getWidth() + this.offsetx;
			tipPosY = this.trigger.getHeight()/2 - this.container.getHeight()/2;
		}
		if (this.align=='rightBottom') {
			tipPosX =  this.trigger.getWidth() + this.offsetx;
			tipPosY = this.trigger.getHeight()/2 - this.container.getHeight()/2 + (this.trigger.getHeight()/2 - this.container.getHeight()/2);
		}
		if (this.align=='bottomLeft') {
			tipPosX = 0 + this.offsetx;
			tipPosY = this.trigger.getHeight() + this.offsety;
		}
		if (this.align=='bottomMiddle') {
			tipPosX =  this.trigger.getWidth()/2 - this.container.getWidth()/2 + this.offsetx;
			tipPosY = this.trigger.getHeight() + this.offsety;
		}
		if (this.align=='bottomRight') {
			tipPosX = this.trigger.getWidth()/2 - this.container.getWidth()/2 + (this.trigger.getWidth()/2 - this.container.getWidth()/2);
			tipPosY = this.trigger.getHeight() + this.offsety;
		}
		if (this.align=='leftTop') {
			tipPosX =  -this.container.getWidth() + this.offsetx;
			tipPosY = this.trigger.getHeight()/2 - this.container.getHeight()/2 - (this.trigger.getHeight()/2 - this.container.getHeight()/2);
		}
		if (this.align=='leftMiddle') {
			tipPosX =  -this.container.getWidth() + this.offsetx;
			tipPosY = this.trigger.getHeight()/2 - this.container.getHeight()/2;
		}
		if (this.align=='leftBottom') {
			tipPosX =  -this.container.getWidth() + this.offsetx;
			tipPosY = this.trigger.getHeight()/2 - this.container.getHeight()/2 + (this.trigger.getHeight()/2 - this.container.getHeight()/2);
		}

		this.container.clonePosition(target, {
			setWidth:false,
			setHeight:false,
			offsetLeft: tipPosX,
			offsetTop: tipPosY
		});

		this.appearEffect = new Effect.Appear(this.container, {
			duration: 0,
			from: 0,
			to: 1.0,
			transition: Effect.Transitions.sinoidal,
			queue: {scope: 'fadeovers', position: 'end'},
			afterFinish: function() {
				this.beingShown = false;
				this.shown = true;
				// Here different things when tip is shown, ajax content, etc.
				if (this.ajax && !this.tipFetched)
					this.getContent();
				this.trigger.fire("tagtip:shown", { tipid: this.container.identify() });
			}.bind(this)
		});
      return false;
  	},

  	hideMenu: function(event) {
  		if (this.appearEffect)
  			this.appearEffect.cancel();
  		this.hideDelayTimer = null;
		this.hideEffect = Effect.DropOut(this.container, {
			afterFinish: function() {
         	this.shown = false;
         	this.trigger.fire("tagtip:hidden", { tipid: this.container.identify() });
         }.bind(this)
     	});
		return false;
  	},

  	hideDelayed: function(event) {
  		clearTimeout(this.showDelayTimer);
  		if (this.hideDelayTimer) clearTimeout(this.hideDelayTimer);
  		this.hideDelayTimer = setTimeout(this.hideMenu.bind(this), this.hideDelay);
  	},

  	setContent: function(text) {
  		this.content.update(text);
  	},

  	getContent: function() {
		new Ajax.Request(this.ajax.url, {
				method: this.ajax.method,
				parameters: this.ajax.parameters,
				onCreate: function() {
					this.content.update('...');
				}.bind(this),
				onComplete: this.ajax.onComplete,
				onSuccess: function(transport) {
    				this.content.update(transport.responseText);
    				if (!this.ajaxRefresh)
    					this.tipFetched = true;
				}.bind(this)
			}
  		);
  	}
});

