// All the user-related scripts for registration, user data modification and password reminder.

function initUserRegisterStep1Events(contextPath, eventName) {
        jslog.debug('user-registration-step1: domready');

        //Adding ajax event for form submit to step 2
        var btn = document.getElement('input[id=userRegisterForm1-submit]');
        btn.removeEvents('click');
        btn.addEvent('click', function(e) {
          jslog.debug('userRegistrationForm: submit');
          this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
          this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
          });
          e = new Event(e);
          $('userRegisterForm1').getElement('input[name=_eventName]').value = eventName;
          AjaxSpinner.show();
          doAjaxRequest(new Ajax(contextPath + '/user/UserRegister.action',
            {
              method: 'post',
              data: $('userRegisterForm1'),
              update: $('userRegister-container'),
              evalScripts: true,
              onComplete: function() {
                AjaxSpinner.hide();
              }
            }));
          e.stop();
        });
        if ($('input[name=privacyPolicyModalTitle]')) {
            addEventPolicyLink(contextPath, $('input[name=privacyPolicyModalTitle]').value);
         } else {
            addEventPolicyLink(contextPath, 'Informativa privacy');
         };
         if ($('input[name=cartaPiuRUlesModalTitle]')) {
        	 addCartaPiuRulesLink(contextPath, $('input[name=cartaPiuRUlesModalTitle]').value);
          } else {
        	  addCartaPiuRulesLink(contextPath, 'Regolamento cartaPiù Online');
          };
          	  addScopriVantaggiLink(contextPath, 'Scopri i Vantaggi');
          
          
        
      // Adding events for user communities: show/hide table with addresses.
//      if ($('allowToBeContactedRadio')) {
//        $('allowToBeContactedRadio').addEvent('click', function() {
//          if ($('webSiteLinkUploader')) {
//            $('webSiteLinkUploader').setStyle('display', 'block');
//          };
//        });
//      };
//      if ($('nonAllowToBeContactedRadio')) {
//        $('nonAllowToBeContactedRadio').addEvent('click', function() {
//          if ($('webSiteLinkUploader')) {
//            $('webSiteLinkUploader').setStyle('display', 'none');
//          };
//        });
//      };
    
      // Adding a form submission for the add link button: the whole form is submitted anyway, but nothing is saved.
      var addUserCommunity = $('userRegisterForm1').getElement('input[name=addUserCommunity]');
      if (addUserCommunity) {
        addUserCommunity.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        addUserCommunity.addEvent('click', function(e) {
          this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
          this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
          });
          e = new Event(e);
          AjaxSpinner.show();
          $('userRegisterForm1').getElement('input[name=_eventName]').value = 'addUserCommunity';
          $('userRegisterForm1').getElement('input[name=editedUserCommunity.id]').value = ''; 
          doAjaxRequest(new Ajax(contextPath + '/user/UserRegister.action',
            {
              method: 'post',
              data: $('userRegisterForm1'),
              update: $('userRegister-container'),
              evalScripts: true,
              onComplete: function() {
                AjaxSpinner.hide();
              }
            }));
          e.stop();
        });
      };
    
      // Adding delete events for the delete buttons: the delete is just a reset of the form data for the given line.
      $('userRegisterForm1').getElements('input[name=deleteUserCommunity]').each(function(deleteButton) {
        deleteButton.addEvent('click', function(e) {
          e = new Event(e);
          $('userRegisterForm1').getElement('input[name=_eventName]').value = 'deleteUserCommunity';
          var index = this.id.slice(this.id.lastIndexOf('_') + 1);
          $('userRegisterForm1').getElement('input[name=editedUserCommunity.id]').value = index;
          $('userRegisterForm1').getElements('input[type=hidden]').each(function(input) {
            if (input.getProperty('name') == 'userCommunities[' + index + '].link') {
              input.value = '';
            };
            if (input.getProperty('name') == 'userCommunities[' + index + '].type') {
              input.value = '';
            };
          });
          if ($('userRegisterForm1').getElement('tr[id=userCommunity_' + index + ']')) {
            $('userRegisterForm1').getElement('tr[id=userCommunity_' + index + ']').setStyle('display', 'none');
          };
          e.stop();
        });
      });
}

