/**
 * @author ragoncalves
 */
(function($) {
	$.extend({
		TVI24Sondagem:{			
			cookie : function (name, value, options) {
		            if (typeof value != 'undefined') {
		                options = options || {};
		                if (value === null) {
		                    value = '';
		                    options.expires = -1;
		                }
		                var expires = '';
		                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
		                    var date;
		                    if (typeof options.expires == 'number') {
		                        date = new Date();
		                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
		                    } else {
		                        date = options.expires;
		                    }
		                    expires = '; expires=' + date.toUTCString();
		                }		             
		                var path = options.path ? '; path=' + (options.path) : '';
		                var domain = options.domain ? '; domain=' + (options.domain) : '';
		                var secure = options.secure ? '; secure' : '';
		                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		                return true;
		            } else {
		                var cookieValue = null;
		                if (document.cookie && document.cookie != '') {
		                    var cookies = document.cookie.split(';');
		                    for (var i = 0; i < cookies.length; i++) {
		                        var cookie = $.trim(cookies[i]);
		                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
		                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
		                            break;
		                        }
		                    }
		                }
		                return cookieValue;
		            }
		    },
			
			showResult:function (){                
				var sondagemResult = $('<div class="results"></div>');
				$(TVI24SondagemData).each(function (){
					 sondagemResult.append(
					 $('<div class="reply">' +
		                  this.resp +
		                  '<div class="bar">' +
		                    '<div class="barpercent">'+this.value+'%</div>' +
		                    '<div class="baractive" style="width:'+ this.value +'%"></div>' +
		                  '</div>' +
		                '</div>'
		              )					 
					 );					
				});
				
				$("#sondagemconteudo").html(sondagemResult);
                return true;
			},

            encodeValue: function (str) {
                var div = document.createElement('div');
                var text = document.createTextNode(str);
                div.appendChild(text);
                return encodeURIComponent(div.innerHTML);
            },

            sendVote:function (form){                
                var id= $("input[name='pgt_id']",form).val();
                this.cookie('tvi24sondagem',id,{'expires':'7'});                
                var data='tipo=json&cookie_ant=';
                form.find("textarea, :text, :password, :radio:checked, :hidden").each(function() {
                    data += "&" + this.name + "=" + $.TVI24Sondagem.encodeValue(this.value);
                });
                $.ajaxSetup({
                        url: "/proxy/?", type: 'post', dataType: 'json', contentType: "application/x-www-form-urlencoded",
                        success: function(json) {return true;},
                        error: function(json){return false;}
                });                
                this.showResult();
                return $.ajax({data: data});
            },

			start:function(){
				if (typeof(TVI24SondagemData)=='object'){
				
					var idSondagem=$("input[name='pgt_id']", $('#sondagem')).val();
					var oldidSondagem=this.cookie('tvi24sondagem');
					if (idSondagem == oldidSondagem){                    
						this.showResult();
					} else {                
	                    $('#sondagem').submit(function(){                        
	                        $.TVI24Sondagem.sendVote($(this));
	                        return false;
	                    });
	                }                
	                $('#formularioResultados', $('#sondagem')).live('click',function() {
	                    $.TVI24Sondagem.showResult();
	                    return false;
	                });   
					
				}	
			}						
		}		
	});
})(jQuery);
