/**
 * @author dbc
 */

// commenti
$(document).ready(function () {

	if ($('#messagelist').length > 0) { // solo se esiste nella pagina l'elemento message list
		html = '<div id="messageform">'
		html += 'Nome  <br /> <input maxlength="50" type="text" id="nome" name="nome"><br />';
		html += 'E mail ( non verr&agrave; pubblicata )  <br /><input maxlength="50" type="text" id="email" name="email"><br />';
		html += 'Messaggio ( max 500 caratteri ) <br /> <textarea maxlength="500" id="message" name="message"></textarea><br />';
		html += '<i>( La redazione si riserva il diritto di rimuovere i messaggi non  ritenuti consoni alle finalit&agrave; del sito )</i>';
		html += '<br /><br /><a style="float:right;" href="javascript:addcomment();"><span class="label">INVIA</span></a><img id="wait" style="float:left;visibility:hidden;" src="../../../../images/gifs/wait.gif">';
		html += '<span style="float:left;color:red;" id="tips"></span> <br /></div>';
		//	html += '<div style="clear:both;margin-top:5px;" id="messagelist"></div>'
		$("#uc").html(html);
		getcomments();
	}
	if ($('#homemessagelist').length > 0){
		gethomecomments();	
	}
	if ($('#comment_history').length > 0){
		getcommentshistory();	
	}


/*
	var p = $("#image_container");
	var tot = 0;
	$('div.thumbnail').each(function(index) { tot++; });
	$('#image_container').width( $('div.thumbnail').width() * (tot + 1)) ; 

*/	
});


function addcomment()
{
	var error = false;
	$('#nome, #message, #email').css('border-color','gray');
	$('#tips').html('');
	
	// validazione dei campi
	if (jQuery.trim($('#nome').val()) == '') {
		error = true;
		$('#nome').css('border-color','red')
	}
	if ( jQuery.trim($('#email').val()) == '' )  {
		error = true;
		$('#email').css('border-color','red')
	}
	if ( jQuery.trim($('#message').val()) == '' )  {
		error = true;
		$('#message').css('border-color','red')
	}
	if (error) {
		$('#tips').html('Compilare i dati mancanti.');
		return;
	}
	
	$('#wait').css('visibility','visible');
	
	var query = $('form#mform').serialize();
	$.ajax({
     type: "POST",
     url: "/php_files/set_comment.php",
	 data: query,
     success: function(html) {
	 	// sbianco i campi
		$('#nome').val('');
		$('#email').val('');
		$('#message').val('');
		// ricarico i messaggi
		getcomments();

		$('#wait').css('visibility','hidden');
		$('#tips').html('Il tuo commento &egrave; stato pubblicato. Grazie per il contributo!');
	 }
	 });
}

function getcomments()
{
	id = $('#id_elemento').val();
	$.ajax({
     type: "POST",
     url: "/php_files/get_comments.php",
	 data: "id="+id,
     success: function(html) {
	 	$('#messagelist').html(html);
	 }
	 });
}

function gethomecomments()
{
	$.ajax({
     type: "POST",
     url: "/php_files/get_home_comments.php",
     success: function(html) {
	 	$('#homemessagelist').html(html);
	 }
	 });
}

function getcommentshistory()
{
	$.ajax({
     type: "POST",
     url: "/php_files/get_history_comments.php",
     success: function(html) {
	 	$('#comment_history').html(html);
	 }
	 });
}

function hit(banner_id)
{
	$.ajax({
     type: "POST",
     url: "/hit.php",
	 data: "id="+banner_id,
     success: function(html) {
	 }
	 });
}