//Opens the modal box for privacy info in user-register-step1 and in user-personal-data 
function addEventPolicyLink(contextPath, title) {
	  if ($('privacyPolicyLink')) {
		//Adding event to privacy link.
		$('privacyPolicyLink').addEvent('click', function(e) {
		    jslog.debug('privacyPolicyLink domready');
		    e = new Event(e);
			e.stop();
			openPrintMOOdalBox(contextPath + '/fcom/it/home/pages/infoutili/privacy.content', null, "600px");
	    });
	  };
	}

//Opens the modal box for privacy info in user-register-step1 and in user-personal-data 
function addCartaPiuRulesLink(contextPath, title) {
	  if ($('cartaPiuRulesLink')) {
		//Adding event to privacy link.
		$('cartaPiuRulesLink').addEvent('click', function(e) {
		    jslog.debug('cartaPiuRulesLink domready');
		    e = new Event(e);
			e.stop();
			openPrintMOOdalBox(contextPath + '/fcom/it/home/pages/infoutili/cartaPiuRegolamento.content', null, "600px");

	    });
	  };
	}

function addScopriVantaggiLink(contextPath, title) {
	  if ($('cartaPiuRulesLink')) {
		  var link = contextPath + '/fcom/it/home/pages/infoutili/registrazioneScopriVantaggi.content';
		  //Adding event to privacy link.
		$('scopriVantaggiLink').addEvent('click', function(e) {
		    jslog.debug('ScopriVantaggiLink domready');
		    e = new Event(e);
			e.stop();
			
			openScopriVantaggiLink(link, title);

	    });
	  };
	}

function openScopriVantaggiLink(sLinkHref, title) {

	var contents = new Element('div');
	AjaxSpinner.show();

	var ajaxOptions = {
		method :'get',
		update :contents,
		onComplete : function() {
			var mainContent = new Element('div');
			mainContent.setStyles( {
				height :270 ,
				width :500 
			});
			mainContent.setStyle("overflow", "auto");
			contents.injectInside(mainContent);
			var iframeEl = new Element('iframe', {
				id :"iframePrint",
				src :sLinkHref,
				display :"none"
			});
			iframeEl.setStyle("display", "none");
			iframeEl.injectInside(mainContent);

			openAlertMOOdalBox(mainContent, null, 500, 500);
			AjaxSpinner.hide();
		},
		onFailure : function() {
			AjaxSpinner.hide();
		}
	};
	this.ajaxRequest = new Ajax(sLinkHref, ajaxOptions).request();
}

function openYouEffeDisclaimer(sLinkHref, title) {

	var contents = new Element('div');
	AjaxSpinner.show();

	var ajaxOptions = {
		method :'get',
		update :contents,
		onComplete : function() {
			var mainContent = new Element('div');
			mainContent.setStyles( {
				height :270 ,
				width :500 
			});
			mainContent.setStyle("overflow", "auto");
			contents.injectInside(mainContent);
			var iframeEl = new Element('iframe', {
				id :"iframePrint",
				src :sLinkHref,
				display :"none"
			});
			iframeEl.setStyle("display", "none");
			iframeEl.injectInside(mainContent);

			openAlertMOOdalBox(mainContent, null, 500, 500);
			AjaxSpinner.hide();
		},
		onFailure : function() {
			AjaxSpinner.hide();
		}
	};
	this.ajaxRequest = new Ajax(sLinkHref, ajaxOptions).request();
}

/*
 * Updates the sidebar personal data when the user changes the data in the main page, if the sidebar is shown.
 * Uses a safety random param to avoid caching.
 */
function ajaxUpdateSidebarPersonalData(contextPath) {
  if ($('sidebarpersonaldata-container')) {
    AjaxSpinner.show();
    doAjaxRequest(new Ajax(contextPath + '/user/SidebarPersonalData.action',
      {
        method: 'post',
        data: Object.toQueryString({ safetyParam: (Math.random() * 1000) }),
        update: $('sidebarpersonaldata-container'),
        evalScripts: true,
        onComplete: function() {
          AjaxSpinner.hide();
        }
      }));
  };
}

/*
 * All the ajax events in the personal page for the personal data modifications.
 */
