// JavaScript Document
function showScore(){
var user_response=new Array();
correct_ans=new Array();
var score=0;
user_response[0]=document.my_form.tf0.value.toLowerCase();
correct_ans[0]="quando è o-zonestudio che te lo realizza";
user_response[1]=document.my_form.tf1.value.toLowerCase();
correct_ans[1]="350€";
user_response[2]=document.my_form.tf2.value.toLowerCase();
correct_ans[2]="0922412377";
user_response[3]=document.my_form.tf3.value.toLowerCase();
correct_ans[3]="o-zonestudio@o-zonestudio.com";
user_response[4]=document.my_form.tf4.value.toLowerCase();
correct_ans[4]="250€";
user_response[5]=document.my_form.tf5.value.toLowerCase();
correct_ans[5]="o-zonestudio";
user_response[6]=document.my_form.tf6.value.toLowerCase();
correct_ans[6]="ascoltare persone, parenti, amici x clientelismo";
user_response[7]=document.my_form.tf7.value.toLowerCase();
correct_ans[7]="informare bene il tuo possibile utente";
user_response[8]=document.my_form.tf8.value.toLowerCase();
correct_ans[8]="animazioni richmedia e informazione specializzata";
user_response[9]=document.my_form.tf9.value.toLowerCase();
correct_ans[9]="subito, in questo istante";
for(i=0;i<user_response.length;i++){
	if(user_response[i]==correct_ans[i]){
		score+=1;
	}
}
alert("Il tuo risultato è:"+score);
alert("La risposta corretta è :"+correct_ans);
}
/* -----------------------------------------------------------------------------
	Trackings
------------------------------------------------------------------------------*/
function trackFrame(track) {
	$('body').append('<iframe src="" style="display:none;"></iframe>');
}


/* -----------------------------------------------------------------------------
	Formulario / Controllo
------------------------------------------------------------------------------*/
function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email) || email.substr(-3)=='.co') {
		return false;
	}
	return true;
}

// Cambia lo stato di un elemento
function switchStatus(selecteur, status){
	if (status == 'n') {
		$(selecteur).parent('div').addClass('focus');
	}
	else
	{
		$(selecteur).parent('div').removeClass('focus');
	}
	$(selecteur).parent('div').children('span.n,span.o,span.dn').removeClass().addClass(status);
}


function countErrors(selector)
{
	var nbErrors = $(selector).find('span.n:visible').length;
	return nbErrors;
}

function blinkError(selector){
	$(selector).find('span.n:first').fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
}

/* -----------------------------------------------------------------------------
	Visualizzare / Nascondere
------------------------------------------------------------------------------*/
function openModal(href){
	$.get(href, function(data) {
		if ($.browser.msie && $.browser.version.substring(0,1) === '6') {$('div.firstDiv>div').not('#overlay-modal, #modalStroke').addClass('ie6hidden').hide();}
		$('html, body').animate({scrollTop: 0}, 800);
		$('div.firstDiv').prepend(data);
	});
}


function closeModal(f){
	$('#modalContent div.content').slideUp('normal', function() {
		// Animazioner completa.
		$('#modalStroke, #overlay-modal').remove();
		if ($.browser.msie && $.browser.version.substring(0,1) === '6') {$('div.firstDiv>div.ie6hidden').show();}
		if (typeof f == "function") {
			f();
		}
	});
}

function showLogin(){
	hideCities(function() {
		$('#login').animate({marginTop: "-25px"}, 300, function() {
			$('#login').css('display','none');
			$('#toptools').css('display','block').animate({marginTop: "0px"}, 700);
		});
	});
}

function hideLogin(f){
	if ($('#toptools:visible').size()==1) {
		$('#toptools').animate({marginTop: "-112px"}, 400, function() {
			$('#login').css('display','block');
			$('#toptools').css('display','none');
			$('#login').animate({marginTop: "0px"}, 300);
			if (typeof f == "function") {
				f();
			}
		});
	}
	else if (typeof f == "function") {
		f();
	}
}

