// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}

var myrules = {
  '.remove': function(e){
    el = Event.findElement(e);
    target = el.href.replace(/.*#/, '.')
    el.up(target).hide();
    if(hidden_input = el.previous("input[type=hidden]")) hidden_input.value = '1';
		else el.up(target).innerHTML='';
  },
  '.add_nested_item': function(e){
    el = Event.findElement(e);
    template = eval(el.href.replace(/.*#/, ''))
    $(el.rel).insert({     
      bottom: replace_ids(template)
    });
  },
  '.add_nested_item_lvl2': function(e){
    el = Event.findElement(e);
    elements = el.rel.match(/(\w+)/g)
    parent = '.'+elements[0]
    child = '.'+elements[1]
    
    child_container = el.up(parent).down(child)
    parent_object_id = el.up(parent).down('input').name.match(/.*\[(\d+)\]/)[1]
    
    template = eval(el.href.replace(/.*#/, ''))

    template = template.replace(/(attributes[_\]\[]+)\d+/g, "$1"+parent_object_id)
    
    child_container.insert({     
      bottom: replace_ids(template)
     });
  }
};

function toggle_images() {
	$$('.image').each(function(item) {item.toggle();});
	$$('.auto_align').each(function(item) {Element.toggleClassName(item, 'left');});
	$$('.filename').each(function(item) {item.toggle();});
}

var UnobtrusiveAjaxLinker = Class.create({ 

  initialize: function() {
		this.options = Object.extend({
      container: 'pagination_container',
      selector: 'div.pagination a',
			indicator: 'loading-indicator'
    }, arguments[0] || {});
    this.initLinks();
  },  

  initLinks: function() {
		$(this.options.container).select(this.options.selector).invoke('observe', 'click', this.linkHandler.bind(this));
  },  

  linkHandler: function(event) {
    event.stop();
    new Ajax.Request(event.element().getAttribute('href'),{
      method: 'get',
			onLoading: $(this.options.indicator).show()
    });
  }

});

var UnobtrusiveSortBinderGeneric = Class.create({ 

  initialize: function(options, params) {
		this.options = Object.extend({
      container: 'data_table',
			indicator: 'loading'
    }, options || {});
    this.params = params;
		this.initSortLinks();
		// this.makeUnsort(); // Not working for some reason
  },  

  initSortLinks: function() {
		$$('#'+this.options.container+' th')
			.invoke('observe', 'click', this.sortLinkHandler.bindAsEventListener(this))
			.invoke('observe','mouseover',this.thOver.bindAsEventListener(this))
			.invoke('observe','mouseout',this.thOut.bindAsEventListener(this));
  },

  makeColUnsortable: function(col) {
		// alert(col.id);
		Event.stopObserving(col, 'click', this.sortLinkHandler.bindAsEventListener(this));
		Event.stopObserving(col, 'mouseover', this.thOver.bindAsEventListener(this));
		Event.stopObserving(col, 'mouseout', this.thOut.bindAsEventListener(this));
	},

	makeUnsort: function() {
		$$('#'+this.options.container+' th.nosort').each(function(col) {
			this.makeColUnsortable(col);
		}.bind(this));
	},

  sortLinkHandler: function(e) {
		e.stop();
		elem = Event.element(e);
		if (!elem.hasClassName('nosort')) { // hack, because makeColsUnsortable() is not working for some reason
	    col_name = elem.id;
			sort_order = elem.hasClassName('asc') ? 'desc' : 'asc';
			new Ajax.Request(this.options.url,{
	      method: 'get',
				parameters: Object.extend(this.params, {'sort_order':sort_order,'sort_col':col_name,'indicator':this.options.indicator}),
				onLoading: $(this.options.indicator).show()
	    });
		}
  },
	
	thOver: function(e) {
		elem = Event.element(e);
		if (!elem.hasClassName('nosort')) { // hack, because makeColsUnsortable() is not working for some reason
			elem.addClassName('on');
		}
	},

	thOut : function(e){
		elem = Event.element(e);
		if (!elem.hasClassName('nosort')) { // hack, because makeColsUnsortable() is not working for some reason
			elem.removeClassName('on');
		}
	}

});

var AjaxifyPublishLinks = Class.create({ 

  initialize: function() {
    this.initLinks();
  },  

  initLinks: function() {
		$$('.publish-btn').invoke('observe', 'click', this.linkHandler.bind(this));
  },  

  linkHandler: function(event) {
    event.stop();
    elem = event.element();
		new Ajax.Request(elem.getAttribute('href'),{
      method: 'get',
			onLoading: $(elem).innerHTML = 'Publishing, please wait... <img src="/images/ajax-loader.gif" alt="loading" />'
    });
  }

});