function initUserPersonalDataEditEvents(contextPath) {
  // Events for the form of the user image.
  var userPersonalDataImageDiv = $('userPersonalDataImage');
  if (userPersonalDataImageDiv) {
    // WARNING! This is a SPECIAL event that uses an hidden iframe to submit a file via ajax.
    var savePersonalDataImage = userPersonalDataImageDiv.getElement('input[name=updateCustomerImage]');
    if (savePersonalDataImage) {
      savePersonalDataImage.removeEvents('click');
      savePersonalDataImage.addEvent('click', function(e) {
        this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
        });
        e = new Event(e);
        //This below is NOT optional, because after a delete the _eventName is still set to "delete"
        userPersonalDataImageDiv.getElement('input[name=_eventName]').value = 'updateCustomerImage';
        AjaxSpinner.show();
        new iframe(userPersonalDataImageDiv.getElement('form'), {
          update: $('userpersonaldata-container'),
          evalScripts: false,
          onComplete: function() {
            parent.jslog.debug('userPersonalDataForm: response received from updateCustomer');
            AjaxSpinner.hide();
            //Because of the use of the iframe, validation error presence is stored in a separated hidden.
            var valErr = window.document.getElementById('responseHasValidationErrors');
            var hasValErrorsFrame = ((valErr) && (valErr.value == "true")); // Becames true if there are validation errors: now it's unused but may come back useful again. 
            // This below is ABSOLUTELY NECESSARY. Because of the iframe, there are no script imports in the frame, so a window.addEvent won't work.
            // Don't know why, but with iframe the event domready of the parent won't work correctly, so I modified the library to evaluate this after the response injection.
            parent.initUserPersonalDataEditEvents(contextPath);
            ajaxUpdateSidebarPersonalData(contextPath);
          }
        }).request();
        e.stop();
      });
    }
    
    //Adding ajax event for deleting user image
    var imageDelete = userPersonalDataImageDiv.getElement('a[id=deleteCustomerImage]');
    if (imageDelete) {
      imageDelete.addEvent('click', function(e) {
        jslog.debug('deleteCustomerImage: submit');
        e = new Event(e);
        e.stop();
        openConfirmMOOdalBox('Vuoi eliminare la tua immagine personale?', function () {
          AjaxSpinner.show();
          doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
            {
              method: 'post',
              data: Object.toQueryString({ _eventName: 'deleteCustomerImage', safetyParam: (Math.random() * 1000) }),
              update: $('userpersonaldata-container'),
              evalScripts: true,
              onComplete: function() {
                ajaxUpdateSidebarPersonalData(contextPath);
                AjaxSpinner.hide();
              }
            }));
        }, null, null, "OK", false);
      });
    }
  }
  
  // Events for the form of username, password and carta piu association.
  var userLoginAndPasswordDiv = $('userLoginAndPassword');
  if (userLoginAndPasswordDiv) {
    var saveLoginAndPassword = userLoginAndPasswordDiv.getElement('input[name=updateCustomerLoginAndPassword]');
    if (saveLoginAndPassword) {
      saveLoginAndPassword.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
      saveLoginAndPassword.addEvent('click', function(e) {
        this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
        });
        e = new Event(e);
        AjaxSpinner.show();
        userLoginAndPasswordDiv.getElement('input[name=_eventName]').value = 'updateCustomerLoginAndPassword';
        doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
          {
            method: 'post',
            data: userLoginAndPasswordDiv.getElement('form'),
            update: $('userpersonaldata-container'),
            evalScripts: true,
            onComplete: function() {
              ajaxUpdateSidebarPersonalData(contextPath);
              AjaxSpinner.hide();
            }
          }));
        e.stop();
      });
    }
  };
    
  var userNumeroCartaPiu = $('userNumeroCartaPiu');
  if (userNumeroCartaPiu) {
    //Adding ajax event for form submit, saving association with cartaPiu (may not exist on page)
    var mergeCartaPiuCustomer = userNumeroCartaPiu.getElement('input[name=mergeCartaPiuCustomer]');
    if (mergeCartaPiuCustomer) {
      mergeCartaPiuCustomer.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
      mergeCartaPiuCustomer.addEvent('click', function(e) {
        this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
        });
        e = new Event(e);
        jslog.debug('userPersonalDataForm: submit mergeCartaPiuCustomer');
        //This below is NOT optional, because after a delete the _eventName is still set to "delete"
        userNumeroCartaPiu.getElement('input[name=_eventName]').value = 'mergeCartaPiuCustomer';
        AjaxSpinner.show();
        doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
          {
            method: 'post',
            data: userNumeroCartaPiu.getElement('form'),
            update: $('userpersonaldata-container'),
            evalScripts: true,
            onComplete: function() {
              ajaxUpdateSidebarPersonalData(contextPath);
              AjaxSpinner.hide();
            }
          }));
        e.stop();
      });
    };
  }
  
  // Events for the last form with all the other user data.
  var userOtherPersonalDataDiv = $('userOtherPersonalData');
  if (userOtherPersonalDataDiv) {
    //Province updater event, at page loading the provincia is already populated
    var country = userOtherPersonalDataDiv.getElement('select[name=editedCustomer.country]');
    var prov = userOtherPersonalDataDiv.getElement('select[name=editedCustomer.prov]');
    country.addEvent('change', function(e) {
        jslog.debug('userPersonalDataForm: change country');
        provinceUpdater(country, prov);
    });
    
    if ($('input[name=privacyPolicyModalTitle]')) {
        addEventPolicyLink(contextPath, $('input[name=privacyPolicyModalTitle]').value);
      } else {
        addEventPolicyLink(contextPath, 'Informativa privacy');
      };

    var saveOtherPersonalData = userOtherPersonalDataDiv.getElement('input[name=updateCustomerOtherData]');
    if (saveOtherPersonalData) {
      saveOtherPersonalData.addEvent('click', function(e) {
        e = new Event(e);
        AjaxSpinner.show();
        userOtherPersonalDataDiv.getElement('input[name=_eventName]').value = 'updateCustomerOtherData';
        doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
          {
            method: 'post',
            data: userOtherPersonalDataDiv.getElement('form'),
            update: $('userpersonaldata-container'),
            evalScripts: true,
            onComplete: function() {
              ajaxUpdateSidebarPersonalData(contextPath);
              AjaxSpinner.hide();
            }
          }));
        e.stop();
      });
    };
  };

  // Events for the form with communities.
  var userContactsCommunities = $('userContactsCommunities');
  if (userContactsCommunities) {
    // Adding events for user communities: show/hide table with addresses.
    // WARNING! THIS RADIO IS AUTOSUBMITTING ITS VALUE
    if ($('allowToBeContactedRadio')) {
      $('allowToBeContactedRadio').addEvent('click', function(e) {
        e = new Event(e);
        AjaxSpinner.show();
        userContactsCommunities.getElement('input[name=_eventName]').value = 'autoSaveUserAllowedToBeContacted';
        doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
          {
            method: 'post',
            data: userContactsCommunities.getElement('form'),
            update: $('userpersonaldata-container'),
            evalScripts: true,
            onComplete: function() {
              ajaxUpdateSidebarPersonalData(contextPath);
              AjaxSpinner.hide();
            }
          }));
        if ($('webSiteLinkUploader')) {
          $('webSiteLinkUploader').setStyle('display', 'block');
        };
        e.stop();
      });
    };
    if ($('nonAllowToBeContactedRadio')) {
      $('nonAllowToBeContactedRadio').addEvent('click', function(e) {
        e = new Event(e);
        AjaxSpinner.show();
        userContactsCommunities.getElement('input[name=_eventName]').value = 'autoSaveUserAllowedToBeContacted';
        doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
          {
            method: 'post',
            data: userContactsCommunities.getElement('form'),
            update: $('userpersonaldata-container'),
            evalScripts: true,
            onComplete: function() {
              ajaxUpdateSidebarPersonalData(contextPath);
              AjaxSpinner.hide();
            }
          }));
        if ($('webSiteLinkUploader')) {
          $('webSiteLinkUploader').setStyle('display', 'none');
        };
        e.stop();
      });
    };
  
    // Events for the last form with all the other user data.
    var userCommunitiesDiv = $('webSiteLinkUploader');
    if (userCommunitiesDiv) {
      // Adding a form submission for the add link button: the whole form is submitted anyway.
      var addUserCommunity = userCommunitiesDiv.getElement('input[name=addUserCommunity]');
      if (addUserCommunity) {
        addUserCommunity.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        addUserCommunity.addEvent('click', function(e) {
          this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
          this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
          });
          e = new Event(e);
          AjaxSpinner.show();
          userContactsCommunities.getElement('input[name=_eventName]').value = 'addUserCommunity';
          doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
            {
              method: 'post',
              data: userContactsCommunities.getElement('form'),
              update: $('userpersonaldata-container'),
              evalScripts: true,
              onComplete: function() {
                ajaxUpdateSidebarPersonalData(contextPath);
                AjaxSpinner.hide();
              }
            }));
          e.stop();
        });
      };
    
      // Adding delete events for the delete buttons
      userCommunitiesDiv.getElements('input[name=deleteUserCommunity]').each(function(deleteButton) {
        deleteButton.addEvent('click', function(e) {
          e = new Event(e);
          AjaxSpinner.show();
          var params = { _eventName: 'deleteUserCommunity' };
          params['editedUserCommunity.id'] = this.id.slice(this.id.lastIndexOf('_') + 1);
          params['safetyParam'] = (Math.random() * 1000);
          doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
            {
              method: 'post',
              data: Object.toQueryString(params),
              update: $('userpersonaldata-container'),
              evalScripts: true,
              onComplete: function() {
                ajaxUpdateSidebarPersonalData(contextPath);
                AjaxSpinner.hide();
              }
            }));
          e.stop();
        });
      });
    };
  };
 
  // Events for the last form with all the other user data.
  var userYouTubeDataDiv = $('userYouTubeData');
  var tokenYouTube = document.getElementById("youTubeToken").value;
  if(tokenYouTube != "") {  
	if (userYouTubeDataDiv) {
    var saveYouTubeId = userYouTubeDataDiv.getElement('input[name=addYouTubeData]');
    if (saveYouTubeId) {
    	saveYouTubeId.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
    	saveYouTubeId.addEvent('click', function(e) {
        this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        this.addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
        });
        e = new Event(e);
        AjaxSpinner.show();
        userYouTubeDataDiv.getElement('input[name=_eventName]').value = 'addYouTubeData';
        doAjaxRequest(new Ajax(contextPath + '/user/UserPersonalData.action',
          {
            method: 'post',
            data: userYouTubeDataDiv.getElement('form'),
            update: $('userpersonaldata-container'),
            evalScripts: true,
            onComplete: function() {
              ajaxUpdateSidebarPersonalData(contextPath);
              AjaxSpinner.hide();
            }
          }));
        e.stop();
      });
    }
  };
  };

}

