/*/////////////////////////////////////////////////////// CREDITS ///////////////////
_______________________________________________________________________________________________________

 |	
 |	CRMforBILLING Website Scripting
 |	by Cristiano Rastelli - Area Web <more info: www.didoo.net>
 |	Last Update: June 2007
 |

 _______________________________________________________________________________________________________

	Table of Contents
	-----------------
	Configuration
	Global Variables


	Class Declarations
	------------------	

	Common
	. footer				[ initialize / swapoff / swapon ]

	Countdown
	. countdown				[ initialize / timeticker ]


	Functions Declarations
	-----------------------

	Detection
	. browserSupportDomHandling

	Common
	. zeroPad	

	Function Calls
	--------------
	. window onload initialize
	
_______________________________________________________________________________________________________ */




/*/////////////////////////////////////////////////////// CLASS DEFINITIONS ////////////////////
_______________________________________________________________________________________________________ */

/*............................... COMMON ........*/


var swapimage = new Class({

	options: {
		subfix: '_active',
		preload: true
		// onMouseover: Class.empty,
		// onMouseout: Class.empty,
		// onClick: Class.empty
	},

	initialize: function(image,preload) {

		this.image = image;

		// set source paths
		this.image.off_src = this.image.getProperty('src');
		this.image.act_src = this.image.off_src.substring(0,this.image.off_src.lastIndexOf('.')) + this.options.subfix +this.image.off_src.substring(this.image.off_src.lastIndexOf('.'));
		
		// preload  active image
		if (preload) {
			new Asset.image(this.image.act_src);
		}

		// assign behaviour
		this.image.addEvent('mouseover', this.swapon.bindAsEventListener(this.image));
		this.image.addEvent('mouseout', this.swapoff.bindAsEventListener(this.image));

	},

	swapon: function(){	

		this.setProperty("src",this.act_src);

		// this.fireEvent('onMouseover', this.element);
		// return this;

	},

	swapoff: function(){	

		this.setProperty("src",this.off_src);

		// this.fireEvent('onMouseout', this.element);
		// return this;

	}

})


var crmMenu = new Class({

	initialize: function() {

		this.menu = $('boxHeaderMenuList');

		if ($('boxHeaderMenu') && this.menu) {	// check HTML vs. expected DOM correspondence

			// get a reference to the images
			this.menuitems = this.menu.getElements('img');

			// set src values, preload assets, assign the behavior to the image icons
			this.menu.swap = new Array();
			for (var i=0; i<this.menuitems.length; i++) {
				this.menu.swap[i] = new swapimage(this.menuitems[i]);
			}
			
			// show active menu
			this.submenu = $('boxMainSubLeftSubMenu');
			if(this.submenu && this.submenu.className.test('submenu[1-5]')) {

				var cAct = this.submenu.className.charAt(this.submenu.className.length-1).toInt() - 1;

				$('boxHeaderMenu').getElement('#boxHeaderMenuEffect div.current').setStyles({
					'width' 		: this.menuitems[cAct].getCoordinates().width + 'px',
					'left' 			: this.menuitems[cAct].getCoordinates().left - this.menu.getCoordinates().left + 'px',
					'visibility'	: 'visible'
				});

			}

		}

	}

})


