/*
** NewPeople.nl tagcloud javascript file
*/

/*
** Settings
*/
var tagMorphDuration = 0.6;
var jobsPerJobListPage = 6;
var defaultTagColor = 'rgb(68,68,68)';
var disabledTagColor = 'rgb(190,190,190)';
var selectedTagColor = 'rgb(255,255,255)';


/*
** Global variables
*/
var selectedTagNames = [];				// Currently selected tags
var lastXHRurl = false;					// Used for only updating from most recent xhr request
var isMorphingCloud = false;			// True when cloud is being morphed
var queuedTransport = false;			// used for queueing up clicks for when the tagcloud is animating
var currentJobListPage = false;
var amountOfJobListPages = false;
var rssLinkTag = false;

var selectedEmployee = false;


/*
** OnLoad events
*/
document.observe('dom:loaded', function() {
	if ( $('cloud') )
	{
		initializeSelectedTagNames();
		bindTags();
		initializeRSSLinkTag()
	}
	if ( $('jobList') )
		bindJobList();
	if ( $('job') )
		bindJobActions();
	if ( $('employeeList') )
		bindEmployeeOverviewList();
	if ( $('incentiveList') )
		bindIncentiveOverviewLists();
});


/*
** Cloud functions
*/
function initializeSelectedTagNames()
{
	var tags = $$('div#cloud a.tag');
	for (i=0, l=tags.length; i<l; ++i)
	{
		tag = tags[i];
		if ( tag.hasClassName('selected') )
			selectedTagNames.push(tag.innerHTML)
	}
}

function bindTags()
{
	var tags = $$('div#cloud a.tag');
	for (i=0, l=tags.length; i<l; ++i)
	{
		tag = tags[i];
		tag.href = "/#";
		tagColor = tag.getStyle('color');
		if ( tagColor == 'rgb(0, 0, 238)' )
			tag.setStyle({ color: 'rgb(68, 68, 68)' })
		else
			tag.setStyle({ color: tagColor });
		tag.onclick = function() { selectTag($(this)); return false }
	}
}

function selectTag(tag)
{
	//var tag = event.element();

	/*if ( selectedTagNames.length == 10 )
		alert("U kunt maximaal 10 tags selecteren.");
	else*/
	if ( ( ! tag.hasClassName('disabled') ) || ( tag.hasClassName('selected') ) )
	{
		tag.setStyle({ color: '' });
		if ( tag.hasClassName('selected') )
		{
			selectedTagNames = selectedTagNames.without(tag.innerHTML);
			tag.removeClassName('selected')
		}
		else
		{
			if ( selectedTagNames.length == 10 )
			{
				alert("U kunt maximaal 10 tags selecteren.");
				return false
			}
			selectedTagNames.push(tag.innerHTML);
			tag.addClassName('selected')
		}

		requestCloudUpdate();
		show_spinner()
	}
	
	return false
}

function selectNone()
{
	var selectedTags = $$('div#cloud a.tag.selected');
	for (i=0, l=selectedTags.length; i<l; ++i)
	{
		tag = selectedTags[i];
		tag.setStyle({ color: '' });
		tag.removeClassName('selected')
	}
	selectedTagNames = [];
	requestCloudUpdate();
	show_spinner()
}

function requestCloudUpdate()
{
	lastXHRurl = "/tags/" + selectedTagNames.join("+");
	new Ajax.Request(lastXHRurl, { onSuccess: handleCloudUpdateResponse });
	show_spinner()
}

function tagString(tag_name)
{
	if ( selectedTagNames.length == 0 )
		return tag_name
	else
		if ( selectedTagNames.indexOf(tag_name) == -1 )
			return selectedTagNames.join("+") + "+" + tag_name
		else
			return selectedTagNames.without(tag_name).join("+")
}

function handleCloudUpdateResponse(transport)
{
	if ( isMorphingCloud )
		queuedTransport = transport
	else
		if ( transport.request.url == lastXHRurl )
		{
			response = transport.responseText.evalJSON();
			updateCloud(response.tags);
			updateJobs(response.jobs);
			updateRSSLinkTag();
			if ( $('chartContainer') )
				if ( response.chart )
					$('chartContainer').update(response.chart)
				else
					$('chartContainer').update('')
		}
}