function initPasswordReminderEvents(contextPath) {
        jslog.debug('password-reminder: domready');

        //Adding ajax event for password reminder form submit (requesting Carta Piu data step)
        var passwordReminderFormRequestCartaPiu = $('submitPasswordReminderRequestFormCartaPiu');
        if (passwordReminderFormRequestCartaPiu) {
          passwordReminderFormRequestCartaPiu.addEvent('click', function(e) {
            jslog.debug('passwordReminderFormRequest: submit');
            e = new Event(e);
            $('passwordReminderFormRequest').getElement('input[name=_eventName]').value = 'savePasswordReminderRequestCartaPiu';
            AjaxSpinner.show();
            doAjaxRequest(new Ajax(contextPath + '/user/UserPasswordReminder.action',
              {
                method: 'post',
                data: $('passwordReminderFormRequest'),
                update: $('paswordReminder-container'),
                evalScripts: true,
                onComplete: function() {
                  AjaxSpinner.hide();
                }
              }));
            e.stop();
          });
        };

        //Adding ajax event for password reminder form submit (requesting registered user data step)
        var passwordReminderFormRequestRegistered = $('submitPasswordReminderRequestFormRegistered');
        if (passwordReminderFormRequestRegistered) {
          passwordReminderFormRequestRegistered.addEvent('click', function(e) {
            jslog.debug('passwordReminderFormRequest: submit');
            e = new Event(e);
            $('passwordReminderFormRequest').getElement('input[name=_eventName]').value = 'savePasswordReminderRequestRegistered';
            AjaxSpinner.show();
            doAjaxRequest(new Ajax(contextPath + '/user/UserPasswordReminder.action',
              {
                method: 'post',
                data: $('passwordReminderFormRequest'),
                update: $('paswordReminder-container'),
                evalScripts: true,
                onComplete: function() {
                  AjaxSpinner.hide();
                }
              }));
            e.stop();
          });
        };

        //Adding ajax event for password reminder form submit (updating password step)
        var passwordReminderFormUpdate = $('submitPasswordRemindeUpdateForm');
        if (passwordReminderFormUpdate) {
          passwordReminderFormUpdate.addEvent('click', function(e) {
            jslog.debug('passwordReminderFormUpdate: submit');
            e = new Event(e);
            $('passwordReminderFormUpdate').getElement('input[name=_eventName]').value = 'updateUserPassword';
            AjaxSpinner.show();
            doAjaxRequest(new Ajax(contextPath + '/user/UserPasswordReminder.action',
              {
                method: 'post',
                data: $('passwordReminderFormUpdate'),
                update: $('paswordReminder-container'),
                evalScripts: true,
                onComplete: function() {
                  AjaxSpinner.hide();
                }
              }));
            e.stop();
          });
        };
}

