// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function () {
    $.ajaxSetup({
        beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
        }
    });
    
    $.address.change(function(event) {

      var container = "twocolumns";
      var url = "";
      var aux = "";
            
      if( (event.value != "/") && ((event.value.indexOf('!') == 1) || (event.value.indexOf('|') == 1) || (event.value.indexOf('!') == 0) || (event.value.indexOf('|') == 0)) )
      {
        
        if(event.value.indexOf('!') >= 0)
        {
          aux = event.value.split("!");
        }
        else
        {
          aux = event.value.split("|");
        }
        
        url = aux[1]

        if(url.indexOf("*")!=(-1))
        {
          aux = url.split("*");
          container = aux[0]
          url = aux[1]
        }
        $('#' + container).html("<img src='/images/loader.gif' />");
        $('#' + container).load(url);
      }


    });
 


		$(".editable_list").children("li").mouseover(function()
		{
				$(this).addClass("editable_list_hover");
		    $(this).children(".actions-wrapper").show();
		});

		$(".editable_list").children("li").mouseout(function()
		{
			$(this).removeClass("editable_list_hover");
		  $(this).children(".actions-wrapper").hide();
		});





		$(".ajax_link").click(function()
		{
			if (confirm($(this).attr("rel"))) $.get($(this).attr("href"), {}, function(response){}, "script");   
			return false;
		});


       
});


jQuery.fn.submitWithAjax = function(callback)
{
    this.submit(function()
    {
        var form_id = $(this).attr("id");
        var button_name = $("form#"+form_id+" input:submit").val();
        $("form#"+form_id+" input:submit").val("Enviando......");
        $("form#"+form_id+" input:submit").attr("disabled","true");
        $.post($(this).attr("action"),$(this).serialize(),function(){
           $("form#"+form_id+" input:submit").val(button_name);
           $("form#"+form_id+" input:submit").removeAttr("disabled");
        },"script");       
        return false;
    });
}

jQuery.fn.openIn = function(container)
{
  this.click(function() {
    if((container == "") || (container == null))
    {
      $.address.value("!" + $(this).attr('href'));
    }
    else
    {
      $.address.value("!" + container + "*" + $(this).attr('href'));
    }
    return false;
  });
}

jQuery.fn.exists = function(){return $(this).length>0; }

function play_video_in_feed(e)
{
	$(e).hide();
	$(e).next(".video-player-in-feed").slideDown('fast');
}

$(document).ready(function(){
		
		$(".notification").hide();
		$(".notification").slideDown('slow');
		setTimeout(function(){ $(".notification").slideUp('slow'); }, 5000);
		
	
    $("table tr").mouseover(function(){
       $(this).addClass("hover"); 
    });
    $("table tr").mouseout(function(){
       $(this).removeClass("hover"); 
    });
    
    // $("a.button").corners();
    
    $("a[rel*=facebox]").facebox();

		$("a.submit").click(function()
		{
			submitForm(this);
		});
		
		$(".video-thumb-in-feed").click(function(){
			play_video_in_feed(this)
		});
				
    if (document.getElementById("toolbar_search_advanced_options")){$("#toolbar_search_advanced_options").corners();}
		
    // $(function(){
    //         $('a[href*=#]').click(function() {
    //           if ((location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')) && (location.hostname == this.hostname)) {
    //             var $target = $(this.hash);
    //             $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
    //             if ($target.length) {
    //               var targetOffset = $target.offset().top;
    //               $('html,body').animate({scrollTop: targetOffset}, 1000);
    //               return false;
    //             }
    //           }
    //         });
    //     });
		

});

function scrollPageTo(my_hash)
{
  var target = $("#" + my_hash);
  if (target.length) {
    var targetOffset = target.offset().top;
    $('html,body').animate({scrollTop: targetOffset}, 1000);
    return false;
  }
}

