document.observe("dom:loaded", function() {
  var authToken = $$('meta[name=csrf-token]').first().readAttribute('content'),
    authParam = $$('meta[name=csrf-param]').first().readAttribute('content'),
    formTemplate = '<form method="#{method}" action="#{action}">\
      #{realmethod}<input name="#{param}" value="#{token}" type="hidden">\
      </form>',
    realmethodTemplate = '<input name="_method" value="#{method}" type="hidden">';

  function handleRemote(element) {
    var method, url, params;

    if (element.tagName.toLowerCase() == 'form') {
      method = element.readAttribute('method') || 'post';
      url    = element.readAttribute('action');
      params = element.serialize(true);
    } else {
      method = element.readAttribute('data-method') || 'get';
      url    = element.readAttribute('href');
      params = {};
    }

    var event = element.fire("ajax:before");
    if (event.stopped) return false;

    new Ajax.Request(url, {
      method: method,
      parameters: params,
      asynchronous: true,
      evalScripts: true,

      onLoading:     function(request) { element.fire("ajax:loading", {request: request}); },
      onLoaded:      function(request) { element.fire("ajax:loaded", {request: request}); },
      onInteractive: function(request) { element.fire("ajax:interactive", {request: request}); },
      onComplete:    function(request) { element.fire("ajax:complete", {request: request}); },
      onSuccess:     function(request) { element.fire("ajax:success", {request: request}); },
      onFailure:     function(request) { element.fire("ajax:failure", {request: request}); }
    });

    element.fire("ajax:after");
  }

  $(document.body).observe("click", function(event) {
    var message = event.element().readAttribute('data-confirm');
    if (message && !confirm(message)) {
      event.stop();
      return false;
    }

    var element = event.findElement("a[data-remote=true]");
    if (element) {
      handleRemote(element);
      event.stop();
    }

    var element = event.findElement("a[data-method]");
    if (element && element.readAttribute('data-remote') != 'true') {
      var method = element.readAttribute('data-method'),
        piggyback = method.toLowerCase() != 'post',
        formHTML = formTemplate.interpolate({
          method: 'POST',
          realmethod: piggyback ? realmethodTemplate.interpolate({ method: method }) : '',
          action: element.readAttribute('href'),
          token: authToken,
          param: authParam
        });

      var form = new Element('div').update(formHTML).down().hide();
      this.insert({ bottom: form });

      form.submit();
      event.stop();
    }
  });

  // TODO: I don't think submit bubbles in IE
  $(document.body).observe("submit", function(event) {
    var message = event.element().readAttribute('data-confirm');
    if (message && !confirm(message)) {
      event.stop();
      return false;
    }

    var inputs = event.element().select("input[type=submit][data-disable-with]");
    inputs.each(function(input) {
      input.disabled = true;
      input.writeAttribute('data-original-value', input.value);
      input.value = input.readAttribute('data-disable-with');
    });

    var element = event.findElement("form[data-remote=true]");
    if (element) {
      handleRemote(element);
      event.stop();
    }
  });

  $(document.body).observe("ajax:complete", function(event) {
    var element = event.element();

    if (element.tagName.toLowerCase() == 'form') {
      var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
      inputs.each(function(input) {
        input.value = input.readAttribute('data-original-value');
        input.writeAttribute('data-original-value', null);
        input.disabled = false;
      });
    }
  });
});



