jQuery.noConflict();
/**
 * @fileoverview Global js functions used on most pages.
*/
/* Create NetR namespace */
if(typeof NetR == "undefined"){ var NetR = {}; }

/**
 * @requires jQuery
 * @class Module with tabbed content
 * @constructor
 * @param {String or Object} id_or_node The module for which to add tabs
 */
NetR.TabbedModule = function(id_or_node,options){
	this.options = options || {};
	this.el      = typeof id_or_node == "string" ? jQuery("#" + id_or_node) : jQuery(id_or_node);
	this.el.addClass("tabbed-module");
	this._createTabs();
};
NetR.TabbedModule.prototype = {
	/**
	 * Activates a given tab
	 * @param {Object} tab A tab from the this.tabs array
	 */
	activateTab: function(tab){
		jQuery(this.tabs).each(function(){
			jQuery(this.link).removeClass("sel");
			jQuery(this.content).removeClass("active");
		});
		this.tabs_ul.attr("class", tab.content.id + "-active module-tabs clearfix");
		jQuery(tab.link).append(this.active_tab_suffix);
		jQuery(tab.link).addClass("sel");
		jQuery(tab.content).addClass("active");
	},

	/**
	 * Creates the neccessary markup for all tabs
	 * @private
	 */
	_createTabs: function(){
		var self     = this;
		this.tabs    = [];
		this.tabs_ul = jQuery("<ul class=\"module-tabs clearfix\"></ul>").insertAfter(jQuery("h2",this.el));
		if(this.options.before_tabs){ jQuery("<p></p>").text(this.options.before_tabs).attr("class", "structural").insertBefore(this.tabs_ul); }
		jQuery(".module-content", this.el).each(function(){
			var tab     = {};
			tab.content = this;
			tab.label   = jQuery(jQuery(".tab-label", this)[0]).text();
			tab.link    = jQuery("<a href=\"#" + tab.content.id + "\"><span></span>" + tab.label +"</a>").addClass("tab-" + tab.content.id);
			if(jQuery(tab.content).is(".active")){ tab.link.addClass("sel"); }
			tab.link.appendTo(self.tabs_ul).wrap("<li></li>");
			tab.link.click(function(e){
				e.preventDefault();
				self.activateTab(tab);
			});
			self.tabs.push(tab);
		});
	}
};

/**
 * Adds an onclick handler that brings up an alert for all links that do not lead anywhere
 * in this prototype. Remove before deploying.
 */
var NetRLinkInfo = {
	init:function() {
		var links = document.getElementsByTagName('A');
		var re = /inactive/;
		for (var i = 0; i < links.length; i++) {
			if (re.test(links[i].getAttribute('href',2))) { /* The second parameter is needed for IE to return the actual value of the href attribute */
				links[i].onclick = NetRLinkInfo.linkinfo;
			}
		}
	},
	linkinfo:function() {
		alert('This link is not active in the prototype.');
		return false;
	}
};


/**
* ready function
*/