function checkAll( form_id, field_class, flag )
{
   if (flag == 0)
   {
      $("form#" + form_id + " INPUT."+field_class).attr('checked', false);
   }
   else
   {
      $("form#" + form_id + " INPUT."+field_class).attr('checked', true);
   }
}

function submitForm(e)
{
    $(e).parents("form:first").submit();    
}



$.fn.duplicate = function(count, cloneEvents) {
	var tmp = [];
	for ( var i = 0; i < count; i++ ) {
		$.merge( tmp, this.clone( cloneEvents ).get() );
	}
	return this.pushStack( tmp );
};

RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
 };


function add_fields(singular, plural, additional_wrapper_class)
{
    if(additional_wrapper_class)
		{
			var parent_wrapper = "#" + plural + "." + additional_wrapper_class;
		}
		else
		{
			var parent_wrapper = "#" + plural;
		}

    var count = $( parent_wrapper + " > ." + singular).size(); 
    var id = singular + "_element_" + count;
    
    // need to obtain the first input name of our nested elements, do some parsing to obtain the first number
    var name = $(parent_wrapper + ' .' + singular + ':first input:first').attr("name"); //contact[contact_phones_attributes][0][name]
    var aux = name.split("[" + plural + "_attributes]"); // 0:contact[contact_phones_attributes] 1:[0][name]
    var aux2 = aux[1].split("]"); // 0:[0 1:][name]
    var aux3 = aux2[0].split("["); // 0: 1:0
    var first_number = parseInt(aux3[1]); // 0 (int) (usually cero)
        
    // need to obtain the last input name of our nested elements, do some parsing to obtain the last number
    var name = $(parent_wrapper + ' .' + singular + ':last input:last').attr("name"); //contact[contact_phones_attributes][0][name]
    
    var aux = name.split("[" + plural + "_attributes]"); // 0:contact[contact_phones_attributes] 1:[0][name]
    var aux2 = aux[1].split("]"); // 0:[0 1:][name]
    var aux3 = aux2[0].split("["); // 0: 1:0
    var number = parseInt(aux3[1]); // 0 (int)
    
    // now duplicate the first object with a little cross to remove it, just in case and resetted values
    $(parent_wrapper + ' .' + singular + ':first').duplicate(1).attr("id",id).appendTo(parent_wrapper);
    $(parent_wrapper + " #" + id).hide();
    $(parent_wrapper + " #" + id).append("<span class='remove-element'><a class='remove-link' href='#' onclick=\"remove_element('" + id + "'); return false;\"><img width='16' src=\"/images/icons/24/minus.png\" /></a></span>");
    $(parent_wrapper + " #" + id).append("<div class='clear'></div>");
    
    // new index
    var new_number = number + 1
        
    // replace all instances text in fields [name]
    var string_to_look_for = "[" + plural + "_attributes][" + first_number + "]";
    var string_to_place_into = "[" + plural + "_attributes][" + new_number + "]";
    var regexpr = new RegExp(RegExp.quote(string_to_look_for), 'g');
    var html = $(parent_wrapper + " #" + id).html();    
    var new_html = html.replace(regexpr, string_to_place_into);
    $(parent_wrapper + " #" + id).html(new_html);
    
    // replace all instances text in fields [id]
    var string_to_look_for = "_" + plural + "_attributes_" + first_number + "_";
    var string_to_place_into = "_" + plural + "_attributes_" + new_number + "_";
    var regexpr = new RegExp(RegExp.quote(string_to_look_for), 'g');
    var html = $(parent_wrapper + " #" + id).html();    
    var new_html = html.replace(regexpr, string_to_place_into);
    $(parent_wrapper + " #" + id).html(new_html);
    
    // reset values and enable fields
    reset_values(parent_wrapper + " #" + id);
    enable_fields(parent_wrapper + " #" + id);
    
    // show
    $(parent_wrapper + " #" + id).slideDown('fast');
    
}

function enable_fields(where)
{
    $(where + " input").removeAttr("disabled");
    $(where + " select").removeAttr('disabled');
    $(where + " textarea").removeAttr('disabled');
}