function initUserFirstAccessEvents(contextPath) {
        jslog.debug('user-first-access: domready');

        //Adding ajax event for submitting the new user data.
        var userFirstAccessFormRequest = document.getElement('input[id=submitUserFirstAccessFormRequest]');
        if (userFirstAccessFormRequest) {
          userFirstAccessFormRequest.addEvent('click', function(e) {
            jslog.debug('userFirstAccessFormRequest: submit');
            e = new Event(e);
            document.getElement('form[id=userFirstAccessForm]').getElement('input[name=_eventName]').value = 'updateUserDataFirstAccess';
            AjaxSpinner.show();
            doAjaxRequest(new Ajax(contextPath + '/user/UserFirstAccess.action',
              {
                method: 'post',
                data: document.getElement('form[id=userFirstAccessForm]'),
                update: $('userfirstaccess-container'),
                evalScripts: true,
                onComplete: function() {
                  AjaxSpinner.hide();
                }
              }));
            e.stop();
          });
        };

        //Adding ajax event for successful data update.
        if ($('afterFirstAccessRedirectUrl')) {
          jslog.debug($('afterFirstAccessRedirectUrl').href);
          new CountdownLink($('afterFirstAccessRedirectUrl'), 15).start();
        };
        
        //Redirect to the home page in case of error.
        if ($('firstAccessErrorRedirectUrl')) {
          location.href = $('firstAccessErrorRedirectUrl').href;
        };        
}

