(function($){

  // Store the initial location.hash so that the event isn't triggered when
  // the page is first loaded.
  var last_hash = location.hash,

    // An id with which the polling loop can be canceled.
    timeout_id;

  // Special event definition.
  $.event.special.hashchange = {
    setup: function() {
      // If the event is supported natively, return false so that jQuery
      // will bind to the event using DOM methods instead of using the
      //  polling loop.
      if ( 'onhashchange' in window ) { return false; }

      // Start the polling loop if it's not already running.
      start();
    },
    teardown: function() {
      // If the event is supported natively, return false so that jQuery
      // will bind to the event using DOM methods instead of using the
      // polling loop.
      if ( 'onhashchange' in window ) { return false; }

      // Stop the polling loop. Since this event is only evern bound to
      // the `window` object, multiple-element tracking is unnecessary.
      stop();
    },
    add: function( handleObj ) {
      // Save a reference to the bound event handler.
      var old_handler = handleObj.handler;

      // This function will now be called when the event is triggered,
      // instead of the bound event handler.
      handleObj.handler = function(event) {

        // Augment the event object with the location.hash at the time
        // the event was triggered.
        event.fragment = location.hash.replace( /^#/, '' );

        // Call the originally-bound event handler, complete with modified
        // event object! The result from this call doesn't need to be
        // returned, because there is no default action to prevent, and 
        // nothing to propagate to.
        old_handler.apply( this, arguments );
      };
    }
  };

  // Start (or continue) the polling loop.
  function start() {
    // Stop the polling loop if it has already started.
    stop();

    // Get the current location.hash. If is has changed since the last loop
    // iteration, store that value and trigger the hashchange event.
    var hash = location.hash;
    if ( hash !== last_hash ) {
      $(window).trigger( 'hashchange' );
      last_hash = hash;
    }

    // Poll, setting timeout_id so the polling loop can be canceled.
    timeout_id = setTimeout( start, 100 );
  };

  // Stop the polling loop.
  function stop() {
    clearTimeout( timeout_id );
  };

})(jQuery);

//-------------- pt-br

/* Brazilian initialisation for the jQuery UI date picker plugin. */
/* Written by Leonildo Costa Silva (leocsilva@gmail.com). */
jQuery(function($){
	$.datepicker.regional['pt-BR'] = {
		closeText: 'Fechar',
		prevText: 'Anterior',
		nextText: 'Pr&oacute;ximo',
		currentText: 'Hoje',
		monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
		'Jul','Ago','Set','Out','Nov','Dez'],
		dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
		dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		weekHeader: 'W',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});

//-------------- End Jquery plugins --------------------------------------

Cnec = {};
Cnec.bind = function(fn, obj){return function(){fn.apply(obj, arguments)};}
Cnec.bindfn = function(fn, obj){return function(){ return fn.apply(obj, arguments)};}
Cnec.bindComponents = function()
{
	var elements = arguments[0] == null ? document.getElementsByTagName("*") : arguments[0].getElementsByTagName("*");
	var i;
	for(i = 0; i<elements.length; i++)
	{
		try{
			if((!elements[i].attributes) || (!elements[i].attributes.cnec)) continue;
			var element = elements[i];	
			eval('var args =' + elements[i].attributes.cnec.nodeValue.replace(/&apos;/g,'\'')+';');
			if(!args) continue;
			var comp;
			for(comp = 0; comp < args.length; comp++)
				new args[comp].code(elements[i], args[comp]);
		}
		catch(ex){alert(ex);}
	}
}
Cnec.pageRect = function()
{
	return {'x':document.documentElement.offsetWidth, 'y': Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight - document.documentElement.scrollTop)};
}
Cnec.viewPort = function()
{
	var x =  self.pageXOffset ? self.pageXOffset : document.documentElement.scrollLeft;	
	var width = self.innerWidth ? self.innerWidth : document.documentElement.clientWidth;
	var y = self.pageYOffset ? self.pageYOffset : document.documentElement.scrollTop;
	var height = self.innerHeight ? self.innerHeight : document.documentElement.clientHeight;
	return {'x':x, 'y':y, 'width':width, 'height':height};
}
Cnec.getRect = function(e)
{
	var width = e.offsetWidth;
	var height = e.offsetHeight;
	
	var left = 0;
	var top = 0;
	
	if (e.offsetParent)
	{
		left = e.offsetLeft
		top = e.offsetTop
		
		while (e = e.offsetParent) 
		{
			left += e.offsetLeft;
			top += e.offsetTop;
		}
	}
	
	return {"x": left, "y": top, 'width':width, 'height':height}
}

Cnec.posAt = function(obj) 
{
  var pos = arguments[1] ? arguments[1] : 'cm';
	var rect = arguments[2] ? this.getRect(arguments[2]) : Cnec.viewPort();
	var off = arguments[3] ? arguments[3] : {x:0,y:0};
	var orect = Cnec.getRect(obj);
	
	obj.style.position = 'absolute';
	var x = rect.x;
	var y = rect.y;
  //calc x
  if(pos.match(/c/)){x += Math.round((rect.width - orect.width) /2);}
  else if(pos.match(/r/)) {x += rect.width-2;}
  //calc y
  if(pos.match(/m/)){y += Math.round((rect.height - orect.height) /2);}
  else if(pos.match(/b/)) {y += rect.height;} 
  else if(pos.match(/t/)) {y -= rect.height;} 
	obj.style.top = y+off.y + "px";
	obj.style.left = x+off.x + "px";
}


Cnec.darken = function ()
{
	var div = document.createElement('div');
	var d = Cnec.pageRect();
	var d2 = Cnec.viewPort();
	//alert(d.width);
	div.style.top = '0';
	div.style.left = '0';
	div.style.width = d.x + "px";
	div.style.height = Math.max(d.y, d2.height) + "px";
	div.style.backgroundColor = arguments[0] ? arguments[0] : "black";
	div.style.position = 'absolute';
	$(div).css('opacity', .8);
	document.body.appendChild(div);
	return div;
}