function reset_values(where)
{
    $(where + " input").not(":button, :submit, :reset").val("");
    $(where + " input[type=checkbox]").removeAttr('checked');
    $(where + " select option").removeAttr('selected');
    $(where + " textarea").val("");
}

function remove_element(id)
{
    $("#" + id).remove();
}

function insertForm(relative_url, container, highlight)
{
	$("#"+container).hide();
	url = base_url + relative_url;
  $.get(url, "", function(response){ 
		$("#" + container).html(response);
		$("#" + container).addClass("inserted-form");
		$("#" + container).slideDown('fast');
		if(highlight == true){ $("#" + container).effect("highlight", {}, 1000); }
		scrollPageTo(container);
	});
}

function empty_container(container)
{
	$("#" + container).attr("class","");
	$("#" + container).slideUp('fast',function(){
		$("#" + container).html("");
	});
}

function process_invitation(url)
{
	$.get(url,null,null,"script");       
  return false;
}


function moreDetails(elementId) 
{
	if ($('#more-details').css("display") == "none")
	{	$('#'+elementId).html("Ver menos...");}
	else
	{	$('#'+elementId).html("Ver más...");	}
	$('#more-details').slideToggle();
}

function parameterize(source,target)
{
  var str = string_to_slug($("#"+source).val());
  $("#"+target).val(str);
}

function string_to_slug(str) {

  str = str.replace(/^\s+|\s+$/g, ''); // trim

  var from = "ÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛàáäâèéëêìíïîòóöôùúüûÑñÇç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuuaaaaeeeeiiiioooouuuunncc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from[i], "g"), to[i]);
  }

  str = str.replace(/[^a-zA-Z0-9 -]/g, '').replace(/\s+/g, '-').toLowerCase();
  
  return str;
}

function qtip(target,content,color,tail_position)
{
  if((color == "") || (color == null)){ color = "cream"; } // available colors: cream, dark, light, green, red, blue
  
	if(content.indexOf("#") == 0)
	{
		content = $(content).html();
	}
	
  if(tail_position == "topRight")     { position1 = "topRight";       position2 = "bottomLeft"; }
  if(tail_position == "topMiddle")    { position1 = "topMiddle";      position2 = "bottomMiddle"; }
  if(tail_position == "topLeft")      { position1 = "topLeft";        position2 = "bottomRight"; }
  if(tail_position == "bottomRight")  { position1 = "bottomRight";    position2 = "topLeft"; }
  if(tail_position == "bottomMiddle") { position1 = "bottomMiddle";   position2 = "topMiddle"; }
  if(tail_position == "bottomLeft")   { position1 = "bottomLeft";     position2 = "topRight"; }
  if(tail_position == "leftTop")      { position1 = "leftTop";        position2 = "rightTop"; }
  if(tail_position == "leftMiddle")   { position1 = "leftMiddle";     position2 = "rightMiddle"; }
  if(tail_position == "leftBottom")   { position1 = "leftBottom";     position2 = "rightBottom"; }
  if(tail_position == "rightTop")     { position1 = "rightTop";       position2 = "leftTop"; }
  if(tail_position == "rightMiddle")  { position1 = "rightMiddle";    position2 = "leftMiddle"; }
  if(tail_position == "rightBottom")  { position1 = "rightBottom";    position2 = "leftBottom"; }
    
  $(target).qtip({
     content: content,
     position: {corner: {tooltip: position1,target: position2}},show: 'mouseover',hide: 'mouseout',style: {border: {width: 2,radius: 10},padding: 10,textAlign: 'left',tip: true,name: color}
  });
}

