/*
 * Default Scripts
 */



/*******************************************************************************
 * Constants
 */

// Defines the location of the root directory
var BASEDIR = "/default/";



/*******************************************************************************
 * Services
 */
var Services = {
  initialize: function() {
    this.alert = new Alert({path: BASEDIR + "libs/moozy/alerts/", theme: "custom"});
    this.topper = new Topper({path: BASEDIR + "libs/moozy/topper/", percentage: 100, text: "Haut de la page", theme: "custom", title: "Revenir tout en haut de la page"});
  },
  getAlert: function() {
    return this.alert;
  }
};




/*******************************************************************************
 * All pages
 */
var all = {
  start: function() {
    // Retrieves the form for the newsletter
    var form = $E("#newsletter FORM");
    
    if (form !== null) {
      form.addEvent("submit", function(event) {
        // Stops event propagation (no other listener will ever get it)
        event.stop();
        
        // Initializes a checker object (and gives it access to services)
        var checker = new Checker(Services, {effect: "shaking",
                                             rules: {
                                               email: {
                                                 message: "Veuillez préciser une adresse email valide"
                                               },
                                               length: {
                                                 minimum: {
                                                   message: "Veuillez entrer au moins %0 caractères pour votre adresse email"
                                                 },
                                                 maximum: {
                                                   message: "Veuillez entrer au maximum %0 caractères pour votre adresse email"
                                                 }
                                               },
                                               required: {
                                                 message: "Veuillez préciser une adresse email"
                                               }
                                             }});
        
        // Checks that the user has entered a valid email address
        if (checker.check("subscriber", {required: {allowDefaultValue: true}, email: {}, length: {minimum: {value: 6}, maximum: {}}})) {
          Services.getAlert().info("Inscription à la newsletter en cours"); 
          
          this.submit();
        }
      });
      
      // Retrieves the submit button
      var button = $E("#newsletter FORM BUTTON");
      
      if (button !== null) {
        button.addEvent("click", function(event) {
          // Stops event propagation (no other listener will ever get it)
          event.stop();
          
          // Removes focus on the button to get a nicer display
          this.blur();
          
          // Makes sure the Google Analytics library is loaded and available and
          // tracks this click as a goal step
          if (typeof pageTracker === "object") {
            pageTracker._trackPageview("/newsletter/click");
          }
          
          // Submits form by starting the associated event that will check all
          // the required information has been entered by the user
          form.fireEvent("submit", event);
        });
      }
    }
    
    // Fixes 'focus' CSS support on Internet Explorer 7 as well as a 
    // background image display problem on textareas (the background image 
    // scrolls when the user enters too much text)
    if (Browser.Engine.trident && Browser.Engine.version === 5) {
      // Simulates the ':focus' pseudo-selector on text input fields
      $$("FORM INPUT").each(function(input) {
        input.addEvent("focus", function(event) {
          input.addClass("focus");
        });
        
        input.addEvent("blur", function(event) {
          input.removeClass("focus");
        });
      });
      
      // Simulates the ':focus' pseudo-selector on textaresa and fixes the
      // background image display problem 
      var textarea = $E("FORM TEXTAREA");
      
      if (textarea !== null) {
        var paragraph = textarea.getParent();
        
        if (paragraph !== null) {
          paragraph.addClass("textarea");
          
          textarea.addEvent("focus", function(event) {
            paragraph.addClass("focus");
          });
          
          textarea.addEvent("blur", function(event) {
            paragraph.removeClass("focus");
          });
        }
      }
    }
  }
};


/*******************************************************************************
 * Contact page
 */
