dojo.require('dojo.rpc.JsonService');
dojo.require("dojo.fx");


var rpcDef1 = {
	"serviceType": "JSON-RPC",
	"serviceURL": "/json/userPanel.php",
	"methods":[
		{
			"name": "saveObject",
			"parameters":[
				{"name": "sObject"}
			]
		},
		{
			"name": "updateObject",
			"parameters":[
				{"name": "sObject"}
			]
		},
		{
			"name": "deleteObject",
			"parameters":[
				{"name": "sObject"}
			]
		},
		{
			"name": "doLogout"
		},
		{
			"name": "getUserItemCountsRaw"
		},
		{
			"name": "saveNotes",
			"parameters": [
			    {"name": "sObject"}
			]
		},
		{
			"name": "isSearchSaved",
			"parameters":[
				{"name": "uniqRef"}
			]
		},
		{
			"name": "fetchNextBookmarkedAd",
			"parameters":[
			    {"name": "nCurrentPage"},
			    {"name" : "nItemsPerPage"}
			 ]
			
		}
	]
}

var userPanel = new dojo.rpc.JsonService(rpcDef1);

function bookmarkAction(id, adsType, action) {
	switch (action) {
		case "saveNotes":
		case "update":
			var notes = (dojo.byId('adsNotes-writable-text-'+id).value).trim();
			var properties = {
				'fkAdsId' : id,
				'adsType' : adsType,
				'notes' : notes
			};
		break;
		default:
			var properties = {
				'fkAdsId' : id,
				'adsType' : adsType
			} 
		break;
	}
	var callback = function(res) {
		bookmarkedAdsHandler(id, action, res);
	}
	normalizedAction = action;
	
	if (action == "deleteInPlace") {
		normalizedAction = 'delete';
	}
	if (action == "saveInPlace") {
		normalizedAction = 'save';
	}
	userPanelAction('BookmarkedAds', properties, normalizedAction, callback);
}

function userAdAction(id, action) {
	userPanelAction('UserAds', {'id' : id}, action, function() {window.location.reload()});
}

function doLogout(locationToLoad) {
	var deferred = userPanel.doLogout();
	deferred.addCallback(
		function(res) {
			ekFacebook.logout();
			
			if (!locationToLoad) {
				window.location.reload();
			} else {
				window.location = locationToLoad;
			}
		}
	);
}

function userPanelAction(type, properties, action, callback) {
	var deferred;
	var temp;

	switch (action) {
		case "save":
			deferred = userPanel.saveObject(
					{'type' : type, 
					'properties' : properties
			});
			temp = function(res) { 
				callback(res); updateUserItemsCount(); 
			};
			break;
		case "update":
				deferred = userPanel.updateObject(
					{'type' : type, 
					'properties' : properties
			});
			break;
		case "delete":
			deferred = userPanel.deleteObject(
					{'type' : type, 
					'properties' : properties
			});
			temp = function(res) { 
				callback(res);
				updateUserItemsCount(); 
			};
			break;
		case "saveNotes":
			deferred = userPanel.saveNotes(
				{'type' : type,
				'properties' : properties
			});
			temp = function(res) {
				callback(res);
				finishedEditing(properties.fkAdsId, res);
			};
			break;
	}
	if (temp) {
		deferred.addCallback(temp);
	} else {
		deferred.addCallback(callback);
	}
}

function bookmarkedAdsHandler(id, action, res) {
	if (action=='delete' && res==true) {
		show("cancellando"+id);
		actions(id);
	} else if (action=='save' && res==true) {
		alert("Annuncio salvato tra i preferiti");
		window.location.reload();
	} else if(action=='deleteInPlace' && res==true) {
		showBookmarkAction('Save', id);
	} else if(action=='saveInPlace' && res==true) {
		showBookmarkAction('Delete', id);
	} else {
		if (res == 'noauth') {
			VsUserDialog.show('Login');	
		} else {
			//alert(res);
		}
	}
}

function updateUserItemsCount() {
	var deferred = userPanel.getUserItemCountsRaw();
	function updateUserPanel(res) {
		if (dojo.byId('numBookmarkedAds')) {
			dojo.byId('numBookmarkedAds').innerHTML = res.numBookmarkedAds;
		}
		if (dojo.byId('numBookmarkedSearches')) {
			dojo.byId('numBookmarkedSearches').innerHTML = res.numBookmarkedSearches;
		}
		if (dojo.byId('numUserAds')) {
			dojo.byId('numUserAds').innerHTML = res.numUserAds;
		}
	}

	deferred.addCallback(updateUserPanel);
}

