var PageTools = Class.create();

PageTools.prototype = {

  _waContext: "/zoneCart/",
  _categoryTreeUrl: "CategoryTree.html",
  _userInfoUrl: "UserInfo.html",
  _addProductActionUrl: "AddProduct.ajax",
  _loadStatesActionUrl: "LoadStates.ajax",
  _addCourseProductsActionUrl: "AddCourseProducts.ajax",
  _addMemberCartActionUrl: "AddProductBundle.ajax",
  _logoutActionUrl: "Logout.ajax",
  _closeOrderActionUrl: "CloseOrder.ajax",
  _loadAddressActionUrl: "LoadCustomerAddress.ajax",
  _findULCourseActionUrl: "FindULCourse.ajax",
  _loadRatingsActionUrl: "LoadRatings.html",
  _popupProductDetailUrl: "PopupProductDetails.html?code=",
  _removeRatingActionUrl: "RemoveRating.ajax",
  _homePageUrl: "/jahia/Jahia/site/zoneul",
  _cartPageUrl: "",
  _accountPageUrl: "",
  _stateId: "",
  _lastTooltip: null,
  _lastProductCode: "",
  _lastTabId: "",

  initialize: function(cartPageUrl, accountPageUrl) {
    this._cartPageUrl = cartPageUrl;
    this._accountPageUrl = accountPageUrl;

    this.loadUserInfo();
  },

  loadUserInfo: function(){
    try
    {
      var params = "accountUrl=" + this._accountPageUrl.replace(';jsessionid', '');
      params += "&logoutUrl="+ this._homePageUrl.replace(';jsessionid', '');
      params += "&cartUrl="+ this._cartPageUrl.replace(';jsessionid', '');
      params += "&matrix=" + this.getMatrix();
      var myAjax = new Ajax.Request(this._waContext + this._userInfoUrl,{method:'get', parameters: params, onSuccess: this.refreshUserInfo.bind(this)});
    }
    catch(e){}
  },

  loadCategoriesForType: function(url, type, elementId){
    try
    {
      var params = "baseLink=" + encodeURI(url.replace(';jsessionid', ''));
      params += "&type="+ type;
      params += "&matrix=" + this.getMatrix();
      var myAjax = new Ajax.Request(this._waContext + this._categoryTreeUrl,{method:'get', parameters: params, onSuccess: this.refreshElement.bind(this, elementId)});
    }
    catch(e){}
  },

  loadCategoriesForId: function(url, id, elementId){
    try
    {
      var params = "baseLink=" + encodeURI(url.replace(';jsessionid', ''));
      params += "&id="+ id;
      params += "&matrix=" + this.getMatrix();
      var myAjax = new Ajax.Request(this._waContext + this._categoryTreeUrl,{method:'get', parameters: params, onSuccess: this.refreshElement.bind(this, elementId)});
    }
    catch(e){}
  },

  refreshElement: function(elementId, resp){
    try
    {
      Element.update(elementId, resp.responseText);
    }
    catch(e){}
  },

  refreshUserInfo: function(resp){
    try
    {
      Element.update('zoneCartUserInfo', resp.responseText);
    }
    catch(e){}
  },

  checkAll: function(theField){
    try
    {
      if(theField.length && theField.length > 1)
      {
        for(var i = 0; i < theField.length; i++)
        {
          theField[i].checked = true;
        }
      }
      else
      {
        theField.checked = true;
      }
    }
    catch(e){}
  },

  addCourseProductsToCart: function(theForm){
    try
    {
      var params = "matrix=" + this.getMatrix();
      params += "&courseId="+theForm.courseId.value;
      var productCodes = theForm.productCode;
      if(productCodes.length && productCodes.length > 1)
      {
        for(var i = 0; i < productCodes.length; i++)
        {
          if(productCodes[i].checked)
          {
            params += "&code=" + productCodes[i].value;
          }
        }
      }
      else
      {
        if(productCodes.checked)
        {
          params += "&code=" + productCodes.value;
        }
      }
      var myAjax = new Ajax.Request(this._waContext + this._addCourseProductsActionUrl,{method:'get', parameters: params, onSuccess: this.refreshCartInfo.bind(this)});
    }
    catch(e){}
  },

  addToCart: function(theForm){
    try
    {
      var params = "matrix=" + this.getMatrix();
      if(theForm.code)
      {
        params += "&code=" + theForm.code.value;
      }
      if(theForm.masterCode)
      {
        params += "&masterCode=" + theForm.masterCode.value;
      }
      params += "&quantity=" + theForm.quantity.value;
      params += "&rssIdentifier=" + theForm.rssIdentifier.value;
      if(theForm.size)
      {
        params += "&size=" + this.clearAccentuedChar(theForm.size.options[theForm.size.selectedIndex].value);
      }
      if(theForm.color)
      {
        params += "&color=" + this.clearAccentuedChar(theForm.color.options[theForm.color.selectedIndex].value);
      }
      var myAjax = new Ajax.Request(this._waContext + this._addProductActionUrl,{method:'get', parameters: params, onSuccess: this.refreshCartInfo.bind(this)});
    }
    catch(e){}
  },

  clearAccentuedChar: function(s){
    var newValue = s.replace('è', 'e');
    newValue = newValue.replace('é', 'e');
    newValue = newValue.replace('ô', 'o');
    newValue = newValue.replace('à', 'a');
    return newValue;
  },

  addMemberCard: function(bundleId){
    try
    {
      var params = "matrix=" + this.getMatrix();
      params += "&bundleIdentifier=2";
      var myAjax = new Ajax.Request(this._waContext + this._addMemberCartActionUrl,{method:'get', parameters: params, onSuccess: this.goToCart.bind(this)});
    }
    catch(e){}
  },

  refreshCartInfo: function(resp){
    try
    {
      var result = eval('(' + resp.responseText + ')');
      if(result)
      {
        if(eval(result.success))
        {
          Element.update('basket-article', result.sizeText);
          Element.update('basket-total', result.subTotal);
          if(parseInt(result.size) > 0)
          {
            Element.show('basket-checkout');
          }
          else
          {
            Element.hide('basket-checkout');
          }
          if(result.successMessage)
          {
            this.displayAddToCartMessage(result.successMessage);
          }
        }
        else if(result.errorMessage)
        {
          this.displayAddToCartErrorMessage(result.errorMessage)
        }
      }
    }
    catch(e){}
  },

  displayAddToCartMessage: function(msg){
    var html = "<fieldset class=\"info\">";
    html += "<legend class=\"info\">SUCC&Egrave;S</legend>";
    html += msg;
    html += "</fieldset>";
    Element.setStyle('successAddToCart', {marginLeft: '48px'});
    Element.update('successAddToCart', html);
    Element.show('successAddToCart');
  },

  displayAddToCartErrorMessage: function(msg){
    var html = "<fieldset class=\"error\">";
    html += "<legend class=\"error\">ATTENTION</legend>";
    html += msg;
    html += "</fieldset>";
    Element.setStyle('successAddToCart', {marginLeft: '48px'});
    Element.update('successAddToCart', html);
    Element.show('successAddToCart');
  },

  displayInfoMessage: function(msg){
    var html = "<fieldset class=\"info\">";
    html += "<legend class=\"info\">SUCC&Egrave;S</legend>";
    html += msg;
    html += "</fieldset>";
    Element.update('messageBoxContent', html);
    Element.show('messageBox');
    window.scroll(0,0);
  },

  displayErrorMessage: function(msg){
    var html = "<fieldset class=\"error\">";
    html += "<legend class=\"error\">ATTENTION</legend>";
    html += msg;
    html += "</fieldset>";
    Element.update('messageBoxContent', html);
    Element.show('messageBox');
    window.scroll(0,0);
  },

  closeOrder: function(){
    try
    {
      var params = "matrix=" + this.getMatrix();
      params += "&ajax=true";
      var myAjax = new Ajax.Request(this._waContext + this._closeOrderActionUrl,{method:'get', parameters: params, onSuccess: this.redirectToHome.bind(this)});
    }
    catch(e){alert(e);}
  },

  updateFormAddress: function(id, form){
    if( id > 0 )
    {
      try
      {
        var params = "matrix=" + this.getMatrix();
        params += "&id="+id;
        var myAjax = new Ajax.Request(this._waContext + this._loadAddressActionUrl,{method:'get', parameters: params, onSuccess: this.updateAddressForm.bind(this,form)});
      }
      catch(e){alert(e);}
    }
    else
    {
      this.updateAddressForm( form, null );
    }
  },

  updateAddressForm: function(form, resp){
    var map = this.checkError(resp);

    try
    {
    if( map )
    {
      form.street1.value = map.street1;
      form.street2.value = map.street2;
      form.postalCode.value = map.postalCode;
      form.title.value = map.title;
      form.phone.value = map.phone;
      form.workPhone.value = map.workPhone;
      form.fax.value = map.fax;
      form.firstName.value = map.firstName;
      form.lastName.value = map.lastName;
      form.city.value = map.city;
      this._stateId = map.stateId;
      this.setSelectedValue(form.countryId, map.countryId );
      this.loadStates( map.countryId, form.stateId );
    }
    else
    {
      form.street1.value = "";
      form.street2.value = "";
      form.postalCode.value = "";
      form.title.value = "";
      form.phone.value = "";
      form.workPhone.value = "";
      form.fax.value = "";
      form.firstName.value = "";
      form.lastName.value = "";
      form.city.value = "";
    }
    }
    catch(e){alert(e);}
  },

  checkError: function( resp )
  {
    try
    {
      var result = eval('(' + resp.responseText + ')');

      if(result)
      {
        if(result.success)
        {
          return result;
        }
        else if(result.errorMessage)
        {
          this.displayErrorMessage(result.errorMessage)
        }
      }
    }
    catch(e){}
    return null;
  },

  setSelectedValue: function( selectBox , newSelected)
  {
    for( var i=0; i < selectBox.options.length; i++ )
    {
        if( selectBox.options[i].value == newSelected )
        {
            selectBox.options[i].selected = true;
        }
        else
        {
            selectBox.options[i].selected = false;
        }
    }
  },

  redirectToHome: function(resp){
    try
    {
      var result = eval('(' + resp.responseText + ')');
      if(result)
      {
        document.location.href = this._homePageUrl;
      }
    }
    catch(e){alert(e);}
  },

  logout: function( newUrl )
  {
    try
    {
      var params = "";
      var myAjax = new Ajax.Request(this._waContext + this._logoutActionUrl + '?matrix=' + Math.round(Math.random() * 10000),{method:'get', parameters: params, onSuccess: this.callbackLogout.bind(this, newUrl)});
    }
    catch(e){alert(e);}
  },

  callbackLogout: function( newUrl, resp)
  {
    document.location = newUrl;
  },

  goToCart: function(resp){
    try
    {
      var result = eval('(' + resp.responseText + ')');
      if(result)
      {
        if(eval(result.success))
        {
          document.location.href=this._cartPageUrl;
        }
        else if(result.errorMessage)
        {
          this.displayAddToCartErrorMessage(result.errorMessage)
        }
      }
    }
    catch(e){
      document.location.href=this._cartPageUrl;
    }

  },

  loadStates: function( countryId, selectBox ){
      try
      {
        var params = "matrix=" + Math.round(Math.random() * 10000);
        params += "&id="+countryId;
        var myAjax = new Ajax.Request(this._waContext + this._loadStatesActionUrl,{method:'get', parameters: params, onSuccess: this.updateStates.bind(this,selectBox)});
      }
      catch(e){alert(e);}
  },

  updateStates: function( selectBox, resp ){
    selectBox.options.length = 0;
    Element.hide("stateIdRequired");
    Element.hide("postalCodeIdRequired");
    var map = this.checkError(resp);
    if( map.success == 'true' )
    {
      var states = map.states;
      if( states  && states.length > 0)
      {
        Element.show("stateIdRequired");
        Element.show("postalCodeIdRequired");
        for( var i=0; i<states.length; i++ )
        {
          var selected = this._stateId == states[i].id;
          selectBox.options[i] = new Option(states[i].name_fr, states[i].id, selected, selected);
        }
      }
    }
  },

  confirmDeleteCourseElement: function(){
    return confirm("Voulez-vous vraiment supprimer ce manuel ?");
  },

  confirmDeleteCourse: function(){
    return confirm("Voulez-vous vraiment supprimer ce cours ?");
  },

  findCourseName: function( form ){
    try
    {
      var code = form.code.value;
      if(code != '-')
      {
        var params = "matrix=" + Math.round(Math.random() * 10000);
        params += "&code="+code;
        var myAjax = new Ajax.Request(this._waContext + this._findULCourseActionUrl,{method:'get', parameters: params, onSuccess: this.callbackFindULCourse.bind(this, form)});
      }
      else
      {
        alert("Vous devez entrer un code du cours.");
      }
    }
    catch(e){alert(e);}
  },

  callbackFindULCourse: function(form, resp){
  try
    {
      var map = this.checkError(resp);
      if( map && map.name && map.name != '')
      {
        form.name.value = map.name;
        this.setSelectedValue(form.session);
      }
      else
      {
        alert("Ce cours est introuvable");
      }
    }
    catch(e){alert(e);}
  },

  showTooltip: function (id){
    this.hideTooltip();
    Element.setStyle(id, {display: 'block', left: '420px'});
    this._lastTooltip = id;
  },

  hideTooltip: function (){
    if(this._lastTooltip)
      Element.setStyle(this._lastTooltip, {display: 'none'});
  },


  popup: function( url, name, width, height, scroll )
  {
    var params;
    var x = 0;
    var y = 0;

    x = (screen.availWidth / 2) - (width / 2);
    y = (screen.availHeight / 2) - (height / 2);


    params = "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=" + (scroll ? "yes" : "auto") +  ",status=no,left=" + x + ",top=" + y;
    //alert(params);
    var theMatrix = Math.round(Math.random() * 10000);

    var newURL = url;

    myEngineWin = window.open( newURL, name, params );
    myEngineWin.focus();
  },

  popupProductDetail: function(productCode, extraParams){
    if(!extraParams)
    {
      extraParams = "";
    }
    this.popup(this._waContext + this._popupProductDetailUrl + productCode + extraParams,"popupProductDetail", 580, 500, true);
  },

  goToProductDetails: function(productCode){
    document.location.href = currentPageUrl + '?productCode=' + productCode;
  },

  checkPaymentModeNotEmpty: function(theForm){
    var notEmpty = false;
    if(theForm.paymentMode.length){
      for(var i = 0; i < theForm.paymentMode.length; i++)
      {
        if(theForm.paymentMode[i].checked)
        {
          notEmpty = true;
        }
      }
    } else {
      notEmpty = theForm.paymentMode.checked;
    }
    if(notEmpty)
    {
      theForm.submit();
    }
    else
    {
      alert("Vous devez choisir un mode paiment.");
    }
  },

  showTab: function(tabId){
    var tabs = Element.immediateDescendants('tabs-items');
    for(var i = 0; i < tabs.length; i++)
    {
      tabs[i].className = "";
      $(tabs[i].id + 'Content').hide();
    }
    $(tabId).className = "active";
    $(tabId + 'Content').show();
  },

  getMatrix: function(){
    return Math.round(Math.random() * 10000);
  },

  loadRatings: function(code, tabId, pageId, sortBy){
    this._lastProductCode = code;
    this._lastTabId = tabId;
    var params = "matrix=" + Math.round(Math.random() * 10000);
    params += "&productCode="+code;
    params += "&page="+pageId;
    params += "&sortBy="+sortBy;
    var myAjax = new Ajax.Request(this._waContext + this._loadRatingsActionUrl,{method:'get', parameters: params, onSuccess: this.callbackLoadRatings.bind(this, tabId)});
  },

  changeRatingsPage: function(newPage, sortBy){
    this.loadRatings(this._lastProductCode, this._lastTabId, newPage, sortBy);
  },

  callbackLoadRatings: function(tabId, resp){
  try
    {
      var result = resp.responseText;

      if(result)
      {
        Element.update(tabId + 'Content', result);
        this.showTab(tabId);
      }
    }
    catch(e){alert(e);}
  },

  removeRating: function(id){
    var params = "matrix=" + Math.round(Math.random() * 10000);
    params += "&id="+id;
    var myAjax = new Ajax.Request(this._waContext + this._removeRatingActionUrl,{method:'get', parameters: params, onSuccess: this.reloadPage.bind(this)});
  },

  reloadPage: function(resp){
    document.location.reload();
  }

}