jQuery(document).ready(function($){

/**
* Finds all .modules with two or more .module-contents in it and creates .module-tabs for them
*/
$('.module').each(function() {
	if($(this).children('.module-wrapper').children('.module-content').length > 1) {
		new NetR.TabbedModule($(this));
	}
});

if (document.getElementById('description') != null && document.getElementById('remaining') != null) {
	counterDescription();
}


//comment form submit
/*submitform=false
 $("#commentform").submit(function() {
	$(".error").hide();
	if(submitform)
		return true;
      url = '/json/islogin';
	  result=true;
	  $.post(url,{ },function (data){
					
					if($("textarea").val() == ""){

							$(".submit-area").before("<div class='error'>Pon tu comentario<div>");
							result=false;
					}

					if(data == 0)
					{											
						if($("input:text").val() == "")
						{	
							$(".submit-area").before("<div class='error'>Pon tu url openid <div>");
							result=false;
						}

					}
								

					if(result){
						submitform=true;
					    $("#commentform").submit();
					}
				}
				
			);
    return false;

    });*/



// preview box
$("#ud_text").keyup(function() {
    $comment = $(this).val();
    $comment = $comment.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />').replace(/(&lt;\/?)script/g,"$1noscript");
    $('#ud_preview').html( $comment );
});

// remove the hint in the email subscription box
$("#feedburnermail").val("Pon tu email para suscribirte").one('click',function(){
   $(this).val("");
});

// add target to google search box to stay xhtml compliant
$("#search").attr("target","_top");

$('#private-remove-expert').bind('click', function ()
                                          {
                                              userid = $(this).attr('name');
                                              removeExpert(userid);
                                              $('#private-following').fadeOut('slow');
                                          });


$("a.abuse-ico-ireport, a.post-vote-up, a.post-vote-down, a.gallery-vote-up, a.gallery-vote-down").bind("click", function actions(){

	var action = $(this).attr("class");

	if (action == 'abuse-ico-ireport' ) {
		var action = 'abuse';
	    var tparent = $(this).parents('li.comment');
		var arg = tparent.attr("id");
	} else {
		var tparent = $(this).parents('div.blog-rate');
		var arg = tparent.attr("id");
	}

	url = '/json/'+action+'/'+arg;
	
	$.post(url, { },
         function (data)
         {
			if (data == 1)
            {
			     alert("Necesitas estar registrado para votar");
			}
            else if (data == 2)
            {   
                 if (action == 'abuse' ) {
                   alert("ya denunciaste este comentario"); 
                 } else {
                   alert("Ya has votado");
                 }				 
			} 
			else if (data == 4)
            {    
                 if (action == 'abuse' ) {
                   alert("usted no puede denunciar su comentario"); 
                 } else {
                   alert("No puedes votar tu propio comentario");
                 }					 
			}
			else if (data == 5)
            {
				 alert("Ha superado el m&aacute;ximo negativo por d&iacute;a");
			}
			else if (data == 6)
            {
				 alert("No tienes suficiente karma para hacer un voto negativo");
			}
			else if (data == 0)
                {
				if (action == 'abuse' ) {
				   alert("Gracias por reportar");
				} else if(action == 'gallery-vote-up' || action == 'gallery-vote-down')
				{
						changeClass(tparent, 'gallery-vote-up', 'gallery-vote-up-disabled');
						changeClass(tparent, 'gallery-vote-down', 'gallery-vote-down-disabled');

						var votes = parseInt($("div.blog-votes",tparent.parent()).children().html());
						if (votes) {
						// hide/unhide counter
						if (action == 'gallery-vote-up') {
							votes = votes + 1;
						} else if (action == 'gallery-vote-down') {
							votes = votes - 1;
						}
					} else if (action == 'gallery-vote-up') {
						tparent.prepend('<div class="blog-votes"><strong>1</strong> voto</div>');
					}
				} else {
                    $('a.post-vote-up', tparent).fadeOut('slow',
                        function ()
                        {
    	                    $('a.post-vote-up', tparent).unbind("click");
    	                    $('a.post-vote-up', tparent).removeClass('a.post-vote-up').addClass('post-vote-up-disabled').show();
    	                    $('a.post-vote-up-disabled', tparent).bind("click", function ()
    	                                                         {
    	                                                             alert('Ya has votado');
    	                                                             return false; });
                            $('a.post-vote-up-disabled', tparent).fadeIn('normal');
                    });
                    
                    $('a.post-vote-down', tparent).fadeOut('slow',
                        function ()
                        {
    	                    $('a.post-vote-down', tparent).unbind("click");
    	                    $('a.post-vote-down', tparent).removeClass('a.post-vote-down').addClass('post-vote-down-disabled').show();
    	                    $('a.post-vote-down-disabled', tparent).bind("click", function ()
    	                                                         {
    	                                                             alert('Ya has votado');
    	                                                             return false; });
                            $('a.post-vote-down-disabled', tparent).fadeIn('normal');
                    });

                    numVotes = parseInt($('#num'+arg).html());

				    if(action == 'post-vote-down') {
				        if (numVotes != 0) {
					        content = (numVotes - 1);
					    }
				    } else {
						content = (numVotes + 1);
					}

					$('#num'+arg).html(content);
					$('#num'+arg).highlightFade({color:'happing',
					                             speed:2000,
					                             iterator:'sinusoidal'});
				}
			}
		});

	return false;
	});

	$(".deletecomment").click(function() {
		answer = confirm ("Se suprime el comentario \n 'OK' para borrar, 'Cancel' para detener el proceso.");
		if (answer) {
			var action = $(this).attr("class");
			var arg = $(this).attr("id");
			url = '/json/deletecomment/'+arg;

			$.post(url, { },
				 function (data) {
					if (data == 1)
					{
						alert('por favor ingrese en wp-admin');
					} else{

						$('#c'+arg).hide();	

						commentCount = parseInt($("a.comments").html());

						if(commentCount != 1 ) {
								content = (commentCount -1) +' comentarios';
						} else {
							content = (commentCount -1) +' comentario';
						}

						$("a.comments").html(content);
					}
				 });
		}							
	});

});