function hideFbc(){
	$('A.openFbConnect').css('display','none');
}


function showCities(){
	hideLogin(function() {
		var thisHeight = $('#showCities').height();
		$('#showCities').css({
			'margin-top' : '-'+thisHeight+'px',
			'display' : 'block'
		}).animate({marginTop: "0px"}, 300);
	});
}

function hideCities(f){
	var thisHeight = $('#showCities').height();
	$('#showCities').animate({marginTop: '-'+thisHeight+'px'}, 500, function() {
		$('#showCities').css('display','none');
	});
	if (typeof f == "function") {
		f();
	}
}
/* -----------------------------------------------------------------------------
	Cookies
------------------------------------------------------------------------------*/
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
	c_start=document.cookie.indexOf(c_name + "=");
	if (c_start!=-1)
	{
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

/* -----------------------------------------------------------------------------
	Conto alla rovescia
------------------------------------------------------------------------------*/
var _countDowncontainer=0;
var _currentSeconds=0;
var _reboursSelecteur=$('span.time:first');

function ActivateCountDown(selecteur) {
	_reboursSelecteur=selecteur;
	window.setTimeout("CountDownTick()", 1000);
}

function CountDownTick() {
	_reboursSelecteur.each(function(index) {
		SetCountdownText($(this),$(this).attr('rel')-1);
		if ($(this).attr('rel') <=0) {
			$(this).parents('div.buy').slideUp('slow').remove();
			$(this).parents('div.dinfos').children('div.buy').slideUp('slow').remove();
			$(this).parents('div.countdown').remove();
		}
	});
	window.setTimeout("CountDownTick()", 1000);
}

function SetCountdownText(selecteur,seconds) {
	selecteur.attr('rel',seconds);
	var minutes=parseInt(seconds/60);
	seconds = (seconds%60);
	var hours=parseInt(minutes/60);
	minutes = (minutes%60);
	selecteur.html('<span class="number">'+AddZero(hours)+'</span><span class="unites">h</span><span class="number">'+AddZero(minutes)+'</span><span class="unites">min</span><span class="number">'+AddZero(seconds)+'</span><span class="unites">sec</span>');
}

function AddZero(num) {
	return ((num >= 0)&&(num < 10))?"0"+num:num+"";
}

/* -----------------------------------------------------------------------------
	Google Maps
------------------------------------------------------------------------------*/
var markerLat; var markerLong; var markerTitle; var markerHtml; var showMarker = 0; var centerLat; var centerLong; var mapZoom;
function map_init(){
	var myOptions = {
		zoom: parseInt(mapZoom)
		,center: new google.maps.LatLng(centerLat, centerLong)
		,mapTypeId: google.maps.MapTypeId.ROADMAP
		,disableDefaultUI: true
		,navigationControl: true
		,navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	if (showMarker == 1) {
	    var marker = new google.maps.Marker({
	        position: new google.maps.LatLng(markerLat, markerLong),
	        map: map,
	        title:markerTitle
	    });

	    var infowindow = new google.maps.InfoWindow({
	        content: markerHtml
	    });
		infowindow.open(map,marker);
		// google.maps.event.addListener(marker, 'click', function() {infowindow.open(map,marker);});
	}
}


/* -----------------------------------------------------------------------------
	Facebook
------------------------------------------------------------------------------*/

var inviteLast;
function facebook_invite_users(inviteFor) {

	if (inviteFor == null) {
		inviteFor = inviteLast;
	}
	else
	{
		inviteLast = inviteFor;
	}

	// Si pas connecté, connect puis callback
	FB.Connect.get_status().waitUntilReady( function( status ) {
		switch ( status ) {
			case FB.ConnectState.connected:
				loggedIn = true;
				break;
			case FB.ConnectState.appNotAuthorized:
			case FB.ConnectState.userNotLoggedIn:
				FB.Connect.requireSession(facebook_invite_users);
				loggedIn = false;
		}
	});


	// Si connecté
	if (loggedIn == true) {

		$.post("actions/ajaxActions.php", {
			'ajaxAction': 'getDeal',
			'serialised': inviteLast
		},
		function(data){
			if (data.erreur == '0') {
				var popupTitre	= 'Inviate questa offerta ai vostri amici';	// Titre Barre bleue popup
				var fbAction	= 'Invita i tuoi amici.';			// Sous-titre popup
				var fbType		= 'Dealissime';					// Bouton action : "send XX invitation"
				var fbContent	= data.deal;					// Texte dans l'invitation
				var fbLabel		= 'Scoprite la offerta';			// Action dans l'invitation
				var fbUrl		= data.lien;						// Lien dans l'invitation + Retour
				var fbmlCode='<fb:request-form \
			                    action="'+fbUrl+'" \
			                    method="POST" \
			                    invite="true" \
			                    type="'+fbType+'" \
			                    content="'+fbContent+' \
								<fb:req-choice url=\''+fbUrl+'\' label=\''+fbLabel+'\'></fb:req-choice>"> \
			                    <fb:multi-friend-selector \
			                    showborder="false" \
			                    actiontext="'+fbAction+'" \
								email_invite="false" \
								cols="4" \
								rows="3"> \
			        </fb:request-form>';
				var dialog = new FB.UI.FBMLPopupDialog(popupTitre,fbmlCode);
				dialog.setContentWidth(650);
				dialog.setContentHeight(550);
				dialog.show();

			}
			else
			{
				alert('erreur');
			}
		}, "json");


	}


}


/* -----------------------------------------------------------------------------
	Lancements onLoad
------------------------------------------------------------------------------*/
$(function() {



	/* -----------------------------------------------------------------------------
	Liens submit
	------------------------------------------------------------------------------*/
	$('A.submit').click(function(){
		$(this).parents('form:first').submit();
		return false;
	});

	/* -----------------------------------------------------------------------------
	Bloc login
	------------------------------------------------------------------------------*/
	$('A.showLogin').click(function(){
		showLogin();
		return false;
	});

	$('A.hideLogin').click(function(){
		hideLogin();
		return false;
	});

	$('A.showLoginFromModal').live('click', function() {
		closeModal(showLogin);
		return false;
	});


	/* -----------------------------------------------------------------------------
	Bloc Villes
	------------------------------------------------------------------------------*/
	$('A.showCities').click(function(){
		if ($('#showCities').is(':visible')) {
			hideCities();
		}
		else
		{
			showCities();
		}
		return false;
	});



	/* -----------------------------------------------------------------------------
		Social / FB
	------------------------------------------------------------------------------*/


	$('A.openFbConnect').click(function(){
		FB.Connect.requireSession(function(){
			var cookie_date = new Date ( );  // COokie pour un an
			cookie_date.setTime(cookie_date.getTime() + 1000 * 60 * 60 * 24 * 365)
			document.cookie = "fbConnected=1;expires=" + cookie_date.toGMTString();
			location.reload(true);
		});
		return false;
	});


	$('A.closeFbConnect').click(function(){
		var thisRedir = $(this).attr('href');
		FB.Connect.logoutAndRedirect(thisRedir);
		return false;
	});

	$('a.fbShare').live('click', function() {
		var thisUrl=$(this).attr('href');
		var thisTitle=$(this).attr('title');
		window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(thisUrl)+'&t='+encodeURIComponent(thisTitle),' sharer', 'toolbar=0, status=0, width=626, height=436');
		return false;
	});

	/* -----------------------------------------------------------------------------
	Si cookie fbconnect
	------------------------------------------------------------------------------*/
	if (getCookie('fbConnected')==1) {
		hideFbc();
	}


	/* -----------------------------------------------------------------------------
		Offrir - uniquement sur panier
	------------------------------------------------------------------------------*/

	$('A[target=changeModal]').live('click', function() {
		var thisModal = $(this).attr('href');
		$('#overlay-modal, #modalStroke').fadeOut("slow",function(){
			$.get(thisModal, function(data) {
				$('#overlay-modal, #modalStroke').remove()
				$('div.firstDiv').prepend(data);
			});
		});
		return false;
	});


	$('A[target=modal], A.openModal').live('click', function() {
		closeModal();
		var thisModal = $(this).attr('href');
		openModal(thisModal);
		return false;
	});

	$('A[target=modalMap]').click(function(){
		closeModal();
		var thisModal = $(this).attr('href');
		$.get(thisModal, function(data) {
			$('html, body').animate({scrollTop: 0}, 800);
			$('div.firstDiv').prepend(data.html);
			markerLat	= data.markerLat;
			markerLong	= data.markerLong;
			markerTitle	= data.markerTitle;
			markerHtml	= data.markerHtml;
			showMarker	= data.showMarker;
			centerLat	= data.centerLat;
			centerLong	= data.centerLong;
			mapZoom		= data.mapZoom;
			$.getScript("http://maps.google.com/maps/api/js?sensor=false&callback=map_init");
		},
		'json');
		return false;
	});


	$('A.closeModal').live('click', function() {
		closeModal();
		return false;
	});


	/*--------------------------------------------
		formulaires standard
	----------------------------------------------*/

	// Champ mail
	$('input.obligatoire_mail:visible').live('keyup blur', function() {
		if (!checkEmail($(this).val())) {
			switchStatus(this, 'n');
		}
		else
		{
			switchStatus(this, 'o');
		}
	});

	// Champ obligatoire
	$('input.obligatoire:visible, textarea.obligatoire:visible').live('keyup blur', function() {
		if ($(this).val() == '' || $(this).val() == null) {
			switchStatus(this, 'n');
		}
		else
		{
			switchStatus(this, 'o');
		}
	});

	// Champ obligatoire numérique
	// Champ numérique
	$('input.obligatoire_numerique, input.numerique, input.cp').keydown(function(e)
     {
		var key = e.charCode || e.keyCode || 0;
		var thisVal = $(this).attr('value');
		if (key == 38)
		{
			$(this).attr('value',parseInt(thisVal)+1);
		}
		else if (key == 40)
		{
			var newVal = parseInt(thisVal)-1;
			if (newVal < 1) {newVal = 1;}
			$(this).attr('value',newVal);
		}
		// autorise backspace, tab, delete, fleches, chiffres, pavé numérique
		if (
			key == 8 ||
			key == 9 ||
			key == 46 ||
			(key >= 37 && key <= 40) ||
			(key >= 48 && key <= 57) ||
			(key >= 96 && key <= 105))
		{
			return true;
		}
		return false;
	});

	// Checkbox obligatoire
	$('input.obligatoire_checkbox:visible').live('click', function() {
		var thisName = $(this).attr('name');
		var isChecked  = $('input[name='+thisName+']:checked').length;
		if (isChecked == 1) {
			switchStatus(this, 'o');
			//console.log('checked');
		}
		else
		{
			switchStatus(this, 'n');
		}
	});

	// Champ obligatoire numérique
	$('input.obligatoire_numerique:visible, select.obligatoire_numerique:visible').live('keyup blur', function() {
		if ($(this).val() == '' || $(this).val() == null || isNaN($(this).val())) {
			switchStatus(this, 'n');
		}
		else
		{
			switchStatus(this, 'o');
		}
	});


	$('input.addn[name=email]').focus(function(){
		var thisVal = $(this).val();
		if (thisVal == $(this).attr('title') || thisVal == 'Vous devez saisir une adresse e-mail valide') {$(this).val('');}
	}).blur(function(){
		var thisVal = $(this).val();
		if (thisVal == '') {$(this).val($(this).attr('title'));}
		/*
		else if (!checkEmail($(this).val())) {
			$(this).val('Vous devez saisir une adresse e-mail valide');
		}
		*/
	});

	/*--------------------------------------------
		formulaire standard
	----------------------------------------------*/
	$('form.standardForm A.submit').live('click', function() {
		var thisForm = $(this).parents('form');
		$(thisForm).find('input:visible, textarea:visible').each(function(index) {
				$(this).focus().blur();
		});
		// reste-t-il des erreurs ?
		if (countErrors($(thisForm)) == 0) {
			// ajax submit !
			if ($(thisForm).find('input[name=ajaxAction]')) {
				$.post("actions/ajaxActions.php", {
					'ajaxAction': $(thisForm).find('input[name=ajaxAction]').val(),
					'serialised': $(thisForm).serialize()
				},
				function(data){
					if (data.erreur == '0') {
						$('#modalContent div.title h3').html(data.html.titre);
						$('#modalContent div.content').html('<p>'+data.html.content+'</p>');
						$(thisForm).slideUp();
					}
					else
					{
						alert('erreur');
					}
				}, "json");
			}
			// Submit
			else
			{
				$(thisForm).submit();
			}
		}
		else
		{
			blinkError($(thisForm));
		}
		return false;
	});


	/*--------------------------------------------
		formulaires openInviter
	----------------------------------------------*/
	$('form.openInviterForm A.submit').live('click', function() {
		var thisForm = $(this).parents('form');
		$(thisForm).find('input:visible, textarea:visible').each(function(index) {
				$(this).focus().blur();
		});
		// reste-t-il des erreurs ?
		if (countErrors($(thisForm)) == 0) {
			// ajax submit !
			if ($(thisForm).find('input[name=ajaxAction]')) {
				$.post("actions/ajaxActions.php", {
					'ajaxAction': $(thisForm).find('input[name=ajaxAction]').val(),
					'serialised': $(thisForm).serialize()
				},
				function(data){
					if (data.erreur == '0') {
						$(thisForm).slideUp();
						$('#modalContent div.title h3').html(data.html.titre);
						$('#modalContent div.content').html('<p>'+data.html.content+'</p>');
					}
					else
					{
						$('.openInviterError').html('');
						for ( keyVar in data.erreurs ) {
							switchStatus($('input[name='+keyVar+']'),'n');
							$('.openInviterError').append(data.erreurs[keyVar]);
						}
					}
				}, "json");
			}
			// Submit
			else
			{
				$(thisForm).submit();
			}
		}
		else
		{
			blinkError($(thisForm));
		}
		return false;
	});


	/*--------------------------------------------
		checkboxes openInviter
	----------------------------------------------*/
	$('input.checkAll').live('click', function() {
		var thisRel = $(this).attr('rel');	// Champ d'action
		thisRel = thisRel.substr(1, thisRel.length);
		var isChecked=$(this).attr('checked')?1:0;
		if (isChecked==1) { $('input[rel='+thisRel+']').attr('checked','isChecked'); }
		else { $('input[rel='+thisRel+']').removeAttr('checked'); }
	});

	/*--------------------------------------------
		formulaire d'inscription newsletter
	----------------------------------------------*/
	$('form.newsletterForm').submit(function(){
		$('input.addn[name=email]').focus().blur();
		if (checkEmail($('input.addn[name=email]').val())) {
			$.post("actions/ajaxActions.php", {
				'ajaxAction': $('form.newsletterForm input[name=ajaxAction]').val(),
				'serialised': $('form.newsletterForm').serialize()
			},
			function(data){
				if (data.erreur == '0') {
					$('form.newsletterForm').before('<p>'+data.html.content+'</p>').remove();
				}
				else
				{
					$('input.addn[name=email]').val('Vous devez saisir une adresse e-mail valide');
				}
			}, "json");

		}
		else
		{
			$('input.addn[name=email]').val('Vous devez saisir une adresse e-mail valide');
		}
		return false;
	});

	/* -------------------------------------------------------------------------
		Facebook
	--------------------------------------------------------------------------*/
	$('A.fbInvite').live('click', function() {
		var inviteFor = $(this).attr('href').slice($(this).attr('href').indexOf('?') + 1);
		$('html, body').animate({scrollTop: 0}, 800);
		closeModal(facebook_invite_users(inviteFor));
		return false;
	});



});