function categorized_form(container_open_status)
{
	if ( container_open_status == ""){ container_open_status = "closed"; }
	if ( container_open_status == "closed" )
	{
		$("#categorized_form .form_fields").hide();
	}
  $("#categorized_form h4.categorized_form_section_title").click( function(){
    title_id = $(this).attr("id")
    content_id = $(this).next("div").attr("id")
    $(".form_fields:not(#"+content_id+")").slideUp();
    $("#categorized_form h4.categorized_form_section_title a:not(#"+title_id+" a)").removeClass("open");
    $(this).next("div").slideToggle();
    if($(this).children("a").hasClass("open") ==  true)
    {
      $(this).children("a").removeClass("open");
    }
    else
    {
      $(this).children("a").addClass("open");
    }
  });
  $("#categorized_form h4 a").addClass("closed");
  $("#categorized_form h4.categorized_form_section_title:last").addClass("last");
  $("#categorized_form .form_fields:last").addClass("last");
}

function moreActivities(element,page,et,eid)
{
	if(!et)
	{
		et = ""
	}
	
	if(!eid)
	{
		eid = ""
	}
	
  page = parseInt(page) + 1;
  $(element).hide();
  $(element).parents("div:first").append("<img src='/images/loaders/fb-blue.gif' />");
	var url = base_url + "/activities?page="+page;
	if(et != "" && eid != "")
	{
		url = url + "&et=" + et + "&ei=" + eid;
	}
  $.get(url,"",function(response){
    $(element).parents("div:first").replaceWith(response);
  });
}


function inAjax(url, where) 
{
	// $("#"+where).load(url);
  // $("#"+where).hide();
  $("#"+where).html("<img src='/images/loaders/fb-blue.gif' />");
  $.get( url,"",function(response){  
		$("#"+where).html(response); 
	});

}

function OpenInDiv(where, e) 
{
	// $("#"+where).load(url);
  // $("#"+where).hide();
	url = $(e).attr("href");
  $("#"+where).html("<img src='/images/loaders/fb-blue.gif' />");
  $.get( url,"",function(response){  
		$("#"+where).html(response); 
	});

	return false;

}



function openCommentForm(activity_id)
{
  $(".activity_"+activity_id+"_wall .new_wall_post").slideToggle();
}

