/**
 *
 * @fileoverview Gestisce la pagina di conferma ordine
 *
 * @filename ordine.js
 * @requires owjslib.js, layoutServizio.js, servizio.js, YAHOO.util.Dom, YAHOO.util.Connect, YAHOO.lang.JSON;
 * @created 2008-05-07
 * @original author Giampaolo Bellavite
 * @copyright Kemen s.r.l.
 * @license Mozilla Public License Version 1.1
 * @version 0.1
 * @$LastChangedDate:: 2011-02-15#$
 * $LastChangedRevision: 4116 $
 * $LastChangedBy: faser $
*/

if(typeof(HOL) == 'undefined') {var HOL = {}};

/*** Constructor ***/
HOL.ordine = function(cartPosition) {
	var _cartPosition = cartPosition;
	this.getCartPosition = function(){
		return _cartPosition;
	};	
};

/*** Public methods ***/

/**
 * Mostra il loader accanto al titolo della pagina
 */
HOL.ordine.prototype.showLoader = function() {
	
};

/**
 * Nasconde il loader accanto al titolo della pagina
 */
HOL.ordine.prototype.hideLoader = function() {
	
};
/**
 * Sostituisce la tabella con il riassunto dei pagamenti utilizzando newContent
 * @param {string} newContent
 */
HOL.ordine.prototype.setOrderPriceSummary = function(newContent) {
	Dom.get('orderPriceSummary').innerHTML = newContent;
	return false;
};

/**
 * Sostituisce il contenuto del layer con i pagamenti disponibili usando newContent
 * @param {string} newContent
 */
HOL.ordine.prototype.setOrderPaymentType = function(newContent) {
	Dom.get('orderPaymentType').innerHTML = newContent;
	return false;
};

/**
 * Imposta l'ordine come urgente e ricarica la tabella dei prezzi e dei pagamenti disponibili
 * @param {boolean} urgente Se e' urgente o no
 */
HOL.ordine.prototype.setUrgente = function(urgente){
	var oOrdine = this;
	var callback = {
		success: function(oResult){
			var parsedResponse = JSON.parse(oResult.responseText);
			if(parsedResponse.urgente==1) {
				oOrdine.getForm().urgente[1].checked=true;
			}
			else {
				oOrdine.getForm().urgente[0].checked=true;
			}
			oOrdine.setOrderPriceSummary(parsedResponse.orderPriceSummary); // ricarico la tabella con i prezzi
			oOrdine.setOrderPaymentType(parsedResponse.orderPaymentType); // ricarico i pagamenti disponibili
			HOL.forms.enableSubmit(oOrdine.getForm());
			oOrdine.hideLoader();
		},
		failure: function(oResult){			
			oOrdine.hideLoader();
			oOrdine.showError(oResult);
			HOL.forms.enableSubmit(oOrdine.getForm());
		}
	};
	
	oOrdine.showLoader();
	
	HOL.forms.disableSubmit(oOrdine.getForm());

	Conn.setForm(oOrdine.getForm());
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=setUrgente', 
								  callback);
	// reset the form state after the submit
	Conn.resetFormState(); 
	return false;
};
/**
 * Cambia il tipo di pagamento ricaricando i prezzi e i tipi di pagamento disponibili
 * @param {Integer} idPagamento ID del pagamento da impostare
 */
HOL.ordine.prototype.switchPagamento = function(idPagamento){
	var oOrdine = this;
	var callback = {
		success: function(oResult){		
			$("#sidebarBox").html(oResult.responseText);
									
		},
		failure: function(oResult){			
			HOL.layoutServizio.hideSidebarLoader();			
		}
	};
	
	HOL.layoutServizio.showSidebarLoader();
	
	$("#order-errore").empty();	
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=switchPagamento'+'&newIdPagamento='+idPagamento, 
								  callback);	
	return false;
};
/**
 * Switcha gli indirizzi di spedizione vs. l'indirizzo di fatturazione
 * @param {boolean} showAddr Se mostrare il layer con gli indirizzi di spedizione o no
 */
HOL.ordine.prototype.switchSendingAddress = function(showAddr){
	Dom.setStyle('divIndElenco', 'display', showAddr ? 'block' : 'none');
	var val = showAddr ? 1 : 0;
	var oConn = Conn.asyncRequest('GET', '/_ajax.ordine.cfm?_isXHR=true&method=setIndirizzoSpedizione&value=' + val,{});	
	return false;
};
/**
 * Imposta la notifica dell'SMS via ajax
 * @param {Object} el Input text con il numero di cellulare
 */
