// Set the cookie when the user has voted
function set_cookie () {
	jQuery.setCookie( 'PASSAGEN_ROLLOUT_POLL', 'voted', {
		duration : 2 // In days
	});
}

// Parse the XML document
// and create the html structure for the poll
function parse_poll_xml ( xml ) {
	
	// Preparing the different elements with all the attributes that we can
	var poll = jQuery('<div/>').addClass('poll');
	var javascript = jQuery('<script type="text/javascript"/>');
	var image = jQuery('<img/>').css('width','150px');
	var question = jQuery('<p/>').css({ marginTop: '0px', fontWeight: 'bold' });
	var form = jQuery('<form name="pollForm"/>');
	var answers = jQuery('<div/>');
	var submit = jQuery('<input type="submit"/>').val('Rösta');
	var result_link = jQuery('<a/>').text('Se resultat').css({ display: 'block', marginTop: '10px' }).attr('href','#pollResult');
	
	// Going through the XML and attaching the attributes to the elements
	jQuery(xml).find('poll').each(function(){
		
		image.attr('src', jQuery(this).find('question').find('img').attr('src') );
		question.text( jQuery(this).find('question').text() );
		
		jQuery(this).find('answer').each(function () {
			
			var $this = jQuery(this);
			
			var label = jQuery('<label/>').attr('for', $this.attr('id') ).text( $this.text() );
			
			var input = jQuery('<input type="radio"/>')
						.val( $this.attr('id') )
						.attr('id', $this.attr('id'))
						.attr('name', 'answer_id');
			
			answers.append(input,label,'<br/>');
		});
		
		submit.click(function (e) {
			e.preventDefault();
			set_cookie();
			hide_rollout_poll(jQuery('.pollContainer'));
			addLoc(jQuery(xml).find('form').find('question_id').text());
		})
		result_link.click(function (e) {
			e.preventDefault();
			addLocShow(jQuery(xml).find('form').find('question_id').text());
		})
		
		// Appending everything all the poll elements to the form
		form.append(answers,submit,result_link);
		
	});
	
	// Return the complete poll
	return poll.append(image,'<br/>',question,form);
	
} 

// Create the poll container and run the AJAX
// to fetch the poll XML
function create_rollout_poll () {
	var poll = jQuery('<div/>');
	poll.addClass('pollContainer')
		.css({ 
			position: 'absolute',
			width: '150px',
			padding: '20px',
			left: '-210px',
			top: '350px',
			backgroundColor: '#eee',
			border: '8px solid #fff',
			zIndex: 10
		});
	
	var logo = jQuery('<img/>');
	logo.attr('src','http://www.passagen.se/img/global/passagen_logo_150x19.gif')
		.css({
			marginBottom: '10px'
		});

	var link = jQuery('<a/>');
	link.attr('href','#closePoll')
		.addClass('closePoll')
		.html('[x] Visa inte omr&ouml;stning')
		.css({
			display: 'block',
			marginTop: '10px',
			textDecoration: 'none'
		}).click(function(e) {
			e.preventDefault();
			set_cookie();
			hide_rollout_poll(poll);
		});
	
	// Yay, AJAX!
	jQuery.ajax({
		type: "GET",
		url: "/survey2/show_poll.fcgi?section_id=1;placement=1;xml=1",
		dataType: "xml",
		success: function(xml) {
			html = parse_poll_xml (xml);
			poll.append(logo,html,link);
			jQuery('body').append(poll);
			show_rollout_poll(poll);
		}, 
		error: function (xhr, textStatus, thrownError){
	        console.log(xhr.status + " - " + xhr.statusText + "\n" + textStatus + "\n" + thrownError);
        }
    });
	
}

// Animation helper functions
function show_rollout_poll ( element ) {
	element.animate({
		left: '20px'
	}, 2000 );
}

function hide_rollout_poll ( element ) {
	element.animate({
		left: '-210px'
	}, 500 );
}

document.write('<style type="text/css">div.pollContainer{-moz-box-shadow:2px 2px 2px #aaa;-webkit-box-shadow:2px 2px 2px #ccc;box-shadow:2px 2px 2px #aaa}</style>')

$(document).ready( function () {
	/*
	var c_value = jQuery.readCookie( 'PASSAGEN_ROLLOUT_POLL' );
	var d_width = jQuery(document).width();				
	
	if(self.document.location.hash.substring(1) == 'delete_cookie') {
		jQuery.delCookie( 'PASSAGEN_ROLLOUT_POLL' );
	}
	
	if(c_value != 'voted' && d_width > 1200) {
		create_rollout_poll();
	}
	*/
});

// Function to open a new window for the vote
function addLoc(num) {
	window.open('http://www.passagen.se/survey2/register_vote.fcgi?popup=1&question_id='+num+'&answer_id=' + get_radio(), 'fonstar', "height=500,width=370,scrollbars=yes");
}

// Function to open a new window to see vote results
function addLocShow(num) {
	window.open('http://www.passagen.se/survey2/show_votes.fcgi?question_id='+num+'&popup=1', 'fonstar', "height=500,width=370,scrollbars=yes");
}

// Getting the answer value when voting
function get_radio(num) {
	for(i=0; i<document.pollForm.answer_id.length;i++)
	{
		if(document.pollForm.answer_id[i].checked)
		{
			return document.pollForm.answer_id[i].value;
		}
	}
}