/* form di registrazione */
function register()
{
	var error = '';
	var standard = 'solid 1px gray';
	// validazione dei campi
	var n = $('#join_form input:text[name=name]').val()
	$('#join_form input:text[name=name]').css('border',standard)
	
	var surname = $('#join_form input:text[name=surname]').val()
	$('#join_form input:text[name=surname]').css('border',standard)

	var email = $('#join_form input:text[name=email]').val()
	$('#join_form input:text[name=email]').css('border',standard)


	var pwd = $('#join_form input:password[name=password]').val()
	$('#join_form input:password[name=password]').css('border',standard)

	var pwd1 = $('#join_form input:password[name=password_repeat]').val()
	$('#join_form input:password[name=password_repeat]').css('border',standard)

	var nl = $('#join_form input:checkbox[name=newsletter]:checked').val()
	
	if (n.length == 0) {
		$('#join_form input:text[name=name]').css('border','solid 2px red')
		error += "Compilare Nome<br />";
	}
	if (surname.length == 0) {
		error += "Compilare Cognome<br />";
		$('#join_form input:text[name=surname]').css('border','solid 2px red')
	}
	
	if(email.length == 0){
		error += "Compilare Indirizzo Email<br />";
		$('#join_form input:text[name=email]').css('border','solid 2px red')
	} 

	if (pwd.length == 0) {
		error += "Compilare Password<br />";
		$('#join_form input:password[name=password]').css('border', 'solid 2px red')
	}
	else 
		if (pwd.length < 6) {
			error += "La lunghezza della Password deve essere di almeno 6 caratteri<br />";
			$('#join_form input:password[name=password]').css('border', 'solid 2px red')
		}
		else 
			if (pwd.length > 10) {
				error += "La lunghezza della Password deve essere al massimo di 10 caratteri<br />";
				$('#join_form input:password[name=password]').css('border', 'solid 2px red')
			}
			else 
				if (pwd1.length == 0) {
					error += "Compilare Ripeti Password<br />";
					$('#join_form input:password[name=password_repeat]').css('border', 'solid 2px red')
				}
				else 
					if (pwd != pwd1) {
						error += "I valori inseriti in Password e Ripeti Password sono diversi<br />";
						$('#join_form input:password[name=password_repeat]').css('border', 'solid 2px red')
					}

	$('#error_msg').html(error)
	
	// invio richiesta
	if (error.length == 0) {
		var query = $('form#join_form').serialize();
		$('img#wait_img').css('visibility','visible');
		$.ajax({
			type: "POST",
			url: "/register.php",
			data: query,
			success: function(html){
				if (html == 'OK') {
					$('div#registration_form').html('<div style="text-align:center;font-weight:bold;margin-top:120px;font-size:18pt;">Grazie per esserti registrato a Waltellina.com.</div>');
				} else {
					$('#error_msg').html(html)
				}
				$('img#wait_img').css('visibility','hidden');
			}
		});
	}
	
}


/* menu jquery */
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open()
{  jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $(this).find('ul').css('visibility', 'visible');}

function jsddm_close()
{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

function jsddm_timer()
{  closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}

$(document).ready(function()
{  $('#jsddm > li').bind('mouseover', jsddm_open)
   $('#jsddm > li').bind('mouseout',  jsddm_timer)});

document.onclick = jsddm_close;



// utilities
var continua_flag = true;
var older_flag = true;
function open_close( sch , link , msg , flag)
{
	if (flag)
	{
		$(sch).show('blind',{},1000);
		$(link).html('Chiudi');
		flag = false;
	} else {
		$(sch).hide(1000);
		$(link).html(msg);
		flag = true;
	}
	return flag;
}
function continua(){
	continua_flag = open_close('#scheda_long','#schedacmd a', 'Continua', continua_flag);
}
function older()
{
	older_flag = open_close('#older_long','#oldercmd a', 'Visualizza i messaggi pi&ugrave; vecchi&nbsp;', older_flag);
}

// funzioni galleria
var page = 0;
var photo_per_page = 4;
var element;
var start =  0;
var stop;
var speed = 20;


function scroll(next)
{
	var p = $("#image_container");
	var tot_photo = 0;
	$('div.thumbnail').each(function(index) { tot_photo++; });


	tot_page = Math.floor(tot_photo / photo_per_page) ;
	rest_photo = ( tot_photo % photo_per_page );
	if (( tot_photo % photo_per_page ) > 0 ) tot_page++;
	photo_width = ( $('div.thumbnail').width() + 10)
	page_width = photo_width * photo_per_page;
	
	
	/*
	 * start e stop sono gli offset di partenza e di arrivo del div container
	 */
	
	if ( next )
		page++;
	else if ( page > 0)
		page--;

	if (page == tot_page ) page = tot_page -1;
	
	stop =  page * page_width;
	
	/*
	 * ultima pagina, si può avere una pagina solo parziale
	 * be aware le page iniziano da 0 finiscono e ( tot_page -1 )
	 */
	if (page == ( tot_page - 1) && rest_photo > 0) {
		stop -= ( photo_per_page - rest_photo ) * photo_width;
	}
	

//	alert('tot_page:'+tot_page+' mod:'+rest_photo)
//	alert('page:'+page+' start:'+start+' stop:'+stop+' width:'+page_width)

	element = p;

	if (next) {
		slideleft();
	}
	else {
		slideright();
	}
}

function slideleft( )
{
	if (start < stop)  {
		start += 20;
		element.css('left','-'+start+'px');
		setTimeout( 'slideleft( )' , speed );
	}
}
function slideright( )
{
	if (start > stop)  {
		start -= 20;
		element.css('left','-'+start+'px');
		
		setTimeout( 'slideright( )' , speed );
	}
}



/* stampa pdf */
// Controlla gli spazi vuoti nella compilazione dei campi di testo
function trim(stringa){
	while(stringa.substring(0, 1) == " ")
		stringa = stringa.substring(1, stringa.length);
	
	while(stringa.substring(stringa.length-1, stringa.length) == " ")
		stringa = stringa.substring(0, stringa.length-1);
	
	return replace('"', '\'', stringa);
}

// Esegue un "str_replace"
function replace(f, r, s){
	var ra = r instanceof Array, sa = s instanceof Array, l = (f = [].concat(f)).length, r = [].concat(r), i = (s = [].concat(s)).length;
	while(j = 0, i--)
	while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j < l);
	
	return sa ? s : s[0];
}