function addModifyTextarea(adsId)
{
	var textAreaContainer = dojo.byId('adsNotes-'+adsId);
	var buttonContainer = dojo.byId('adsNotesButton-'+adsId);

	var button = document.createElement('input');
	button.type="button";
	button.value="salva";
	button.onclick = function () {
		bookmarkAction(adsId, 'ad', 'update');
	}
	var textarea = document.createElement('textarea');
	textarea.rows = 3;
	textarea.cols= 45;
	textarea.id = "notes-"+adsId;
	textarea.value = textAreaContainer.innerHTML;

	buttonContainer.innerHTML = '';
	buttonContainer.appendChild(button);

	textAreaContainer.innerHTML = '';
	textAreaContainer.appendChild(textarea);
}


function removeModifyTextarea(adsId)
{
	var textAreaContainer = dojo.byId('adsNotes-'+adsId);
	var buttonContainer = dojo.byId('adsNotesButton-'+adsId);
	var button = document.createElement('input');
	button.type= "button";
	button.value= "modifica";
	button.onclick = function () {
		addModifyTextarea(adsId);
	}
	buttonContainer.innerHTML = '';
	buttonContainer.appendChild(button);

	textAreaContainer.innerHTML = dojo.byId("notes-"+adsId).value;
}

function toggleShowNotesBox(id) {
	var block = dojo.byId('adsNotesBlock-'+id);
	var link = dojo.byId('adsNotesLink-'+id);
	var showNotesButton = dojo.byId('showNotesButton-' + id);
	var addNotesButton = dojo.byId('addNotesButton-' + id);

	if (notesBuffer[id] == null || notesBuffer[id] == '') {
		showNotesButton.style.display = 'none';
		addNotesButton.style.display = 'block';
	} else {
		showNotesButton.style.display = 'block';
		addNotesButton.style.display = 'none';
	}
	if (block.style.display == "block") {
		block.style.display = 'none';
	} else if (block.style.display == "none") {
		block.style.display = 'block';
	}
}

notesBuffer = Array();
function switchToEditing(id) {
	var textAreaContainer = dojo.byId('adsNotes-writable-'+id);
	var callToAction = dojo.byId('adsNotes-clickable-'+id);
	var textArea = dojo.byId('adsNotes-writable-text-'+id);

	textAreaContainer.style.display = 'block';
	callToAction.style.display = 'none';
	textArea.value = notesBuffer[id];
	textArea.focus();
}

function finishedEditing(id, editedNote) {
	var textAreaContainer = dojo.byId('adsNotes-writable-'+id);
	var callToActionContainer = dojo.byId('adsNotes-clickable-'+id);
	var callToAction = dojo.byId('adsNotes-clickable-text-'+id);

	textAreaContainer.style.display = 'none';
	callToActionContainer.style.display = 'block';

	notesBuffer[id] = editedNote;
	if (editedNote == '') {
		callToAction.innerHTML = dojo.byId('labelText').innerHTML;// "Aggiungi
																	// una nota
																	// sull'annuncio";
	} else {
		callToAction.innerHTML = notesBuffer[id]
			+ dojo.byId('labelText2').innerHTML;// "Clicca qui per modificare";;
	}
}

function saveNote(id) {
	bookmarkAction(id, 'ad', 'saveNotes');
}

/**
 * 
 * 
 * @param id
 * @param lat @deprecated now you should create manually: miniMap(id, lat, lng, 6);
 * @param lng @deprecated now you should create manually: miniMap(id, lat, lng, 6);
 * @param labelText
 * @return
 */
function togglePreviewBox(id, lat, lng,labelText) {
	var box = dojo.byId('previewBox-' + id);
	var label = dojo.byId('previewLabel-'+id);
	var imageOpen = dojo.byId('previewImageOpen-'+id);
	var imageClose = dojo.byId('previewImageClose-'+id);
	var footer = dojo.byId('item_footer_'+id);

	if(box.style.visibility == 'visible') {
		box.style.visibility = 'hidden';
		box.style.display = 'none';
		box.style.height = '1px';
		label.innerHTML = labelText;
		imageOpen.style.display = 'block';
		imageClose.style.display = 'none';
		footer.style.display = 'block';
	} else if(box.style.visibility == "hidden") {
		box.style.display = 'block';
		box.style.visibility = 'visible';
		box.style.height = null;
		label.innerHTML = labelText;
		imageOpen.style.display = 'none';
		imageClose.style.display = 'block';
		if (lat != null && lng != null) {
			footer.style.display = 'none';
		}
	}
}