Cnec.Animate = function(args)
{
	this.duration = args.duration;
	this.start = new Date().getTime();
	this.callback = args.callback;
	this.ref = Cnec.bind(this.go, this);
	setTimeout(this.ref,33);
	this.backwards = false;
	
}
Cnec.Animate.prototype = {
'go':function()
{
	this.current = new Date().getTime();
	var cur = this.current - this.start;
	this.callback(cur/this.duration);
	if(cur > this.duration) {return;}
	setTimeout(this.ref,33); 
}
}

function CnecGallery(element, args)
{
	this.imgClickRef = Cnec.bindfn(this.showImage, this);
	this.keyDownRef = Cnec.bindfn(this.keyDown, this);
	this.clickRef = Cnec.bindfn(this.click, this);
	this.images = $(element).find('.thumbImage img');
	for(var i = 0; i<this.images.length; i++)
	{
		$(this.images[i]).bind('click', {index:i}, this.imgClickRef);
	}
	this.current = -1;
	this.window = false;
	$(document).bind('keydown', this.keyDownRef);
}


CnecGallery.prototype.showImage = function(e)
{
	this.current = e.data.index;
	
	
	var src = e.currentTarget.src.replace(/-thumb.jpg/, '.jpg');
	var title = e.currentTarget.parentNode.parentNode.title;
	if(this.window)
	{
		$(this.window).find(".the-image")[0].src = src;
		$(this.window).find("p")[0].innerHTML = title;
		return;
	}
	this.bg = Cnec.darken();
	
	this.window = $("<div id='ImageViewer'><a title='próxima (seta direita)' class='next'></a><a title='anterior (seta esquerda)' class='previous'></a><img class='the-image' src='" + src + "' onload='Cnec.posAt(this.parentNode)'  /><a class='close' title='fechar (pressione Esc)'>X</a><p>" + title + "</p></div>").appendTo(document.body)[0];
	this.bg.style.zIndex = 4;
	this.window.style.zIndex = 5;
	this.createPhotoScroller();
	
	$(this.window).click(this.clickRef); 
	$(this.bg).dblclick(Cnec.bindfn(this.close, this));
	Cnec.posAt(this.window);
	this.open = true;
	this.setSelected();
	if(e && e.preventDefault) e.preventDefault();
}

CnecGallery.prototype.createPhotoScroller = function()
{
	var html = "<div class='photoScroll'><a class='next'></a><a class='previous'></a><div class='items'>";
	for(var i = 0; i<this.images.length; i++)
	{
		html +=  "<img class='img imgIndex" + i+ "' src='" + this.images[i].src + "' />"; 
	}
	
	var scroller = $(html + "</div></div>").appendTo(this.window);
	this.hscroller = new HScroller(scroller[0], {inc:589, 'speed':500 });
	
}

CnecGallery.prototype.keyDown = function(e)
{
	if(!this.window) return;
	if(e.keyCode == 27) return this.close();
	if(e.keyCode == 37)	return this.prev();
	if(e.keyCode == 39)	return this.next();
}

CnecGallery.prototype.click = function(e)
{
	if(e.target.className.match(/imgIndex(\d+)/))
	{
		var index = parseInt(RegExp.$1);
		this.current = index - 1;
		this.next();
		return;
	}
	
	if((e.target.parentNode == this.window) && $(e.target).hasClass('next')) return this.next();
	if((e.target.parentNode == this.window) && $(e.target).hasClass('previous')) return this.prev();
	if($(e.target).hasClass('close')) return this.close();
}

CnecGallery.prototype.close = function()
{
	$(this.bg).remove();
	$(this.window).remove();
	this.window = null;
	this.open = false;
}

CnecGallery.prototype.prev = function()
{
	var index = this.current - 1;
	if(index<0) return;
	this.showImage({'currentTarget' : this.images[index], 'data':{'index':index}});
	this.setSelected();
}

CnecGallery.prototype.next = function()
{
	index = this.current + 1;
	if(index>this.images.length-1) return;
	this.showImage({'currentTarget' : this.images[index], 'data':{'index':index}});
	this.setSelected();
}

CnecGallery.prototype.setSelected = function()
{
	var selected = $(this.window).find('.selected');
	selected.removeClass('selected');
	selected = $(this.window).find('.imgIndex' + this.current);
	selected.addClass('selected');
	var items = selected[0].parentNode;
	var inc = items.scrollLeft - selected[0].offsetLeft;
	var start = items.scrollLeft;
	var ex = this.hscroller;
	if(inc<0)
	{
		inc *= -1;
		new Cnec.Animate({'duration':500, 'callback': function(e){items.scrollLeft = start + Math.min(inc,inc*e) ; ex.adjust();} });
		return;
	}
	new Cnec.Animate({'duration':500, 'callback': function(e){items.scrollLeft = start - Math.min(inc,inc*e) ; ex.adjust();} });
}

//cookies

Cnec.Cookies = {};
Cnec.Cookies.read = function()
{
	var s = document.cookie;
	for(var i in Cnec.Cookies)
	{
		if(i.match(/^(read|write|remove)$/)) continue;
		Cnec.Cookies[i] = null;
	}
	s.replace(/(\w+?)=(.*?)(; |$)/g, function(a, b, c)
	{
		if(!c) return;
		Cnec.Cookies[b] = unescape(c); 
		
	});
}

Cnec.Cookies.write  = function(cookie, value)
{
	Cnec.Cookies[cookie] = value;
	var expires = "";
	if(arguments[2])
	{
		var now = new Date();
		now.setSeconds(arguments[2]);
		expires = ";expires=" + now.toGMTString();
	}
	document.cookie = cookie + "=" + escape(value) + expires + ";path=/";
}
Cnec.Cookies.remove  = function(cookie)
{
	var date = new Date();
	date.setTime(date.getTime()-50);
	document.cookie= cookie+"=; expires="+ date.toGMTString();
	Cnec.Cookies.read();
}
Cnec.Cookies.read();

