new YShout({
	yPath: 'shoutbox/',
	log: 1,
	postsHeight: 350
});

Ext.BLANK_IMAGE_URL = "http://www.drowtales.com/~pathtopower/resources/images/default/s.gif";

function showWindowWithUrl(a, b, c, d)
{
	var win = new Ext.Window({
		  layout:'fit',
		  width:c,
		  height:d,
		  closeAction:'hide',
		  plain: true,
		  autoLoad : a,
		  modal:true,
		  title: b,
		  autoScroll: true
	  });
	win.show();
}

var Voter =
{
	MaxTitleLength: 0,
	MaxDescLength: 0,
	CurrentList: null,
	Data: null,
	AjaxLoader: null,
	HoverDelayedTask: new Ext.util.DelayedTask(),
	/**
	 * desc = array of votingDropdown
	 * votingDropdown =
	 * {
	 *		ArchiveID : 9,
	 *		ChapterID : 1,
	 *		TitleText : 'Daydream 1: Space Age 2',
	 *		StatusText : '3 hours ago',
	 *		TotalVotes : 3,
	 *		Locked : false,
	 *		OptionsEnabled : true,
	 *		Choices : array of votingChoice
	 * }
	 * votingChoice =
	 * {
	 *		ChoiceID : 1234,
	 *		Title : 'Kick ass',
	 *		Description : 'Everyone goes to kick ass in an orderly manner',
	 *		Author : 'Durlyn',
	 *		Time : new Date(1901, 0, 1, 23, 59, 43),
	 *		Votes: 1
	 * }
	 */
	generateVoteDropdowns: function (desc, maxTitleLength, maxDescLength )
	{
		Voter.Data = desc;
		
		var sb = [];
		var i,j;

		var savedScrollPos = 0;
		var savedId = null;

		if ( Voter.CurrentList )
		{
			savedScrollPos = Voter.CurrentList.scrollTop;
			savedId = Voter.CurrentList.id;
		}

		Voter.MaxTitleLength = maxTitleLength;
		Voter.MaxDescLength = maxDescLength;
		
		for ( i = 0; i < desc.length; i++ )
		{
			sb.push('<div class="vdHeader',( desc[i].OptionsEnabled || desc[i].Choices.length > 0 ? '':' disabled'),'" style="z-index:',10-i,'" id="vdHeader',i,'" onclick="Voter.headerClick(event,this)">',
				'<span class="vdStatus',(desc[i].TotalVotes < 1 || desc[i].Locked ? ' locked' : ''),'"',(desc[i].TotalVotes < 1 || desc[i].Locked ? ' title="Voting locked"' : ''),'>[', desc[i].Choices.length,' choice',
				desc[i].Choices.length == 1 ? '' : 's',']</span>',desc[i].TitleText);

			if ( desc[i].OptionsEnabled || desc[i].Choices.length > 0 )
			{
				sb.push('<div class="vdList" id="vdList',i,'" onclick="Voter.listClick(event)">');
				Voter.generateDropdownListContents(sb, i, desc[i]);
				sb.push('</div>');
			}
			sb.push('</div>')
		}
		//var container = Ext.get('votingContainer');
		//container.update(sb.join(''));
		document.getElementById('votingContainer').innerHTML = sb.join('');

		if ( savedId )
		{
			Voter.CurrentList = document.getElementById(savedId);
			Voter.CurrentList.style.display='block';
			Voter.CurrentList.scrollTop = savedScrollPos;
		}
		for ( i = 0; i < desc.length; i++ )
		{
			var votes = [];
			for ( j = 0; j < desc[i].Choices.length; j++)
				votes[j] = desc[i].Choices[j].Votes;
			Voter.calculateVoteImages(i, votes);
		}
	},
	generateDropdownListContents: function(sb, i, desc)
	{
		var j;
		desc.Choices.sort(function(a,b){return a.Time == b.Time ? 0 : (a.Time > b.Time ? -1 : 1);});
		for ( j = 0; j < desc.Choices.length; j++)
		{
			sb.push(
				'<div class="vdChoice">',
					'<div class="vdChoiceTitle">',desc.Choices[j].Title,'</div>',
					'<div class="vdChoiceDescription">',desc.Choices[j].Description,'</div>',
					'<div class="vdAuthor">- ',desc.Choices[j].Author, ', ', (navigator.userAgent.toLowerCase().indexOf('chrome') > -1 ? desc.Choices[j].Time.toLocaleDateString() + ' ' + desc.Choices[j].Time.toLocaleTimeString() : desc.Choices[j].Time.toLocaleString()),'</div>',
					'<div class="vdButtons" id="vdButtons',i,'_',j,'">',
						'<img src="pics/vote1.png" alt="Vote 1" style="display:none" onmouseover="Voter.voteHover(',i,',',j,',1);" onmouseout="Voter.voteUnhover(',i,',',j,',1);" onclick="Voter.voteClick(',i,',',j,',1);">',
						'<img src="pics/vote2.png" alt="Vote 2" style="display:none" onmouseover="Voter.voteHover(',i,',',j,',2);" onmouseout="Voter.voteUnhover(',i,',',j,',2);" onclick="Voter.voteClick(',i,',',j,',2);">',
						'<img src="pics/vote3.png" alt="Vote 3" style="display:none" onmouseover="Voter.voteHover(',i,',',j,',3);" onmouseout="Voter.voteUnhover(',i,',',j,',3);" onclick="Voter.voteClick(',i,',',j,',3);">',
						'<img src="pics/tooltip-vote-1.png" id="vdButtonsTooltip',i,'_',j,'" alt="Tooltip" style="display:none" class="vdTooltip">',
				'</div>',
				'</div>'
			);
		}
		if ( desc.OptionsEnabled && !desc.Locked )
		{
			sb.push(
				'<table cellspacing="0" cellpadding="0" class="vdInsertChoice">',
					'<tr>',
						'<th></th>',
						'<td class="h1">Insert choice</td>',
					'</tr>',
					'<tr>',
						'<th>Title:</th>',
						'<td><input type="text" maxlength="',Voter.MaxTitleLength,'" size="50" id="vdTitle',i,'"></td>',
					'</tr>',
					'<tr>',
						'<th>Description:</th>',
						'<td><textarea wrap="soft" id="vdDescription',i,'" onkeyup="Voter.limitDesc(this)" onchange="Voter.limitDesc(this)" onpaste="Voter.limitDesc(this)"></textarea></td>',
					'</tr>',
					'<tr>',
						'<th></th>',
						'<td class="submit"><img src="pics/insert_choice.png" alt="Insert choice!" onclick="Voter.insertClick(',i,',',desc.ArchiveID,',',desc.ChapterID, ')"></td>',
					'</tr>',
				'</table>'
			);
		}
	},
	limitDesc: function(el)
	{
		if ( el.value.length > Voter.MaxDescLength )
			el.style.backgroundColor = 'salmon';
		else
			el.style.backgroundColor = '';
	},
	headerClick: function(ev, me)
	{
		if ( !ev )
			ev = event;
		if ( ev.stopPropagation )
			ev.stopPropagation();
		else
			ev.cancelBubble = true;
		
		var list = document.getElementById(me.id.replace('vdHeader', 'vdList'));
		if ( !list )
			return;

		if ( Voter.CurrentList )
		{
			Voter.CurrentList.style.display = 'none';
			if ( Voter.CurrentList == list )
			{
				Voter.CurrentList = null;
				return;
			}
		}
		Voter.CurrentList = list;
		list.style.display="block";
	},
	listClick: function(ev)
	{
		if ( !ev )
			ev = event;
		if ( ev.stopPropagation )
			ev.stopPropagation();
		else
			ev.cancelBubble = true;
	},
	bodyClick: function(ev)
	{
		if ( Voter.AjaxLoader && Voter.AjaxLoader.isVisible() )
			return;
		if ( Voter.CurrentList )
		{
			Voter.CurrentList.style.display = 'none';
			Voter.CurrentList = null;
		}
	},
	insertClick: function(id, archiveID, chapterID)
	{
		var text = document.getElementById('vdTitle'+id).value;
		var description = document.getElementById('vdDescription'+id).value;

		var err = [];
		if ( text.length > Voter.MaxTitleLength )
			err.push("Title length must be at most " + Voter.MaxTitleLength + " characters!");
		if ( text.length < 1 )
			err.push("Must enter title!");
		if ( description.length > Voter.MaxDescLength )
			err.push("Description length must be at most " + Voter.MaxDescLength + " characters!");
		if ( description.length < 1 )
			err.push("Must enter description!");
		if ( err.length > 0 )
		{
			alert(err.join("\r\n"));
			return;
		}
		Voter.showAjaxLoader();
		Ext.Ajax.request({
			url: 'insertoption.php',
			method: 'POST',
			params: {title: text, description: description, archiveID: archiveID, chapterID: chapterID},
			success: function(response,options)
			{
				Voter.hideAjaxLoader();
				var data = eval('('+response.responseText+')');
				if ( typeof(data) == 'string' )
					alert(data);
				else
				{
					Voter.generateVoteDropdowns(data, Voter.MaxTitleLength, Voter.MaxDescLength);
					Voter.CurrentList.scrollTop = 0;
				}
			},
			failure: function(response,options)
			{
				Voter.hideAjaxLoader();
				alert('Oops, error ' + response.status +' ocurred: ' + response.statusText);
			}
		});
	},
	voteHover: function(dropdown,choice,vote)
	{
		var Choices = Voter.Data[dropdown].Choices;
		var votes = [];
		for ( j = 0; j < Choices.length; j++)
			votes[j] = Choices[j].Votes;

		votes[choice] = (vote <= votes[choice] ? vote-1 : vote);

		Voter.HoverDelayedTask.delay(50, function()
		{
			Voter.calculateVoteImages(dropdown, votes);
			var el = document.getElementById('vdButtonsTooltip'+dropdown+'_'+choice);
			if ( votes[choice] > 0 )
			{
				el.src = "pics/tooltip-vote-"+votes[choice]+".png";
				el.style.display="block";
			}
			else
			{
				el.style.display="";
			}
		});
	},
	voteUnhover: function(dropdown,choice,vote)
	{
		var Choices = Voter.Data[dropdown].Choices;
		var votes = [];
		for ( j = 0; j < Choices.length; j++)
			votes[j] = Choices[j].Votes;

		Voter.HoverDelayedTask.delay(50, function()
		{
			Voter.calculateVoteImages(dropdown, votes);
			document.getElementById('vdButtonsTooltip'+dropdown+'_'+choice).style.display="";
		});
	},
	voteClick: function(dropdown,choice,vote)
	{
		Voter.showAjaxLoader();
		Ext.Ajax.request({
			url: 'vote.php',
			method: 'POST',
			params: {choiceID: Voter.Data[dropdown].Choices[choice].ChoiceID, count: (vote <= Voter.Data[dropdown].Choices[choice].Votes ? vote-1 : vote)},
			success: function(response,options)
			{
				Voter.hideAjaxLoader();
				var data = eval('('+response.responseText+')');
				if ( typeof(data) == 'string' )
					alert(data);
				else
					Voter.generateVoteDropdowns(data, Voter.MaxTitleLength, Voter.MaxDescLength);
			},
			failure: function(response,options)
			{
				Voter.hideAjaxLoader();
				alert('Oops, error ' + response.status +' ocurred: ' + response.statusText);
			}
		});
	},
	calculateVoteImages: function(dropdown,votes)
	{
		var i, j, el;

		if ( Voter.Data[dropdown].Locked )
		{
			for ( i = 0; i < votes.length; i++ )
			{
				el = document.getElementById('vdButtons'+dropdown+'_'+i);

				for ( j = 0; j < 3; j++ )
				{
					if ( votes[i] > j )
					{
						el.childNodes[j].src = 'pics/vote'+(j+1)+'.png';
						el.childNodes[j].style.display = '';
					}
					else
						el.childNodes[j].style.display = 'none';

					el.childNodes[j].onclick = null;
					el.childNodes[j].onmouseover = null;
					el.childNodes[j].onmouseout = null;
					el.childNodes[j].style.cursor = 'default';
				}
			}
			return;
		}

		var extraVotes = Voter.Data[dropdown].TotalVotes;
		for ( i = 0; i < votes.length; i++ )
			extraVotes -= votes[i];
		if ( extraVotes < 0 )
			extraVotes = 0;
		for ( i = 0; i < votes.length; i++ )
		{
			el = document.getElementById('vdButtons'+dropdown+'_'+i);

			for ( j = 0; j < 3; j++ )
			{
				if ( votes[i] > j )
				{
					el.childNodes[j].src = 'pics/vote'+(j+1)+'.png';
					el.childNodes[j].style.display = '';
				}
				else if ( extraVotes+votes[i] > j )
				{
					el.childNodes[j].src = "pics/vote0.png";
					el.childNodes[j].style.display = '';
				}
				else
					el.childNodes[j].style.display = 'none';
			}
		}
	},
	showAjaxLoader: function()
	{
		if ( !Voter.AjaxLoader )
			Voter.AjaxLoader = new Ext.Window({
				  layout:'fit',
				  width:130,
				  height:130,
				  closable:false,
				  draggable: false,
				  plain: true,
				  modal:true,
				  title: 'Please wait...',
				  html: '<div class="ajaxLoader"></div>'
			  });
		Voter.AjaxLoader.show();
	},
	hideAjaxLoader: function()
	{
		if ( !Voter.AjaxLoader )
			return;
		Voter.AjaxLoader.hide();
	}
}
document.onclick = Voter.bodyClick;
