
// Adds the .js mime to URLs, so that Rails fires the correct respond_to response.
var mimeifyUrl = function(url){
  if (/\.js/.test(url)){
    return url;
  } else if (/\?/.test(url)) {
    return url.replace('?', '.js?');
  } else {
    return url + '.js';
  }
};

$.fn.railsLoad = function(location){
  var self = this;
  $.ajax({
    url: mimeifyUrl(location),
    beforeSend: self.spin(true),
    success: function(response, status){
      $(self).html(response);
      $('#loading').remove();
    }
  });
};

//place this in views where needed to show loading image
//= image_tag('ajax-loader.gif', :id => 'spinner', :class => 'spinner', :style => 'display:none;')
$.ajaxSetup ({
   //beforeSend: show_spinner,
   //success: hide_spinner,
   complete: remove_spinner,
   error: ajax_processing_error_notification
 });
 
 $.fn.spin = function(append) {
   if (append)
      $(this).append('<span id="loading"><img src="/images/spinner.gif"/></span>');
   else
      $(this).after('<span id="loading"><img src="/images/spinner.gif"/></span>');
 };


 function show_spinner(){  
  $('.spinner').show();  
 }; 


 function remove_spinner(){
  $('#loading').remove();  
 };

 function ajax_processing_error_notification(){  
  $('.spinner').hide();  
  alert('There was an error processing your request.');  
 };

//To insert text or other elements into textarea at cursor point
//usage: inyectarTexto('wmd-input', 'text')
function inyectarTexto(elemento,valor){
 var elemento_dom = document.getElementById(elemento);
 if (document.selection) {
  elemento_dom.focus();
  sel=document.selection.createRange();
  sel.text=valor;
  return;
 } if (elemento_dom.selectionStart||elemento_dom.selectionStart=="0") {
  var t_start=elemento_dom.selectionStart;
  var t_end=elemento_dom.selectionEnd;
  var val_start=elemento_dom.value.substring(0,t_start);
  var val_end=elemento_dom.value.substring(t_end,elemento_dom.value.length);
  elemento_dom.value=val_start+valor+val_end;
 } else {
  elemento_dom.value+=valor;
 }
}

function limitChars(textid, limit, infodiv)
{
	var text = $('#'+textid).val();	
	var textlength = text.length;
	if(textlength > limit)
	{
          $('span.' + infodiv).html('You cannot write more then '+limit+' characters!');
          $('#'+textid).val(text.substr(0,limit));
          return false;
	}
	else
	{
          $('span.' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
          return true;
	}
};

$.fn.emptySelect = function() { 
    return this.each(function(){ 
      if (this.tagName=='SELECT') this.options.length = 0; 
    }); 
};

$.fn.loadSelect = function(optionsDataArray) {
//alert(optionsDataArray);  
return this.emptySelect().each(function(){ 
    if (this.tagName=='SELECT') { 
      var selectElement = this; 
      $.each(optionsDataArray,function(index,optionData){ 
        var option = new Option(optionData.caption, optionData.value); 
        if ($.browser.msie) { 
          selectElement.add(option); 
        } 
        else { 
          selectElement.add(option,null); 
        } 
      }); 
    } 
  }); 
};

$.fn.setReadOnly = function(readonly) {
  return this.css('opacity', readonly ? 0.5 : 1.0).find(':input') 
             .attr('disabled', readonly);
             //.val(readonly ? '' : val())
};

//retrieve value of url parameter (example.com?someparam=name&otherparam=8&id=6)
//$.urlParam('someparam') --> 'name'
$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}


//short for document ready
$(function(){
  
  //quote of the day on master.haml
  $("ul#quote-highlight").hide();
  $("ul#quote-highlight").fadeIn(3000);
  
  $('textarea').autogrow();
  
  $('a.tooltip-prompt').show();
  $('a.tooltip-prompt').tooltip({
    bodyHandler: function() {
      return $('div#tooltip-help').html();
    },
    showURL: false,
    extraClass: "standard"
  });
  

	//load search input boxes with default hint value		
	$('#search_q').each(function() {
		var default_value = this.value;
		//$(this).css('color', '#666'); //put this in css file
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
				//$(this).css('color', '#333');
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
				//$(this).css('color', '#666');
			}
		});		
	});


	$('.toggle-wrapper').show();
//toggle closed forums division in forums index	
	$('#closed-forums').hide();
	//if ($('a#toggle-closed-forums').length > 0) {
	  //alert('hello');
	//}
	$('a#toggle-closed-forums').click(function() {
	  $('#closed-forums').slideToggle(400);
	  $(this).text($(this).text() == 'Show Closed Forums' ? 'Hide Closed Forums' : 'Show Closed Forums'); 
	  return false;
	});

	//toggle forum description in topics index
	$('#forum-description').hide();
	
	$('a#toggle-forum-description').click(function() {
	  $('#forum-description').slideToggle(400);
	  //this works too but needed to swap background image as well - too nasty using a ternary for both
	  //$(this).text($(this).text() == "Show Forum Description" ? "Hide Forum Description" : "Show Forum Description");
	  if ($(this).text() == "Forum Description"){
	    $(this).text("Hide Forum Description");
	    $(this).css('background-image', 'url("/images/u-go-to.gif")');
	  }  
	  else {
	    $(this).text("Forum Description");
	    $(this).css('background-image', 'url("/images/d-go-to.gif")');	  
	  }
     
	  return false;
	});


});