function connectContact(id,provenienza,type) {
	dojo.addOnLoad(function() {
		if (dojo.byId('contact-' + id)) {
			dojo.connect(dojo.byId('contact-' + id), 'onclick', function (evt) {
				dojo.stopEvent(evt);
				var sBaseUrl = escape(location.href);
				VsUserDialog.show('privateContact',{page: "/over/"+type+"/" + id + ".html?bu="+sBaseUrl+"&prov="+provenienza});
			});
		}		
	});
}

function connectOverStatic(id,n) {
	dojo.require("dijit._base.place");
	var staticPageTitles = new Array();

	if (n == undefined)
		n = '';
	
	dojo.addOnLoad(function() {
		if (dojo.byId('popup-'+id+n)) {
			dojo.connect(dojo.byId('popup-'+id+n), 'onclick', function (evt) {
				dojo.stopEvent(evt);
				
				var sBaseUrl = escape(location.href);
				VsUserDialog.show(id,{page: '/over/'+id+'/'});
			});
		}
	})
}

function showBookmarkAction(type, id) {
	if (document.getElementById('bookmarkSave-' + id)) {
		document.getElementById('bookmarkSave-' + id).style.display = 'none';
	}
	if (document.getElementById('bookmarkDelete-' + id)) {
		document.getElementById('bookmarkDelete-' + id).style.display = 'none';
	}


	if (document.getElementById('bookmark' + type + '-' + id)) {
		document.getElementById('bookmark' + type + '-' + id).style.display = 'block';
	}
}


function reload(id) {
	var newHref = "";
	var tokens = location.href.split('#');
	for (i = 0; i < tokens.length - 1; i++) {
		newHref += tokens[i];
	}
	location.href = newHref + '#' + 'start' + id;
	location.reload();
}
function launchSearch(url, evt) {
	dojo.stopEvent(evt);
	location.href = url;
}
function toggleEmail(id, sendMail, evt, updateFunction) {
	if (evt) {
		dojo.stopEvent(evt);
	}
	var properties = {
		'id' : id,
		'sendEmail' : sendMail
	}
	userPanelAction('BookmarkedSearches', properties, 'update', function() {
		if (updateFunction) {
			updateFunction();
		} else {
			reload(id)
		}
	});
}
function deleteSearch(id, evt) {
	dojo.stopEvent(evt);
	var properties = {
		'id' : id
	}
	userPanelAction('BookmarkedSearches', properties, 'delete', function() {reload(id)});
}

function connectActions(url, id, sendMail) {
	dojo.connect(dojo.byId('bookmarkedSearchesActionLaunch' + id),
			'onclick', this, function(evt) {launchSearch(url, evt)});
	dojo.connect(dojo.byId('bookmarkedSearchesActionToggleEmail' + id),
			'onclick', this, function(evt) {toggleEmail(id, sendMail, evt)});
	dojo.connect(dojo.byId('bookmarkedSearchesActionDelete' + id),
			'onclick', this, function(evt) {
					deleteSearch(id, evt);
			});
}

function connectHoverEffect(id) {
	dojo.connect(dojo.byId('snipAd-' + id),
			'onmouseover', this, function(evt) {
		SetOpacity(document.getElementById('adPanel-' + id), 100);
	});
	dojo.connect(dojo.byId('snipAd-' + id),
			'onmouseout', this, function(evt) {
		SetOpacity(document.getElementById('adPanel-' + id), 50);
	});
}