var HomeMarksBase = {
  
  flashMoods: $A(['good','bad','indif']),
  flashMoodColors: $H({ good:'spring_green', bad:'red', indif:'aqua' }),
  
  getRequestMood: function(request) {
    return (request.status >= 200 && request.status < 300) ? 'good' : 'bad';
  },
  
  authParams: function() {
    var params = {}
    var authParam = $$('meta[name=csrf-param]').first().readAttribute('content');
    var authToken = $$('meta[name=csrf-token]').first().readAttribute('content');
    params[authParam] = authToken
    return $H(params);
  },

  messagesToAlert: function(request) {
    var messages = request.responseJSON;
    var alertText = messages.join(".\n");
    if (alertText.endsWith('.')) { alert(alertText); } else { alert(alertText+'.'); };
  },
  
  messagesToList: function(request) {
    var messages = request.responseJSON;
    var messageList = UL();
    messages.each(function(message){ 
      messageList.appendChild( LI(message.escapeHTML()) );
    });
    return messageList;
  },
  
  redirectToUserHome: function() {
    window.location = '/myhome';
  },
  
  scroll: function() { return document.viewport.getScrollOffsets(); },
  
  viewSize: function() { return document.viewport.getDimensions(); },
  
  pageSize: function() { 
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {	
  		xScroll = window.innerWidth + window.scrollMaxX;
  		yScroll = window.innerHeight + window.scrollMaxY;
  	} else if (document.body.scrollHeight > document.body.offsetHeight){
  		xScroll = document.body.scrollWidth;
  		yScroll = document.body.scrollHeight;
  	} else {
  		xScroll = document.body.offsetWidth;
  		yScroll = document.body.offsetHeight;
  	}
	  var windowWidth, windowHeight;
  	if (self.innerHeight) {
  		if(document.documentElement.clientWidth){
  			windowWidth = document.documentElement.clientWidth; 
  		} else {
  			windowWidth = self.innerWidth;
  		}
  		windowHeight = self.innerHeight;
  	} else if (document.documentElement && document.documentElement.clientHeight) {
  		windowWidth = document.documentElement.clientWidth;
  		windowHeight = document.documentElement.clientHeight;
  	} else if (document.body) { 
  		windowWidth = document.body.clientWidth;
  		windowHeight = document.body.clientHeight;
  	}	
  	if(yScroll < windowHeight){
  		pageHeight = windowHeight;
  	} else { 
  		pageHeight = yScroll;
  	}
  	if(xScroll < windowWidth){	
  		pageWidth = xScroll;		
  	} else {
  		pageWidth = windowWidth;
  	}
  	return { width: pageWidth, height: pageHeight };
  }
  
};





