// ÅÄÖ

// Class to handle all poll functions

var Polls = Class.create({

	initialize: function() {
		this.showingArticle = [];
		this.embeded = false;
	},
	
	vote: function(id, template) {
		
		if($('answers_' + id)) {
			
			$('answers_' + id).request({
				parameters: { id: id },
				onCreate: function() {
					
					// Show loading image while fetching data
					$('right_' + id).update('<img src="/img/ajax-loading.gif" alt="Laddar" title="Laddar" style="margin-left: 160px;" />');
				},
				onComplete: function(truck){
					
					var content = truck.responseText.evalJSON();
					
					// View answers again if error or set flash divs so we can load the flash in them
					$('right_' + id).update(content.content);
					
					$('totvotes_' + id).update('Antal röster <span class="number">' + content.total_votes + '</span> st');
					
					// Display error if any
					if(content.error != '') {
						
						poll.showError(content.error);
						
					}else{
						
						var size = poll.getSize(template);
						
						// Load flash if not a ruler chart
						if(content.poll_type != 4) {
							swfobject.embedSWF("/swf/open-flash-chart.swf", "chart_" + id, size.width, size.height, "9.0.0", "", {"data-file": "/ajax/poll/" + poll.whichPoll(content.poll_type) + "Chart/" + id + "/" }, { wmode: "transparent" });	
						}
						
						if(template == 'Box' || template == 'BoxSmall') {
							
							var links = '<div class="vote"  onclick="' + (poll.embeded ? 'window.open(\'' + content.url + '#kommentera\',\'Kommentera\');' : 'redirect(\'' + content.url + '#kommentera\');') + '">Kommentera</div>';
							links += '<div class="clear"><div class="link"><a href="' + (poll.embeded ? pollurl + '?show=embed' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.showEmbedCodes(\'' + id + '\');"' : '') + ' title="Visa koder för att embedda denna fråga">&lt; Embed &gt;</a></div>';
							links += '<div class="link"><a href="' + (poll.embeded ? pollurl + '?show=report' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.report(\'' + id + '\');"' : '') + ' title="Anmäl denna fråga">Anmäl</a></div></div>';
							
							
						}else{
							
							var links = '<div class="link"><a href="' + (poll.embeded ? pollurl + '?show=embed' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.showEmbedCodes(\'' + id + '\');"' : '') + ' title="Visa koder för att embedda denna fråga">&lt; Embed &gt;</a></div>';
							links += '<div class="link"><a href="' + (poll.embeded ? pollurl + '?show=report' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.report(\'' + id + '\');"' : '') + ' title="Anmäl denna fråga">Anmäl</a></div>';
							links += '<div class="vote" onclick="' + (poll.embeded ? 'window.open(\'' + content.url + '#kommentera\',\'Kommentera\');' : 'redirect(\'' + content.url + '#kommentera\');') + '">Kommentera (' + content.total_comments + ')</div>';
						}
						
						$('links_' + id).update(links);
					}
					
					
				}
			});
		}
	},
	
	getSize: function(template) {
		
		var width = 430;
		var height = 130;
		
		if(template == 'DefaultMedium') {
			
			width = 310;
			height = 100;
			
		}else if(template =='DefaultSmall') {
			
			width = 215;
			height = 90;
			
		}else if(template =='Box') {
			
			width = 225;
			height = 90;
		}else if(template =='BoxSmall') {
			
			width = 170;
			height = 80;
		}
		
		return { width: width, height: height }
		
	},
	
	whichPoll: function(poll_type) {
		
		var polltype = '';
		
		// Decide what poll to show
		if(poll_type == 1) {
			
			polltype = 'pie';
			
		}else if(poll_type == 2) {
			
			polltype = 'bar';
			
		}else if(poll_type == 3) {
			
			polltype = 'line';
			
		}
		
		return polltype;
	},
	
	report: function(pollid, commentid) {
		
		// Fetch error html
		new Ajax.Request('/ajax/poll/report/', {
				parameters: { pollid: pollid, commentid: commentid },
				asynchronous: false,
				onComplete: function(truck) {
					
					// Display layer
					new topLayer('reportComment', 400, (commentid > 0 ? "Rapportera kommentar" : "Rapportera omröstning"), truck.responseText);
					
					// Observe default values so they dissappear on focus
					poll.observeReport();
				}
		});
		
	},
	
	observeReport: function() {
		
		$('reason').observe('focus', function(event) {
												
			if($('reason').value == 'Anledning') {
				$('reason').value = '';	
			}
		});
		
		$('firstname2').observe('focus', function(event) {
												
			if($('firstname2').value == 'Förnamn') {
				$('firstname2').value = '';	
			}
		});
		
		$('lastname2').observe('focus', function(event) {
												
			if($('lastname2').value == 'Efternamn') {
				$('lastname2').value = '';	
			}
		});
		
		$('email').observe('focus', function(event) {
												
			if($('email').value == 'E-post') {
				$('email').value = '';	
			}
		});
	},
	
	checkDefaultReportValues: function() {
		
		if($('reason').value == 'Anledning') {
			$('reason').value = '';	
		}
		
		if($('firstname2').value == 'Förnamn') {
			$('firstname2').value = '';	
		}
		
		if($('lastname2').value == 'Efternamn') {
			$('lastname2').value = '';	
		}
		
		if($('email').value == 'E-post') {
			$('email').value = '';	
		}
	},
	
	sendReport: function(pollid, commentid) {
		
		poll.checkDefaultReportValues();
		
		new Ajax.Request('/ajax/poll/report/', {
				parameters: { pollid: pollid, commentid: commentid, firstname: $('firstname2').value, lastname: $('lastname2').value, email: $('email').value, reason: $('reason').value },
				asynchronous: false,
				onComplete: function(truck) {
					
					if(truck.responseText == '+SENT') {
						var message = '<br />Tack för din rapport, du kommer få ett mail så fort en administratör har sett över din rapport.';
					}else{
						var message = truck.responseText;	
					}
					
					$('layer-content-reportComment').update(message);
					
					poll.observeReport();
				}
		});
		
	},
	
	view: function(id, what, template) {
		
		var answer = false;
		
		$$('form#answers_' + id + ' input').each(function(obj) {

			if(obj.checked) {
				answer = true;
			}
		});
		
		if(answer) {
			
			alert("Du har valt ett alternativ, vill du rösta? I så fall klicka på rösta.");
			
		}else{
			
			// Show loading image
			$('right_' + id).update('<img src="/img/ajax-loading.gif" alt="Laddar" title="Laddar" style="margin-left: 160px;" />');
			
			new Ajax.Request('/ajax/poll/view/', {
				parameters: { id: id, what: what, template: 'Default' },
				asynchronous: true,
				onComplete: function(truck) {
					
					var content = truck.responseText.evalJSON();
					$('right_' + id).update(content.content);
					
					if(what == 'results') {
						
						var size = poll.getSize(template);
						
						// If not ruler chart we load flash
						if(content.poll_type != 4) {
							swfobject.embedSWF("/swf/open-flash-chart.swf", "chart_" + id, size.width, size.height, "9.0.0", "", {"data-file": "/ajax/poll/" + poll.whichPoll(content.poll_type) + "Chart/" + id + "/" }, { wmode: "transparent" });
						}
						
						if(template == 'Box' || template == 'BoxSmall') {
							
							var links = '<div class="viewResult" onclick="poll.view(\'' + id + '\', \'answers\', \'' + template + '\');">Rösta</div>';
							links += '<div class="vote" onclick="' + (poll.embeded ? 'window.open(\'' + content.url + '#kommentera\',\'Kommentera\');' : 'redirect(\'' + content.url + '#kommentera\');') + '">Kommentera</div>';
							links += '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=embed' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.showEmbedCodes(\'' + id + '\');"' : ' target="_blank"') + ' title="Visa koder för att embedda denna fråga">&lt; Embed &gt;</a></div>';
							links += '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=report' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.report(\'' + id + '\');"' : ' target="_blank"') + ' title="Anmäl denna fråga">Anmäl</a></div>';
							
							
						}else{
							var links = '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=embed' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.showEmbedCodes(\'' + id + '\');"' : ' target="_blank"') + ' title="Visa koder för att embedda denna fråga">&lt; Embed &gt;</a></div>';
							links += '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=report' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.report(\'' + id + '\');"' : ' target="_blank"') + ' title="Anmäl denna fråga">Anmäl</a></div>';
							links += '<div class="viewResult" onclick="poll.view(\'' + id + '\', \'answers\', \'' + template + '\');">Rösta</div>';
							links += '<div class="vote" onclick="' + (poll.embeded ? 'window.open(\'' + content.url + '#kommentera\',\'Kommentera\');' : 'redirect(\'' + content.url + '#kommentera\');') + '">Kommentera (' + content.total_comments + ')</div>';
						}
						
					}else{
						
						if(template == 'Box' || template == 'BoxSmall') {
							
							
							if(content.voted) {
								
								var links = '<div class="vote" onclick="' + (poll.embeded ? 'window.open(\'' + content.url + '#kommentera\',\'Kommentera\');' : 'redirect(\'' + content.url + '#kommentera\');') + '">Kommentera</div>';
								
							}else{
								
								var links = '<div class="viewResult" onclick="poll.view(\'' + id + '\', \'results\', \'' + template + '\');">Visa Resultat</div>';
								links += '<div class="vote" onclick="poll.vote(\'' + id + '\', \'' + template + '\');">Rösta</div>';
								
							}
							
							links += '<div class="clear"><div class="link"><a href="' + (poll.embeded ? content.url + '?show=embed' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.showEmbedCodes(\'' + id + '\');"' : ' target="_blank"') + ' title="Visa koder för att embedda denna fråga">&lt; Embed &gt;</a></div>';
							links += '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=report' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.report(\'' + id + '\');"' : ' target="_blank"') + ' title="Anmäl denna fråga">Anmäl</a></div>';
							
							if(!content.voted) {
								links += '<div class="link"><a href="' + content.url + '#kommentera" title="Kommentera"' + (poll.embeded ? ' target="_blank"' : '') + '>Kommentera</a></div>';	
							}
							
							links += '</div>';
							
						}else{
						
							var links = '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=embed' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.showEmbedCodes(\'' + id + '\');"' : ' target="_blank"') + ' title="Visa koder för att embedda denna fråga">&lt; Embed &gt;</a></div>';
							links += '<div class="link"><a href="' + (poll.embeded ? content.url + '?show=report' : 'javascript:void(0);') + '"' + (!poll.embeded ? ' onclick="poll.report(\'' + id + '\');"' : ' target="_blank"') + ' title="Anmäl denna fråga">Anmäl</a></div>';
							if(content.voted) {
								
								links += '<div class="vote" onclick="' + (poll.embeded ? 'window.open(\'' + content.url + '#kommentera\',\'Kommentera\');' : 'redirect(\'' + content.url + '#kommentera\');') + '">Kommentera (' + content.total_comments + ')</div>';
								
							}else{
								
								links += '<div class="link"><a href="' + content.url + '#kommentera" title="Kommentera"' + (poll.embeded ? ' target="_blank"' : '') + '>Kommentera (' + content.total_comments + ')</a></div>';
								links += '<div class="viewResult" onclick="poll.view(\'' + id + '\', \'results\', \'' + template + '\');">Visa Resultat</div>';
								links += '<div class="vote" onclick="poll.vote(\'' + id + '\', \'' + template + '\');">Rösta</div>';
							}
						}
					}
					
					$('links_' + id).update(links);
					
				}
			});
		}
		
	},
	
	showEmbedCodes: function(id) {
		
		var html = "<br />Här hittar du embedkoderna för att embedda en omröstning på din sida!<br /><br />Du kan se exempel på hur dom ser ut <a href=\"/img/exempel.jpg\" target=\"_blank\" class=\"example\">här</a>!<br /><br /><strong>Standard</strong><br /><input type=\"text\" class=\"embedCode\" value=\"&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.voter.se/embed/poll.js?style=Default&amp;id=" + id + "&quot;></script>\" /><br />";
		
		html += "<strong>Standard - Mellan</strong><br /><input type=\"text\" class=\"embedCode\" value=\"&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.voter.se/embed/poll.js?style=DefaultMedium&amp;id=" + id + "&quot;></script>\" /><br />";
		
		html += "<strong>Standard - Mini</strong><br /><input type=\"text\" class=\"embedCode\" value=\"&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.voter.se/embed/poll.js?style=DefaultSmall&amp;id=" + id + "&quot;></script>\" /><br />";
		
		html += "<strong>Box</strong><br /><input type=\"text\" class=\"embedCode\" value=\"&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.voter.se/embed/poll.js?style=Box&amp;id=" + id + "&quot;></script>\" /><br />";
		
		html += "<strong>Box - Mini</strong><br /><input type=\"text\" class=\"embedCode\" value=\"&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.voter.se/embed/poll.js?style=BoxSmall&amp;id=" + id + "&quot;></script>\" />";
		
		new topLayer('embedCodes', 700, "Embed koder", html);
		
	},
	
	showArticle: function(id) {
		if(!this.showingArticle[id]) {
			this.showingArticle[id] = true;
			
			$('article_' + id).setStyle({ visibility: 'hidden', display: 'block'});
			
			//poll.fixArticlebg(id, $('article_' + id).getHeight());
			
			$('article_' + id).setStyle({ visibility: 'visible', display: 'none'});
			
			new Effect.BlindDown('article_' + id, { queue: { position: 'end', scope: 'article' + id, limit: 1 }});
			
			
			
			
			
			$('readmore_' + id).update('<a href="javascript:void(0);" onclick="poll.hideArticle(\'' + id + '\');" title="Dölj">Dölj!</a> <img src="/img/arrow-blue-up.png" alt="Dölj" title="Dölj" onclick="poll.hideArticle(\'' + id + '\');" />');
		}
	},
	
	fixArticlebg: function(id, height) {
		
		var obj = new Element('div', {'class': 'articleBg', id: 'bg-' + id });
		
		obj.setStyle({ top: $('article_' + id).cumulativeOffset().top + 'px', left: $('article_' + id).cumulativeOffset().left + 'px', height: (height-30) + 'px', display: 'none' });
			
		document.body.appendChild(obj);
		
		obj.appear({ duration: 1.0, to: 0.9 });
	},
	
	hideArticle: function(id) {
		new Effect.BlindUp('article_' + id, { queue: { position: 'end', scope: 'article' + id, limit: 1 }});
		
		//$('bg-' + id).fade({ duration: 2.0, from: 0.9, to: 0 });
		//setTimeout('$(\'bg-' + id + '\').remove();', 2000);
		
		this.showingArticle[id] = false;
		$('readmore_' + id).update('<a href="javascript:void(0);" onclick="poll.showArticle(\'' + id + '\');" title="Läs mer">Läs mer!</a> <img src="/img/arrow-blue-down.png" alt="Läs mer" title="Läs mer" onclick="poll.showArticle(\'' + id + '\');" />');
	},
	
	showError: function(message) {
		alert("showing error: " + message);
	},
	
	displayResult: function(obj, percent, answer) {
		obj.innerHTML = answer + "<br />" + percent + "%";
	},
	
	removeComment: function(id) {
		new Ajax.Request('/ajax/poll/removeComment/', {
			parameters: { id: id },
			asynchronous: true,
			onComplete: function(truck) {
				if(truck.responseText == '+OK') {
					$('comment_' + id).update('<i>Kommentaren är nu raderad</i>');
				}else{
					alert("Du är inte administatör");	
				}
			}
		});
	}
});

var poll = new Polls();