function connectLinkEffect(id, url, src) {
	dojo.connect(dojo.byId('bubbleClickContainer-' + id), 'onclick', this, function(evt) {
		var target = evt.target ? evt.target : evt.srcElement;
		if(target.className.indexOf('noRedirect') < 0) {
			VsUtil.windowLocationReverse(url);
		}
	});
	
	if(dojo.byId('adDescriptionText-' + id)) {
		dojo.connect(dojo.byId('adDescriptionText-' + id), 'onclick', this, function(evt) {
			var target = evt.target ? evt.target : evt.srcElement;
			if(target.className.indexOf('noRedirect') < 0) {
				VsUtil.windowLocationReverse(url);
			}
		});
	}
}

	function onOverAd(id) {
		dojo.byId('snipAd-' + id).style.cursor = 'hand';
		dojo.byId('snipAd-' + id).style.backgroundColor = '#F0F0F0';
	}
	
	function onOutAd(id) {
		dojo.byId('snipAd-' + id).style.cursor = 'pointer';
		dojo.byId('snipAd-' + id).style.backgroundColor = 'white';
	}

		function _isChildOf(parent, child) {
			if( child != null ) {			
				while( child.parentNode ) {
					if( (child = child.parentNode) == parent ) {
						return true;
					}
				}
			}
			return false;
		}
		
		function fixOnMouseOut(element, event, functionCallString) {
			if (dojo.isIE && dojo.isIE <9) { 
				var target = null;
				if( event.toElement ) {				
					target = event.toElement;
				} else if(event.relatedTarget ) {				
					target = event.relatedTarget;
				}
				if( !_isChildOf(element, target) && element != target ) {
					//TODO: need to EVAL javascript code to AVOID finally IE Flickering.
					eval(functionCallString);
				}
			} else {
				eval(functionCallString);
			}
		}

function connectAgencyMap(advertiserUrl, comuneKeyurl, id) {
	if (dojo.byId('map-' + id)) {

		dojo.connect(dojo.byId('map-' + id), 'onclick', function (evt) {
			dojo.stopEvent(evt);
			VsUserDialog.show('Map',{page: "/over/mappaagenzia/" + advertiserUrl + "-" +
					comuneKeyurl + "-" + "agenzia" + "_" + id + ".html"});
		});

	}
}




function addClass (element,className){
	var classAux = element.className;
	element.className = classAux +" "+ className;
}

function deleteClass(element,className){
	var classAux = element.className;
	classAux = classAux.replace(className,"");
	element.className = classAux;
}
	

function SetOpacity(elem, opacityAsInt) {
	var opacityAsDec = opacityAsInt;

	if (opacityAsInt > 100) {
		opacityAsInt = opacityAsDec = 100;
	} else if (opacityAsInt < 0) {
		opacityAsInt = opacityAsDec = 0;
	}

	opacityAsDec /= 100;

	if (opacityAsInt < 1) {
		opacityAsInt = 1; // for IE7 bug, text smoothing cuts out if 0
	}

	elem.style.opacity = (opacityAsDec);
	elem.style.filter  = "alpha(opacity=" + opacityAsInt + ")";
}


function saveSearchAction() {
	dojo.disconnect(clickObject.connectionHandle);
	var deferred = userPanel.saveObject(
		{'type' : 'BookmarkedSearches', 'properties' : searchParams});

	deferred.addCallback(function() {
		updateUserItemsCount();
		isSearchSaved(searchParams.uniqRef);
	});
}


function saveSearchAndActivateMailAction() {
	searchParams.sendEmail = 1
	saveSearchAction();
}

function isSearchSaved(uniqRef) {
	var deferred = userPanel.isSearchSaved(
			{'uniqRef' : uniqRef});
	deferred.addCallback(
			function(res) {
						if(res){
							searchIsSaved(res);
							
						}
						else{
							searchIsSaved(res);
							
						}
			}
	);
}

function searchIsSaved(isSaved){
	if(isSaved){
		hide('savedSearchRightItem');
		hide('searchIsNotSaved');
		hide('newsletterEmail');
		show('searchIsSavedBottom');
		show('searchIsSaved');
	}
	else{
		show('searchIsNotSaved');
	}
}

/**
 * Save the current search as a newsletter (not a bookmarked_searche since the user isn't registered)
 */
function newsletterSave(){
	var newsletterSendRpcDef = {
	"serviceType": "JSON-RPC",
	"serviceURL": "/json/newsletter.php",
	"methods":[
		{
			"name": "sendEmail",
			"parameters":[
				{"name": "userEmail"},
				{"name": "formValue"}
			]
		}
	]
	};
	var rpcService = new dojo.rpc.JsonService(newsletterSendRpcDef);
	var deferred = rpcService.sendEmail(dojo.byId('email').value, searchParams);
	deferred.addCallback(function(res2) {
			if(res2) {
				dojo.byId('Error_email').innerHTML = ekLang._("Confirmation Email successfully send");
				VsUserDialog.show("newsletterNonLogged",{container: 'newsletterNonLogged'});
				dojo.byId('email').value = "";		
			} else {
				dojo.byId('Error_email').innerHTML = ekLang._("Error sending confirmation email");
			}
		});
}