var HomeMarksModalClass = Class.create(HomeMarksBase,{
  
  initialize: function() {
    this.build();
    this.mask = $('modalmask'); 
    this.progress = $('modal_progress');
    this.apWrapper = $('modal_html_ap-wrapper');
    this.relWrapper = $('modal_html_rel-wrapper');
    this.topShadow = $('modal_html_top');
    this.contentWrap = $('modal_html');
    this.content = $('modal_content');
    this.initButtons();
    this.queue = {position:'end', scope:'modalscope'};
  },
  
  build: function() {
    var body = $$('body').first();
    var maskHTML = DIV({id:'modalmask',style:'display:none;'},[DIV({id:'modal_progress',style:'display:none;',onclick:'location.reload();'})]);
    var modalHTML = DIV({id:'modal_html_ap-wrapper'},[
      DIV({id:'modal_html_rel-wrapper',style:'display:none;'},[
        DIV({id:'modal_html_border'},[
          DIV({id:'modal_html'},[
            DIV({id:'modal_content'}),
            DIV({id:'modal_buttons',className:'clearfix'},[
              DIV({id:'modal_button_save',style:'display:none;'}),
              DIV({id:'modal_button_cancel',style:'display:none;'})
            ])
          ]),
        ]),
        DIV({id:'modal_html_top'})
      ])]
    );
    body.insert({top:modalHTML});
    body.insert({top:maskHTML});
  },
  
  show: function(content) {
    var options = Object.extend({contentFor:'misc',color:'timberwolf',showProgress:false}, arguments[1] || {});
    this.contentFor = options.contentFor;
    this.color = options.color;
    this.updateContent(content);
    this.showContentButtons();
    this.toggleMask('on');
    if (options.showProgress) { this.toggleProgress('on') };
    this.toggleObservers('on');
    this.toggleModal('on');
    // TODO: Account for action area.
    // document.stopObserving('keypress', actionAreaHelper);
    // if (this.action_bar().hasClassName('barout')) { toggleActionArea('inbox'); }
  },
  
  showBookmarkModal: function(content) {
    this.show(content,{contentFor:'bookmark',showProgress:true});
    this.bmLoading = $('loadinghomemarks');
    this.bmForm = $('savehomemarks_form');
    this.bmName = $('savehomemarks_name');
    if (this.bmLoading) { 
      this.bmLoading.remove();
      this.bmName.value = document.title;
    };
    this.bmForm.observe('submit',this.saveBookmarkModal.bindAsEventListener(this));
    this.saveButton.observe('click',this.saveBookmarkModal.bindAsEventListener(this));
  },
  
  saveBookmarkModal: function(event) {
    event.stop();
    var rjsCreate = document.createElement('script');
    rjsCreate.type = 'text/javascript';
    rjsCreate.src = this.bmForm.action + '&' + this.bmForm.serialize();
    this.bmForm.disable();
    document.body.appendChild(rjsCreate);
    return false;
  },
  
  startHide: function() {
    this.toggleObservers('off');
    this.toggleProgress('on');
    this.toggleModal('off');
  },
  
  completeHide: function() {
    this.toggleProgress('off');
    this.toggleMask('off');
  },
  
  hide: function() {
    this.startHide();
    this.completeHide();
    if (this.contentFor == 'bookmark' && !this.bmLoading) {
      setTimeout(function(){ 
        window.location.href = $('savehomemarks_url').value;
      },0650);
    };
    // TODO: Account for action area.
    // document.observe('keypress', actionAreaHelper);
  },

  updateContent: function(content) {
    this.topShadow.setStyle({width:this.dimensions().topWidth+'px'});
    this.contentWrap.setStyle({width:this.dimensions().contentWidth, height:this.dimensions().contentHeight});
    this.contentWrap.className = this.color;
    if (content) { this.content.update(content); };
    this.center();
  },
  
  showContentButtons: function() {
    this.allButtons.invoke('hide');
    switch (this.contentFor) { 
      case 'misc'     : $A([this.cancelButton]).invoke('show'); break;
      case 'box'      : $A([this.cancelButton,this.saveButton]).invoke('show'); break; 
      case 'bookmark' : $A([this.cancelButton,this.saveButton]).invoke('show'); break; 
    }
  },
  
  center: function() {
    this.mask.setStyle({height: this.pageSize().height + 'px'});
    this.progress.setStyle({top: (this.scroll().top + 60) + 'px'});
    var total = this.pageSize().width - this.dimensions().topWidth;
    var left = (total/2).ceil();
    if (left < 0) left = 0;
    this.apWrapper.setStyle({left:left+'px'});
  },
  
  dimensions: function() {
    switch (this.contentFor) { 
      case 'misc'     : return { topWidth:452, contentWidth:'400px', contentHeight:'auto' };
      case 'box'      : return { topWidth:652, contentWidth:'600px', contentHeight:'300px' }; 
      case 'bookmark' : return { topWidth:352, contentWidth:'300px', contentHeight:'145px' }; 
    }
  },
  
  toggleMask: function(toggle) {
    var options = { duration:0.2, queue:this.queue };
    if (toggle == 'on') { this.mask.appear(Object.extend(options,{from:0.0,to:0.9})); }
    else { this.mask.fade(options); };
  },
  
  toggleObservers: function(toggle) {
    if (toggle == 'on') {
      this.modalResizeObserver = this.center.bindAsEventListener(this);
      Event.observe(window,'resize', this.modalResizeObserver);
      Event.observe(window,'scroll', this.modalResizeObserver);
      this.keypressObserver = this.keypress.bindAsEventListener(this);
      document.observe('keypress', this.keypressObserver);
    }
    else {
      Event.stopObserving(window,'resize',this.modalResizeObserver);
      Event.stopObserving(window,'scroll',this.modalResizeObserver);
      document.stopObserving('keypress',this.keypressObserver);
    };
  },
  
  toggleProgress: function(toggle) {
    var options = {duration:0.2, queue:this.queue}
    if (toggle == 'on') { this.progress.appear(options); } else { this.progress.fade(options); };
  },
  
  toggleModal: function(toggle) {
    var options = { duration:0.4 }; // Helps speed by removing: queue:this.queue} 
    if (toggle == 'on') { this.relWrapper.slideDown(options); } else { this.relWrapper.slideUp(options); };
  },
  
  keypress: function(event) {
    if (event.keyCode == Event.KEY_ESC) { this.hide(); };
  },
  
  initButtons: function() {
    this.cancelButton = $('modal_button_cancel');
    this.cancelButton.observe('click',this.hide.bindAsEventListener(this))
    this.saveButton = $('modal_button_save');
    this.allButtons = $A([this.cancelButton,this.saveButton]);
  }
  
  
});


document.observe('dom:loaded', function(){
  HomeMarksModal = new HomeMarksModalClass();
});