HOL.ordine.prototype.setNotificaSMS = function(el){
	if(!this.validateTelephone(el)) {
		alert("Il numero di telefono non è valido")
		el.focus();
		return false;	
	}
	var n = el.value; // numero di cellulare
	
	var callback = {
		success: function(oResult){			
		},
		failure: function(oResult){			
		}
	};
	
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=setNotificaSMS&n='+n, 
								  callback);
	return true;
};

/**
 * Mostra la finestra con la richiesta del numero di cellulare
 */
HOL.ordine.prototype.showNotificaSMS = function() {
	var oOrdine = this;
	var callback = {
		success: function(oResult){
			HOL.panels.dialog.setBody(oResult.responseText);
			HOL.panels.dialog.center();
			Dom.get('notifica_cellulare').value=oOrdine.getForm().notifica_sms.value;
			Dom.get('notifica_cellulare').select();
		},
		failure: function(oResult){			
			HOL.panels.dialog.setBody("Errore nel caricamento.");
		}
	};
	HOL.windowBox.showMessage('Numero di cellulare', 'Loading...');
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=showNotificaSMS', 
								  callback);
								  
	return false;
};


HOL.ordine.prototype.validateTelephone = function(el) {
	el.value = ow.core.trim(el.value);
	if((el.value.length > 1 && el.value.length < 6) || isNaN(el.value)) {	
		return false;				
	}else{	
		return true;		
	}	
};

/**
 * Mostra la finestra con la richiesta di ricarica
 */
HOL.ordine.prototype.showPanelAbbonamento = function() {
	var oOrdine = this;
	return HOL.panels.showDialogContent('Ricarica credito prepagato',
										   '/_ajax.ordine.cfm?_isXHR=true&method=showPanelAbbonamento&pos='+oOrdine.getCartPosition(), 
								         	true);
};
/**
 * Aggiunge una ricarica dell'abbonamento
 * @param {Object} credito Valore del credito da aggiungere
 */
HOL.ordine.prototype.addRicaricaAbbonamento = function(credito,form){
	var oOrdine = this;
	var f = form;
	var callback = {
		success: function(oResult){
			$("#sidebarBox").html(oResult.responseText);			
			HOL.forms.enableSubmit(f);
		},
		failure: function(oResult){			
			oOrdine.hideLoader();
			oOrdine.showError(oResult);
			HOL.forms.enableSubmit(f);
		}
	};
	oOrdine.showLoader();

	HOL.forms.disableSubmit(f);
	
	Conn.setForm(f);
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=addRicaricaAbbonamento&pos='+oOrdine.getCartPosition()+'&credito='+credito, 
								  callback);
	// reset the form state after the submit
	Conn.resetFormState(); 
	return false;
};
/**
 * Elimina la ricarica dell'abbonamento
 */
HOL.ordine.prototype.deleteRicaricaAbbonamento = function(){
	var oOrdine = this;
	var callback = {
		success: function(oResult){
			var parsedResponse = JSON.parse(oResult.responseText);
			oOrdine.setOrderPriceSummary(parsedResponse.orderPriceSummary); // ricarico la tabella con i prezzi
			oOrdine.setOrderPaymentType(parsedResponse.orderPaymentType); // ricarico i pagamenti disponibili
			HOL.forms.enableSubmit(oOrdine.getForm());
			Dom.setStyle('trDisclaimerAbb','display','none');
			oOrdine.hideLoader();
		},
		failure: function(oResult){			
			oOrdine.hideLoader();
			oOrdine.showError(oResult);
			HOL.forms.enableSubmit(oOrdine.getForm());
		}
	};
	oOrdine.showLoader();

	HOL.forms.disableSubmit(oOrdine.getForm());

	Conn.setForm(oOrdine.getForm());
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=deleteRicaricaAbbonamento&pos='+oOrdine.getCartPosition(), 
								  callback);
	// reset the form state after the submit
	Conn.resetFormState(); 
	return false;
};

/**
 * Acquisto di una ricarica per l'abbonamento
 */