var contactpage = {
  start: function() {
    // Retrieves the form element
    var form = $E("#content FORM");
    
    if (form !== null) {
      form.addEvent("submit", function(event) {
        // Stops event propagation (no other listener will ever get it)
        event.stop();
        
        // Initializes a checker object (and gives it access to services)
        var checker = new Checker(Services, {effect: "opacity",
                                             rules: {
                                               email: {
                                                 message: "Veuillez préciser une adresse email valide pour ce champ"
                                               },
                                               length: {
                                                 fixed: {
                                                   message: "Veuillez entrer exactement %0 caractères pour ce champ"
                                                 },
                                                 minimum: {
                                                   message: "Veuillez entrer au moins %0 caractères pour ce champ"
                                                 },
                                                 maximum: {
                                                   message: "Veuillez entrer au maximum %0 caractères pour ce champ"
                                                 }
                                               },
                                               number: {
                                                 "float": {
                                                   message: "Veuillez préciser un nombre à virgule pour ce champ"
                                                 },
                                                 integer: {
                                                   message: "Veuillez préciser une valeur entière pour ce champ"
                                                 },
                                                 minimum: {
                                                   message: "Veuillez préciser une valeur plus grande que %0"
                                                 },
                                                 maximum: {
                                                   message: "Veuillez préciser une valeur plus petite que %0"
                                                 }
                                               },
                                               required: {
                                                 message: "Veuillez préciser une valeur pour ce champ"
                                               }
                                             }});
        
        // Checks that the user has entered pertinent values
        if (checker.check("name", {required: {allowDefaultValue: true}, length: {minimum: {value: 2}, maximum: {}}})) {
          if (checker.check("email", {required: {allowDefaultValue: true}, email: {}, length: {minimum: {value: 6}, maximum: {}}})) {
            if (checker.check("subject",  {required: {allowDefaultValue: true}, length: {minimum: {value: 2}, maximum: {}}})) {
              if (checker.check("message", {required: {allowDefaultValue: true}, length: {minimum: {value: 50}, maximum: {value: 16384}}})) {
                Services.getAlert().info("Envoi du message en cours"); 
                
                this.submit();
              }
            }
          }
        }
      });
      
      // Retrieves the submit button
      var button = $E("#content FORM BUTTON");
      
      if (button !== null) {
        button.addEvent("click", function(event) {
          // Stops event propagation (no other listener will ever get it)
          event.stop();
          
          // Removes focus on the button to get a nicer display
          this.blur();
          
          // Makes sure the Google Analytics library is loaded and available and
          // tracks this click as a goal step
          if (typeof pageTracker === "object") {
            pageTracker._trackPageview("/contact/click");
          }
          
          // Submits form by starting the associated event that will check all
          // the required information has been entered by the user
          form.fireEvent("submit", event);
        });
      }
      
      // Retrieves the first message displayed
      var message = $E(".message");
      
      if (message !== null) {
        // Processes message according to its type
        if (message.hasClass("failure")) {
          // Retrieves all the links contained into the failure message
          var links = message.getElements("UL LI A");
          
          links.each(function(link) {
            // Retrieves the hash of this link
            var hash = link.hash;
            
            // Handles only links pointing to elements on the same page (should 
            // be input fields)
            if (hash.startsWith("#")) {
              // Remove first character (i.e #)
              var identifier = hash.substr(1, hash.length);
              
              // Retrieves the corresponding input field
              var field = $(identifier);
              
              if (field !== null) {
                link.addEvent("click", function(event) {
                  // Stops event propagation (no other listener will ever get it)
                  event.stop();
                  
                  // Makes sure the field is visible (displayed in the viewport)
                  if (field.isInside(window, 50)) {
                    this.highlightField(field);
                  } else {
                    // Initializes smooth scrolling effect
                    var scrollEffect = new Fx.Scroll(window, {offset: {'y': -100}, link: "cancel"});
                    
                    // Highlights field only when scrolling is done
                    scrollEffect.addEvent("onComplete", function() {
                      this.highlightField(field);
                    }.bind(this));
                    
                    // Scrolls the window to the field
                    scrollEffect.toElement(field);
                  }
                }.bind(this));
              }
            }
          }.bind(this));
        } else if (message.hasClass("success")) {
          // Makes sure the Google Analytics library is loaded and available and
          // tracks this subscription as a goal
          if (typeof pageTracker === "object") {
            pageTracker._trackPageview("/contact/success");
          }
        }
      }
      
      // Retrieves the first field
      var field = $("name");
      
      // Positions cursor on the first field of the form at loading time
      if (field !== null) {
        field.focus();
      }
    }
  },
  highlightField: function(field) {
    // Places cursor onto the field
    field.focus();
    
    // Retrieves the highlight effect associated to this field
    var highlightEffect = field.retrieve("effect.error");
     
    // Initializes the highlight effect if necessary
    if (highlightEffect === null) {
      highlightEffect = new Fx.Highlight(field, {count: 2, duration: 100, link: "cancel", type: "opacity"});
      
      // Associates the highlight effect to this field to be able to reuse it
      // later on
      field.store("effect.error", highlightEffect);
    }
    
    // Initiates highlighting
    highlightEffect.start(0);
  }
};




/*******************************************************************************
 * Homepage
 */
var homepage = {
  start: function() {
    // Retrieves the text associated to the screenshot
    var text = $E("#highlight .text");
    
    if (text !== null) {
      // Initializes visual effect
      var effect = new Fx.Tween(text, {property: "opacity", duration: 1500});
      
      // Hides the text at startup
      effect.set(0);
      
      // Removes style previously set through the javascript-enabled stylesheet
      // to avoid flickering
      text.setStyle("display", "block");
      
      // Displays the text gradually when page has finished loading
      effect.start.delay(1200, effect, 1);
    }
  }
};