// Conta gli elementi per classe
function getElementsByClass(searchClass, node, tag){
	var classElements = new Array();
	
	if(node == null)
		node = document;
	
	if(tag == null)
		tag = '*';
	
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	
	for(i=0, j=0; i<elsLen; i++){
		if(pattern.test(els[i].className)){
			classElements[j] = els[i];
			j++;
		}
	}
	
	return classElements;
}

// Crea e submitta la form per l'invio dei dati all'FPDF
function creaPDF()
{
	addFPDF($('#fpdf_title').text(), 
			$('#fpdf_subtitle').text(), 
			$('#fpdf_subtitle2').text(), 
			$('#fpdf_text').text()+$('#scheda_long').text(), 
			$('#fpdf_contatti').text(), 
			getElementsByClass('fpdf_img'));
}



function addFPDF(title, subtitle, subtitle2, text, tabella, img){
	top.consoleRef = window.open('', 'fpdf');
	top.consoleRef.document.writeln('<html>');
	top.consoleRef.document.writeln('<head>');
	top.consoleRef.document.writeln('<title>Valtellina Valchiavenna: manifestazioni, escursioni, alpinismo, parchi e musei, prodotti tipici</title>');
	top.consoleRef.document.writeln('</head>');
	top.consoleRef.document.writeln('<body onLoad="document.fpdf.submit(); self.focus();">');
	top.consoleRef.document.writeln('<form name="fpdf" method="post" action="../../../../Library/fpdf/index.php">');
	top.consoleRef.document.writeln('<input type="hidden" name="title" value="' + trim(title) + '">');
	top.consoleRef.document.writeln('<input type="hidden" name="subtitle" value="' + trim(subtitle) + '">');
	top.consoleRef.document.writeln('<input type="hidden" name="subtitle2" value="' + trim(subtitle2) + '">');
	top.consoleRef.document.writeln('<input type="hidden" name="text" value="' + trim(text) + '">');
	
/*
	if(tabella.length > 0){
		var arr_tbl = new Array();
		
		for(var i=0; i<tabella.length; i++)
			arr_tbl[i] = tabella[i].innerHTML;
		
		var string_tbl = arr_tbl.toString();
		
		top.consoleRef.document.writeln('<input type="hidden" name="tbl" value="' + trim(string_tbl) + '">');
	}

*/	
	top.consoleRef.document.writeln('<input type="hidden" name="tbl" value="' + trim(tabella) + '">');
	
/*
	if(img.length > 0){
		var arr_img = new Array();
		
		for(var i=0; i<img.length; i++)
			arr_img[i] = img[i].src;
		
		var string_img = arr_img.toString();
		top.consoleRef.document.writeln('<input type="hidden" name="img" value="' + trim(string_img) + '">');
	}

*/	
	 $("img.fpdf_img").each(function(){
		top.consoleRef.document.writeln('<input type="hidden" name="img" value="' + trim($(this).attr('src')) + '">');
      });

	top.consoleRef.document.writeln('</form>');
	top.consoleRef.document.writeln('</body>');
	top.consoleRef.document.writeln('</html>');
 	top.consoleRef.document.close();
}

