/**
 * @author morettip
 */

document.write('<script type="text/javascript" src="/uff-it-static/style/js/debug.js"></script>');
var valueOfIdToDelete;
var requestFormTypeToDelete;
var mypage = {	
	popup: false, 
	ui: false,
	isIE: Prototype.Browser.IE,
	intPositioner: false,
	firstPositioning: true,
	popupLoadComplete: false, 
	
	config: {
		informationPage: '/it/myPage/initInformationPopUpmyPage.htm',
		//loginForm: 'mypage_09.html', 											/*** DEV ***/
		loginForm: '/it/myPage/loginForm.htm',
		advancedSearchForm:'/it/advancedSearchFormsearch.htm',
		editAdvancedSearchForm:'/it/editAdvancedSearchFormsearch.htm',
		subscriptionPopup: '/it/myPage/showPopupUserSubscribe.htm',
		myPageBanner: '/it/banners/myPageBannerMyPageInit.htm',
		myPageAttachmentBanner:'/it/banners/attachmentBannerMyPageInit.htm',
		myPageFavouriteBanner:'/it/banners/favouriteBannerMyPageInit.htm',
		myPagePopup: '/it/myPage/showPopupmyPage.htm',
		//loginDone: 'T17_form_mutui_01_logged.html',
		//subscriptionForm: 'mypage_10.html',
		subscriptionForm: '/it/myPage/showUserSubscribe.htm',
		passwordRecoveryForm: '/it/myPage/Password.htm',
		//elements: 'UFF-it-static-war/WebContent/style/js/mypageElements.htm'	/*** DEV ***/
		elements: '/uff-it-static/style/js/mypageElements.htm'
	},
	
	alert: function( text ) 
	{
		this.getPopup ();
		this.loadElement ( 'mypage-popup-loading' );
		//$$('.mypage-popup-close')[0].hide();
	},

	isLogged: function()
	{
		return ($$('.box-lb-mypage.logged').length > 0 || $$('form[name=logoutForm]').length > 0) ? true : false;
	},

	loadPage: function( url, callback ) 
	{
		new Ajax.Request ( url, {
			method: 		'get',
			onSuccess: 		callback
		});
	},
	
	loadElement: function( element, callback ) 
	{
		if (mypage.ui == false) {
			// Carico la prima volta gli elementi della mypage
			mypage.preloadUiElements ( true, function() {
				mypage.setPopupContent(mypage.ui, element);
				if (callback != null) 
					callback();
			});
		} else {
			mypage.setPopupContent(mypage.ui, element);
			if (callback != null) 
				callback();
		}
	},
	
	loadElementFromPage: function( url, element, callback ) 
	{
		var content;
		new Ajax.Request(url, {
			method: 'get',
			onException: function(t, e){ /*alert("exception:  " + e.message);*/ },
			onSuccess: function(response) {
				content = new Element('div').insert(response.responseText.stripScripts());
				mypage.setPopupContent(content, element);
				if (callback != null) 
					callback();
			},
			onFailure: function(){ alert("failure loading " + url); }		
		});
	},
	
	preloadUiElements: function( init, callback ) {
		new Ajax.Request(mypage.config.elements, {
			method: 'get',
			onException: function(t, e) { /*alert("exception:  " + e.message);*/ },
			onSuccess: function(response){
				mypage.ui = new Element('div').insert(response.responseText.stripScripts());
				response.responseText.evalScripts();
				if (!init) {
					mypage.setPopupContent(mypage.ui, element);
					if (callback != null) 
						callback();
				}
			}
		});
	},
	
	getElement: function( element ) 
	{
		var obj = mypage.ui.getElementsByClassName (element)[0];
		mypage.setPopup ( obj );
	},
	
	doSubscription: function() 
	{
		this.intPositioner = false;
		this.preloadPopup ();
		this.loadPage ( mypage.config.subscriptionForm, mypage.setPopupContent );
	},
	
	postSubscription: function() 
	{
		if (mypage.popup != false) {
			$('UserSubscribe').request({
				onComplete: function(req) { 
					if (req.responseText == "OK")
						mypage.onSubscriptionComplete();
					else 
						mypage.setPopupContent(req);
				}
			})
		} else 
			$('UserSubscribe').submit();
	},
	
	postLogin: function(onSubmitAction) 
	{
		if (mypage.popup != false) {
			if ($('redirectUrlPopup')) 
				$('redirectUrlPopup').value = '/it/myPage/showOkmyPage.htm';
			$('formLoginMypage').action += '?rnd=' + Math.random();
			Form.request($('formLoginMypage'), {
				method: 'get',
				onComplete: function(req) { 
					if (req.responseText == "OK"){
						mypage.onLoginComplete();
					}
					else{
						mypage.setPopupContent(req);
					}
				}
			});
			if (onSubmitAction) return false;		
		} else {
			$('formLoginMypage').submit();
			if (onSubmitAction) return true;
		}
	},
	
	postPasswordRecovery: function(onSubmitAction) 
	{
		if (mypage.popup != false) {
			Form.request(document.Password, {
				onComplete: function(req) { 
					mypage.setPopupContent(req);
				}
			});
			if (onSubmitAction) return false;
		} else {
			$('Password').submit();
			if (onSubmitAction) return true;
		}
	},
	
	reloadMypageBanner: function()
	{
		new Ajax.Updater($$('.box-lb-mypage')[0], mypage.config.myPageBanner);
	},
	
	reloadMypageFavouriteBanner: function()
	{
		new Ajax.Updater($$('.box-lb-0')[0], mypage.config.myPageFavouriteBanner);
	},
	
	reloadMypageAttachmentBanner: function()
	{
		new Ajax.Updater($$('.box-lb-1')[0], mypage.config.myPageAttachmentBanner);
	},
	
	onSubscriptionComplete: function()
	{
		this.reloadMypageBanner();
		this.subscriptionPopup();
	},
	
	subscriptionPopup: function() 
	{
	    this.preloadPopup ();
	    this.loadPage ( this.config.subscriptionPopup, mypage.setPopupContent );
	},
	
	setRedirectUrl: function(popupName, redirectUrl){
		if(redirectUrl == '') 
			redirectUrl = window.location.href;
		var index = redirectUrl.lastIndexOf("?");
		if (index >0) {
			redirectUrl = redirectUrl.substr(0, index)
		}
		if (popupName != "none"){
		return redirectUrl = redirectUrl + '?popup=' + popupName;}
		else{return redirectUrl;}
		
	},
	
	onLoginComplete: function()
	{
		this.reloadMypageBanner();
		var index = location.href.lastIndexOf("myPage.htm");
		if ( index > 0) {
			location.href=this.setRedirectUrl('login', location.href);
		}
		this.loginPopup();
	},
	
	loginPopup: function() 
	{
	    this.showPopup(this.config.myPagePopup, 'mypage-popup-login');
	},
	
	submitConfirm: function(link, messageKey) 
	{
		this.showPopup(this.config.myPagePopup + '?confirmLink=' + link + '&messageKey=' + messageKey, 'mypage-form-submit-confirm');
	},
	
	submitConfirmGreen: function(link, messageKey) 
	{
		this.showPopup(this.config.myPagePopup + '?confirmLink=' + link + '&messageKey=' + messageKey, 'mypage-form-submit-confirm-green');
	},
	
	logoutPopup: function() 
	{
	    this.showPopup(this.config.myPagePopup, 'mypage-popup-logout');
	},
	
	confirmDeletePopup: function(className, valueOfId) 
	{
		valueOfIdToDelete = valueOfId;
	    this.showPopup(this.config.myPagePopup, className);
	    
	},
	
	confirmRichiesteSalvateDeletePopup: function(className, valueOfId, requestFormType) 
	{
		valueOfIdToDelete = valueOfId;
		requestFormTypeToDelete = requestFormType;
	    this.showPopup(this.config.myPagePopup, className);
	    
	},
	
	addFavouritePopup: function() 
	{
	    this.showPopup(this.config.myPagePopup, 'mypage-popup-favourite-add');
	},
	
	deleteFavouritePopup: function() 
	{
	    deleteFavourite(valueOfIdToDelete,'/deleteFavouritemyPage.htm');
		this.reloadMypageFavouriteBanner();
	    this.showPopup(this.config.myPagePopup, 'mypage-popup-favourite-delete');
	},
	
	deleteRichiesteSalvateNoPopup: function() 
	{
		deleteRichiesteSalvate(valueOfIdToDelete,'/deleteRichiesteSalvatemyPage.htm',requestFormTypeToDelete);
		//this.closePopup();
		location.href=this.setRedirectUrl('none', location.href);
	},
	
	deletePreventiviSalvatiNoPopup:function(){
		deletePreventiviSalvati(valueOfIdToDelete,'/deletePreventiviSalvatimyPage.htm');
		//this.closePopup();
		location.href=this.setRedirectUrl('none', location.href);
	},
	
	deleteAttachmentPopup: function() 
	{
		deleteAttachment(valueOfIdToDelete,'/deleteAttachmentmyPage.htm');
		this.reloadMypageAttachmentBanner();
	    this.showPopup(this.config.myPagePopup, 'mypage-popup-attachment-delete');
	},
	
	showPopup: function(pageUrl, element, callback) 
	{
		this.preloadPopup ();
		this.loadElementFromPage (pageUrl, element, callback );
	},	
	onSubmitSubscriptionComplete: function()
	{
		//var elem = mypage.getHtmlContent (mypage.ui, 'mypage-box-session-registered');
	},
	
	doLogin: function() 
	{
		this.preloadPopup();
		if ($('formLoginMypage')) {
			// I'm in the mypage login. Must rewrite
			$('formLoginMypage').name = "formContatto_2";
			$('redirectUrl').id = "redirectUrl_2";
			$('formLoginMypage').id = "formLoginMypage_2";
		}
		this.loadPage ( this.config.loginForm + '?rnd=' + Math.random(), mypage.setPopupContent );
	},

	doAdvancedSearch: function(){
		this.preloadPopup();
		this.loadPage ( this.config.advancedSearchForm, mypage.setPopupContent );
		
	},
	
	doEditAdvancedSearch: function(){
		this.preloadPopup();
		this.loadPage ( this.config.editAdvancedSearchForm, mypage.setPopupContent );
		
	},
	
	doPasswordRecovery: function( step ) 
	{
		this.preloadPopup();
		this.loadElementFromPage (this.config.passwordRecoveryForm, step == 2 ? 'mypage-password-recovery-2' : 'mypage-password-recovery', mypage.setPopupContent );
	},
	
	setPopupContent: function(content, type) 
	{
		if (content) {
			if (mypage.isIE) {
				$$('select').invoke("hide");
			}
			mypage.setPopup ((content.responseText) ? content.responseText.stripScripts() : content, type );
		}
	},
	
	preloadPopup: function() 
	{
		this.getPopup ();
		this.loadElement ( 'mypage-popup-loading' );
		//$$('.mypage-popup-close')[0].hide();
	},
	
	getPopup: function () 
	{
		if (this.popup != false) 
			return this.popup;
		else {
			// Popup init
			var popup = new Element("div", {id: "mypage_popup"}).addClassName ("s-mypage");
			var mpw = new Element ("div").addClassName ("mypage-popup-window");
			var mpc = new Element ("div").addClassName ("mypage-popup-content").update('<div style="padding:20px 30px">Caricamento...</div>');
			//var mpcl = new Element ("div").addClassName ("mypage-popup-close");
			mpw.appendChild(mpc);
		
			//mpw.appendChild(mpcl);
			popup.appendChild(mpw);
			document.body.appendChild(popup);
			Event.observe(document.body, "click", mypage.closePopup);
			
			//$$('.mypage-popup-close')[0].observe("click", mypage.closePopup);
			this.startPopupPositioner();
			this.popup = popup;
			return popup;
		}
	},
	
	startPopupPositioner: function() 
	{
		if (this.intPositioner == false && $("mypage_popup")) {
			mypage.firstPositioning = true;
			this.intPositioner = setInterval(function() {
				if ($("mypage_popup")) {
					if (mypage.firstPositioning == true) {
						mypage.firstPositioning = false;
						var topPos = document.viewport.getHeight() / 2 - $("mypage_popup").getDimensions().height / 2;
						$("mypage_popup").style.top = ((topPos < 0 ? 10 : topPos) + document.viewport.getScrollOffsets().top) + "px";
					}
					$("mypage_popup").style.left = (document.viewport.getWidth() / 2 - $("mypage_popup").getDimensions().width / 2 + document.viewport.getScrollOffsets().left) + "px";
					if (document.getElementsByClassName("lightbox-content").length > 0)
						$$(".mypage-popup-content")[0].style.width = $$(".lightbox-content")[0].getDimensions().width + "px"
				} else 
					mypage.stopPopupPositioner();
			}, 250);
		} else 
			mypage.stopPopupPositioner();
	},
	
	stopPopupPositioner: function()
	{
		clearInterval(this.intPositioner);
		this.intPositioner = false;
	},
	
	
	setPopup: function( content, type ) 
	{
		mypage.getPopup();
		//$$('.mypage-popup-close')[0].show();
		if (type != null)
			var content = mypage.getHtmlContent (content, type);
		else 
			var content = mypage.getHtmlContent (content, 'lightbox-content');
		
		// Inserisco il contenuto
		$$('.mypage-popup-content')[0].update ( content );
		// Centro il layer
		// Fix per label invisibili su IE [subscription form]
		if (mypage.isIE) {
			if ($$('.subscription-form').length > 0) 
				$A($$('.subscription-form')[0].getElementsByTagName('label')).each(function(e){	e.style.top = 'auto';});
			if ($$('.prelogin-form').length > 0)
				$A($$('.prelogin-form')[0].getElementsByTagName('label')).each(function(e) { e.style.top = "-3px";	});
			if ($$('.mypage-password-recovery').length > 0)
				$A($$('.mypage-password-recovery')[0].getElementsByTagName('label')).each(function(e) { e.style.top = "-20px";	});
		}
		$$('.mypage-popup-content')[0].insert ('<div class="clr"></div>');
		$$('.mypage-popup-content')[0].scrollTop = 0;
		mypage.popupLoadComplete = true;
		//$$('.mypage-popup-close')[0].show();
	},
	
	getHtmlContent: function(content, portion) 
	{
		var helper = new Element('div');
		helper.insert ( (content.responseText != null) ? content.responseText.stripScripts() : (typeof content == 'string') ? content.stripScripts() : content );
		var contentDiv = helper.getElementsByClassName (portion)[0];
		return contentDiv;
	},
	
	closePopup: function(e) 
	{
		if ($('mypage_popup') != null && (!e || !Event.element(e).up('div[id=mypage_popup]')))
			mypage.myPagePopupRemove();
	},
	
	 myPagePopupRemove: function() {
		if ($('mypage_popup') != null ) {
			mypage.popup = false;
			mypage.intPositioner = false;
			$('mypage_popup').remove();
			Event.stopObserving(document.body, "click", mypage.closePopup);
			if (mypage.isIE) 
				$$('select').invoke("show");
		}
	}
	
}