function initUserSummaryCartaPiuEvents(contextPath, hasValidationErrors) {
        jslog.debug('user-summary-cartapiu: domready');

        if ((hasValidationErrors) && ($('fieldsetRequestCartaPiuDetails'))) {
           $('fieldsetRequestCartaPiuDetails').setStyle('display', 'block');
           document.getElement('a[id=linkShowRequestCartaPiuDetails]').getParent().setStyle('display', 'none');
        };
         
        var linkShowRequestCartaPiuDetails = document.getElement('a[id=linkShowRequestCartaPiuDetails]');
        if (linkShowRequestCartaPiuDetails) {
          linkShowRequestCartaPiuDetails.addEvent('click', function(e) {
            jslog.debug('user-summary-cartapiu: show request');
            e = new Event(e);
            if ($('fieldsetRequestCartaPiuDetails')) {
               $('fieldsetRequestCartaPiuDetails').setStyle('display', 'block');
               linkShowRequestCartaPiuDetails.getParent().setStyle('display', 'none');
            };
            e.stop();
          });
        };
        
        //Adding ajax event for requesting Carta Piu account statement
        var linkRequestCartaPiuDetails = document.getElement('a[id=linkRequestCartaPiuDetails]');
        if (linkRequestCartaPiuDetails) {
          linkRequestCartaPiuDetails.addEvent('click', function(e) {
            jslog.debug('user-summary-cartapiu: request details');
            e = new Event(e);
            AjaxSpinner.show();
            doAjaxRequest(new Ajax(contextPath + '/user/UserSummaryCartaPiu.action',
              {
                method: 'post',
                  data: $('summaryCartaPiuAccountStatementForm'),
                update: $('usersummarycartapiu-container'),
                evalScripts: true,
                onComplete: function() {
                  AjaxSpinner.hide();
                }
              }));
            e.stop();
          });
        };
}

function initUserRichiestaCartapiuFakePage(contextPath, isNegozio) {
// This seems quite unuseful, why don't we go directly to the form page? Because if we do that the form page will be
// cached on the server and when retrieved with a get (link) the prepopulated data of the last user will be always shown.
// So bear with this until a smarter cache is not implemented.
  var update = $('userrichiestacartapiu-container');
  var fromShop = false;
  if(isNegozio == 'true')
  {
  	fromShop = true;
  }
  if (update) {
      AjaxSpinner.show();
      doAjaxRequest(new Ajax(contextPath + '/UserRichiestaCartapiu.action',
          {
            method: 'post',
            data: Object.toQueryString({ safetyParam: (Math.random() * 1000), _eventName : 'loadAndShowPersonalData', fromShop :  fromShop}),
            update: update,
            evalScripts: true,
            onComplete: function() {
              AjaxSpinner.hide();
              scrollToElement(update);
            }
      }));
  };
}