function twitterCallback(twitters) {
  var statusHTML = [];
	var username = ""
	var pic = "";
	var color = "";
  for (var i=0; i<twitters.length; i++){
    username = twitters[i].user.screen_name;
    pic = twitters[i].user.profile_image_url;
    color = twitters[i].user.profile_sidebar_fill_color;
 		var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
	// alert(username);
	
  $('#twitter_update_list.'+username.toLowerCase()).html("<li style='background:#"+color+"'><img style='float:left; margin-right:5px;' src='"+pic+"' /><h1>"+username+"</h1></li>"+statusHTML.join(''));
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}


function follow(form_id) {
	 $.post($("#" + form_id).attr("action"), $("#" + form_id).serialize(), function(data){
			$("#" + form_id).parent().html(data);
	 });
}

function change_follow_level(form_id,level)
{
  $("#" + form_id + " #following_level").val(level);
  follow(form_id);
}



function fave(e) 
{
	 $.get("/element_followers/fave", {eid: $(e).attr("rel"), et: e.id , do_action: $(e).attr("class") }, function(data){
			if (data == "starred")
			{
				$(e).removeClass();
				$(e).addClass("unfave");
				$("#star_"+$(e).attr("id")+"_"+$(e).attr("rel")).attr("src", "/images/icons/16/star_on.png");
			}
			else
			{
				$(e).parents("li:first").remove();
				// $(e).removeClass();
				// $(e).addClass("fave");
				// $("#star_"+$(e).attr("id")+"_"+$(e).attr("rel")).attr("src", "/images/icons/16/star_off.png");

			}
	 });
}

function unfollow(e) 
{

	if (confirm("Deseas dejar de seguir este elemento?")) 
	{

		$.get("/element_followers/unfollow", {eid: $(e).attr("rel"), et: e.id , do_action: $(e).attr("class") }, function(data){
			if (data == "done")
			{
				$(e).parents("li:first").fadeOut();
			}
		});
	}
}



function clear_status(user_id)
{
  $.get("/users/"+user_id+"/clear_status", {rid: "efde56473"}, function(response){
    if (response == "ok") 
    {
        $("#current_status").html("");        
        $("#status_actions").html("");        
    }
  });
}


function setFlashNotice(content) {
    $(document.body).prepend("<div id='flash' class='notification notice png_bg' style='display: none;'>"+content+"</div>");
    $(".notification").slideDown(1000); 
    setTimeout(function(){ $(".notification").slideUp('slow'); }, 3000);
}


function show_options(column_id) 
{
	$("#column_options_menu_"+column_id).slideToggle();
}




function delete_feed(feed_id, token) 
{
  if (confirm("¿Deseas eliminar esta actividad del newsfeed? (no se puede deshacer)")) {
    $.post("/activities/delete_activity/","activity_id=" + feed_id + "&authenticity_token=" + token,null,"script");        
  }

}


function sendAsynchronousForm(e, no_confirmation_required, confirm_text) 
{
	// JC function, send a form from an element to destroy but it respond via ajax
	if (no_confirmation_required == true) 
	{
		confirmation = true;
	}
	else 
	{
		confirm_text = (confirm_text)? confirm_text : "Are you sure?";
	 	confirmation = confirm(confirm_text);
	}
	
	if (confirmation == true)
	{
		form_obj = $(e).parents("form:first");
		$.post($(form_obj).attr("action"), $(form_obj).serialize(), function(response){}, "script");
	}
	return false;
}






$('form a.add_record').live('click', function() {  
  var assoc   = $(this).attr('data-model');                 // Name of model
  var content = $('#' + assoc + '_fields_template').html(); // Fields template
  
  // Make a unique ID for the new record
  var regexp = new RegExp('new-id-here', 'g');
  var new_id = new Date().getTime();
  content = content.replace(regexp, new_id)
    
  // inject the content into the page
  $(this).parent().before(content);
  return false;
});

$('form a.remove_record').live('click', function() {
  $(this).closest('.new_fields').remove();
  return false;
});





function sendAsynchronousForm(e, confirm_text, waiting_text)
{
  //Validar si viene el texto para confirmar, mostrar el dialogo o no mostrarlo segun sea el caso
  if ((confirm_text) ? confirm(confirm_text) : true)
	{
	   //Devinir la variable que lleva el elemento del formunario
	   form2send = $(e).parents("form:first");
	   // Si viene el texto de espera
	   if (waiting_text)
	   {
	     //Almacenar temporalmente el texto actual
	     current_text = ($(e).val()) ? $(e).val() : $(e).html();
	    //Si es spinner o loader cargar la imagen gif animada
	    if (waiting_text == "spinner") { waiting_text ="<img src='/images/interface/spinner.gif' />cargando...";}
	    else if (waiting_text == "loader") {waiting_text ="<img src='/images/interface/loader.gif' />cargando...";}
	    //Setear el texto actual del botón o elemento por el waiting text
	    $(e).html(waiting_text);
	    $(e).val(waiting_text);
	    //Desactivar el elemento para evitar que reenvien varias veces...
	     $(e).attr("disabled","true");
	   }

	  //revisar si el form tiene id, en caso que no, asignarlo para posteriormente enviarlo en el form
	  if (!$(e).attr("id"))
		{
	    var random_form_id = Math.floor(Math.random()*11);
	    $(e).attr("id", "form_trigger_"+random_form_id);
	  }


	   //Como no trae multipart hacer el post por ajax
	   $.post($(form2send).attr("action"), $(form2send).serialize(), function(response)
	   {
	    //Si traía un waiting text en este callback debe restituir el texto original al elemento
	     if (waiting_text)
	    {
	      $(e).val(current_text);
	      $(e).html(current_text);
	     // Volver a activar el elemento
	      $(e).removeAttr("disabled");
	    }
	   }, "script");   


  }
  //Siempre retornar falso
  return false;
}




