var OsamaGrid=Class.create({
  initialize:function(gridWrapper){
    if(this.wrapper=gridWrapper){
      this.updateBound=this.update.bindAsEventListener(this);
      this.startObserving();
    }
  },
  startObserving:function(){
    this.filter=this.wrapper.down('div.filter');
    // this.filter.select('a').invoke('observe','click',this.updateBound);
    this.wrapper.select('div.filter a').invoke('observe','click',this.updateBound);
    // if(this.pagination=this.wrapper.down('div.pagination')){
    //   // this.pagination.select('a').invoke('observe','click',this.updateBound);
    //   this.wrapper.select('div.pagination a').invoke('observe','click',this.updateBound);
    // }
    this.wrapper.select('div.pagination a').invoke('observe','click',this.updateBound);
  },
  stopObserving:function(){
    this.filter.select('a').invoke('stopObserving','click',this.updateBound);
    if(this.pagination){
      this.pagination.select('a').invoke('stopObserving','click',this.updateBound);
    }
  },
  update:function(ev){
    var a=ev.element(), _this=this;
    if(a.tagName.toLowerCase()=='img'){a=a.up('a')}
    if(a.tagName.toLowerCase()!='a'){return}
    this.stopObserving();
    
    var h=_this.wrapper.getHeight();
    var newPanel;if(newPanel=$('new-osama-panel')){
      newPanel.up().update(newPanel.innerHTML);
    }
    this.wrapper.setStyle({position:'relative',height:h+'px'}).update(
      new Element('div',{id:'old-osama-panel'}).setStyle({position:'absolute',top:'0',left:'0',width:'100%',height:'100%'}).update(_this.wrapper.innerHTML)
    );
    $('old-osama-panel').morph('opacity:0.5');
    this.wrapper.insert({bottom:
      new Element('div',{'class':'loading'})
        .setStyle({position:'absolute',top:'-10px',left:'0',lineHeight:h+'px',opacity:0})
        .update('Loading... <img src="/images/loading1.gif" width="29" height="29" alt="loading" />').appear({to:0.75})
    });
    
    new Ajax.Request(a.href,{
      method:'get',
      onSuccess:function(xhr){
        if(xhr.responseText==null){_this.remoteError;return}
        
        _this.wrapper.insert({bottom:
          new Element('div',{id:'new-osama-panel'}).setStyle({position:'absolute',top:'0',left:'0',width:'100%',height:'100%',display:'none'}).update(xhr.responseText)
        });
        $('old-osama-panel').fade({afterFinish:function(ef){ef.element.remove()}});
        var newPanel=$('new-osama-panel').appear();
        _this.wrapper.select('div.loading').invoke('fade');
        newPanel.setStyle({height:'auto'});
        _this.wrapper.setStyle({height:newPanel.getHeight()+'px'});
        if (a.match('div.pagination a')) {
          a.scrollTo();    
        }     
        _this.startObserving();
      },
      onFailure:_this.remoteError
    });
    ev.stop();
  },
  remoteError:function(){
    alert('Oops, there was a problem; please try again later.');
  }
});

var OsamaTypeLink = Class.create(RemoteLink, {
  initialize: function($super, a) {
    this.div = $('new-osama-placeholder');
    this.ol = $('osama-type-list');
    $super(a);
  },
  act: function($super, event) {
    this.a.highlight();
    $super(event);
  },
  renderSuccess: function(xhr) {
    var partial = xhr.responseText;
    this.div.update(partial);
    new Effect.BlindDown(this.div, {
      afterFinish: function() {
        new Effect.BlindUp(this.ol, {duration: 0.10})
      }.bind(this)
    });
    // this.div.select('a#step-one').invoke('observe', function(event) {
    //   event.stop();
    //   new Effect.BlindUp(this.div, {
    //     afterFinish: function() {
    //       new EffectBlindDown(this.ol)
    //     }.bind(this)
    //   });
    // }.bind(this));
  }
});

var OsamaNewFormLink = Class.create({
	initialize:function(list) {
		this.list = list;
    this.list.select('a').invoke('observe','click',this.update.bindAsEventListener(this));
	},
	update:function(ev) {
		var a = ev.element(), _this = this;
		new Ajax.Request(a.href, {
			method:'get',
			onSuccess:function(xhr){
        if(xhr.responseText==null){ _this.remoteError;return }
				var form;
				if(!(form=$('new-osama-placeholder'))) {return}
        form.update(xhr.responseText);
        // new Effect.AppearDown(form);
        form.show();

        _this.startObservingForm();
      }
		});
		ev.stop();
	},
	startObservingForm:function(){
    var f=$('osama-new-form'); if (f) {
      var inputs = f.select('input[type=text]', 'select', 'input[type=password]', 'input[type=file]', 'input[type=checkbox]')
                    .reject(function(input) { return input.readAttribute('disabled') == 'disabled' });
      inputs.each(function(elt) {
    		elt.observe('focus', function(ev) {
    		  var el=ev.element();
    			el.up('li').addClassName('focus');
    			el.previous('label').select('em').invoke('show');
    		});
    		elt.observe('blur', function(ev) {
    		  var el=ev.element();
    			el.up('li').removeClassName('focus');
    			el.previous('label').select('em').invoke('hide');
    		});
    	});
    	if (inputs.any()) {
    	  if (f.down('.fieldWithErrors input')) {
      		f.down('.fieldWithErrors input').focus();
      	} else {
      		inputs.first().focus();
      	};
    	};
    };
	},
	changeList:function(){
		this.list.addClassName('test');
	},
	remoteError:function(){
    alert('Oops, there was a problem; please try again later.');
  }
});

function copy_text_to_clipboard(text2copy) {
  if (window.clipboardData) {
    window.clipboardData.setData("Text",text2copy);
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="/flash/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}


document.observe('dom:loaded',function(){
  var gridWrapper; if(gridWrapper=$('osama-grid-wrapper')){
    new OsamaGrid(gridWrapper);
  }
	
  var list = $('osama-relationship-list');
  if (list) { formLink = new OsamaNewFormLink(list); }
    
  // if ($$('ol#osama-type-list').any()) {
  //   $$('#osama-type-list').invoke('select', 'a')
  //                         .reduce()
  //                         .each(function(a) {
  //                           // new OsamaTypeLink(a);
  //                         });
  // };


	function initOsamaEmbed(){
		var embedWrapper; if(embedWrapper=$$('body#osamas-show div.main div.embed')[0]){
			embedWrapper.select('a.toggle').invoke('observe','click',function(ev){
				embedWrapper.select('p.clear, div.code, a.close').each(function(el){
					if(el.visible()){ el.hide() }else{ el.show(); }
				});
				ev.stop();
			});
			embedWrapper.select('a.copy-to-clipboard').invoke('observe','click',function(ev){
				if (embedWrapper.select('.embed-code')[0]) {
					copy_text_to_clipboard(embedWrapper.select('.embed-code')[0].value);
					ev.element().innerHTML = "Copied!"
				}
				ev.stop();
			});
		}
	};
	initOsamaEmbed();
});