var crmFooter = new Class({

	initialize: function() {

		this.boxfoot = $('boxFooter');
		this.credits_link = $('boxFooterCredits_link');
		this.credits_popup = $('boxFooterCredits_popup');

		if (this.boxfoot && $('boxFooterAlliance')) {	// check HTML vs. expected DOM correspondence

			// get a reference to the images
			this.icons = this.boxfoot.getElements('img');

			// set src values, preload assets, assign the behavior to the image icons
			this.boxfoot.swap = new Array();
			for (var i=0; i<this.icons.length; i++) {
				this.boxfoot.swap[i] = new swapimage(this.icons[i]);
			}

		}

		if (this.boxfoot && $('boxFooterCredits')) {	// check HTML vs. expected DOM correspondence

			// assign the behavior to the credits link
			this.credits_link.addEvent('click', this.popup.bindAsEventListener(this.credits_popup));
			this.credits_link.onclick = function(){return false;}
	
			// initialise the opacity effect & hide credits
			this.credits_popup.popupfx = new Fx.Style(this.credits_popup.id, 'opacity').set(0);
		}

	},

	swapon: function(){	
		this.setProperty("src",this.act_src);
	},

	swapoff: function(){	
		this.setProperty("src",this.off_src);
	},
	
	popup: function() {
		var cop = this.getStyle('opacity').toFloat();
		if(cop < 0.1) {
			this.popupfx.start(cop,1);
		} else if(cop > 0.9) {
			this.popupfx.start(cop,0);
		}
	}

})


/*............................... HOMEPAGE ........*/