//hscroller

HScroller = function (element, args)
{
	this.element = element; 
	this.inc = args.inc;
	this.speed = args.speed ? args.speed : 1000;
	var controls = $(element).find('.items,.previous,.next');
	this[controls[0].className] = controls[0];
	this[controls[1].className] = controls[1];
	this[controls[2].className] = controls[2];
	$(element).click(Cnec.bind(this.click, this));
	this.adjust();
}

HScroller.prototype.click = function(e)
{
	
	var x = e.target;
	var items = this.items;
	var start = items.scrollLeft;
	var inc = this.inc;
	var ex = this;
	if(x.className=='next') new Cnec.Animate({'duration':this.speed, 'callback': function(e){items.scrollLeft = start + Math.min(inc,inc*e) ; ex.adjust();} });
	if(x.className=='previous') new Cnec.Animate({'duration':this.speed, 'callback': function(e){items.scrollLeft = start - Math.min(inc,inc*e) ; ex.adjust();}});
	return false;
	
}
HScroller.prototype.adjust = function()
{
	if(this.items.scrollLeft < 1) $(this.previous).addClass('disabled');
	else $(this.previous).removeClass('disabled');;
	if((this.items.scrollWidth - this.items.scrollLeft) <= this.inc+6) $(this.next).addClass('disabled');
	else $(this.next).removeClass('disabled');
}

Scroller = function (element, args)
{
	this.element = element; 
	this.inc = args.inc;
	this.speed = args.speed ? args.speed : 1000;
	var controls = $(element).find('.items,.previous,.next');
	this[controls[0].className] = controls[0];
	this[controls[1].className] = controls[1];
	this[controls[2].className] = controls[2];
	$(element).click(Cnec.bind(this.click, this));
	this.adjust();
}

Scroller.prototype.click = function(e)
{
	
	var x = e.target;
	var items = this.items;
	var start = items.scrollTop;
	var inc = this.inc;
	var ex = this;
	if(x.className=='next') return new Cnec.Animate({'duration':this.speed, 'callback': function(e){items.scrollTop = start + Math.min(inc,inc*e) ; ex.adjust();} });
	if(x.className=='previous') return new Cnec.Animate({'duration':this.speed, 'callback': function(e){items.scrollTop = start - Math.min(inc,inc*e) ; ex.adjust();}});
	
}
Scroller.prototype.adjust = function()
{
	if(this.items.scrollTop<1) $(this.previous).addClass('disabled');
	else $(this.previous).removeClass('disabled');
	if((this.items.scrollHeight - this.items.scrollTop) <= this.inc+6) $(this.next).addClass('disabled');
	else  $(this.next).removeClass('disabled');
	
}


Date.prototype.year = function(){return parseInt(this.getYear())+ (navigator.userAgent.match(/gecko|Opera/i) ? 1900 : 0);}
function Calendar(element, args)
{
	var d = new Date();
	if(args.date)
	{
		args.date.match(/(\d+)-(\d+)-(\d+)/)
		d = new Date(RegExp.$1, parseInt(RegExp.$2.replace(/^0/,''))-1 , 1);
	}
	var months = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"];
	var month = months[parseInt(d.getMonth())];
	
	d.setDate(1);
	var skip = d.getDay();
	s = ""; 
	if(args.next && args.next.length>0) s += "<a class='next' href='" +  args.next +"'></a>";
	if(args.previous && args.previous.length>0) s+= "<a class='previous' href='" +  args.previous +"'></a>";
	s = "<table><caption>" + s + month + " - " + d.year() +"<caption><tr><th>d</th><th>s</th><th>t</th><th>q</th><th>q</th><th>s</th><th>s</th></tr><tr>";
	
	for(i=0;i<skip;i++)s+="<td class='skip'></td>";
	
	d.setMonth(d.getMonth()+1);
	d.setDate(-1);
	max = d.getDate()+1;
	count = skip;
	for(i=1;i<=max;i++)
	{
		var comment = args.comments && args.comments[i] ? ' title="' + args.comments[i] + '"': ""; 
		var classes = args.classes && args.classes[i] ? ' class="' + args.classes[i] + '"' : "";
		var href = args.hrefs && args.hrefs[i] ? ' onclick="location = \'' + args.hrefs[i] + '\'">' : ">";
		
		s += "<td" + comment + classes + href + i +"</td>";
		if((++count) == 7){count = 0; s+="</tr><tr>";}
	}
	skip = 7 - count;
	for(i=0;i<skip;i++) s+="<td class='skip'></td>";
	element.innerHTML = s + "</tr></table>";
}

Cnec.Hover  = function(element, args)
{
	if(!args.hoverClass) args.hoverClass = 'hover'; 
	if(args.buttonMode)	$(element).click(function(){
		if(args.target == 'blank')
		{
			window.open($(this).find("a")[0].href);
			return false;
		}
		else	
			location = $(this).find("a")[0].href;}
	);
	$(element).hover(function (e) { $(this).addClass(args.hoverClass);}, function (e) { $(this).removeClass(args.hoverClass);});
}

Cnec.Focus  = function(element, args)
{
	var focusClass  = !args.focusClass ? 'focus' : args.focusClass;
	var focusElement = !args.focusElement ? element : args.focusElement;
	$(element).focus(function (e) { $(focusElement).addClass(focusClass);});
	$(element).blur( function (e) { $(focusElement).removeClass(focusClass);});
}

Cnec.FullHeight  = function(element, args)
{
	var h1 = $("html").height();
	var h2 = Cnec.viewPort().height; 
	if(h1 < h2)
	{
		var addSize = h2 - h1;
		var height = $(element).height();
		$(element).height(height + addSize);
	}
}