/*******************************************************************************
 * Magento page
 */
var magentopage = {
  start: function() {
    // Builds a container for the soft overlay
    var container = new Element("DIV");
    container.set("id", "overlay");
    container.setStyle("display", "none");
    container.setStyle("height", window.getScrollHeight() + "px");
    container.inject(document.body);
    
    // Initializes visual effect
    var opacityEffect = new Fx.Tween(container, {property: "opacity", duration: 300, link: "cancel"});
    
    // Hides the mask at startup
    opacityEffect.set(0);
    
    // Removes style previously set to avoid flickering
    container.removeStyle("display");
    
    // Initializes the lightbox mechanism
    ReMooz.assign("#thumbnails A", {
      centered: true,
      resize: false,
      generateTitle: function(element) {
        return null;
      },
      onOpen: function() {
        // Retrieves a pointer to the close() method of the ReMooz component
        var close = this.close.bind(this);
        
        // Adds two events to close the lightbox whenever the user clicks 
        // outside it or he types on a key
        document.addEvent("keydown", close);
        container.addEvent("click", close);
      },
      onOpenEnd: function() {
        // Displays a soft overlay to highlight the screenshot
        opacityEffect.start(0, 0.2);
      },
      onClose: function() {
        // Retrieves a pointer to the close() method of the ReMooz component
        var close = this.close.bind(this);
        
        // Removes the events previously assigned
        document.removeEvent("keydown", close);
        container.removeEvent("click", close);
        
        // Hides the soft overlay now
        opacityEffect.start(0.2, 0);
      }
    });
    
    var container = $E("#features");
    
    if (container !== null) {
      // Injects a new DIV element between the list of features and their parent
      // element to be able to initialize a tab instance using a container
      // element
      var element = new Element("DIV");
      element.adopt(container.getChildren());
      container.grab(element);
      
      // Builds the navigation section dynamically:
      // 
      //   <ul>
      //     <li class="page">1</li>
      //     <li class="page">2</li>
      //     <li class="next">suivant</li>
      //     <li class="previous disabled">précédent</li>
      //   </ul>
      // 
      
      var list = new Element("UL");
      list.inject(container);
      
      element = new Element("LI");
      element.addClass("page");
      element.set("text", 1);
      element.inject(list);
      
      element = new Element("LI");
      element.addClass("page");
      element.set("text", 2);
      element.inject(list);
      
      element = new Element("LI");
      element.addClass("previous");
      element.addClass("disabled");
      element.set("text", "précédent");
      element.inject(list);
      
      // Keeps a reference to the previous button
      var previous = element;
      
      element = new Element("LI");
      element.addClass("next");
      element.set("text", "suivant");
      element.inject(list);
      
      // Keeps a reference to the next button
      var next = element;
      
      // Initializes tabs component
      var tabs = new Tabs({mode: "opacity"});
      var instance = tabs.enable("#features UL LI.page" , "#features DIV");
      
      // Attaches the previous and next buttons to the tabs component to be able
      // to be notified of events
      instance.setNext(next);
      instance.setPrevious(previous);
      
      // Activates the previous tab when the user clicks on the previous button
      previous.addEvent("click", function(event) {
        instance.previous();
      });
      
      // Disables the previous button if the first tab is displayed
      previous.addEvent("change", function(event) {
        if (instance.isFirst()) {
          this.addClass("disabled");
        } else {
          this.removeClass("disabled");
        }
      });
      
      // Activates the nest tab when the user clicks on the next button
      next.addEvent("click", function(event) {
        instance.next();
      });
      
      // Disables the next button if the last tab is displayed
      next.addEvent("change", function(event) {
        if (instance.isLast()) {
          this.addClass("disabled");
        } else {
          this.removeClass("disabled");
        }
      });
    }
  }
};



/*******************************************************************************
 * Newsletter page
 */
