// Copyright (c) 2010, Cloudera, inc. All rights reserved.

Account = new Class({
  
  Implements: Options,
  
  options: {
    cookieName: 'account',
    cookieDuration: 3650, //365 Days
    accountURL: '/account.php',
    closable: false,
    newsletter: true,
    message: '',
    heading: 'Please Register',
    fields: {}, //Fields to initialize the registration form with
    agreementVersion: '',
    loginRedirectURL: document.location.href,
    contentElement: '.inner',
    registerSubmitClass: '.submit-inquiry',
    backRegisterSubmitClass: '.submit-inquiry',
    closeRegisterSubmitClass: '.submit-close',
    agreementSubmitClass: '.submit-inquiry',
    campaignID: '',
    hideMaskedContent: true,
    maskTarget: document.body
  },
  
  initialize: function(element, options){
    this.element = element;
    this.setOptions(options);
    this.account = this.getCookie();
    this.contentVisible = true;
    if(this.options.closable) this.makeClosable();
    if(!this.account || !this.account.verified || !this.account.agreement){
      if(this.options.hideMaskedContent) this.hideContent();
      this.loadContent({
        redirect: this.options.loginRedirectURL,
        agreement_version: this.options.agreementVersion,
        campaign_id: this.options.campaignID,
        newsletter: this.options.newsletter
      });
    }
  },
  
  hideContent: function(){
    this.contentVisible = false;
    $(this.options.maskTarget).setStyle('visibility', 'hidden');
  },
  
  revealContent: function(){
    this.contentVisible = true;
    $(this.options.maskTarget).setStyle('visibility', 'visible');
  },
  
  loadContent: function(data){
    this.modalMasking = this.modalMasking || new Mask(this.element.getElement(this.options.contentElement)).show();
    var req = new Request({
      url: this.options.accountURL,
      evalScripts: false,
      data: data || '',
      onComplete: function(text){
        this.modalMasking.destroy();
        if(text.substr(0, 2) != ';;') {
          alert('Invalid response from server.');
          return; 
        }
        var json = JSON.parse(text.substr(2));
        if(json.authenticated && json.verified && json.agreement) {
          this.hide();
          this.revealContent();
        } else {
          this.render();
          this.element.getElement(this.options.contentElement).set('html', json['content']);
          this.resize();
          if(!json.authenticated){
            this.attachRegistrationEvents();
          } else if(!json.verified){
            this.attachValidationEvents();
          } else if(!json.agreement){
            this.attachAgreementEvents();
          }
        }
      }.bind(this)
    }).send();
  },
  
  makeClosable: function(){
    var div = new Element('div', {'class': 'btn-close'});
    var a = new Element('a', {
      'href': '#',
      'html': 'close',
      'events': {
        'click': function(){
          this.hide();
          return false;
        }.bind(this)
      }
    });
    div.adopt(a).inject(this.element.getElement(this.options.contentElement), 'before');
  },
  
  getCookie: function(){
    var account = Cookie.read(this.options.cookieName);
    return account ? JSON.decode(account) : {};
  },
  
  setCookie: function(val){
    var account = val ? JSON.encode(val) : null;
    Cookie.write(this.options.cookieName, account, {
      duration: this.options.cookieDuration,
      domain: document.location.host.toLowerCase().replace('www.',''),
      path: '/'
    });
  },
  
  render: function(){
    if(this.rendered) return;
    this.rendered = true;
    this.renderMask();
    this.showModal();
  },
  
  hide: function(){
    this.revealContent();
    this.destroyMask();
    this.hideModal();
    this.resize();
  },
  
  resize: function(){
    var targetHeight = this.options.maskTarget.getSize().y, modalHeight = this.element.getSize().y + 80;
    if(targetHeight < modalHeight || !this.contentVisible) this.options.maskTarget.setStyle('height', modalHeight + 'px');
    else this.options.maskTarget.setStyle('height', 'auto');
    if(this.mask) this.mask.resize(); //resize mask over content
  },
  
  attachRegistrationEvents: function(){
    var inpt = this.element.getElement('input[type="text"]');
    if(inpt) inpt.focus();
    
    if(this.element.getElement('form')){
      for(field in this.options.fields){
        this.element.getElement('input[name="' + field +'"]').set('value', this.options.fields[field]);
      }
      
      this.element.getElement('input[name="newsletter"]').checked = this.options.newsletter;
      this.element.getElement('.message').set('html', this.options.message);
      this.element.getElement('.heading').set('html', this.options.heading);
      
      this.validator = new Form.Validator.Inline(this.element.getElement('form'), {
        useTitles: true,
        errorPrefix: '',
        onFormValidate: function(passed, form, event){
          if (passed){
            this.loadContent(
              this.element.getElement('form').toQueryString() +
              '&agreement_version=' + this.options.agreementVersion +
              '&redirect=' + encodeURIComponent(this.options.loginRedirectURL) +
              '&campaign_id=' + encodeURIComponent(this.options.campaignID)
            );
          }
        }.bind(this)
      });

      this.element.getElement(this.options.registerSubmitClass).addEvent('click', function(){
        this.validator.validate();
        return false;
      }.bind(this));
    }
  },
  
  attachValidationEvents: function(){
    if(this.element.getElement(this.options.closeRegisterSubmitClass)) {
      this.element.getElement(this.options.closeRegisterSubmitClass).addEvent('click', function(){
        this.hide();
        return false;
      }.bind(this));
    } else {
      this.element.getElement(this.options.backRegisterSubmitClass).addEvent('click', function(){
        this.setCookie(); //Clears account cookie
        this.loadContent({
          redirect: this.options.loginRedirectURL,
          agreement_version: this.options.agreementVersion,
          campaign_id: this.options.campaignID,
          newsletter: this.options.newsletter
        });
        return false;
      }.bind(this));
    }
  },
  
  attachAgreementEvents: function(){
    this.element.getElement(this.options.agreementSubmitClass).addEvent('click', function(){
      this.loadContent({
        redirect: this.options.loginRedirectURL,
        agreement_version: this.options.agreementVersion,
        campaign_id: this.options.campaignID,
        agreement: 1,
        newsletter: this.options.newsletter
      });
      return false;
    }.bind(this));
  },
  
  showModal: function(){
    this.element.getParent().show();
  },
  
  hideModal: function(){
    this.element.getParent().hide();
  },
  
  renderMask: function(){
    this.mask = this.mask || new Mask(this.options.maskTarget);
    this.mask.show();
  },
  
  destroyMask: function(){
    if(!this.mask) return;
    this.mask.destroy();
  }
});