Cnec.PlaceHolder = function(element, args) 
{
	//if(Zadig.ie && (element.type=='password')){element.value='senha'; return;}
	this.element = element;
	this.hint = args.hint;
	this.isPassword = element.type == 'password'? true : false;
	$(element).bind('focus', Cnec.bind(this.focus, this));
	$(element).bind('blur', Cnec.bind(this.blur, this));
	this.blur(null);
}
Cnec.PlaceHolder.prototype.focus = function (e)
{
	if(this.element.value == this.hint)
	{
		$(this.element).removeClass("placeHolderMode");
		this.element.value = '';
		if(this.isPassword){this.element.type = 'password'; this.element.focus()}
	}
}
Cnec.PlaceHolder.prototype.blur = function (e){
	if(this.element.value == '') 
	{
		this.element.value = this.hint;
		$(this.element).addClass("placeHolderMode");
		if(navigator.userAgent.indexOf("MSIE")== -1)this.element.type='text';
	}
}


Cnec.VotingBox = function (element, args)
{
	this.element = element;
	this.endpoint = args.endpoint;
	this.votesCount = args.votesCount;
	this.contentId = args.contentId;
	this.votesTotal = args.votesTotal;
	this.votesAverage = this.votesCount == 0 ? 0 : Math.round(this.votesTotal / this.votesCount);
	this.stars = $(element).find(".star");
	this.stars.mouseenter(Cnec.bind(this.over, this));
	this.stars.click(Cnec.bind(this.click, this));
	$(element).mouseleave(Cnec.bind(this.out, this));
}

Cnec.VotingBox.prototype.addVotes = function (value)
{
	this.votesCount = this.votesCount + 1;
	this.votesTotal = this.votesTotal + value + 1;
	this.votesAverage = Math.round(this.votesTotal / this.votesCount);
	this.setVotes(this.votesAverage - 1);
	$(this.element).find(".totalVotes").html("(" + this.votesCount + ")");
	
	$.ajax({
		  url: this.endpoint,
		  dataType: 'json',
		  data: {jsoncall: '{"service":"VotingService", "method":"vote", "parameters":[' + this.contentId + ' , ' + (value + 1) +  ']}'},
		  success: Cnec.bind(this.onVote, this)
		});
}

Cnec.VotingBox.prototype.onVote = function (e)
{
	new Cnec.FancyHint(this.element, e);
}

Cnec.VotingBox.prototype.over = function (e)
{
	for(var i=0; i<5; i++)
	{
		if(this.stars[i] == e.target)
		{
			this.setVotes(i+1);
			return;
		}
	}
}

Cnec.VotingBox.prototype.click = function (e)
{
	for(var i=0; i<5; i++)
	{
		if(this.stars[i] == e.target)
		{
			this.addVotes(i++);
			return;
		}
	}
}

Cnec.VotingBox.prototype.out = function (e)
{
	this.setVotes(this.votesAverage);
}

Cnec.VotingBox.prototype.setVotes = function(value)
{
	for(var i=0; i<5; i++)
	{
		$(this.stars[i]).addClass("on");
		if(value <= i) $(this.stars[i]).removeClass("on");
	}
}

Cnec.FancyHint = function (element, msg)
{
	this.element = $("<span class='fancy-hint'>" + msg + "<span class='fancy-hint-bottom'></span></span>");
	$("body").append(this.element);
	this.element.position({
		  "my": "center",
		  "at": "top",
		  "of": $(element)
		});
	this.element.css("opacity", 0);
	this.element.animate({opacity:1, top: '-=15'}, "slow", Cnec.bindfn(this.startHide, this) );		
}

Cnec.FancyHint.prototype.startHide = function ()
{
	setTimeout(Cnec.bindfn(this.hide, this), 2000);
}
Cnec.FancyHint.prototype.hide = function ()
{
	this.element.animate({opacity:0, top: '-=15'}, "slow", Cnec.bindfn(this.destroy, this));
}
Cnec.FancyHint.prototype.destroy = function ()
{
	this.element.remove();
}