function updateCloud(newTags)
{
	isMorphingCloud = true;
	selectedTagNames = [];
	var tags = $$('div#cloud a.tag');
	for (i=0, l=tags.length; i<l; ++i)
	{
		tag = tags[i];
		newTag = newTags[tag.id];
				
		if ( newTag.selected )
			selectedTagNames.push(tag.innerHTML);
		
		tag.className = "tag" + ( newTag.disabled ? " disabled" : "" ) + ( newTag.selected ? " selected" : "" );
		
		if ( newTag.selected )
			newColor = selectedTagColor
		else if ( newTag.disabled )
			newColor = disabledTagColor
		else
			newColor = defaultTagColor;
		
		if ( i+1 < l )
			new Effect.Morph(tag, {
				style: { fontSize: newTag.weight + "%", color: newColor },
				duration: tagMorphDuration
			})
		else
			new Effect.Morph(tag, {
				style: { fontSize: newTag.weight + "%", color: newColor },
				duration: tagMorphDuration,
				afterFinish: afterMorphingCloud
			})
	}
}

function afterMorphingCloud()
{
	isMorphingCloud = false;
	if ( queuedTransport )
	{
		handleCloudUpdateResponse(queuedTransport);
		queuedTransport = false
	}
	else
		hide_spinner()
}

/*
** Job-list functionality
*/
function bindJobList()
{
	var jobList = $$('div#jobList ul#jobs li');
	for (i=0, l=jobList.length; i<l; ++i)
	{	
		jobListItem = jobList[i];
		jobListItem.setStyle({ cursor: 'pointer' });
		jobListItem.onclick = function() { selectJob($(this)) };
		jobListItem.onmouseover = function() { $(this).addClassName('hover') };
		jobListItem.onmouseout = function() { $(this).removeClassName('hover') };
		jobListItem.getElementsByTagName('a')[0].onclick = function() { return false }
	}
	
	var pagers = $$('div#jobList #pager a.page_button');
	for (i=0, amountOfJobListPages=pagers.length; i<amountOfJobListPages; ++i)
	{
		pagers[i].onclick = function() { selectJobListPage(this.id.split("page")[1]); return false }
	}
	$('prev_page').onclick = function() { selectJobListPage(Number(currentJobListPage)-1); return false }
	$('next_page').onclick = function() { selectJobListPage(Number(currentJobListPage)+1); return false }
		
	if ( $('pager').getElementsByClassName('active').length > 0 )
		currentJobListPage = $('pager').getElementsByClassName('active')[0].id.split("page")[1]
	else
		currentJobListPage = 1;
	
	if ( $('reset') )
		$('reset').onclick = function() { selectNone(); return false }
}

function selectJob(job)
{
	if ( $$('div#jobList li.active').length == 1 )
		$$('div#jobList li.active')[0].removeClassName('active');
	job.addClassName('active');
	window.location.href = job.getElementsByTagName('a')[0].href
}

function selectJobListPage(page)
{
	if ( currentJobListPage != page )
	{
		$('page' + currentJobListPage).removeClassName('active');
		$('page' + page).addClassName('active');
		
		var jobList = getJobListItemsByPage(currentJobListPage);
		for (i=0, l=jobList.length; i<l; ++i)
			jobList[i].hide();
		
		currentJobListPage = page;
		
		var jobList = getJobListItemsByPage(currentJobListPage);
		for (i=0, l=jobList.length; i<l; ++i)
			jobList[i].show();
		
		if ( currentJobListPage == 1 )
			$('prev_page').hide()
		else
			$('prev_page').show();
		if ( currentJobListPage == amountOfJobListPages )
			$('next_page').hide()
		else
			$('next_page').show()
	}
}

function getJobListItemsByPage(page)
{
	start = page * jobsPerJobListPage - jobsPerJobListPage;
	end = page * jobsPerJobListPage;
	var jobList = $$('div#jobList ul#jobs li');
	if ( end >= jobList.length )
		end = jobList.length;
	return jobList.slice(start, end)
}

function updateJobs(jobs)
{
	$('jobList').update(jobs);
	bindJobList()
}

function show_spinner()
{
	$('right').hide();
	$('spinner').show()
}

function hide_spinner()
{
	$('right').show();
	$('spinner').hide()
}