function hide(id){
	if(dojo.byId(id))
		dojo.byId(id).style.display='none';
}

function show(id){
	if(dojo.byId(id))
		dojo.byId(id).style.display='block';
}

/**
 * This function show the "Complete Registration" dialog that allow a
 * NewsletterUser to complete the registration process and become a "member"
 * 
 * It's called in tpl-utent.xsl when there is a validation error on field 'email' of the type 'newsletterUser'
 */
function completeRegistration() {
    if (VsUserDialog.actionToDoAfterLogging) {
		dojo.disconnect(VsUserDialog.actionToDoAfterLogging);
	}
	parent.VsUserDialog.currentDialog.hide();
	var sUrl = "/utenti/completaRegistrazione.html?email="+ dojo.byId('email').value;
	if (dojo.byId('firstName').value != '' && dojo.byId('firstName').value.length > 2) {
		sUrl += '&firstName=' + dojo.byId('firstName').value;
	}
	if (dojo.byId('lastName').value != '' && dojo.byId('lastName').value.length > 2) {
		sUrl += '&lastName=' + dojo.byId('lastName').value;
	}
	parent.VsUserDialog.show("CompleteRegistration",{page: sUrl});
}

///*****************************************************////////////////

function show(s){
	div = dojo.byId(s);
	div.style.display = 'block';
}


function actions(id){
	
	divCancelato = "snipAd-"+id;
		 	
	if (nBookmarkedAds > nItemPagina*nCurrentPage){
		 dojo.xhrGet( {
		        url: "/nextBookmarkedAds.html?pag="+nCurrentPage, 
		        handleAs: "text",
		
		        timeout: 5000,
		     
		        load: function(response, ioArgs) { 
			 		
			 		var newdiv = document.createElement('div');
			 		newdiv.innerHTML = response;
			 		dojo.byId("AdsTable").appendChild(newdiv);
		            var aDivAds = newdiv.childNodes;
		           
		            divAd = aDivAds[0];
		            divAd.style.display = "block";
		    		
		            efectCancel = dojo.fx.wipeOut({node: divCancelato,duration: 1500});
		        	efectCancel.play();
		            
		    		return response; 
		        },
		        
		        error: function(response, ioArgs) {
		          console.error("HTTP status code: ", ioArgs.xhr.status);
		          return response;
		        }
		 });
	}
	else{
		dojo.byId('AdsTable').style.height="auto";
		efectCancel = dojo.fx.wipeOut({node: divCancelato,duration: 1500});
		efectCancel.play();
	}
	
	
	nBookmarkedAds--;
	dojo.byId('totalBookmarkedAds').innerHTML = nBookmarkedAds+" annunci salvati";
	
	var nPagine = (nBookmarkedAds/nItemPagina)+1;
	var auxDiv;
	
	if(Math.floor(nPagine) == nPagine && (auxDiv = dojo.byId('paginazione-'+nPagine))) {
		auxDiv.style.display = "none";
		if(nCurrentPage == nPagine-1)
			dojo.byId('next').style.display = "none"
	}
	
	if(nBookmarkedAds <= ((nCurrentPage*5)-5)){
		nCurrentPage--;
		document.location.href= "/utenti/annunciPreferiti.html?pag="+nCurrentPage;
	}
	
	if((nPagine -1) == 1 && (auxDiv = dojo.byId('pageNavTable'))){
		auxDiv.style.display = "none";
	}
	
}

function newAdsList(){
	//dojo.byId().style.display = "block";
	show("loadingSearch");

	dojo.xhrGet( {
	        url: "/ajax/vendita/residenziale/Lazio/Roma/Roma/Appartamento/pag5/Appartamento.html",
	        handleAs: "text",
	
	        timeout: 5000,
	     
	        load: function(response, ioArgs) { 
		 		dojo.byId('AdsList').innerHTML = response;
		 
//		 		var newdiv = document.createElement('div');
//		 		newdiv.innerHTML = response;
		 		//dojo.byId("AdsTable").appendChild(newdiv);
//	            var aDivAds = newdiv.childNodes;
//	           
//	            divAd = aDivAds[0];
//	            divAd.style.display = "block";
//	    		
//	    		return response; 
	        },
	        
	        error: function(response, ioArgs) {
	          console.error("HTTP status code: ", ioArgs.xhr.status);
	          return response;
	        }
	 });
	//setTimeout(hide("loadingSearch"), 400000);
}