HOL.ordine.prototype.buyCredit = function(theForm) {
	
	var oOrdine = this;
	var myForm = theForm;
	var callback = {
		success: function(oResult){
		
			var parsedResponse = JSON.parse(oResult.responseText);
			
			// Controllo se c'e' un errore di validazione
			if (parsedResponse.CFValidationError) {
				HOL.forms.catchValidationError(parsedResponse.CFValidationError, 'order-errore', myForm);
				HOL.forms.enableSubmit(myForm);
				oOrdine.hideLoader();
			}			
			else {
				HOL.forms.cleanValidationError(myForm,'order-errore');
				location='/subscriptions/do.cfm';
			}
			return false;
		},
		failure: function(oResult){		
			
			HOL.forms.cleanValidationError(myForm,'order-errore');
			oOrdine.hideLoader();
			oOrdine.showError(oResult);
			HOL.forms.enableSubmit(myForm);
		}
	};
	oOrdine.showLoader();
	HOL.forms.cleanValidationError(myForm,'order-errore');
	HOL.forms.disableSubmit(myForm);
	Conn.setForm(myForm);
	var oConn = Conn.asyncRequest('POST', 
								  '/_ajax.ordine.cfm?_isXHR=true&method=creditoAbbonamento', 
								  callback);
								  
	// reset the form state after the submit
	Conn.resetFormState(); 
	return false;
	
};
/**
 * Imposta la notifica degli SMS dalla finestra
 */
HOL.ordine.prototype.setNotificaSMSFromWin = function(){
	var oOrdine = this;
	HOL.panels.dialog.hide();
	oOrdine.getForm().notifica_sms.value=Dom.get('notifica_cellulare').value;
	oOrdine.getForm().notifica_sms.checked=true;
	oOrdine.setNotificaSMS(oOrdine.getForm().notifica_sms);
	return false;
};
/**
 * Invia l'ordine
 */
HOL.ordine.prototype.send = function(theForm,target) {
	
	var oOrdine = this;
	var myForm = theForm;
	var target = target;
	var callback = {
		success: function(oResult){
			var parsedResponse = JSON.parse(oResult.responseText);
			// Controllo se c'e' un errore di validazione
			if (parsedResponse.CFValidationError) {
				HOL.forms.catchValidationError(parsedResponse.CFValidationError, 'order-errore', myForm);
				HOL.forms.enableSubmit(myForm);
				oOrdine.hideLoader();
				target.disabled = false;
			}			
			else {
				var action = "/order/orderDoPayment.cfm?id="+parsedResponse;
			 	$(myForm).attr("action",action);
				$(myForm).submit();				
			}
			return false;
		},
		failure: function(oResult){		
			oOrdine.hideLoader();
			oOrdine.showError(oResult);
			HOL.forms.enableSubmit(myForm);
			return false;
		}
	};
	oOrdine.showLoader();
	$("#order-errore").empty();
	target.disabled = true;
	
	Conn.setForm(theForm);
	var totale = document.getElementById("totaleOrdineDaPagare").value;
	var oConn = Conn.asyncRequest('POST','/_ajax.ordine.cfm?_isXHR=true&method=send', callback,"totale=" + totale);
	// reset the form state after the submit
	Conn.resetFormState(); 
	return false;
};
/**
 * Mostra la finestra del contratto
 * @param {Object} id Id del servizio
 * @param {Object} name Nome della checkbox da checkare
 */
HOL.ordine.prototype.showContratto = function(id, name) {
	if(!name) {
		name='contratto';
	};
	HOL.windowBox.showDialogContent('Condizioni contrattuali', 
										   '/_ajax.common.cfm?_isXHR=true&method=contratto&id='+id+'&name='+name,
								         	true,null, 500,350);
};

/**
 * Mostra la finestra con il disclaimer di un servizi (note relative al servizio)
 * @param {Object} id Id del servizio
 */
HOL.ordine.prototype.showDisclaimer = function(id) {
	HOL.windowBox.showDialogContent('Condizioni di acquisto del documento', 
										  '/_ajax.common.cfm?_isXHR=true&method=disclaimer&id='+id, 
								         	true,null, 400,350);
};

/**
 * Migliore gestione degli errori
 * @param {Object} oResult
 */
HOL.ordine.prototype.showError = function(oResult) {
	var parsedResponse = JSON.parse(oResult.responseText);
	if(parsedResponse.CFRequestError.errorType == 'hol.cartPositionNotFound') {
		alert('Ordine perduto: è trascorso troppo tempo e la tua sessione è scaduta - l\'ordine è stato annullato.');
		location.reload();
	}
	else {
		HOL.panels.showError(oResult);
	}
	return false;
}

