/***********************************************************
Scriptname: 	jquery.poll.js
Dependencies: 	jquery.1.4.3
Version: 		1.0 live
Description:	Handling the poll

Copyright: 		Webavance B.V. 2011 for Dusk!
Legal: 			Any use of this script without Webavance B.V.
				express written consent is prohibited
************************************************************/

$(document).ready( function() {
	if ($('.poll_wrapper').length) $('.poll_wrapper').poll();
});

(function($) {
	
	$.fn.poll = function(c) {
		var e = $(this);
		var a = e.find('a, input[type=submit]');
		var d = e.attr('poll-id');
		
		url = location.host;
		fullurl = document.location.href;
		pathurl = fullurl.replace('http://'+url, "");
		language = pathurl.substr(0, 4);
		
		if (!c) c = {};
		
		c = $.extend({
			url: '/module/ajax'+language+'/polls_save/'
		}, c);
		
		if (!!!ReadCookie('hasvoted_' + d)) {
			a.bind('click', function(x) {
				x.preventDefault();
				x.cancelBubble = true;
				
				var opt = e.find('input[type=radio]:checked, input[type=checkbox]:checked').val();
			
				_s({"poll_opt": opt });
			});
		} else {
			_s();
		}
		
		function _s(v) {
			var t = (!v) ? 'GET' : 'POST' ;
			if (!v) v = [];
			var u = c.url + '?pid=' + d;
			
			$.ajax({
  				url: u,
  				data: 'poll_opt=' + v.poll_opt,
  				poll_opt: d,
  				cache: false,
  				dataType: 'json',
				type: t,
				success: function(r) {
					document.cookie = 'hasvoted_' + (this.poll_opt) + '=true;path=/;max-age=' + (60*60*24*365) + ';'
			
					e.children().remove();
					var tv = 0;
					$(r.items.votes).each( function(y, vote) {
						tv = parseInt(vote.votes) + tv;
						$(
							'<div class="poll_result_item">' + 
							'<div class="poll_result_label">' + vote.title + '</div>' + 
							'<div class="poll_result_display" value="' + vote.votes + '"><span class="bar"></span><span class="perc"></span></div>' + 
							'</div>'
						).appendTo(e);
					});
					
					$('.poll_result_display').each(function(y, z) {
						var prc = Math.ceil(($(z).width()-20)/tv);
						
						$(z).find('span.perc').text(Math.round(parseInt($(z).attr('value')) / (tv/100)) + '%');
						
						$(z).find('span.bar')
							.delay(y*200)
							.animate({
								width: prc * parseInt($(z).attr('value'))
							}, 'slow');
					});
				},
				error: function(r) {
					$('<div class="poll_item error">Error in poll</div>').insertBefore(e.find('.poll_item:first'));
				}
			});
		}
	};
	
})($);

function ReadCookie(cookieName) {
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return ""; 
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length; 
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
