/* IOL PIsa
 * 0.4 Invia la mail ad un amico
 * 0.5 Alert via email
 * 0.6 Fix per IE 6
 * 0.7 Conteggio automatico annunci in HP
 * 0.7.1 Cancellazione completa cookie annunci favoriti
 * 0.8.1 Gestione inserimento nuovi annunci
 * 0.8.2 Reso parametrico il separatore dei links ultime ricerche
 * 0.8.3 Disabilitazione link "Annunci preferiti" nella pagina di visualizzazione preferiti
 * 0.8.4 Modifica alberatura oggetto emailAlert
 * 0.8.5 Gestione form emailAlert in HomePage
 * 0.8.6 Modifica alberatura oggetto emailToFriend. INserimento messaggi in HP in seguito invio amico
 * 0.8.7 Modifiche per emailToFriend
 */
var annunciData={
	IOLjsVersion:'/jss/IOLjs/IOLjs.console.0.1.js',
	favourites:
	{
		annunciFavouritesCookieName:"annfvs",
		annunciFavouritesDisplayLinkName:"saved-ads-link",
		annunciFavouritesDisplayLinkText:"saved-ads-link-text",
		annunciFavouritesDisplayDivName:"saved-ads-div-text",
		savedTabs:"",
		docCookies:"",
		console:{ log:function(){}, close:function(){} },
		init:function ()
		{
			//Da eseguire sul document ready!
			//alert("init fav");
			if(this.docCookies==="")
			{
				try{
					this.console = IOLjs.console;
				}
				catch(ec)
				{}
				this.docCookies = IOLjs.cookies;
				//alert("doc cookies");
			}
			
			if(this.savedTabs==="")
			{
				this.savedTabs = [];
				var a=this.docCookies.get(this.annunciFavouritesCookieName);
				if( a !== "" )
				{
					this.savedTabs=a.split(",");
				}
			}
			this.marksAll();
			this.showCounter();
			return;
		},

		marksAll:function()
		{
			for(var a=0;a<this.savedTabs.length;a++)
			{
				var b="#star_" + this.savedTabs[a];
				if ( ( $(b) ) && ($(b).hasClass("ad-star-grey")) )
				{
					$(b).removeClass("ad-star-grey");
					$(b).addClass("ad-star-yellow");
				}
			}
		},
		
		save:function ()
		{
			
			this.docCookies.set( { 'name':this.annunciFavouritesCookieName,
									'value':this.savedTabs.join(","),
									'expire':10*365 } );
		},

		erase:function()
		{
			this.docCookies.unset( { 'name':this.annunciFavouritesCookieName,'path':"/" } );
			this.docCookies.unset( { 'name':this.annunciFavouritesCookieName,'path':"/annunci/" } );
			//window.location.reload();
			window.location.href="/hpannunci.html";
		},

		click:function(idValue)
		{
			//IOLjs.console.log(idValue);
			this.toggle(idValue);
		},

		
		toggle:function(idValue)
		{
		
			var b="#star_" + idValue;
			if($(b).hasClass("ad-star-grey"))
			{
				$(b).removeClass("ad-star-grey");
				$(b).addClass("ad-star-yellow");
				this.savedTabs.push(idValue);
			}
			else
			{
				$(b).removeClass("ad-star-yellow");
				$(b).addClass("ad-star-grey");
				
				a=$.inArray(idValue,this.savedTabs);
				while ( a !== -1 )
				{
					this.savedTabs.splice(a,1);
					a=$.inArray(idValue,this.savedTabs);
				}
				
				
			}
			this.showCounter();
			this.save();
		},

		clickOnFrameFav:function(b)
		{
			var a=Yakaz.get(b).getElementsByTagName("button")[0];
			toggleFav(a,b);
		},

		showCounter:function()
		{
			//Visualizza quanti sono gli annunci selezionati
			var b=$("#" + this.annunciFavouritesDisplayDivName);
			var adsCount = this.savedTabs.length;
				
			if(adsCount>=1)
			{
				var self = this;
				$("#"+this.annunciFavouritesDisplayLinkName).bind("click", function(){
					self.lookup();
					return false;
				});
				$("#"+this.annunciFavouritesDisplayLinkName).removeClass("disabled");
				$("#saved-ads").show();
				if (adsCount===1) {
					$(b).html("<b>" + adsCount + "</b> Annuncio preferito");
				}
				else {
					$(b).html("<b>" + adsCount + "</b> Annunci preferiti");
				}
				$("#" + this.annunciFavouritesDisplayLinkText).html("Annunci preferiti (" + adsCount + ")");
			}
			else
			{
				$("#"+this.annunciFavouritesDisplayLinkName).bind( "click",  function(){
					return false;
				});
				$("#"+this.annunciFavouritesDisplayLinkName).addClass("disabled");
				$("#saved-ads").hide();
			}
		},
		
		lookup:function()
		{
			if ( this.savedTabs.length > 0 ) 
			{
				document.location.href= "/annunci/abin/annunci?idart=" + this.savedTabs.join("|");
			}
		}
	},
	lastSearches:
	{
		linksSep:"&#160;&#160;-&#160;&#160;",
		mainDivShowHide:"",
		reset:function(){
			IOLjs.cookies.unset( { 'name':"saa",'path':"/" } );
			IOLjs.cookies.unset( { 'name':"saa",'path':"/annunci/" } );
			$("#" + mainDivShowHide).hide();
		},
		showInDiv:function(mainDivId,divId,linksSep) {
			if (typeof(linksSep)!='undefined')
			{
				this.linksSep=linksSep;
			}
			if ( ( $("#" + mainDivId).length > 0 ) && ( $("#" + divId).length > 0 ) )
			{
				mainDivShowHide=mainDivId;
				$( "#" + divId).empty();
				var saaCookie = IOLjs.cookies.get("saa");
				if (saaCookie !== '')
				{
					var saaCookieDecoded = Base64.decode(saaCookie);
					if (saaCookieDecoded.length >= 0)
					{
						
						var saaItems = saaCookieDecoded.split("|");
						$("#" + mainDivId).show();
						var saaI;
						for (saaI=0; saaI<saaItems.length; saaI++)
						{
							if (saaI>0)
							{
								$( "#" + divId  ).append(this.linksSep);
							}
							var itemData = unescape(saaItems[saaI].replace(/\+/g," ")).split(",");
							$( "#" + divId  ).append( this._getLinkHtml( itemData ) );
						}
						if (saaI){
							$("#"+mainDivShowHide).show();
						}
					}
				}
			}
		},
		_getLinkHtml:function(itemData)
		{
			if ( typeof(itemData!=='undefined') )
			{
				return '<a style="white-space: nowrap;" href="/annunci/abin/annunci?query=' + escape(itemData[1]) + 
											'&searchCity=' + escape( IOLjs.strings.getValueOrDefault(itemData[2],'-','') ) + 
											'&ta=' + IOLjs.strings.getValueOrDefault(itemData[0],'','-1') + '" class="citta_lnk " >' + (itemData[1] + IOLjs.strings.getValueOrDefault(itemData[2],'-','',', ')) + '</a>';
			}
			else
			{
				return "";
			}
		}
	
	},
	commands:{
		emailToFriend: this.emailToFriend
	},
	
	emailToFriend:
	{
		opened:false,
		fieldsOuterDiv:'friendEmailBox',
		//messagesOuterDiv:'outer_email_form_messages',
		formDivName : 'emailFriendFormDiv',
		formTitleDivName : 'emailFriendTitle',
		selectedArtId:-1,
		closeDiv: function(artId){
			this.opened = false;
			if ( typeof(artId)==='undefined' )
			{
				artId = this.selectedArtId;
			}
			$("#closeEmailForm_" + artId).hide();
			$("#openEmailForm_" + artId).show();
			$("#" + this.fieldsOuterDiv ).hide();
			//$("#" + this.messagesOuterDiv ).hide();
			this.selectedArtId = -1;
		},
		openDiv: function(artId, md5){
			this.opened = true;
			this.selectedArtId = artId;
			$("#email_friend_messages").html("");
			$("#" + this.formDivName).show();
			$(".openEmailForm").show();
			$(".closeEmailForm").hide();
			//$("#" + this.messagesOuterDiv ).hide();
			$("#email_artid").val(artId);
			$("#email_md5").val(md5);
			$("#openEmailForm_" + artId).hide();
			$("#closeEmailForm_" + artId).show();
			$("#" + this.fieldsOuterDiv ).show();
			$("#" + this.fieldsOuterDiv ).css({	"top":$("#closeEmailForm_" + artId).offset().top + 20,
												"left":$("#closeEmailForm_" + artId).offset().left-390
											});

		},
		openSaveCompletedMsg:function( email ) {
			//if ( this.openPopupBox() === true ) {
			if ( this.opened === true ) {
				$("#" + this.formDivName).hide();
				$("#" + this.formTitleDivName ).hide();
				newMsg = "L'invio dell'email all'amico è stata registrata.<br/>" +
							"Per completare l'invio, clicca sul link presente nella e-mail<br/>"+
							"di conferma che ti è stata inviata all'indirizzo<br/><br/>"+
							"<span class='confirmEmailClass'>" + email + "</span>";
				$("#email_friend_messages").html(newMsg);
			}
		},
		send:function(){
			var email_target = $("#email_target").val();
			var email_source = $("#email_source").val();
			var self=this;
			if (annunciData.tests.isValidEmail(email_target) === false)
			{
				alert("Indirizzo Email dell'amico non valido!");
				return false; 
			}
			
			if (annunciData.tests.isValidEmail(email_source) === false)
			{
				alert("Indirizzo email non valido!");
				return false; 
			}

			var artId = $("#email_artid").val();
			//$("#" + this.fieldsOuterDiv ).hide();
			//$("#" + this.messagesOuterDiv ).show();
			/*$("#" + this.messagesOuterDiv).css({	"top":$("#closeEmailForm_" + artId).offset().top + 20,
													"left":$("#closeEmailForm_" + artId).offset().left-0
												});
			*/
			$.get('/annunci/abin/inam.pl',
					{
						idart:$("#email_artid").val(),
						m:$("#email_md5").val(),
						b:$("#email_body").val(),
						to:$("#email_target").val(),
						from:$("#email_source").val()
					},
					function(data) {
						var newMsg="";
						if (data==='1') {
							newMsg = "L' e-mail è stata inviata!";
							self.openSaveCompletedMsg($("#email_source").val());
						}
						else {
							newMsg = "L' e-mail non è stata inviata! Si prega di riprovare!";
							$("#email_friend_messages").html(newMsg);
						}
					}
				);
		},
		showHPMessage:function()
		{
			//Visualizza in HP il messaggio di invio email ad amico
			var msg="";
			switch (IOLjs.location.params.get('cfa'))
			{
				case "1":
					msg = "Email ad un amico inviata";
					break;
				case "-1":
					msg = "Email ad un amico non inviata";
					break;
				default:
					
					break;
			}
			if ( msg !== '' )
			{
				$("#innerHpMessages").html( msg );
				$("#hpMessages").show();
			}
			
		},
		hideHPMessage:function()
		{
			$("#innerHpMessages").html( "" );
			$("#hpMessages").hide();
		}

	},
	emailAlert:
	{
		opened:false,
		openFormHP:function() {
			if ( this.opened === true )
			{
				return;
			}
			$("#tabsAnnunci").hide();
			$("#alert_email_messages").html("");
			$("#emailAlertTitle").show();
			$("#emailAlertBox").show();
			$("#emailAlertFormDiv").show();
			
			$("#emailAlertClosed").hide();
			$("#emailAlertOpened").show();
			this.opened = true;
		},
		closeFormHP:function()
		{
			$("#emailAlertBox").hide();
			$("#tabsAnnunci").show();
			$("#emailAlertClosed").show();
			$("#emailAlertOpened").hide();
			this.opened = false;
		},

		openPopupBox:function()
		{
			if ( this.opened === true ) {
				return true;
			}
			$("#alert_email_messages").html("");
			$("#emailAlertBox").show();
			$("#emailAlertBox").css({
				"margin-top":($(window).height()/2 -$("#emailAlertBox").outerHeight()/2),
				"margin-left":($(window).width()/2 -$("#emailAlertBox").outerWidth()/2)
				}
			);
			$("body").append("<div id='background' class='background' ></div>");
			var self=this;
			$("#background").bind("click",function(){
				self.closePopup();
			});
			this.opened = true;
			return true;
		},
		openPopup:function()
		{
			if ( this.openPopupBox() === true ) {
				$("#emailAlertTitle").show();
				$("#emailAlertFormDiv").show();
			}
		},
		closePopup:function()
		{
			$("#emailAlertBox").hide();
			$("#background").remove();
			this.opened = false;
		},
		openSaveCompletedMsg:function( email ) {
			if ( this.openPopupBox() === true ) {
				$("#emailAlertFormDiv").hide();
				$("#emailAlertTitle").hide();
				newMsg = "Il tuo avviso è stato registrato.<br/>" +
							"Per completare l'attivazione, clicca sul link presente nella e-mail<br/>"+
							"di conferma che ti è stata inviata all'indirizzo<br/><br/>"+
							"<span class='confirmEmailClass'>" + email + "</span>";
				$("#alert_email_messages").html(newMsg);
			}
		},
		save:function(gotoSearchResults)
		{
			var email = $("#emailAlertEmail").val();
			var emailFreq = $("#emailAlertFrequency").val();
			var emailQuery = $("#emailAlertQuery").val();
			var emailDove = $("#emailAlertDove").val();
			var self=this;
			if (annunciData.tests.isValidEmail(email) === true)
			{
				$.get('/annunci/abin/saveEmailAlert.pl',
					{
						email:email,
						freq:emailFreq,
						query:emailQuery,
						dv:emailDove
					},
					function(data) {
						var newMsg="";
						if (data === '1') {
							if ( ( typeof(gotoSearchResults)!=='undefined' ) && ( gotoSearchResults===1 ) )
							{
								var url = "/annunci/abin/annunci?ta=-1&query=" + escape(emailQuery) + 
											"&searchCity=&email=" + escape(email);
								location.href = url;
							}
							else
							{
								self.openSaveCompletedMsg(email);
							}
						}
						else {
							newMsg = "Il tuo avviso non è stato registrato! Si prega di riprovare!";
							$("#alert_email_messages").html(newMsg);

						}
					}
				);					
			}
			else
			{
				alert("Indirizzo email non valido!");
				return false;
			}
			
		},
		showHPMessage:function()
		{
			//Visualizza in HP il messaggio di attivazione o rimozione nel caso che esse siano state effettuate
			var msg="";
			switch (IOLjs.location.params.get('al'))
			{
				case "1":
					msg = "Avviso attivato";
					break;
				case "-1":
					msg = "Avviso non attivato";
					break;
				case "2":
					msg = "Avviso annullato";
					break;
				case "-2":
					msg = "Avviso non annullato";
					break;
				default:
					
					break;
			}
			if ( msg !== '' )
			{
				$("#innerHpMessages").html( msg );
				$("#hpMessages").show();
			}
			
		},
		hideHPMessage:function()
		{
			$("#innerHpMessages").html( "" );
			$("#hpMessages").hide();
		}
		
	},
	hpTotalAdvs: {
		advAreaSelected:'',
		totalAvds:{},
		totalSites:0,
		parentDivId:"",
		valueDivId:"",
		sitesCountDivId:"",
		timeInterval:2000,
		separator:' ',
		frequency: 2,
		timerId: 0,
		start: function( parentDivId, sitesCountDivId, valueDivId, sitesCount, startAdvCountObj, advAreaSelected )
		{
			this.advAreaSelected = advAreaSelected;
			this.totalAvds = startAdvCountObj;
			this.totalSites = sitesCount;

			this.parentDivId = parentDivId;
			this.valueDivId = valueDivId;
			this.sitesCountDivId = sitesCountDivId;

			$("#" + this.sitesCountDivId).html( this._formatNumber(this.totalSites) ); 
			this.refreshTotal();
			$("#" + this.parentDivId).show( ); 
		},
		changeArea: function(newArea)
		{
			this.advAreaSelected = newArea;
			clearTimeout(this.timerId);
			this.refreshTotal();
		},
		refreshTotal: function()
		{
			if ( this.valueDivId!=='' ) {
				if ( typeof(this.totalAvds[this.advAreaSelected]) !== 'undefined' ) 
				{
					$("#" + this.valueDivId).html( this._formatNumber( this.totalAvds[this.advAreaSelected] ) ); 
					$("#" + this.parentDivId).show( ); 
					var self=this;
					//Aggiorno tutti i totali
					$.each(this.totalAvds,function(key,value){
							self.totalAvds[key] += self.frequency * 2 * Math.random();
						});
					
					
					if( this.frequency>0 ){
						this.timerId = setTimeout("annunciData.hpTotalAdvs.refreshTotal()",this.timeInterval);
					}

				}
				else {
					$("#" + this.valueDivId).html("");
					$("#" + this.parentDivId).hide( ); 
				}
			}
		},
		_formatNumber: function(b)
		{
			var outString="";
			b=parseInt(b,10);
			b=b.toString();
			nb_char=b.length;
			while (nb_char>0)
			{
				part1="";
				part2="";
				if ( nb_char>3 )  
				{
					part1=b.substr(0,nb_char-3);
					part2=b.substr(nb_char-3,3);
				}
				else
				{
					part1 = "";
					part2 = b;
				}	
				outString = part2 + ( outString != '' ? this.separator : "" ) +  outString;
				b = part1;
				nb_char=b.length;
			}
			return outString;
		}
	},
	newAds:{
		sitesOK : [	{name:'Vivastreet',url:'www.vivastreet.it'},
					{name:'Olx',url:'www.olx.it'},
					{name:'Annunci.net',url:'www.annunci.net'},
					{name:'Kijiji',url:'www.kijiji.it'}
					],
		init: function() {
			$("ul").html();
			$.each(this.sitesOK,function(){
				//alert(this.name);
				$("#sitesListDiv ul").append('<li><a href="http://' + this.url + '" target="_blank" class="citta_lnk">' + this.name + '</a></li>');
			});
			$('#sitesListLnk').toggle(
				function() { $('#sitesListDiv').show(); },
				function() { $('#sitesListDiv').hide(); }
			);
		},
		showFeedFields : function() {
			$("#confirmMsgDiv").hide();
			$('#insertFormDiv').show();
		},
		addFeed : function(formId) {
			var urlValue = $("#furl").val();
			//alert(urlValue);
			var siteOkFound=false;
			$.each(this.sitesOK,function(){
				var prefixValidHttp = "http://" + this.url + "/";
				var prefixValidSimple = this.url + "/";
				if ( ( urlValue.indexOf(prefixValidSimple)===0 ) || ( urlValue.indexOf(prefixValidHttp)===0 ) )
				{
					siteOkFound=true;
				}
			});
			$('#messages').removeClass('messagesKO');
			$('#messages').removeClass('messagesOK');
			if ( siteOkFound === false ) 
			{
				$('#innerMessages').html("Bad url");
				$('#messages').addClass('messagesKO');
				$('#messages').show();
				return false;
			}
			if (annunciData.tests.isValidEmail($("#femail").val()) === false)
			{
				$('#innerMessages').html("Indirizzo Email non valido!");
				$('#messages').addClass('messagesKO');
				$('#messages').show();
				return false; 
			}
			if ( $("#fcategory").val() === '-1' )
			{
				$('#innerMessages').html("Categoria non valida!");
				$('#messages').addClass('messagesKO');
				$('#messages').show();
				return false; 
			}
			$('#messages').hide();

			$.get('/annunci/abin/insertAds.pl',
					{
						url:$("#furl").val(),
						email:$("#femail").val(),
						category:$("#fcategory").val()
					},
					function(data) {
						var newMsg="";
						if (data==='1') {
							newMsg = "L' e-mail è stata inviata!";
							$("#confirmMsgDiv").show();
							$("#insertFormDiv").hide();
						}
						else {
							newMsg = "L' e-mail non è stata inviata! Si prega di riprovare!";
							$('#innerMessages').html(newMsg);
							$('#messages').addClass('messagesOK');
							$('#messages').show();
						}
						/*
						$('#innerMessages').html(newMsg);
						$('#messages').addClass('messagesOK');
						$('#messages').show();
						*/
					}
				);

		},
		hideMessage:function()
		{
			$("#innerMessages").html( "" );
			$("#messages").hide();
		},
		showHPMessage:function()
		{
			//Visualizza in HP il messaggio di attivazione o rimozione nel caso che esse siano state effettuate
			var msg="";
			switch (IOLjs.location.params.get('ia'))
			{
				case "1":
					msg = "Invio di annuncio confermato";
					break;
				case "-1":
					msg = "Invio di annuncio non confermato";
					break;
				default:
					
					break;
			}
			if ( msg !== '' )
			{
				$("#innerHpMessages").html( msg );
				$("#hpMessages").show();
			}
			
		},
		hideHPMessage:function()
		{
			$("#innerHpMessages").html( "" );
			$("#hpMessages").hide();
		}
		

	
	},
	tests:{
		isValidEmail:function(emailToCheck)
		{
			var emailRegex= new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
			if ( ! emailRegex.test(emailToCheck) )
			{
				return false; 
			}
			else
			{
				return true;
			}
		}
	}
};

$(document).ready(	function() {
						annunciData.favourites.init();
					}
				 );

