$(document).ready(function(){
	if($("#viewer").is('div')){
		scrollAndDisplayLightbox();
		doScroll();
	}
	if($('#map').is('div')) {
			displayMap();
	}
	if($('#contactForm').is('form')){
			cleanInputTextInForm();
			formValidation($('#contactForm'),$("#formMessages"),'lib/mail.php');
	}
});
var displayMap = function(){
	var latlng = new google.maps.LatLng(45.46620654095554, 7.8704862060546965);
    var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeControl: true,
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN},
		mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), myOptions);
	var marker = new google.maps.Marker({
	      position: map.getCenter(), 
	      map: map, 
	      title:"Webeventi"
	  });
}
var scrollAndDisplayLightbox = function(){
	$("a.lightboxA").lightBox({
		overlayBgColor: '#000',
		overlayOpacity: 0.6,
		containerResizeSpeed: 350,
		txtImage: '',
		txtOf: ''
	});
}
var doScroll = function(){
	$("#viewer").imageScroller({
			frame:"viewerFrame",
			width:100,
			next:"prev",
			prev:"next",
			child:"div"
			//auto:true
		});
}
var cleanInputTextInForm = function(){
	$(':text').val('');
}
function formValidation(el,messages,requestURL){
	var element = el;
	var msg = messages;
	var urlR = requestURL;
	var showRequest = function(formData, jqForm, options) { 
	    // formData is an array; here we use $.param to convert it to a string to display it 
	    // but the form plugin does this for you automatically when it submits the data 
	    var queryString = $.param(formData); 

	    // jqForm is a jQuery object encapsulating the form element.  To access the 
	    // DOM element for the form do this: 
	    // var formElement = jqForm[0]; 

	   // alert('About to submit: \n\n' + queryString); 
		alert('Stiamo inviando una mail da: '+$("#iEmail").val());
	    // here we could return false to prevent the form from being submitted; 
	    // returning anything other than false will allow the form submit to continue 
	    return true; 
	} 
	// post-submit callback 
	var showResponse = function(responseText, statusText)  {
		clearTimeout(timeID);
	    // for normal html responses, the first argument to the success callback 
	    // is the XMLHttpRequest object's responseText property 

	    // if the ajaxForm method was passed an Options Object with the dataType 
	    // property set to 'xml' then the first argument to the success callback 
	    // is the XMLHttpRequest object's responseXML property 

	    // if the ajaxForm method was passed an Options Object with the dataType 
	    // property set to 'json' then the first argument to the success callback 
	    // is the json data object returned by the server 
		msg.text(responseText).hide(500).show(500);
		var timeID = setTimeout('$("#formMessages").fadeOut(1000)', 4000);
		validateForm.resetForm();
	    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
	       //'\n\nThe output div should have already been updated with the responseText.');
	}
	var validateForm = element.validate({
		debug: false,
		invalidHandler: function(form, validator) {
		      errorsHandler(validator);
		},
		submitHandler: function(form){
			//alert('is valid do something '+el.attr('id')+' boh '+$(form).attr('id'));
			$(form).ajaxSubmit({ 
			        target:        '',   // target element(s) to be updated with server response 
			        beforeSubmit:  showRequest,  // pre-submit callback 
			        success:       showResponse,  // post-submit callback 
			        // other available options: 
			        url: urlR,        // override for form's 'action' attribute 
			        type:  'post',       // 'get' or 'post', override for form's 'method' attribute 
			        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
			        clearForm: true        // clear all form fields after successful submit 
			        //resetForm: true        // reset the form after successful submit 
			        // $.ajax options can be used here too, for example: 
			        //timeout:   3000 
			    });
		},
		rules: {
		     // simple rule, converted to {required:true}
		     name: "required",
		     // compound rule
		     email: {
		       required: true,
		       email: true
		     }
		   },
			messages: {
				nome: "Attenzione campo obbligatorio!",
				cognome: "Attenzione campo obbligatorio!",
				richiesta:"Attenzione campo obbligatorio!",
				consensoUno:"Attenzione campo obbligatorio!",
				email: {
					required: "Abbiamo bisogno del tuo indirizzo email per contattarti!",
					email: "Il tuo indirizzo eamil deve essere nella forma name@domain.com"
				}
			},
			highlight: function(element, errorClass) {
			     $(element).addClass(errorClass).css("border","1px solid red");
			     $(element.form).find("label[for=" + element.id + "]")
			                    .addClass(errorClass);
			  },
			  unhighlight: function(element, errorClass) {
			     $(element).removeClass(errorClass).css("border","1px solid #6BA511");
			     $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
				errorsHandler(this);	
			}
	});
	var errorsHandler = function(form){
		var errors = form.numberOfInvalids();
		if (!errors) {
	        $("#formMessages").fadeOut(1200);	
		}		else {
			var message = errors == 1
	          ? 'Manca un campo obbligatorio.'
	          : 'Mancano ' + errors + ' campi obbligatori.';
				$("#formMessages").text(message).show(1200);
	       // alert(message);
		}
	}
	return false; 
}