jQuery.fn.highlightFade = function(settings) {
	var o = (settings && settings.constructor == String) ? {start: settings} : settings || {};
	var d = jQuery.highlightFade.defaults;
	var i = o['interval'] || d['interval'];
	var a = o['attr'] || d['attr'];
	var ts = {
		'linear': function(s,e,t,c) { return parseInt(s+(c/t)*(e-s)); },
		'sinusoidal': function(s,e,t,c) { return parseInt(s+Math.sin(((c/t)*90)*(Math.PI/180))*(e-s)); },
		'exponential': function(s,e,t,c) { return parseInt(s+(Math.pow(c/t,2))*(e-s)); }
	};
	var t = (o['iterator'] && o['iterator'].constructor == Function) ? o['iterator'] : ts[o['iterator']] || ts[d['iterator']] || ts['linear'];
	if (d['iterator'] && d['iterator'].constructor == Function) t = d['iterator'];
	return this.each(function() {
		if (!this.highlighting) this.highlighting = {};
		var e = (this.highlighting[a]) ? this.highlighting[a].end : jQuery.highlightFade.getBaseValue(this,a) || [255,255,255];
		var c = jQuery.highlightFade.getRGB(o['start'] || o['colour'] || o['color'] || d['start'] || [255,255,128]);
		var s = jQuery.speed(o['speed'] || d['speed']);
		var r = o['final'] || (this.highlighting[a] && this.highlighting[a].orig) ? this.highlighting[a].orig : jQuery.curCSS(this,a);
		if (o['end'] || d['end']) r = jQuery.highlightFade.asRGBString(e = jQuery.highlightFade.getRGB(o['end'] || d['end']));
		if (typeof o['final'] != 'undefined') r = o['final'];
		if (this.highlighting[a] && this.highlighting[a].timer) window.clearInterval(this.highlighting[a].timer);
		this.highlighting[a] = { steps: ((s.duration) / i), interval: i, currentStep: 0, start: c, end: e, orig: r, attr: a };
		jQuery.highlightFade(this,a,o['complete'],t);
	});
};

jQuery.highlightFade = function(e,a,o,t) {
	e.highlighting[a].timer = window.setInterval(function() { 
		var newR = t(e.highlighting[a].start[0],e.highlighting[a].end[0],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newG = t(e.highlighting[a].start[1],e.highlighting[a].end[1],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newB = t(e.highlighting[a].start[2],e.highlighting[a].end[2],e.highlighting[a].steps,e.highlighting[a].currentStep);
		jQuery(e).css(a,jQuery.highlightFade.asRGBString([newR,newG,newB]));
		if (e.highlighting[a].currentStep++ >= e.highlighting[a].steps) {
			jQuery(e).css(a,e.highlighting[a].orig || '');
			window.clearInterval(e.highlighting[a].timer);
			e.highlighting[a] = null;
			if (o && o.constructor == Function) o.call(e);
		}
	},e.highlighting[a].interval);
};

jQuery.highlightFade.defaults = {
	start: [255,255,128],
	interval: 50,
	speed: 400,
	attr: 'backgroundColor'
};

jQuery.highlightFade.getRGB = function(c,d) {
	var result;
	if (c && c.constructor == Array && c.length == 3) return c;
	if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))
		return [parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];
	else if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))
		return [parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];
	else if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))
		return [parseInt("0x" + result[1]),parseInt("0x" + result[2]),parseInt("0x" + result[3])];
	else if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))
		return [parseInt("0x"+ result[1] + result[1]),parseInt("0x" + result[2] + result[2]),parseInt("0x" + result[3] + result[3])];
	else
		return jQuery.highlightFade.checkColorName(c) || d || null;
};

jQuery.highlightFade.asRGBString = function(a) {
	return "rgb(" + a.join(",") + ")";
};

jQuery.highlightFade.getBaseValue = function(e,a,b) {
	var s, t;
	b = b || false;
	t = a = a || jQuery.highlightFade.defaults['attr'];
	do {
		s = jQuery(e).css(t || 'backgroundColor');
		if ((s  != '' && s != 'transparent') || (e.tagName.toLowerCase() == "body") || (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end)) break; 
		t = false;
	} while (e = e.parentNode);
	if (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end) s = e.highlighting[a].end;
	if (s == undefined || s == '' || s == 'transparent') s = [255,255,255];
	return jQuery.highlightFade.getRGB(s);
};

jQuery.highlightFade.checkColorName = function(c) {
    return [214,12,27];
};

function postLogin(){ document.location.reload();}