function initUserRichiestaCartapiuEditEvents(contextPath, hasValErrors) {
  var update = $('userrichiestacartapiu-container');
  if (update) {
    //Province updater event, at page loading the provincia is already populated
    var country = update.getElement('select[name=editedCustomer.country]');
    var prov = update.getElement('select[name=editedCustomer.prov]');
    country.addEvent('change', function(e) {
        jslog.debug('userCartapiuDataForm: change country');
        provinceUpdater(country, prov);
    });

    var save = update.getElement('input[name=inviaRichiestaCartapiu]');
    if (save) {
      save.removeEvents('click');
      save.addEvent('click', function(e) {
        this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
        this.addEvent('click', function(e) {
               e = new Event(e);
               e.stop();
        });
        e = new Event(e);
        AjaxSpinner.show();
        doAjaxRequest(new Ajax(contextPath + '/UserRichiestaCartapiu.action',
          {
            method: 'post',
            data: update.getElement('form[name=userCartapiuDataForm]'),
            update: update,
            evalScripts: true,
            onComplete: function() {
              AjaxSpinner.hide();
              scrollToElement(update);
            }
          }));
        e.stop();
      });
    }
    addEventPolicyLink(contextPath, 'Informativa privacy');
  } 
}

function initUserRichiestaCartaPiuCheckout(contextPath, hasValErrors, storedAddressInvalid) {
  var update = $('userrichiestacartapiu-container');
 
  if (update) {
         //Province updater event, at page loading the provincia is already populated, but here may not exists.
        var countrySelect = document.getElement('select[name=orderData.shippingAddress.country]');
        if (countrySelect != null) {
          countrySelect.addEvent('change', function(e) {
             jslog.debug('userCartapiuDataForm: change country');
             provinceUpdater(countrySelect, document.getElement('select[name=orderData.shippingAddress.prov]'));
          });
        };
        
        //Resetting id of selected address in case of stored address error.
        if (storedAddressInvalid) {
          update.getElements('input[name=orderData.shippingAddressId]').each(function(radio) {
            radio.checked = false;
          });
          if ($('aggiungiIndirizzo')) {
            $('aggiungiIndirizzo').checked = true;
          };
        };
    
        //Adding enable/disable new address to radiobuttons.
        update.getElements('input[name=orderData.shippingAddressId]').each(function(radio) {
          radio.addEvent('click', function(e) {
            if (this.id == 'aggiungiIndirizzo') {
              $('nuovoIndirizzoCheckOut').setStyle('display', 'block');
              update.getElement('input[name=orderData.shippingAddress.name]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.lastname]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.address]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.addressNumber]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.notes]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.zip]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.city]').disabled = false;
              update.getElement('select[name=orderData.shippingAddress.prov]').disabled = false;
              update.getElement('select[name=orderData.shippingAddress.country]').disabled = false;
              update.getElement('input[name=orderData.shippingAddress.phone]').disabled = false;
            } else {
              $('nuovoIndirizzoCheckOut').setStyle('display', 'none');
              update.getElement('input[name=orderData.shippingAddress.name]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.lastname]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.address]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.addressNumber]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.notes]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.zip]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.city]').disabled = true;
              update.getElement('select[name=orderData.shippingAddress.prov]').disabled = true;
              update.getElement('select[name=orderData.shippingAddress.country]').disabled = true;
              update.getElement('input[name=orderData.shippingAddress.phone]').disabled = true;
            }
          });
        });

        //Adding event to privacy link.
        if (update.getElement('a[id=accettazioneCondizioniDiVenditaLink]')) {
          update.getElement('a[id=accettazioneCondizioniDiVenditaLink]').addEvent('click', function(e) {
            e = new Event(e);
            e.stop();
            openPrintMOOdalBox(contextPath + '/fcom/it/home/pages/infoutili/condizionivendita.content', null, "600px");
          });
        };

        var save = update.getElement('input[name=submitPaymentCartaPiu]');
        if (save) {
          jslog.debug('submit-button: click');
          save.removeEvents('click');
          save.addEvent('click', function(e) {
             this.removeEvents('click'); //Avoids double clicks, and the event will be readded at page reloading.
             this.addEvent('click', function(e) {
               e = new Event(e);
               e.stop();
             });
             e = new Event(e);
             AjaxSpinner.show();
             doAjaxRequest(new Ajax(contextPath + '/UserRichiestaCartapiu.action', {
                method: 'post',
                data: update.getElement('form[name=userCartapiuDataForm]'),
                update: update,
                evalScripts: true,
                onComplete: function() {
                   AjaxSpinner.hide();
                   scrollToElement(update);
                }
             }));
             e.stop();
          });
        };
        
        if (update.getElement('a[id=paymentCartaPiuBack]')) {
           update.getElement('a[id=paymentCartaPiuBack]').attachEvent('click', function(e) {
             e = new Event(e);
             AjaxSpinner.show();
             update.getElement('input[name=_eventName]').value = 'showPersonalData';
             doAjaxRequest(new Ajax(contextPath + '/UserRichiestaCartapiu.action', {
                method: 'post',
                data: update.getElement('form[name=userCartapiuDataForm]'),
                update: update,
                evalScripts: true,
                onComplete: function() {
                   AjaxSpinner.hide();
                   scrollToElement(update);
                }
             }));
             e.stop();
          });
        };
   }; 
}
function initRegions() {
	 if(negozi && negozi.length > 0)
	  {
	  var oldRegion='';
	  for(i = 0; i < negozi.length ; i++) 
	  { 
	    var shop= negozi[i];        
	    var region = shop.region;
	    if(region != oldRegion)
	    {
	      var optionx = new Element('option'); 
	      optionx.setProperty('value', shop.region).appendText(shop.region);
	      $('regionPuntoVendita').adopt(optionx);
	      oldRegion = region;
	    }
	  } 
	 }
}
 