// ----------------------------------------------------------
Cnec.toJson = function (obj)
{
	var json = '';
	var comma = '';
	if($.isArray(obj))
	{
		json += '[';
		for(var i=0; i < obj.length; i++)
		{
			json += comma + Cnec.toJson(obj[i]);
			comma = ', ';
		}
		json += ']';
		return json;
	}
	if(typeof obj == 'object')
	{
		json += '{';
		for(var i in obj)
		{
			json += comma + '"' + i + '" : ' + Cnec.toJson(obj[i]);
			comma = ', ';
		}
		json += '}';
		return json;
	}
	if(typeof obj == 'string')
	{
    obj = obj.replace(/&/g, '%26').replace(/\r?\n/g,'\\'+'r'+'\\'+'n');
		return '"' + obj.replace(/"/g, '\\"')  +'"';
	}
	if(typeof obj == 'number')
	{
		return obj;
	}
	return 'null';
}

// RemoteObject
Cnec.RemoteObject = function(endpoint, serviceName)
{
	this.methods = [];
	this.endpoint = endpoint;
	this.serviceName = serviceName;
}

Cnec.RemoteObject.prototype.addMethod = function(name, callback) 
{
	this.methods[name] = {'callback':callback};
	this[name] = this.createMethod(this.callMethod, this, name);
}

Cnec.RemoteObject.prototype.callMethod = function(name) 
{
	var args = new Array();
	for(var i=0; i<arguments.length; i++) args.push(arguments[i]);
	args.shift();
	var request = {"service":this.serviceName, "method": name , "parameters": args};
	request = Cnec.toJson(request);
	$.ajax(
		{
		  "url": this.endpoint,
		  "dataType": 'json',
		  "type": 'POST',
		  "data": {jsoncall: request},
		  "contentType": "application/x-www-form-urlencoded; charset=UTF-8",
		  success: this.methods[name].callback
		}
	);
}

Cnec.RemoteObject.prototype.createMethod = function(fn, obj, name){
	return function(){
	var args = new Array();
	for(var i=0; i<arguments.length; i++) args.push(arguments[i]);
	args.unshift(name);
	fn.apply(obj, args)};
}

// services
Cnec.Enquete = function(element, args)
{
	this.id = args.id;
	this.element = $(element);
	this.endpoint = args.endpoint;
	this.showLink = args.showLink ? true : false;
	this.service = new Cnec.RemoteObject(args.endpoint, "EnqueteService");
	this.service.addMethod("vote", Cnec.bindfn(this.onVote, this));
	this.element.bind("submit", Cnec.bindfn(this.click, this));
}

Cnec.Enquete.prototype.click = function(e)
{
	e.preventDefault();
	var option = $(this.element[0]).find("[name='option']:checked");
	if(option.length == 0) return; 
	this.service.vote(this.id, parseInt(option[0].value));
}

Cnec.Enquete.prototype.onVote = function(e)
{
	var enquetelist = Cnec.Cookies['enquete'];
	enquetelist = (enquetelist == null) ? this.id : enquetelist + "," + this.id;
	Cnec.Cookies.write("enquete", enquetelist, 365 * 24 * 60 * 60);
	
	this.element.find(".submit").remove();
	this.element.find("ul input").remove();
	this.element.find("li").append("<br /><span class='bar'></span><span class='percent'>0%</span>");
	if(this.showLink)
		this.element.append("<p><a href='" +  this.endpoint.replace("json", "enquetes") + "'>Veja mais enquetes</a></p>");
	else
		this.element.append("<p>Obrigado por votar</p>");
	
	var percentage = e;
	var percentage2 = percentage.slice();
	this.element.find(".percent").each(function(){$(this).html(percentage.shift() + "%");});
	this.element.find(".bar").css("backgroundPosition", "-197px");
	this.element.find(".bar").each(function(){$(this).animate({backgroundPosition: Math.round(-195 + (percentage2.shift()/100*165)) + 'px'}, "slow");});
}


//SendToFriendForm
SendToFriendForm = function(element, args)
{
	this.form = $("#Send-To-Friend-Form");
	this.form.draggable({handle: 'h4', containment: 'body'});
	$(element).click(Cnec.bindfn(this.showForm, this));
	this.form.find(".close").click(Cnec.bindfn(this.close, this));
	this.service = new Cnec.RemoteObject(args.endpoint, "SendToFriendService");
	this.service.addMethod("sendEmail", Cnec.bindfn(this.onSend, this));
	this.form.bind("submit", Cnec.bindfn(this.submit, this));
	this.validate = Cnec.bindfn(Cnec.validateForm, this.form[0]);
}

SendToFriendForm.prototype.showForm = function()
{
	document.body.appendChild(this.form[0]);
	this.form.find("input[type='submit']")[0].disabled = false;
	this.form.find("input[type='text'], textarea").attr("value", "");
	
	this.form.css('display', 'block');
	Cnec.posAt(this.form[0]);
	this.form.css('display', 'none');
	this.form.fadeIn();

}

SendToFriendForm.prototype.close = function()
{
	this.form.fadeOut();
}

SendToFriendForm.prototype.submit = function(e)
{
	e.preventDefault();
	if(!this.validate(e)) return;
	this.form.find("input[type='submit']")[0].disabled = true;
	var pageInfo = {};
	pageInfo.url = location.href;
	pageInfo.title = document.title;
	pageInfo.description = $("head meta[name='description']")[0].content;
	
	var emailInfo = {};
	emailInfo.senderName = this.form[0].senderName.value;
	emailInfo.senderEmail = this.form[0].senderEmail.value;
	emailInfo.friendName = this.form[0].friendName.value;
	emailInfo.friendEmail = this.form[0].friendEmail.value;
	emailInfo.comments = this.form[0].comments.value;
	
	this.service.sendEmail(pageInfo, emailInfo);
}

SendToFriendForm.prototype.onSend = function(e)
{
	new Cnec.FancyHint(this.form.find(".submit input")[0], "Mensagem enviada!");
	setTimeout(Cnec.bindfn(this.close , this), 3000);
}

//CommentForm
CommentForm = function(element, args)
{
	this.form = element;
	this.contentId = args.contentId;
	this.service = new Cnec.RemoteObject(args.endpoint, "CommentService");
	this.service.addMethod("comment", Cnec.bindfn(this.onSend, this));
	$(this.form).bind("submit", Cnec.bindfn(this.submit, this));
	this.validate = Cnec.bindfn(Cnec.validateForm, this.form);
}

CommentForm.prototype.submit = function(e)
{
	e.preventDefault();
	if(!this.validate(e)) return;

	var postInfo = {};
	postInfo.email = this.form.email.value;
	postInfo.name = this.form.name.value;
	postInfo.comment = this.form.comment.value;
	
	this.service.comment(this.contentId, postInfo);
}

CommentForm.prototype.onSend = function(e)
{
	this.ip = e;
	new Cnec.FancyHint($(this.form).find(".commentSubmit input")[0], "Obrigado pelo seu comentário!<br /> ");
	setTimeout(Cnec.bindfn(this.close , this), 3000);
}

CommentForm.prototype.close = function(e)
{
	$("html, body").animate({scrollTop: 0}, "fast");
	this.form.email.value = "";
	this.form.name.value = "";
	this.form.comment.value = "";
	$(".comment-ok-message").remove();
	$(this.form.parentNode.parentNode).prepend('<div class="comment-ok-message">Seu comentário foi enviado com sucesso e será publicado após avaliação de nossa equipe.<br /> Por motivos de segurança o endereço de seu computador foi anotado <b style="color:red">' + this.ip + '</b>.</div>');
}

//--------------------------------------------------------------------------
// Cnec Fiedl Constrain
Cnec.validateForm = function(e)
{
	for(var i=0; i< this.elements.length; i++)
	{
		if(this.elements[i].name == null) continue;
		if(this.elements[i].name == '') continue;
		if(this.elements[i].type == 'file') continue;
		if(this.elements[i].constrain != null)
			if(!this.elements[i].constrain.check())
			{
				var hint = $(this).find('.hint');
				if(hint.length > 0)
				{
					hint.html(this.elements[i].constrain.hint);
					var pos = Cnec.getRect(hint[0]).y;
					$("html, body").animate({scrollTop: pos}, "normal");
				}
				return false;
			} 
	}
 	return true;
}


Cnec.FieldConstrain = function (element, args)
{
	 this.element = element;
	 element.constrain = this;
	 this.pattern = args.pattern;
	 this.hint = args.hint;
	 $(this.element).bind("blur", Cnec.bind(this.focusOut, this));	
}

Cnec.FieldConstrain.prototype.focusOut = function(e)
{
  if(this.check()){$(this.element).removeClass("invalid-state");  $(this.element.form).find(".hint").html(''); return;}
  $(this.element.form).find(".hint").html(this.hint);
  $(this.element).addClass("invalid-state");
  new Cnec.FancyHint(this.element, this.hint);
}

Cnec.FieldConstrain.prototype.check = function()
{
	if(this.element.value.match(this.pattern))return true;
	return false;
}

//cpf
Cnec.MatchCPF = function(element, args)
{
	 this.element = element;
	 element.constrain = this;
	 this.pattern = args.pattern;
	 this.hint = args.hint;
	 $(this.element).bind("blur", Cnec.bind(this.onFocusOut, this));	
}

Cnec.MatchCPF.prototype.check = function()
{
	var cpf = this.element.value.replace(/[^\d]/g,'');
	var i2 = 0;
	var t1 = 0;
	var t2 = 0

	for(var i=10; i>=2; i--)
	{
		t1 += parseInt(cpf.charAt(i2))*i;
		t2 += parseInt(cpf.charAt(i2++))*(i+1);
	}

	var r = t1 % 11;
	var t = (t1 - r) / 11; 
	var d1 = r < 2 ? 0 : 11 - r;
	
	t2 += 2 * d1;
	var r2 = t2 % 11;
	var d2 = r2 < 2 ? 0 : 11 - r2;
	
	return cpf.match( new RegExp('.{9}'+d1+''+d2+'$') );
}

Cnec.MatchCPF.prototype.onFocusOut = function(e)
{
	if(this.check()){$(this.element).removeClass("invalid-state");  $(this.element.form).find(".hint").html(''); return;}
	$(this.element.form).find(".hint").html(this.hint);
	$(this.element).addClass("invalid-state");
	new Cnec.FancyHint(this.element, this.hint);
}


// Previous

Cnec.PreviousFieldConstrain = function (element, args)
{
	 this.element = element;
	 element.constrain = this;
	 this.previousField  = args.previousField;
	 this.hint = args.hint;
	 $(this.element).bind("blur", Cnec.bind(this.focusOut, this));	
}

Cnec.PreviousFieldConstrain.prototype.focusOut = function(e)
{
  if(this.check()){$(this.element).removeClass("invalid-state");  $(this.element.form).find(".hint").html(''); return;}
  $(this.element.form).find(".hint").html(this.hint);
  $(this.element).addClass("invalid-state");
  new Cnec.FancyHint(this.element, this.hint);
}

Cnec.PreviousFieldConstrain.prototype.check = function()
{
	if(this.element.value == this.element.form[this.previousField].value )return true;
	return false;
}

$(document).ready(function(){
	Cnec.bindComponents();
	$(".validatedForm").submit(Cnec.validateForm);
	initFontSizeControl();
});


//--------------Password Strengh Checker
Cnec.PasswordStrengthChecker = function(element, args)
{
	element = $(element);
	var fieldToWatch = $(args.fieldToWatch);
	var label = element.find(".label");
	
	function isSequence(term)
	{
		for(var i = 1; i < term.length; i++)
		{
			var c1 = term.charCodeAt(i-1);
			var c2 = term.charCodeAt(i);
			if(Math.abs(c2-c1) > 1) return false;
		}
		return true;
	}
	
	function matchWeakTerms(terms, str)
	{
		if(terms == null) return false;
		for(var i = 0; i < terms.length; i++)
		{
			if(str.toLowerCase() == terms[i].toLowerCase()) return true;
		}
		return false;
	}
	var lastValue = "";
	fieldToWatch.keyup(function()
	{
		var value = fieldToWatch.val();
		if(lastValue == value) return;
		lastValue = value;
		
		element.removeClass('empty');
		element.removeClass('too-weak');
		element.removeClass('weak');
		element.removeClass('good');
		element.removeClass('strong');
		
		value = value.replace(/ /g, "");
		if(value.match(/^$/))
		{
			element.addClass('empty');
			label.html("");
			return;
		}
		
		if(isSequence(value) || matchWeakTerms(args.weakTerms, value))
		{
			element.addClass('too-weak');
			label.html("Muito fraca!");
			return;
		}
		if(value.length < 5 || value.match(/^(\d+|[a-z]+)$/i))
		{
			if(value.length>10){
				element.addClass('good');
				label.html("Boa!");
				return;
			}
			element.addClass('weak');
			label.html("Fraca!");
			return;
		}
		if(value.match(/\d/) && value.match(/[a-z]/i) && value.match(/[^\w\d]/))
		{
			element.addClass('strong');
			label.html("Forte!");
			return;
		}
		
		element.addClass('good');
		label.html("Boa!");
		return;
		
	});		
	
}

//masks
Cnec.FieldMask = function(element, args)
{
  this.element = element;
  this.active = true;
  this.max = 0;
  this.numChars = new Array();
  this.maskChars = new Array();
  this.get='';
  this.replace=''; 
  this.count = 1;
  args.mask.replace(/(#+|[^#]+)/g, Cnec.bindfn(this.parse, this));
  $(element).bind('keyup',  Cnec.bindfn(this.onkup, this));
  $(element).bind('blur',  Cnec.bindfn(this.onBlur, this));
  this.get = new RegExp(this.get+".*?",'g');
  
}

Cnec.FieldMask.prototype.parse = function()
{
	var e = arguments[0];
	if(!e.match('#+'))
	{
		if( this.max==0) this.numChars.push(0);
		this.maskChars.push(e);
		this.max += e.length;
		this.replace+=e;
	}
	else
	{
		this.numChars.push(e.length);
		this.max += e.length;
		this.replace+='$'+ (this.count++);
		this.get+="(\\d{"+e.length+"})";
	}
}

Cnec.FieldMask.prototype.onkup = function(e)
{
	if(!this.active) return;
	if (e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 37 || e.keyCode == 39) return;
	var s = this.element.value;
	if(s.length >= this.max) {
		s = s.substring(0, this.max);
		s = s.replace(/[^\d]+/g, ""); 
		this.element.value = s.replace(this.get, this.replace);
		return;
	}
	
	s = s.replace(/[^\d]+/g, "");
	var nc = 0;
	
	for(var i = 0; i < this.maskChars.length; i++)
	{
		nc += this.numChars[i];
		if(s.length < nc) break;
		var tail =  s.substring(nc);
		var chars = this.maskChars[i] ? this.maskChars[i] : "";
		s = s.substring(0, nc) + chars + (tail == null ? "" : tail);
		nc+= this.maskChars[i].length;
	}
	this.element.value = s;
}

Cnec.FieldMask.prototype.onBlur = function(e)
{
	if(!this.active) return;
	var s = this.element.value;
	if(s.length >= this.max) {
		s = s.substring(0, this.max);
		s = s.replace(/[^\d]+/g, ""); 
		this.element.value = s.replace(this.get, this.replace);
		return;
	}
	
	s = s.replace(/[^\d]+/g, "");
	var nc = 0;
	
	for(var i = 0; i < this.maskChars.length; i++)
	{
		nc += this.numChars[i];
		if(s.length < nc) break;
		var tail =  s.substring(nc);
		var chars = this.maskChars[i] ? this.maskChars[i] : "";
		s = s.substring(0, nc) + chars + (tail == null ? "" : tail);
		nc+= this.maskChars[i].length;
	}
	this.element.value = s;
}


DivSlider = function(element, args)
{
	this.element  = element;
	this.delay = args.delay ? args.delay : 5000;
	this.tagElement = args.tagElement ? args.tagElement : 'DIV';
	this.children = new Array();
	for(var child = this.element.firstChild; child != null; child = child.nextSibling)
	{
		if(child.nodeName == this.tagElement.toUpperCase()) this.children.push(child);
	}
	this.current = 0;
	setInterval(Cnec.bind(this.change, this), this.delay);
}

DivSlider.prototype.change = function()
{
	var oldCurrent = this.current;
	this.current = (oldCurrent + 1) == this.children.length ? 0 : oldCurrent + 1;
	$(this.children[oldCurrent]).fadeOut("normal");
	$(this.children[this.current]).fadeIn("normal");
}

Cnec.RealtimeSearch = function (element, args)
{
	this.service  = new Cnec.RemoteObject(args.endpoint, "RealtimeSearch");
	this.service.addMethod("find", Cnec.bindfn(this.onResult, this));
	this.element = element;
	this.oldValue = "";
	this.skipBlur = false;
	$(this.element.form).bind("submit", Cnec.bindfn(this.submit, this));
	$(this.element).bind("keyup", Cnec.bindfn(this.change, this));
	$(document).bind("click",  Cnec.bindfn(this.hide, this));
}

Cnec.RealtimeSearch.prototype.submit = function (e)
{
	if(this.resultBox == null) return true;
	var selected = this.resultBox.find(".selected"); 
	if(selected.length == 0) return true;
	selected.click();
	return false;
}

Cnec.RealtimeSearch.prototype.hide = function (e)
{
	if(this.resultBox == null) return;
	if(e.target == this.element) return;
	var me= this;
	me.resultBox.fadeOut("normal", function(){me.resultBox.remove();});
	
}

Cnec.RealtimeSearch.prototype.change = function (e)
{
	this.select(e);
	if(this.element.value.length < 3) 
	{
		if(this.resultBox != null)
		{
			var me = this;
			this.resultBox.fadeOut("normal", function(){me.resultBox.remove();});
		}
		this.oldValue = this.element.value;
		return;
	}
	if(this.oldValue != this.element.value)
		this.service.find(this.element.value);
	this.oldValue = this.element.value
}

Cnec.RealtimeSearch.prototype.select = function (e)
{
	if (this.resultBox == null) return;
	if(e.keyCode == 13) return;
	var items = this.resultBox.find("li");
	
	var selectedIndex = -1;
	for(var i = 0; i < items.length; i++)
	{
		if($(items[i]).hasClass("selected"))
		{
			selectedIndex = i;
			break;
		}
	}
	if(selectedIndex >= 0)
		$(items[selectedIndex]).removeClass("selected");
	switch(e.keyCode)
	{
		//up
		case 38:
			if(selectedIndex <= 0)
			{
				$(items[items.length - 1]).addClass("selected")
				this.highlight();
				return;
			}
			$(items[selectedIndex - 1]).addClass("selected")
			this.highlight();
			break;
		//down
		case 40:
			if(selectedIndex+1 == items.length)
			{
				$(items[0]).addClass("selected")
				this.highlight();
				return;
			}
			$(items[selectedIndex + 1]).addClass("selected")
			this.highlight();
			break;
	}
}

Cnec.RealtimeSearch.prototype.highlight = function()
{
	var item = this.resultBox.find(".selected");
	var items = this.resultBox.find("ul");
	var scrollTo = items.scrollTop() + item.position().top;
	items.stop(true);
	items.animate({scrollTop:  scrollTo - 200}, "normal");
}


Cnec.RealtimeSearch.prototype.onResult = function (result)
{
	if(this.resultBox == null)
	{
		this.resultBox = $("<div id='SugestionBox'></div>");
	}
	if(result == "")
	{
		this.resultBox.remove();
		return;
	}
	this.resultBox[0].innerHTML = result;
	$("body").append(this.resultBox);
	this.resultBox.fadeIn("normal");
	this.resultBox.position({
		  "my": "right top",
		  "at": "right bottom",
		  "of": $(this.element.form),
		  "offset": "0 4px"
		});
}


Cnec.HiddenMenu = function (element, args)
{
	this.markSelected = args.markSelected;
	this.my = args.my ? args.my : "left top"; 
	this.at = args.at ? args.at : "left bottom";
	this.offset = args.offset ? args.offset : "0 0";
	this.menu = $(args.menu);
	this.element = $(element);
	this.element[0].hiddenMenu = this;
	this.clickRequired = false;
	this.clickRef = Cnec.bindfn(this.onClick, this);
	this.element.hover(Cnec.bindfn(this.showMenu, this), Cnec.bindfn(this.hideMenu, this));
	this.menu.hover(Cnec.bindfn(this.showMenu, this), Cnec.bindfn(this.hideMenu, this));
}

Cnec.HiddenMenu.prototype.showMenu = function(e)
{
	this.element.addClass("hover");
	if(this.markSelected != null) this.element.parent().addClass(this.markSelected);
	this.menu.css("display" , 'block');
	this.menu.position({
		  "my": this.my,
		  "at": this.at,
		  "of": $(this.element),
		  "offset": this.offset
		});
	
}

Cnec.HiddenMenu.prototype.hideMenu = function(e)
{
	if(this.clickRequired) return;
	if(this.markSelected != null) this.element.parent().removeClass(this.markSelected);
	this.element.removeClass("hover");
	this.menu.css("display" , 'none');
}

Cnec.HiddenMenu.prototype.requireClick = function(e)
{
	this.clickRequired = true;
	$(document).click(this.clickRef);
}


Cnec.HiddenMenu.prototype.onClick = function(e)
{
	var o = e.target;
	var ok = false;
	for(;o != null; o = o.parentNode)
	{
		if(o == this.menu[0])
		{
			ok = true;
			break;
		}
	}
	if(ok) return;
	this.clickRequired = false;
	this.hideMenu(e);
}


//FieldGroupList
/*
 * Div with sub divs classnamed 'item'.
 * those items must have elements classnamed 'add-button' and 'remove-button'
 */
Cnec.FieldGroupList = function (element, args)
{
	var me = this;
	this.element = $(element);
	this.element.find(".item").each(Cnec.bindfn(this.bindEvent, this));
}

Cnec.FieldGroupList.prototype.bindEvent = function(element)
{
	if(arguments[1] != null) element = arguments[1];
	$(element).find('.add-button').click(Cnec.bindfn(this.add, this));
	$(element).find('.remove-button').click(Cnec.bindfn(this.remove, this));
}

Cnec.FieldGroupList.prototype.add = function(e)
{
	var element = e.target != null ? $(e.target).parentsUntil(this.element, '.item')  : e;
	var newElement = element.clone();
	element.after(newElement);
	Cnec.bindComponents(newElement[0]);
	this.bindEvent(newElement);
	newElement.find("input").val("");
	if(arguments[1] != true)
	{
		newElement.hide();
		newElement.slideDown('fast');
	}
	return newElement;
}

Cnec.FieldGroupList.prototype.remove = function(e)
{
	if(this.element.find(".item").length < 2) return;
	var element = $(e.target).parentsUntil(this.element, '.item');
	element.slideUp('fast', function(){element.detach();});
}

function initFontSizeControl()
{
	var c = Cnec.Cookies['fontsize'];
	if(c)
	{
		$(".font-size-control .selected").removeClass('selected');
		fontSizeAdjust("normal", c );
	}
	$(".font-size-control").click(fontSizeControlAdjust);	
}

function fontSizeAdjust(oldSize, newSize)
{
	if(!newSize.match(/big|small|normal/)) newSize = 'normal';
	$(".variable-font-container").removeClass("font-" + oldSize);
	$(".variable-font-container").addClass("font-" + newSize);
	$(".font-size-control ." + newSize).addClass("selected");
	Cnec.Cookies.write('fontsize', newSize, 24*60*60*30);
}

function fontSizeControlAdjust(e) 
{
	if($(e.target).hasClass(".font-size-control")) return;
	var selected  = $(".font-size-control .selected");
	if($(e.target).hasClass("selected")) return;
	if($(e.target).hasClass("plus"))
	{
		if (selected.hasClass("big")) return;
		selected.removeClass("selected");
		if (selected.hasClass("normal")){ 
			fontSizeAdjust("normal", "big");
			return;
		}
		if (selected.hasClass("small")){ 
			fontSizeAdjust("small", "normal");
			return;
		}
	}
	if($(e.target).hasClass("minus"))
	{
		if (selected.hasClass("small")) return;
		selected.removeClass("selected");
		if (selected.hasClass("normal")){
			fontSizeAdjust("normal", "small");
			return;
		}
		if (selected.hasClass("big")){
			fontSizeAdjust("big", "normal");
			return;
		}
	}
	selected.removeClass("selected");
	fontSizeAdjust(selected[0].className, e.target.className);	
}

Cnec.DatePicker = function (element, args)
{
	new Cnec.FieldMask(element, {"mask":"##/##/####"});
	$(element).datepicker($.datepicker.regional["pt-BR"]);
}