/*
** Add/update/remove specific link tag in <head> if necessary
*/
function initializeRSSLinkTag()
{
	rssLinkTag = $('specificRSS');
	if ( ! rssLinkTag )
	{
		rssLinkTag = document.createElement("link");
		rssLinkTag.id = "specificRSS";
		rssLinkTag.type = "application/rss+xml";
		rssLinkTag.rel = "alternate";
		rssLinkTag.title = "";
		rssLinkTag.href = ""
	}
}


function updateRSSLinkTag()
{
	head = document.getElementsByTagName("head")[0];
	if ( rssLinkTag.parentNode == head )
		head.removeChild(rssLinkTag);
	if ( selectedTagNames.length > 0 )
	{
		rssLinkTag.title = "NEWPEOPLE RSS: vacatures met " + selectedTagNames.join(", ");
		rssLinkTag.href = $('feed').getElementsByTagName("a")[0].href;
		document.getElementsByTagName("head")[0].appendChild(rssLinkTag)
	}
}


/*
** Job actions (show/hide application form)
*/

function bindJobActions()
{
	if ( $$('#applySelf .error, #applySelf .success').length == 0 )
		hideApplySelfForm();
	if ( $$('#applyOther .error, #applyOther .success').length == 0 )
		hideApplyOtherForm();
	$('applySelfButton').show();
	$('applyOtherButton').show();
	$$('.closeForm').invoke('show');
	$$('.applySelfLink').each(function(o){ o.onclick = function(){ showApplySelfForm() } });
	$$('.applyOtherLink').each(function(o){ o.onclick = function(){ showApplyOtherForm() } });
	$$('#applySelf .closeForm a')[0].onclick = function(){ hideApplySelfForm(); return false; };
	$$('#applyOther .closeForm a')[0].onclick = function(){ hideApplyOtherForm(); return false; }
}

function showApplySelfForm()
{
	pageTracker._trackPageview('/applySelf/form.html');
	$('applySelf').show();
	//$('applySelfButton').hide();
	hideApplyOtherForm()
}

function hideApplySelfForm()
{
	$('applySelf').hide();
	$('applySelfButton').show()
}

function showApplyOtherForm()
{
	pageTracker._trackPageview('/applyOther/form.html');
	$('applyOther').show();
	//$('applyOtherButton').hide();
	hideApplySelfForm()
}

function hideApplyOtherForm()
{
	$('applyOther').hide();
	$('applyOtherButton').show()
}


/*
** Employee overview page actions (mouseovers)
*/

function bindEmployeeOverviewList()
{
	var employeeList = $$('div#employeeList li');
	for (i=0, l=employeeList.length; i<l; ++i)
	{	
		employeeLink = employeeList[i].getElementsByTagName("a")[0];
		employeeLink.onmouseover = function() { selectEmployee(this.id.split("linkToEmployee")[1]) }
		employeeLink.onmouseout = function() { deselectEmployee(this.id.split("linkToEmployee")[1]) }
	}
	
	var employeeViews = $$('div.employeeView');
	for (i=0, l=employeeViews.length; i<l; ++i)
	{
		if ( employeeViews[i].getStyle("display") != "none" )
			selectedEmployee = employeeViews[i];
		bgurl = employeeViews[i].getStyle("background-image");
		(new Image).src = bgurl.substring(4, bgurl.length-1)
	}
}

function selectEmployee(employeeId)
{
	selectedEmployee.hide();
	$('employee' + employeeId).show();
}


function deselectEmployee(employeeId)
{
	$('employee' + employeeId).hide();
	selectedEmployee.show();
}


/*
** Incentive overview actions
*/

function bindIncentiveOverviewLists()
{
	var jobs = $$('div#relevant_jobs ul li');
	for (i=0, l=jobs.length; i<l; ++i)
	{	
		jobListItem = jobs[i];
		jobListItem.setStyle({ cursor: 'pointer' });
		jobListItem.onclick = function() { selectJob($(this)) };  // Uses same function as the tagclouds joblist, for now
		jobListItem.onmouseover = function() { $(this).addClassName('hover') };
		jobListItem.onmouseout = function() { $(this).removeClassName('hover') };
		jobListItem.getElementsByTagName('a')[0].onclick = function() { return false }
	}

}