function sendimage(title)
{
	document.location.href= "mailto:info@waltellina.com?subject=Immagini "+title;
}

function logbox( )
{
	var waitimg = '<span width="20"><img width="18" heigth="18" style="vertical-align:middle;visibility:hidden;" id="log_wait_img" src="/images/wait.gif"></span>';
	$.ajax({
		type: "POST",
		url: "/islogged.php",
		success: function(html){
			if (html.substring(0,2) == 'OK') {
				$('#logbox').html('<span style="float:right;font-weight:bold;">Ciao '+html.substring(2)+' | <a href="javascript:void(0)" onclick="logout()"> Esci</a>'+waitimg+'</span>')
			} else {
				$('#logbox').html('<span style="float:right;font-weight:bold;"><input id="logemail" onblur="leavefield(this.id)" onfocus="typefield(this.id)" type="text" value="email" style="color:#aaa;border:solid 1px gray;width:90px;"> <input onblur="leavefield(this.id, true)" onfocus="typefield(this.id, true);" type="text" value="password" id="logpwd" style="color:#aaa;width:90px;border:solid 1px gray"> <a href="javascript:void(0)" onclick="login()"> Entra</a> | <a href="/pages/register.html">Registrati</a></span>'+waitimg+'</span>')
			}
		}
	});
}
function typefield(f,pwd)
{
	if(pwd != undefined && pwd)
	{
		$('#'+f)[0].type = 'password';
	}
	if ($('#'+f).val() == $('#'+f)[0].defaultValue) {
		$('#'+f).val('');
		$('#'+f).css('color','#626262');
	}
}
function leavefield(f,pwd)
{
	if ($('#'+f).val() == '') {
		$('#'+f).val($('#'+f)[0].defaultValue);
		$('#'+f).css('color','#aaa');
		if(pwd!=undefined && pwd)
		{
			$('#'+f)[0].type = 'text';
		}
	}
}

function login(){
	$('img#log_wait_img').css('visibility','visible');
	var query = ({ user : $('#logemail').val() , password : $('#logpwd').val() });
	$.ajax({
		type: "POST",
		url: "/login.php",
		data: query,
		success: function(html){
			if (html == 'OK') {
				logbox();
			} else {
				alert('Indirizzo email o password errata!');
			}
			$('img#log_wait_img').css('visibility','hidden');
		}
	});
}

function logout()
{
	$('img#log_wait_img').css('visibility','visible');
	$.ajax({
		type: "POST",
		url: "/logout.php",
		success: function(html){
			logbox();
			$('img#log_wait_img').css('visibility','hidden');
		}
	});
}
var cache_filename;
function download(filename)
{
$.ajax({
		type: "POST",
		url: "/islogged.php",
		success: function(html){
			if (html.substring(0,2) == 'OK') {
				window.location=filename;	
			} else {
				// display login
				cache_filename = filename;
				$( "#dialog-form" ).dialog('open');
			}
		}
	});	
}

/* BANNER UTILITIES */

var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 3;
	
function getRamdomString(){
	var r = "";
	for (var i = 0; i < string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		r += chars.substring(rnum, rnum + 1);
	}
	return r;
}

function getBannerScript( id , url , r , img , width , height )
{
	var a_url = '/redirect.php?id='+id+'&url='+escape(url);

	var banner_html = '';

	if ( img.substr( img.length - "swf".length) == "swf" )
	{

		banner_html = '<div id="flashcontent_'+r+'" align="center"></div> ' 
    		+'<script type="text/javascript"> '
      		+'var so = new SWFObject("'+img+'", "WBanner", "'+width+'", "'+height+'", "8", "#FFFFFF"); '
//      		+'so.addVariable("xmlFile", "dallastoria"); '
	  		+'so.addParam("wmode", "transparent"); '
      		+'so.addParam("quality", "high"); '
      		+'so.addParam("menu", "false"); '
      		+'so.addParam("loop", "false"); '
      		+'so.write("flashcontent_'+r+'"); '
  			+'</script> ';  

	} else {

		w = "";if (width != undefined) w = ' width="'+width+'" ';
		h = "";if (height != undefined) h = ' height="'+height+'" ';
		banner_html =  '<a href="' + a_url + '" id="randomurl_' + r + '" target="_blank"><img src="' + img + '" ' + w + ' ' + h + ' id="randomimage_' + r + '" border="0"></a>';

	}
	
	return banner_html;	
}



