$(document).ready(function(){
	$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled - Adds empty span tag after ul.subnav
	$("ul.topnav li a") .mouseover(function() { //When trigger is clicked...
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
		$(this).parent().hover(function() {
		}, function(){	
			$(this).parent().find("ul.subnav").slideUp('fast'); //When the mouse hovers out of the subnav, move it back up
		});
		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() { 
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

});
		
/*
 * Text Resize
 */
 $(function(){
		$('.resize').click(function(){
			var ourText = $('.page-cont');
			var currFontSize = ourText.css('fontSize');
			var finalNum = parseFloat(currFontSize, 10);
			var stringEnding = currFontSize.slice(-2);
			if(this.id == 'large') {
				finalNum *= 1.2;
			}
			else if (this.id == 'small'){
				finalNum /=1.2;
			}
			ourText.animate({fontSize: finalNum + stringEnding},600);
		});
	});
 
  $(function(){
		$('.resize').click(function(){
			var ourText = $('.bg-comment-box');
			var currFontSize = ourText.css('fontSize');
			var finalNum = parseFloat(currFontSize, 10);
			var stringEnding = currFontSize.slice(-2);
			if(this.id == 'large') {
				finalNum *= 1.2;
			}
			else if (this.id == 'small'){
				finalNum /=1.2;
			}
			ourText.animate({fontSize: finalNum + stringEnding},600);
		});
	});
 
 /*
 * Tabs
 */
 $(function () {
			var tabContainers = $('div.tabs > div');
			tabContainers.hide().filter(':first').show();
			
			$('div.tabs ul.tabNavigation a').click(function () {
				tabContainers.hide();
				tabContainers.filter(this.hash).show();
				$('div.tabs ul.tabNavigation a').removeClass('selected');
				$(this).addClass('selected');
				return false;
			}).filter(':first').click();
		});

/*
 * jQuery Cycle Plugin
 */
$(document).ready(function() {
    $('.slideshow').cycle({
		fx:    'fade', 
    	pause:  1,
		speed:  1000,
		timeout:  5000,
		next:   '#next', 
    	prev:   '#prev'
	});
});

$(function()
{
	$('.democracy').jScrollPane({showArrows:true});
});

// Democracy
// setTimeout holder for the loading dots (...)
var demLoading;

function dem_Vote(that)
{
	inpts = that.getElementsByTagName('input');
	user_added = false;
	ans = -1;
	theSubmit = false;
	for (i = 0; i < inpts.length; i++)
	{
		cur = inpts[i];
		if (cur.type == 'radio' && cur.checked)
		{
			ans = cur.value;
			if (ans == 'newAnswer')
			{
			    user_added = true;
                ans = inpts[i+1].value;
            }
        }
		if (cur.name == 'dem_poll_id')
			poll_id = cur.value;
			
        if (cur.name == 'dem_cookie_days')
            cdays = cur.value;

		if (cur.type == 'submit')
			theSubmit = cur;

	}	
	
	// they haven't checked a box or they added a blank answer
	if (ans == -1 || ans == '')
		return false;

	demLoading = setTimeout(dem_loadingDots.bind(theSubmit), 50);

	path = that.action;
	
	if (user_added)
	{
	   path += "?dem_action=add_answer";
	   path += "&dem_new_answer="+encodeURIComponent(ans);
	   
	} else
	{
	   path += "?dem_action=vote";
	   path += "&dem_poll_"+poll_id+"="+ans;
    } 
    
	path += "&dem_poll_id="+poll_id;
	path += "&dem_ajax=true";
		
	dem_ajax.open("GET", path, true);
	dem_ajax.onreadystatechange = dem_displayVotes.bind(that);
	dem_ajax.send(null);
	

	return false;
}

function dem_addUncheck()
{
	oUL = this.parentNode.parentNode;
	lis = oUL.getElementsByTagName('li');
	
	els = lis[lis.length-1].childNodes;
	
	for (i = els.length-1; i >= 0; i--)
		if (els[i].nodeName.toLowerCase() == 'a')
			els[i].style.display = '';
		else
			els[i].parentNode.removeChild(els[i]);
		
			

	Inp = oUL.getElementsByTagName('input');
    for (i = 0; i < Inp.length; i++)
    {
        Inp[i].onclick = function () { return true };
    }

    return true;
}

function dem_addAnswer(that)
{
    allBoxes = that.parentNode.parentNode.getElementsByTagName('input');
    
    for (i = 0; i < allBoxes.length; i++)
    {
        allBoxes[i].onclick = dem_addUncheck;
		allBoxes[i].checked = false;
    }

	that.style.display = 'none';
	i1 = document.createElement('input');
	i1.type = 'radio';
	i1.value = 'newAnswer';
	i1.checked = true;
	
	i2 = document.createElement('input');
	i2.className = 'addAnswerText';
	
	that.parentNode.appendChild(i1);
	that.parentNode.appendChild(i2);	

	i2.focus();
    
    return false;
}

// very simple ajaxy loading visual
// adds 3 dots to link, then erase and start over
function dem_loadingDots() {
	
	isInput = this.nodeName.toLowerCase() == 'input';
	
	str = (isInput) ? this.value : this.innerHTML;

	if (str.substring(str.length-3) == '...')
		if (isInput)
			this.value     = str.substring(0, str.length-3);
		else
			this.innerHTML = str.substring(0, str.length-3);
	else
		if (isInput)
			this.value     += '.';
		else
			this.innerHTML += '.';
	
	demLoading = setTimeout(dem_loadingDots.bind(this), 200);
}

function dem_clearDots() {
	clearTimeout(demLoading);
}


function dem_getVotes(path, that)
{
	
	that.blur();
	demLoading = setTimeout(dem_loadingDots.bind(that), 50);

	dem_ajax.open("GET", path, true);
	dem_ajax.onreadystatechange = dem_displayVotes.bind(that.parentNode);
	dem_ajax.send(null);

    return false;
}

function dem_displayVotes ()
{
	
	if (dem_ajax.readyState != 4)
		return false;

	if (dem_ajax.status != 200)
	{
		alert('Error '+dem_ajax.status);
		return false;
	}
	
	clearTimeout(demLoading);
	this.innerHTML = dem_ajax.responseText;
}

function dem_getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}


dem_ajax = new dem_getHTTPObject();


/*  from prototype.js */
Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

// Forms
$(document).ready(function() {
	$('form#commentform').submit(function() {
		$('form#commentform .error').remove();
		var hasError = false;
		$('.requiredField').each(function() {
			if(jQuery.trim($(this).val()) == '') {
				var labelText = $(this).prev('label').text().replace(' *','');
				$(this).parent().append('<span class="error">Campo obrigat&oacute;rio</span>');
				hasError = true;
				} else if($(this).hasClass('email')) {
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				if(!emailReg.test(jQuery.trim($(this).val()))) {
					var labelText = $(this).prev('label').text();
					$(this).parent().append('<span class="error">Insira um email v&aacute;lido.</span>');
					hasError = true;
				}
			}
		});
		if(hasError) {
			return false;
		}
	});
});

/*
 * TextLimit - jQuery plugin for counting and limiting characters for input and textarea fields
 * 
 * pass '-1' as speed if you don't want the char-deletion effect. (don't just put 0)
 * Example: jQuery("Textarea").textlimit('span.counter',256)
 *
 * $Version: 2009.07.25 +r2
 * Copyright (c) 2009 Yair Even-Or
 * vsync.design@gmail.com
*/
(function(jQuery) {
	jQuery.fn.textlimit=function(counter_el, thelimit, speed) {
		var charDelSpeed = speed || 15;
		var toggleCharDel = speed != -1;
		var toggleTrim = true;
		var that = this[0];
		var isCtrl = false; 
		updateCounter();
		
		function updateCounter(){
			if(typeof that == "object")
				jQuery(counter_el).text(thelimit - that.value.length+" ");
		};
		
		this.keydown (function(e){ 
			if(e.which == 17) isCtrl = true;
			var ctrl_a = (e.which == 65 && isCtrl == true) ? true : false; // detect and allow CTRL + A selects all.
			var ctrl_v = (e.which == 86 && isCtrl == true) ? true : false; // detect and allow CTRL + V paste.
			// 8 is 'backspace' and 46 is 'delete'
			if( this.value.length >= thelimit && e.which != '8' && e.which != '46' && ctrl_a == false && ctrl_v == false)
				e.preventDefault();
		})
		.keyup (function(e){
			updateCounter();
			if(e.which == 17)
				isCtrl=false;

			if( this.value.length >= thelimit && toggleTrim ){
				if(toggleCharDel){
					// first, trim the text a bit so the char trimming won't take forever
					// Also check if there are more than 10 extra chars, then trim. just in case.
					if ( (this.value.length - thelimit) > 10 )
						that.value = that.value.substr(0,thelimit+100);
					var init = setInterval
						( 
							function(){ 
								if( that.value.length <= thelimit ){
									init = clearInterval(init); updateCounter() 
								}
								else{
									// deleting extra chars (one by one)
									that.value = that.value.substring(0,that.value.length-1); jQuery(counter_el).text('Reduzindo... '+(thelimit - that.value.length));
								}
							} ,charDelSpeed 
						);
				}
				else this.value = that.value.substr(0,thelimit);
			}
		});
		
	};
})(jQuery);

$(function()
{
	jQuery("textarea").textlimit('span.counter',600);
});

/* Print */
$(document).ready(function() {
	$('.tools').prepend('<div class="tool-imprimir"><a href="#imprimir">Imprimir</a></li>');
	$('.tools div.tool-imprimir a').click(function() {
		window.print();
		return false;
	});
});