var newsletter = new Class({

	initialize: function() {

		this.form = $('formNewsletter');
		this.fields = $$('#formNewsletter td.inp input');
		this.submitter = $('invia');
		this.feedback = $('formFeedback');

		
		if (this.form && this.submitter && this.feedback) {	// check HTML vs. expected DOM correspondence
		
			// init validation object;
			this.validator = new FormValidator (this.form, {
				evaluateOnSubmit:false,
				evaluateFieldsOnBlur: false,
				evaluateFieldsOnChange: false,
				errorPrefix: ""
			});
			// set error messages
			this.validator.getValidator('required').options.errorMsg = "Campo obbligatorio"
			this.validator.getValidator('validate-email').options.errorMsg = "Formato email non valido"
	
			// assign the behavior to the submit button
			this.submitter.addEvent('click', this.submit.bindAsEventListener(this));
			this.submitter.onclick = function(){return false;}

		}

	},

	submit: function(){

		// reset messages
		this.validator.reset();

		// check data validation
		if(this.validator.validate()) {
		
			// make the ajax call
			var postString = "modality=ajax";
			this.fields.each( function(fld){ if (fld.value != '') { postString += '&'+fld.id+"="+fld.value; } } );
			// console.log(postString);
			this.ajaxrequest = new Ajax(this.form.getProperty('action'), { 
				method: 'post', 
				postBody: postString, 
				onComplete: this.reply.bindAsEventListener(this),
				onFailure: this.reply_failure.bindAsEventListener(this)
			}).request();
	
			// disable input fields & submit
			this.form.addClass('paused');
			this.fields.each( function(fld){ fld.setProperty('readonly','readonly'); } );
			this.submitter.setProperty('disabled','disabled');

			// IE6 doesn't use the top/bottom & left/right ubiquous declaration to compute height+width
			if(this.feedback.getCoordinates().width < this.form.getCoordinates().width) { this.feedback.setStyle('width',this.form.getCoordinates().width + 'px'); }
			if(this.feedback.getCoordinates().height < (this.form.getCoordinates().height)) { this.feedback.setStyle('height',(this.form.getCoordinates().height)) + 'px'; }
	
			// give visual feedback (ajax loader image & message)
			this.feedback.removeClass('success').removeClass('iserror').addClass('loading');
			this.form.feedfx = new Fx.Style(this.feedback.id, 'opacity').start(0,1);

		} else {
			// highlight labels
			// this.fields.filterByClass('validation-failed').each( function(fld){ $("l_"+fld.id).addClass('evid'); });
		}
		
	},

	reply: function(request){

		// re-enable input fields & submit
		this.form.removeClass('paused');
		this.fields.each( function(fld){ fld.setProperty('readonly',''); } );
		this.submitter.setProperty('disabled','');
	
		// process the JSON data response
		var jfeed = eval('(' + this.ajaxrequest.transport.responseText + ')');
		if (jfeed.curr_status == 'send_success') {
			this.feedback.removeClass('loading').removeClass('iserror').addClass('success');
			// cleanup fields
			this.fields.each( function(fld){ fld.value=''; } );
			// hide feedback message (delayed)
			(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(5000,this);
		} else {
			this.feedback.removeClass('loading').removeClass('success').addClass('iserror');
			// hide feedback message (delayed)
			(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(10000,this);
		}
	
	},

	reply_failure: function(){

		// re-enable input fields & submit
		this.form.removeClass('paused');
		this.fields.each( function(fld){ fld.setProperty('readonly',''); } );
		this.submitter.setProperty('disabled','');
	
		// give visual feedback (stop ajax loader image & update message)
		this.feedback.removeClass('loading').removeClass('success').addClass('iserror');
		// hide feedback message (delayed)
		(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(10000,this);

	}

})


/*............................... COUNTDOWN (TEMP PAGE) ........*/

var countdown = new Class({

	initialize: function() {

		this.targDate = new Date("15 June, 2007"); 
		this.targText = $('cntdwn');
		if(this.targText) {	// check HTML vs. expected DOM correspondence 
			this.timeticker.periodical(500,this);
		}

	},

	timeticker: function(){

		var currDate  = new Date();

		var timeLeft = (this.targDate.getTime() - currDate.getTime()) / 1000;
		var hourLeft = Math.floor((timeLeft / 3600));
		var minsLeft = Math.floor((timeLeft - hourLeft * 3600) / 60);
		var secsLeft = Math.floor((timeLeft - hourLeft * 3600 - minsLeft * 60));

		this.targText.innerHTML = "-" + zeroPad(hourLeft) +":"+ zeroPad(minsLeft) +":"+ zeroPad(secsLeft);

	}

})

var adesione = new Class({

	initialize: function() {

		this.form = $('formAdesione');
		this.fields = $$('#formAdesione td.inp input');
		this.submitter = $('invia');
		this.feedback = $('formFeedback');

		
		if (this.form && this.submitter && this.feedback) {	// check HTML vs. expected DOM correspondence
		
			// init validation object;
			this.validator = new FormValidator (this.form, {
				evaluateOnSubmit:false,
				evaluateFieldsOnBlur: false,
				evaluateFieldsOnChange: false,
				errorPrefix: ""
			});
			// set error messages
			this.validator.getValidator('required').options.errorMsg = "Campo obbligatorio"
			this.validator.getValidator('validate-email').options.errorMsg = "Formato email non valido"
	
			// assign the behavior to the submit button
			this.submitter.addEvent('click', this.submit.bindAsEventListener(this));
			this.submitter.onclick = function(){return false;}

		}

	},

	submit: function(){

		// reset messages
		this.validator.reset();

		// check data validation
		if(this.validator.validate()) {
		
			// make the ajax call
			var postString = "modality=ajax";
			this.fields.each( function(fld){ if (fld.value != '') { postString += '&'+fld.id+"="+fld.value; } } );
			// console.log(postString);
			this.ajaxrequest = new Ajax(this.form.getProperty('action'), { 
				method: 'post', 
				postBody: postString, 
				onComplete: this.reply.bindAsEventListener(this),
				onFailure: this.reply_failure.bindAsEventListener(this)
			}).request();
	
			// disable input fields & submit
			this.form.addClass('paused');
			this.fields.each( function(fld){ fld.setProperty('readonly','readonly'); } );
			this.submitter.setProperty('disabled','disabled');

			// IE6 doesn't use the top/bottom & left/right ubiquous declaration to compute height+width
			if(this.feedback.getCoordinates().width < this.form.getCoordinates().width) { this.feedback.setStyle('width',this.form.getCoordinates().width + 'px'); }
			if(this.feedback.getCoordinates().height < (this.form.getCoordinates().height)) { this.feedback.setStyle('height',(this.form.getCoordinates().height)) + 'px'; }
	
			// give visual feedback (ajax loader image & message)
			this.feedback.removeClass('success').removeClass('iserror').addClass('loading');
			this.form.feedfx = new Fx.Style(this.feedback.id, 'opacity').start(0,1);

		} else {
			// highlight labels
			// this.fields.filterByClass('validation-failed').each( function(fld){ $("l_"+fld.id).addClass('evid'); });
		}
		
	},

	reply: function(request){

		// re-enable input fields & submit
		this.form.removeClass('paused');
		this.fields.each( function(fld){ fld.setProperty('readonly',''); } );
		this.submitter.setProperty('disabled','');
	
		// process the JSON data response
		var jfeed = eval('(' + this.ajaxrequest.transport.responseText + ')');
		if (jfeed.curr_status == 'send_success') {
			this.feedback.removeClass('loading').removeClass('iserror').addClass('success');
			// cleanup fields
			this.fields.each( function(fld){ fld.value=''; } );
			// hide feedback message (delayed)
			(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(5000,this);
		} else {
			this.feedback.removeClass('loading').removeClass('success').addClass('iserror');
			// hide feedback message (delayed)
			(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(10000,this);
		}
	
	},

	reply_failure: function(){

		// re-enable input fields & submit
		this.form.removeClass('paused');
		this.fields.each( function(fld){ fld.setProperty('readonly',''); } );
		this.submitter.setProperty('disabled','');
	
		// give visual feedback (stop ajax loader image & update message)
		this.feedback.removeClass('loading').removeClass('success').addClass('iserror');
		// hide feedback message (delayed)
		(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(10000,this);

	}

})


/*............................... HOMEPAGE ........*/


var infocomm = new Class({

	initialize: function() {

		this.form = $('formContatti');
		this.fields = $$('#formContatti td.inp input','#formContatti td.inp select','#formContatti td.inp textarea');
		this.submitter = $('invia');
		this.feedback = $('formFeedback');

		if (this.form && this.submitter && this.feedback) {	// check HTML vs. expected DOM correspondence
		
			// init validation object;
			this.validator = new FormValidator (this.form, {
				evaluateOnSubmit:false,
				evaluateFieldsOnBlur: false,
				evaluateFieldsOnChange: false,
				errorPrefix: ""
			});
			// set error messages
			this.validator.getValidator('required').options.errorMsg = "Campo obbligatorio"
			this.validator.getValidator('validate-email').options.errorMsg = "Formato email non valido"
	
			// assign the behavior to the submit button
			this.submitter.addEvent('click', this.submit.bindAsEventListener(this));
			this.submitter.onclick = function(){return false;}

		}

	},

	submit: function(){

		// reset messages
		this.validator.reset();

		// check data validation
		if(this.validator.validate()) {
		
			// make the ajax call
			var postString = "modality=ajax";
			this.fields.each( function(fld){ if (fld.value != '') { postString += '&'+fld.id+"="+fld.value; } } );
			// console.log(postString);
			this.ajaxrequest = new Ajax(this.form.getProperty('action'), { 
				method: 'post', 
				postBody: postString, 
				onComplete: this.reply.bindAsEventListener(this),
				onFailure: this.reply_failure.bindAsEventListener(this)
			}).request();
	
			// disable input fields & submit
			this.form.addClass('paused');
			this.fields.each( function(fld){ fld.setProperty('readonly','readonly'); } );
			this.submitter.setProperty('disabled','disabled');

			// IE6 doesn't use the top/bottom & left/right ubiquous declaration to compute height+width
			if(this.feedback.getCoordinates().width < this.form.getCoordinates().width) { this.feedback.setStyle('width',this.form.getCoordinates().width + 'px'); }
			if(this.feedback.getCoordinates().height < (this.form.getCoordinates().height)) { this.feedback.setStyle('height',(this.form.getCoordinates().height)) + 'px'; }
	
			// give visual feedback (ajax loader image & message)
			this.feedback.removeClass('success').removeClass('iserror').addClass('loading');
			this.form.feedfx = new Fx.Style(this.feedback.id, 'opacity').start(0,1);

		} else {
			// highlight labels
			// this.fields.filterByClass('validation-failed').each( function(fld){ $("l_"+fld.id).addClass('evid'); });
		}
		
	},

	reply: function(request){

		// re-enable input fields & submit
		this.form.removeClass('paused');
		this.fields.each( function(fld){ fld.setProperty('readonly',''); } );
		this.submitter.setProperty('disabled','');
	
		// process the JSON data response
		var jfeed = eval('(' + this.ajaxrequest.transport.responseText + ')');
		if (jfeed.curr_status == 'send_success') {
			this.feedback.removeClass('loading').removeClass('iserror').addClass('success');
			// cleanup fields
			this.fields.each( function(fld){ fld.value=''; } );
			// hide feedback message (delayed)
			(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(5000,this);
		} else {
			this.feedback.removeClass('loading').removeClass('success').addClass('iserror');
			// hide feedback message (delayed)
			(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(10000,this);
		}
	
	},

	reply_failure: function(){

		// re-enable input fields & submit
		this.form.removeClass('paused');
		this.fields.each( function(fld){ fld.setProperty('readonly',''); } );
		this.submitter.setProperty('disabled','');
	
		// give visual feedback (stop ajax loader image & update message)
		this.feedback.removeClass('loading').removeClass('success').addClass('iserror');
		// hide feedback message (delayed)
		(function() {this.form.feedfx.duration=3000; this.form.feedfx.start(1,0)}).delay(10000,this);

	}

})



/*/////////////////////////////////////////////////////// FUNCTIONS DEFINITIONS ////////////////////
_______________________________________________________________________________________________________ */


/*............................... DETECTION ........*/

function browserSupportDomHandling() {

	// test if browser can't support advanced features...
	if( !document.getElementById || !document.appendChild || !document.createElement || typeof document.getElementsByTagName("head")[0].innerHTML == "undefined") {
		return false;
	} else {
		return true;
	}
}

/*............................... COMMON ........*/

function zeroPad(n) { return n>9 ? n : '0'+n; }



/*/////////////////////////////////////////////////////// ONLOAD DECLARATION ////////////////////
_______________________________________________________________________________________________________ */

window.onDomReady(function() {

	/* test browser capabilityes (object detection) */
	if (browserSupportDomHandling()) {
	
		// __ COMMON _______________
		
		/* navigation menu  */
		var myMenu = new crmMenu();

		/* acronym tooltips  */
		var acronymTips = new Tips($$('acronym#acrttp'));

		/* footer alliance & credits effect  */
		var myFooter = new crmFooter();

		// __ SPECIFIC INITIALIZE _______________
	
		/* body object */
		var myBody = document.getElementsByTagName("body").item(0);
	
		switch (myBody.id) {
	
		case "pageHome": 
		
			/* form iscrizione newsletter */
			var myNewsletter = new newsletter();
			
			break;
	
		case "pageNews": 
		
			/* form iscrizione newsletter */
			var myNewsletter = new newsletter();
			
			break;
	
		case "pageCountdown": 
		
			/* countdown */
			var myCountdown = new countdown();

			/* form adesione evento 14 giugno */
			var myAdesione = new adesione();
			
			break;

		case "pageContatti":

			var sediTips = new Tips($$('#boxContactReferences .ttptrig'));

			/* form richiesta informazioni commerciali */
			var myInfocomm = new infocomm();

			break;

		case "pageSoftware":

			// var accordion = new Accordion($$('#boxMainSubMiddle h2'), $$('#boxMainSubMiddle ul'), { opacity: false, alwaysHide: true });
			// var accordion = new MultipleOpenAccordion($$('#boxMainSubMiddle h2'), $$('#boxMainSubMiddle ul'), {openAll: false, opacity: false, firstElementsOpen: [] } );
			break;

		case "pageCatenaValore":

			//var accordion = new Accordion($$('#lstChainValue h6'), $$('#lstChainValue ul'), { opacity: false });
			break;

		default : 
			
			break;
	
		}
	}
});