mypage.form = {
		
	saveToolUri: '/tools/saveToolData.htm',
		
	toolSave: function(xml) 
	{
		if (mypage.isLogged())
			mypage.form.doToolSave(xml);
		else {
			mypage.loginPopup = function() {
				mypage.form.doToolSave(xml);
			}
			mypage.doLogin();
		}
	},
		
	doToolSave: function(xml) 
	{
		new Ajax.Request(mypage.form.saveToolUri, {
	        postBody: xml,
	        contentType: 'text/xml',
	        method: 'post',
	        onComplete: function (response) {
	        	var result = response.responseText.split ("<result>")[1].split ("</result>")[0];
	        	mypage.form.saveSessionResult (result, "TOOL");
			}
		});
	},
		
	save: function() 
	{
		if (mypage.isLogged())
			mypage.form.doSave();
		else {
			mypage.loginPopup = function() {
				mypage.form.doSave();
			}
			mypage.subscriptionPopup = function() {
				mypage.form.doSave();
			}
			mypage.doLogin();
		}
	},
	
	doSave: function()
	{
		var formEntityLabel = $('formEntity.label').value;
		mypage.showPopup(mypage.config.myPagePopup, 'mypage-form-save-step-1', function() {
			$$("input[name=formEntityLabel]")[0].value = formEntityLabel;
		});
	},
	
	setEntityLabel: function()
	{
		var formName = $$('.saveForm')[0].name;
		mypage.form.checkinButtons(formName);
		Form.request($$('.saveForm')[0], {
			method: 'get',
			onComplete: function(req) { 
				mypage.form.checkoutButtons(formName);
				mypage.form.saveSessionResult (req.responseText, "PAGE");
			}
		});
	},
	
	checkinButtons: function(formName) 
	{
		mypage.form.formEntityLabel = $$('input[name=formEntityLabel]')[0].value;
		$('formEntity.label').value = mypage.form.formEntityLabel;
		var inp = new Element ("input", { id: "dynamicMypageHiddenInput", type: "hidden", name: "action:save" + formName, value: "SALVA"});
		$$('.saveForm')[0].appendChild (inp);
		if ($$('input[name=action:next' + formName + ']').length > 0)
			$$('input[name=action:next' + formName + ']')[0].name = 'action_skip_next' + formName;
		if ($$('input[name=action:back' + formName + ']').length > 0)
			$$('input[name=action:back' + formName + ']')[0].name = 'action_skip_back' + formName;
	},
	
	checkoutButtons: function(formName) 
	{
		$$('.saveForm')[0].removeChild ($("dynamicMypageHiddenInput"));
		if ($$('input[name=action_skip_next' + formName + ']').length > 0)
			$$('input[name=action_skip_next' + formName + ']')[0].name = 'action:next' + formName;
		if ($$('input[name=action_skip_back' + formName + ']').length > 0)
			$$('input[name=action_skip_back' + formName + ']')[0].name = 'action:back' + formName;
	},
	
	saveSessionResult: function(type, opener)
	{
		if (type == "OK")
			mypage.showPopup(mypage.config.myPagePopup, 'mypage-form-save-step-2-' + opener, function() {
				if (opener == "PAGE") {
					$$('.formEntitySavedLabel')[0].update( mypage.form.formEntityLabel );
					mypage.reloadMypageBanner ();
				}
			});
		else if (type == "KONOLOGGED")
			mypage.showPopup (mypage.config.myPagePopup, 'mypage-form-save-error-konotlogged-' + opener);
		else 
			mypage.showPopup (mypage.config.myPagePopup, 'mypage-form-save-error-ko-' + opener);
	}
		
}

// Debug line. If you delete this, you must delete every istance of "console.log" in the js code
if (!console) var console = { log: function(t) { alert(t)} }