var newsletterpage = {
  start: function() {
    // Retrieves the form element
    var form = $E("#content FORM");

    if (form !== null) {
      form.addEvent("submit", function(event) {
        // Stops event propagation (no other listener will ever get it)
        event.stop();

        // Initializes a checker object (and gives it access to services)
        var checker = new Checker(Services, {effect: "opacity",
                                             rules: {
                                               email: {
                                                 message: "Veuillez préciser une adresse email valide pour ce champ"
                                               },
                                               length: {
                                                 minimum: {
                                                   message: "Veuillez entrer au moins %0 caractères pour ce champ"
                                                 },
                                                 maximum: {
                                                   message: "Veuillez entrer au maximum %0 caractères pour ce champ"
                                                 }
                                               },
                                               required: {
                                                 message: "Veuillez préciser une valeur pour ce champ"
                                               }
                                             }});

        // Checks that the user has entered pertinent values
        if (checker.check("subscriber", {required: {allowDefaultValue: true}, email: {}, length: {minimum: {value: 6}, maximum: {}}})) {
          Services.getAlert().info("Abonnement à la newsletter en cours");

          this.submit();
        }
      });

      // Retrieves the submit button
      var button = $E("#content FORM BUTTON");

      if (button !== null) {
        button.addEvent("click", function(event) {
          // Stops event propagation (no other listener will ever get it)
          event.stop();

          // Removes focus on the button to get a nicer display
          this.blur();

          // Makes sure the Google Analytics library is loaded and available and
          // tracks this click as a goal step
          if (typeof pageTracker === "object") {
            pageTracker._trackPageview("/newsletter/click");
          }

          // Submits form by starting the associated event that will check all
          // the required information has been entered by the user
          form.fireEvent("submit", event);
        });
      }

      // Retrieves the first message displayed
      var message = $E(".message");

      if (message !== null) {
        // Processes message according to its type
        if (message.hasClass("failure")) {
          // Retrieves all the links contained into the failure message
          var links = message.getElements("UL LI A");

          links.each(function(link) {
            // Retrieves the hash of this link
            var hash = link.hash;

            // Handles only links pointing to elements on the same page (should
            // be input fields)
            if (hash.startsWith("#")) {
              // Remove first character (i.e #)
              var identifier = hash.substr(1, hash.length);

              // Retrieves the corresponding input field
              var field = $(identifier);

              if (field !== null) {
                link.addEvent("click", function(event) {
                  // Stops event propagation (no other listener will ever get it)
                  event.stop();

                  // Makes sure the field is visible (displayed in the viewport)
                  if (field.isInside(window, 50)) {
                    this.highlightField(field);
                  } else {
                    // Initializes smooth scrolling effect
                    var scrollEffect = new Fx.Scroll(window, {offset: {'y': -100}, link: "cancel"});

                    // Highlights field only when scrolling is done
                    scrollEffect.addEvent("onComplete", function() {
                      this.highlightField(field);
                    }.bind(this));

                    // Scrolls the window to the field
                    scrollEffect.toElement(field);
                  }
                }.bind(this));
              }
            }
          }.bind(this));
        } else if (message.hasClass("success")) {
          // Makes sure the Google Analytics library is loaded and available and
          // tracks this subscription as a goal
          if (typeof pageTracker === "object") {
            pageTracker._trackPageview("/newsletter/success");
          }
        }
      }

      // Retrieves the first field
      var field = $("subscriber");

      // Positions cursor on the first field of the form at loading time
      if (field !== null) {
        field.focus();
      }
    }
    
    // Retrieves the first message displayed
    var message = $E(".message");
    
    if (message !== null) {
      // Processes only success messages
      if (message.hasClass("success")) {
        // Makes sure the Google Analytics library is loaded and available and
        // tracks this subscription as a goal
        if (typeof pageTracker === "object") {
          pageTracker._trackPageview("/newsletter/success");
        }
      }
    }
  },
  highlightField: function(field) {
    // Places cursor onto the field
    field.focus();

    // Retrieves the highlight effect associated to this field
    var highlightEffect = field.retrieve("effect.error");

    // Initializes the highlight effect if necessary
    if (highlightEffect === null) {
      highlightEffect = new Fx.Highlight(field, {count: 2, duration: 100, link: "cancel", type: "opacity"});

      // Associates the highlight effect to this field to be able to reuse it
      // later on
      field.store("effect.error", highlightEffect);
    }

    // Initiates highlighting
    highlightEffect.start(0);
  }
};



/*******************************************************************************
 * Work page
 */
var workpage = {
  start: function() {
    // Initializes tabs component
    var tabs = new Tabs({mode: "opacity"});
    tabs.enable("#screenshots LI" , "#screenshots .list");
  }
};



/*******************************************************************************
 * Initialization (when document object model is available)
 */
window.addEvent("domready", function() {
  // Initializes services
  Services.initialize();
  
  // Handles behaviors common to all pages
  all.start();
  
  // Retrieves BODY element
  var body = $E("body");
  
  // Extracts id attribute for this element
  var page = body.getProperty("id");
  
  // Handles specific behaviors
  if (page === "workchannelislandspage") {
    workpage.start();
  } else if (page === "contactpage") {
    contactpage.start();
  } else if (page === "homepage") {
    homepage.start();
  } else if (page === "newslettersubscribepage") {
    newsletterpage.start();
  } else if (page === "servicessolutionpage") {
    magentopage.start();
  } else if (page === "workpullinpage") {
    workpage.start();
  }
});