var weStore = new function (){
	this.url = "";
	this.datiFatturaOK = false;
	this.datiSpedizioneOK = false;
	this.costo_singolo = 2;
	this.costo_abbonamento = 0;
	this.referer = null;
	this.usersPerPage = 20; // quanti utenti visualizza nella pagina di amministrazione
	this.usersCursor = -1 * this.usersPerPage;
	this.clickNumber = 0;
	this.numberOfUsers = 0;
	
	this.log = function(comment) {
		if (typeof console !== "undefined") console.log(comment);
	}
	
	this.updateUser = function (data) {
		$j.ajax({
		   type: "POST",
		   url: weStore.url + "/store/update",
		   data: data
		 });
	}
	this.richiestaFatturaStatus = function() {
		$j("#anagrafica").hide();
		if ($j("input[name='fattura']:checked").val() == 'true') {
			$j("#anagrafica").show(300);
			$j("#anagrafica input[text]").attr("required");
			$j("#anagrafica").get(0).checkValidity(); // *
		} else if ($j("input[name='fattura']:checked").val() == 'false'){
			$j("#anagrafica").hide(300);
			$j("#anagrafica input[text]").removeAttr("required");
			$j("#anagrafica input[text]").removeClass("required");	
		}
		// $j("#anagrafica").get(0).checkValidity(); // sposto in prima condizione per bug su IE *
		weStore.updatePayButtonStatus();
	}
	
	this.regalaStatus = function(urlBase, trans_id) {
		$j("#regalaDiv").hide();
		if ($j("#regalaCheckbox").is(":checked")) {
			$j("#regalaDiv").show();
			$j("#regalaDiv input").keyup();
			$j("#regalaDiv input").attr("required","required");
			weStore.updatePayButtonStatus();
		} else {
			$j("#regalaDiv input").removeAttr("required");
			$j("#regalaDiv input").removeClass("required");
			weStore.updateTransactionCausale(trans_id,'abbonamento');
			weStore.updatePaypalReturnURL(urlBase, trans_id, null);
		}
	}
	
	this.updateTransactionCausale = function(trans_id, causale){
		var data ="causale=" + causale + "&trans_id=" + trans_id ;
		$j.ajax({
		   type: "POST",
		   url: weStore.url + "/store/update",
		   data: data,
		   success: function () {
				weStore.updatePayButtonStatus();
			}
		 });
	}
	
	// attiva o disattiva il bottone paypal a seconda delle circostanze	
	this.updatePayButtonStatus = function (){
		var active = true;
		if ($j("select[name=prodotto]").val() == "abbonamento" && $j("#regalaCheckbox").is(":checked")) active = active && weStore.validateRegala();
		if ($j("select[name=prodotto]").val().match(/^abbonamentoC.*$/)) active = active && weStore.datiSpedizioneOK;
		if ($j("input[name='fattura']:checked").val() == 'true') active = active && weStore.datiFatturaOK;
		if (active) $j("#pagamento").show(300);
		else $j("#pagamento").hide(300);
	}
	
	this.validateRegala = function () {
		$j("#statusMessage").html("");
		if (weStore.checkDoubleInsertion($j("#e-mail_destinatario"), $j("#ripeti_e-mail_destinatario"), "E-mail destinatario", "Ripeti e-mail destinatario") && $j("#formAcquisto").get(0).checkValidity()) return true;
		else return false;
	}
	
	this.checkDoubleInsertion = function(a,b,n,nbis) {
		if (a.val() == b.val()) return true;
		$j("#statusMessage").html("Il contenuto del campo %s deve essere uguale a quello del campo %s".replace(/%s/, n).replace(/%s/, nbis));
		return false;
	}
	
	this.populatePayPalButton = function(email) {
		$j("#pagamento input[name=first_name]").val($j("#nomeField").val());
		$j("#pagamento input[name=last_name]").val($j("#cognomeField").val());
		$j("#pagamento input[name=address1]").val($j("#indirizzoField").val());
		$j("#pagamento input[name=city]").val($j("#cittàField").val());
		$j("#pagamento input[name=state]").val($j("#statoField").val());
		$j("#pagamento input[name=zip]").val($j("#capField").val());
		$j("#pagamento input[name=email]").val(email);
	}
	
	this.updatePaypalReturnURL = function(urlBase, trans_id, mailRegalo) {
		var stringaURL = urlBase + "/store/checkout?wetransid=" + trans_id;
		if (weStore.referer != null && weStore.referer != "") stringaURL += "&referer=" + weStore.referer;
		if (mailRegalo != null) {
			$j("input[name=custom]").val(trans_id + "," + mailRegalo);
			var arrayMail = mailRegalo.split("@");
			//$j("input[name=return]").val(stringaURL + "&regaloper=" + arrayMail[0] + "&dominio=" + arrayMail[1]);
			}
			else {
				//$j("input[name=return]").val(stringaURL);
				$j("input[name=custom]").val(trans_id);
			}
	}
	
	this.productStatus = function(urlBase, trans_id) {
		if ($j("#prodottoComboBox").val() == "abbonamento") {
			$j("#abbonamentoDiv").show();
			$j("#creditoDiv").hide();
			$j("#regalaP").show();
			$j("#indirizzoSpedizione").hide(300);
			weStore.updateTransactionCausale(trans_id,"abbonamento");
			weStore.regalaStatus(urlBase, trans_id);
			$j(".totale").html(""+weStore.costo_abbonamento);
			$j("input[name=amount]").val(weStore.costo_abbonamento);
			$j("input[name=item_name]").val("Abbonamento annuale digitale a Narcomafie");
			var data ="importo=" + weStore.costo_abbonamento + "&trans_id=" + trans_id ;
			weStore.updateUser(data);
		}
		else if ($j("#prodottoComboBox").val() == "credito") {
			$j("#regalaP").hide();
			$j("#abbonamentoDiv").hide();
			$j("#creditoDiv").show();
			$j("#indirizzoSpedizione").hide(300);
			weStore.updateTransactionCausale(trans_id,"credito");
			weStore.copieChange(trans_id);
			$j("input[name=item_name]").val("Ricarica credito Narcomafie.it");
			
		}
		else if ($j("#prodottoComboBox").val().match(/^abbonamentoC.*$/)) {
			$j("#abbonamentoDiv").show();
			$j("#creditoDiv").hide();
			$j("#regalaP").hide();
			/*$j("#pIvaP").hide();
			$j("#codFiscP").hide();*/
			$j("#indirizzoSpedizione").show(300);
			$j("#indirizzoSpedizione").get(0).checkValidity();
			
			if ($j("#prodottoComboBox").val() == "abbonamentoC") {
				$j("#statoSField").val("Italia");
				$j("#statoSField").attr("disabled","disabled");
				$j("#capSField").attr("pattern","^.{0}$|^[0-9]{5}$");
				$j("#provinciaSComboBox > option[value=AA]").remove();
				$j("#provSP").show();
				$j(".totale").html(""+weStore.costo_abbonamento_c);
				$j("input[name=amount]").val(weStore.costo_abbonamento_c);
				$j("input[name=item_name]").val("Abbonamento annuale cartaceo a Narcomafie");
				weStore.updateTransactionCausale(trans_id,"abbonamentoC");
				var data ="importo=" + weStore.costo_abbonamento_c + "&trans_id=" + trans_id ;
				weStore.updateUser(data);
			} else $j("#statoSField").removeAttr("disabled");
			if ($j("#prodottoComboBox").val() == "abbonamentoCE") { 
				$j("input[name=amount]").val(weStore.costo_abbonamento_ce);
				$j("input[name=item_name]").val("Abbonamento annuale cartaceo estero a Narcomafie");
				weStore.updateTransactionCausale(trans_id,"abbonamentoCE");
				$j("#provinciaSComboBox > option[value=AA]").remove();
				$j("#provinciaSComboBox").prepend("<option value='AA'>Non applicabile</option>");
				$j("#provinciaSComboBox").val("AA");
				$j("#capSField").removeAttr("pattern");
				$j("#provSP").hide();
				$j(".totale").html(""+weStore.costo_abbonamento_ce);
				var data ="importo=" + weStore.costo_abbonamento_ce + "&trans_id=" + trans_id ;
				weStore.updateUser(data);
			}
			if ($j("#prodottoComboBox").val() == "abbonamentoCS") { 
				$j("input[name=amount]").val(weStore.costo_abbonamento_cs);
				$j("input[name=item_name]").val("Abbonamento annuale cartaceo sostenitore a Narcomafie");
				weStore.updateTransactionCausale(trans_id,"abbonamentoCS");
				$j(".totale").html(""+weStore.costo_abbonamento_cs);
				$j("#capSField").removeAttr("pattern");
				$j("#provinciaSComboBox > option[value=AA]").remove();
				$j("#provinciaSComboBox").prepend("<option value='AA'>Non applicabile</option>");
				$j("#provSP").show();
				
				var data ="importo=" + weStore.costo_abbonamento_cs + "&trans_id=" + trans_id ;
				weStore.updateUser(data);
			}
			$j("#indirizzoSpedizione").get(0).checkValidity();
		}
		$j("input[name=custom]").val(trans_id);
	}
	
	this.copieChange = function (trans_id) {
		var importo = weStore.costo_singolo*$j("#numeroCopieComboBox").val();
		$j(".totale").html(importo+"");
		$j("input[name=amount]").val(importo);
		var data ="importo=" + importo + "&trans_id=" + trans_id ;
		weStore.updateUser(data);
	}
	
	this.populateCopie = function() {
		$j("#numeroCopieComboBox").get(0).options.length = 0;
		$j("#numeroCopieComboBox").get(0).options[0] = new Option('5',5);
		while ($j("#numeroCopieComboBox").get(0).options.length<7) {
			var nValue = 5 + $j("#numeroCopieComboBox").get(0).options.length;
			var nLabel = "" + nValue;
			$j("#numeroCopieComboBox").get(0).options[$j("#numeroCopieComboBox").get(0).options.length] = new Option(nLabel,nValue);
		}
	}
	
	this.listUsers = function(direction, searchTerm, start, howMany) {
		
		if (start !== undefined) {
			weStore.usersCursor = start;
		}
		if (howMany !== undefined) weStore.usersPerPage = howMany;
		if (direction === undefined) direction = 1;
		if (direction != 0) 
			weStore.usersCursor += direction * weStore.usersPerPage;
		if (weStore.usersCursor > weStore.numberOfUsers || weStore.usersCursor < 0) start = weStore.usersCursor = 0;
		else start = weStore.usersCursor;
		howMany = weStore.usersPerPage;
		weStore.log("start: " + start);
		weStore.log("howMany: " + howMany);
			
		var data= 'action=list&start=' + start + '&how_many=' + howMany;
		if (searchTerm !== undefined && searchTerm != null) data += '&search=' + searchTerm;
		$j.ajax ({
			type: "POST",
			url: weStore.url + "/data",
			data: data,
			datatype: "xml",
			success: function (xml){
				var corpoTabella = "";
				$j(xml).find('user').each(function(){
					corpoTabella += "<tr id='" + $j(this).attr('id') + "' class='userRow'>";
					corpoTabella += "<td>" + $j(this).find('name').text() + "</td>";
					if ($j(this).find('expiration').text() == '') corpoTabella += "<td>Mai abbonato</td>";
					else corpoTabella += "<td>" + $j(this).find('subscription').text() + "</td>";
					corpoTabella += "<td";
					($j(this).find('expired').text().trim() == "true") ? corpoTabella += " class='expired'>" : corpoTabella += ">";
					corpoTabella += $j(this).find('expiration').text() + "</td>";
					corpoTabella += "<td>" + $j(this).find('credit').text() + "</td>";
					corpoTabella += "<td class='resetPwd'>Reset pwd</td><td class='deleteUser'>Cancella</td><!--<td>Invia mail</td>--></tr>"	
				});
				$j("#listaUtenti>tbody").html(corpoTabella);
				$j(".userRow").click(function () {
					weStore.getDetailsFor($j(this).attr("id"));
				});
				$j(".userRow>.resetPwd").click( function(){
					var confirm = window.confirm("Vuoi resettare la password dell'utente? Riceverà un email con una nuova password generata casualmente.");
					if (confirm) $j.ajax({
						type: "POST",
						url: weStore.url + "/data",
						data: "action=resetpwd&username=" + $j(this).parent("tr").attr("id"),
						success: function(data) {
							if (data == "1") alert("Password resettata. L'utente è stato informato via posta elettronica");
							else alert("Qualcosa è andato storto.");
						}
					});
					return false;
				});
				$j(".userRow>.deleteUser").click( function() {
					var confirm = window.confirm("Vuoi eliminare l'utente? L'azione è irreversibile.");
					if (!confirm) return false;
					$j.ajax({
						type: "POST",
						url: weStore.url + "/data",
						data: "action=deleteuser&username=" + $j(this).parent("tr").attr("id"),
						success: function(data) {
							if (data == "1") alert("Utente eliminato");
							else alert("Qualcosa è andato storto.");
						}
					});
					weStore.listUsers(0);
					return false;
				})
			}
		 });
	};
	
	this.getDetailsFor = function (id) {
			$j.ajax({
				type: "POST",
				url: weStore.url + "/data",
				data: "action=details&username=" + id,
				datatype: "xml",
				success: function(xml) {
					$j(xml).find('userdata').each(function(){
						$j("#emailStaticPspan").html($j(this).find('user_email').text());
						$j("#emailField").val($j(this).find('user_email').text());
						$j("#emailStaticP").show();
						$j("#emailP").hide();
						
						$j("#nomeField").val($j(this).find('nome').text());
						if ($j(this).find('privato').text() == "1") {
							//if (!$j("input[name=genere]").val() == "privato") 
							$j("#privato").attr('checked','checked');
							$j("#persona_giuridica").removeAttr('checked');
							$j("#cognomeField").val($j(this).find('cognome').text());
							$j("#cognomeP").show();
							$j("#cognomeSField").val($j(this).find('cognomeS').text());
							$j("#cognomeSP").show();
							$j("#cognomeFField").val($j(this).find('cognomeF').text());
							$j("#cognomeFP").show();
							$j("#codFiscField").val($j(this).find('codfisc').text());
							$j("#codFiscP").show();
							$j("#pIvaP").hide();
						} else {
							//if (!$j("input[name=genere]").val() == "ente") 
							$j("#persona_giuridica").attr('checked','checked');
							$j("#privato").removeAttr('checked');
							$j("#cognomeP").hide();
							$j("#cognomeSP").hide();
							$j("#cognomeFP").hide();
							$j("#pIvaField").val($j(this).find('piva').text());
							$j("#codFiscP").hide();
							$j("#pIvaP").show();
						}
						
						$j("#nomeSField").val($j(this).find('nomeS').text());
						$j("#indirizzoSField").val($j(this).find('indirizzoS').text());
						$j("#capSField").val($j(this).find('capS').text());
						$j("#cittàSField").val($j(this).find('cittàS').text());
						$j("#provinciaSComboBox").val($j(this).find('provinciaS').text());
						$j("#statoSField").val($j(this).find('statoS').text());
						$j("#telSField").val($j(this).find('telefonoS').text());
						
						$j("#nomeFField").val($j(this).find('nomeF').text());
						$j("#indirizzoField").val($j(this).find('indirizzoF').text());
						$j("#capField").val($j(this).find('capF').text());
						$j("#cittàField").val($j(this).find('cittàF').text());
						$j("#provinciaComboBox").val($j(this).find('provinciaF').text());
						$j("#statoField").val($j(this).find('statoF').text());
						$j("#telField").val($j(this).find('telefonoF').text());
						
						if ($j(this).find('cartaceo').text() == "1") {
							$j("#digitaleRadio").removeAttr('checked');
							$j("#cartaceoRadio").attr('checked','checked');
							$j("#scadenzaP").show();
						} else {
							$j("#digitaleRadio").attr('checked','checked');
							$j("#cartaceoRadio").removeAttr('checked');
							$j("#scadenzaP").show();
						}
						if ($j(this).find('scadenza').text() == "") {
							$j("#cartaceoRadio").removeAttr('checked');
							$j("#digitaleRadio").removeAttr('checked');
							$j("#maiRadio").attr('checked','checked');
							$j("#scadenzaAbbonamentoField").val("");
							$j("#scadenzaP").hide();
						}
						$j("#scadenzaAbbonamentoField").val($j(this).find('scadenza').text());
						$j("#creditoField").val($j(this).find('credito').text());
						$j("#timestamp").html($j(this).find('modificato').text());
						$j("#backButton").show();
						$j("#aggiungiButton").hide();
						$j("#modificaButton").show();
						$j("#regform").get(0).checkValidity();
						$j("#anagrafica").get(0).checkValidity();
						$j("#anagrafica").show();
						$j("#indirizzoSpedizione").get(0).checkValidity();
						$j("#indirizzoSpedizione").show();
						$j("#userDetails").show();
						$j("#listaUtenti").hide();
						$j("#prevButton").hide();
						$j("#nextButton").hide();
						$j("#searchP").hide();
						$j("#genereP").hide();
						$j("#emailField").get(0).checkValidity();
						
					});
				}
			});
		}
	
	this.resetClickAnd = function () {
		weStore.log("click document");
		weStore.clickNumber = 0;
		$j(".clickAnd").html("&nbsp;");
		$j(".clickAnd").animate({
			width: "50px"
		}, 400, function () {
			$j(".clickAnd").css("background","#009900");
			$j(".clickAnd").html("€2");
		});
		$j(document).unbind("click");
	}
};
