/* Help Section javascript methods */

var Help = {
	
	/* Search form stuff and init */
	
	initSearchForm: function() {
		input = $("search-keywords");
		if(!input) return false;

		input.addClassName('passive');
		
		// Focus handler
		Event.observe(input, "focus", 
			function(event) {
				if(!input.searchValue) {
					input.originalValue = input.value;
					input.value = "";
					input.removeClassName('passive');
				}
			} 
		);
		Event.observe(input, "blur", 
			function(event) {
				if(input.value == "") {
					input.value = (input.originalValue) ? input.originalValue : "Rev # or keyword";
					input.addClassName('passive');
				} else {
					input.searchValue = input.value;
				}
			} 
		);
	},
	
	/* Images alt attribute transformer */
	initImgs: function(){
		$$('.content img[alt]').each(function(img, index){
			var imgBlock = new Element('span', {className: 'img-block ' + img.className});
			img.insert({'after':imgBlock});
			imgBlock.insert({'top':img});
			imgBlock.insert({'bottom':new Element('span', {className: 'img-alt', style: img.className ? ('width:' + (img.width - 1) + 'px') : ''}).update('Fig.' + (index + 1) + ' &mdash; ' + img.alt)});
		});
	},
	
	/* Handling attachments on "edit article" page */
	observeAttachment: function(imgBlock){
	  var containerName = imgBlock.up('div').id;
    var attachmentID = imgBlock.id;
	  var link = imgBlock.down('a.delete');
	  link.observe('click', function(event){
		  Event.stop(event);
  		Modalbox.show('<p>Are you sure you want to permanently delete this asset?</p><input type=\'button\' value=\'Yes, remove it\' onclick=\'Modalbox.hide({afterHide: function(){ Help.removeAttachment("'+attachmentID+'", "'+containerName+'"); }})\' /> or <a href=\'#\' onclick=\'Modalbox.hide();return false;\'>Cancel</a>', {title: 'Confirm attachment remove', width: 400});
  	});
	},
	
	initAttachmentsList: function(containerName){
	  var container = $(containerName);
	  container.select('.img-block').each(function(block){
	    Help.observeAttachment(block);
	  });
	},
	
	removeAttachment: function(attachment, containerName){
	  var container = $(containerName);
	  var removeLink = $(attachment).down('a.delete')
	  var url = removeLink.href;
	  var authenticity_token = removeLink.id;
	  new Ajax.Request(url, {asynchronous:true, evalScripts:true, method:'delete',
	                         parameters:'authenticity_token=' + encodeURIComponent(authenticity_token)});
		new Effect.Shrink($(attachment), {duration: .5});
		if(container.select('.img-block').length == 0){
		  container.hide();
		}
	},
	
	/* Action link handlers and init */
	
	initTopicsList: function(list){
		var list = $(list);
		list.select("h2 .actions a.delete").each(function(link){
			var topicID = link.up('li').id;
			link.observe('click', function(event){
				Event.stop(event);
				Modalbox.show('<p>Are you sure to completely remove this topic? All related articles will be removed too!</p><input type=\'button\' value=\'Yes, remove it\' onclick=\'Modalbox.hide({afterHide: function(){ Help.removeTopic("' + topicID + '"); }})\' /> or <a href=\'#\' onclick=\'Modalbox.hide();return false;\'>Cancel</a>', {title: 'Confirm topic remove', width: 400});
			});
		});
		
		list.select("h2").each(function(topic){
			topic.observe('mouseover', function(e){
				
				if(!this.up('ol').hasClassName('active'))
					Help.showActions(this);
			});
			
			topic.observe('mouseout', function(e){
				if(!this.down('.inplaceeditor-form') && !this.up('ol').hasClassName('active'))
					this._timeout = window.setTimeout(function(){
						Help.hideActions(this);
					}.bind(this), 500);					
			});
			
			var editLink = topic.down('a.edit');
			var url = editLink.href;
			var form_authenticity_token = $('token').value;
			new Ajax.InPlaceEditor(topic.down(), url, {
				ajaxOptions: { method: 'put' },
				callback: function(form, value)
          { return 'authenticity_token='+form_authenticity_token+'&topic[name]='+encodeURIComponent(value) },
        onComplete: function(transport, element) 
          { 
            var new_topic = transport.responseText.evalJSON();
            element.attributes['raw'].value = new_topic.name;
            element.innerHTML = new_topic.rendered_name;            
          },
				okText: 'Save changes',
				cancelText: 'Cancel',
				externalControl: editLink.id,
				externalControlOnly: true,
				highlightcolor: '#EFEFEF',
				highlightendcolor: '#FFF',
				onLeaveEditMode: function(){ Help.hideActions(topic) }
			});
		});
	},
	
	showActions: function(el){
		new Effect.Morph(el, {
			style:'background:#EFEFEF', 
			duration: .25, 
			beforeStart: function(fx){ new Effect.Appear(fx.element.down('.actions'), {duration: .25}) }
		});
		if(el._timeout) Help._clearTimeout(el._timeout);
	},
	
	hideActions: function(el){
		new Effect.Morph(el, {
			style:'background:#FFF', 
			duration: .25, 
			beforeStart: function(fx){ new Effect.Fade(fx.element.down('.actions'), {duration: .25}) }
		});
	},
	
	removeTopic: function(topic){
	  var url = $(topic).down('a').href;
	  var authenticity_token = $('token').value;
	  new Ajax.Request(url, {asynchronous:true, evalScripts:true, method:'delete',
	                         parameters:'authenticity_token=' + encodeURIComponent(authenticity_token)});
		new Effect.Shrink($(topic), {duration: .5});
	},
	
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	},
	
	/* Topics List reorder functionality */
	
	isReordering: false, //Current state of reordering
	
	toggleReorder: function(id, ctrl, input){
		if(!this.isReordering)
			Help.initReorder(id, ctrl, arguments[3]);
		else
			Help.finishReorder(id, ctrl, input, arguments[3]);
	},
	initReorder: function(id, ctrl){
		var list = $(id);
		var ctrl = $(ctrl);
		var help = $(arguments[2]);
		
		this.isReordering = true;
		list.addClassName('active');
		ctrl.addClassName('reorder-active').update('End reordering categories').blur();
		this.fx = new Effect.SlideDown(help, {duration: .35});
		Help.toggleNestedLists(list);
		
		Sortable.create(list);
	},
	finishReorder: function(id, ctrl, input){
		var list = $(id);
		var ctrl = $(ctrl);
		var input = $(input);
		var help = $(arguments[3]);
		
		this.isReordering = false;
		list.removeClassName('active');
		ctrl.removeClassName('reorder-active').update('Reorder categories').blur();
		if(this.fx.state != "Finished")
			this.fx.cancel();
		new Effect.SlideUp(help, {duration: .35});
		Help.toggleNestedLists(list);
		
		var serialized_topics = Sortable.serialize(list);
		var url = ctrl.href;
	  var authenticity_token = $('token').value;
	  var params = 'authenticity_token=' + encodeURIComponent(authenticity_token) + '&' + serialized_topics;
	  new Ajax.Request(url, {asynchronous:true, evalScripts:true, 
	                         method:'put',
	                         parameters:params});
	},
	toggleNestedLists: function(parent){
		$(parent).select('ul').invoke('toggle');
	}
};

/* DomReady extension */
Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);

    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
  },
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
		
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) {
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
        
        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});

/* InPlaceEditor extension 
   If available, use element's "raw" attribute's value for edit text field.
*/
if(Ajax.InPlaceEditor){
  Object.extend(Ajax.InPlaceEditor.prototype, {
    getText: function() {
      var raw_value = this.element.attributes['raw'];
      return raw_value == undefined ? this.element.innerHTML : raw_value.value;
    }
  });
}

Event.onDOMReady(function(){
	Help.initSearchForm();
	//Help.initImgs();
});