function changeRegion() {
   if ($('mailPuntoVendita')) {
     $('mailPuntoVendita').empty();
     var option1 = new Element('option');
     option1.setProperty('value', '').appendText('Seleziona un punto vendita'); 
     $('mailPuntoVendita').adopt(option1);
     if($('regionPuntoVendita').value != '') {
       for(i = 0; i < negozi.length ; i++) { 
         var shop= negozi[i];    
         if(shop.region == $('regionPuntoVendita').value && shop.email != '') {
           var optionx = new Element('option'); 
           optionx.setProperty('value', shop.email).appendText(shop.titleShop  + ' ('+ shop.address + ')');
           $('mailPuntoVendita').adopt(optionx);
         }
       } 
     }
   }
}
 
function changePV(){	
 	 if (($('mailPuntoVendita')) && ($('mailPuntoVendita').value != '')) {	 	
	 	for(i = 0; i < negozi.length ; i++) { 
	        var shop= negozi[i];    
	        if(shop.email == $('mailPuntoVendita').value) {
	        	$('titleShop').value = shop.titleShop;
 	 			$('addressShop').value = shop.address;
	        }
	    } 	 	
 	 } else {
	    $('titleShop').value = '';
 	 	$('addressShop').value = '';
     } 
}
 
function sendProductSignalToFriend(contextPath) {
        jslog.debug('sendProductSignalToFriend');
		$('sendMailForm')._eventName.value = 'submitEmail';
 		AjaxSpinner.show();
 		new Ajax(contextPath + '/user/SignalProductToFriendPopup.action', {
	      method: 'post',
	      data: $('sendMailForm'),
	      update: $('scriviMessaggio'),
	      evalScripts: true,
	      onComplete:function() {
	        if ($('signalTofriendValidationErrors').value == 'true') {
	          MOOdalBox.close();
	        }
	        AjaxSpinner.hide();
	    }}).request();
}

function checkYouTubeAccount() {
	  var youTubeAccount = document.getElementById("editedCustomer.youTubeAccount").value;

	  if(youTubeAccount.length < 2) {
          document.getElementById("validateDataButton").disabled =true;
          document.getElementById("validateYouTubeData").disabled =true;
	  }
	  else {
          document.getElementById("validateDataButton").disabled =false;
          document.getElementById("validateYouTubeData").disabled =false;
	  }
		  
}
