﻿function MakeZoomCall(url, parameters, callback, argument)
{
	var match = /(.*?)index.aspx/;
	destination = location.href.match(match)[1];		
	var proxy = new Ext.data.HttpProxy({'url': destination + url});
	var MsgDef = Ext.data.Record.create([{name: 'message'},{name: 'error', mapping: 'is-error'}]);
	var reader = new Ext.data.JsonReader({totalProperty: 'msg-count', root: 'messages', id: 'msg-id'}, MsgDef);
	proxy.load(parameters, reader, callback, null, argument);
}

function GetRegexMatch(item, regex, index)
{
	if (item.id)
	{
		reg = eval('/' + regex + '/');
		var match = item.id.match(reg);
		if (match)
		{
			return match[index];
		}
		else
		{
			temp = item.id.split('_');
			if (temp)
			{
				return temp[index];
			}
		}
	}
	return null;
}

/* ^^^^^^^^^^^^^^^^^^^^ EVERYTHING ABOVE THIS IS LIBRARY CODE ^^^^^^^^^^^^^^^^^^^^^^^^^^^ */

/*
 This is called by the Zoom Galleries in order to show the current rating for a Zoom Item
*/
function GetStar(articleId)
{
	MakeZoomCall("zoom.ashx", {'lclarticleid': articleId, action: 'GetArticleStar'}, UpdateStar, articleId);
}

/*
	This is the callback invoked when the request to get a Zoom Item's current rating returns successfully. The 
	returned JSON Message should contain a 2 element array where index 0 is the article and index 1 is the rating.
*/		
function UpdateStar(ds, arg, success)
{
	if (success)
	{
		var record = ds.records[0];
		var msg = record.get('message');
		if (record.get('error') == 'false')
		{
			score = msg[1];
			crate = document.getElementById('crate_' + arg);
			if (crate != null && score > 0)
				crate.src = './images/stars/stars' + Math.round((score/2)/5,0)*5 + '.gif';
		}
	}
}

/* ^^^^^^^^^^^^^^^^^^^^ EVERYTHING ABOVE THIS IS GALLERY RELATED ^^^^^^^^^^^^^^^^^^^^^^^^^^^ */

/*
	This is called by the Zoom Item in order to get the rating of the focused item
*/
function GetRating(articleId)
{
	if (articleId > 0)
	{
		initRateThis(articleId);
		MakeZoomCall("zoom.ashx", {'lclarticleid': articleId, action: 'GetArticleRate'}, UpdateRating, articleId); 
	}
	else if (articleId < 0)
	{
		alert('Sorry your vote has already been counted please try again tomorrow');
	}
}

/*
	This is the callback invoked when the request to get the focused Zoom Item's current rating returns successfully.
	The returned JSON message comprises a 7 part array that contains the Article Id, Rating and votes for each
	of the five categories.
*/
function UpdateRating(ds, arg, success)
{
	if (success)
	{
		var record = ds.records[0];
		var msg = record.get('message');
		if (record.get('error') == 'false')
		{
			// Set stars for focus
			score = msg[1];
			cdrate = document.getElementById('cdrate_' + arg);
			if (cdrate && score > 0)
				cdrate.src = './images/stars/stars' + Math.round((score/2)/5,0)*5 + '.gif';

			totalVotes = 0;
			for (index = 2; index < msg.length; index++)
				totalVotes += parseInt(msg[index], 10);
				
			// Set vote total for "rate this"
			total = document.getElementById('rate_' + arg + '_count');
			if (total)
			{
				if (totalVotes)
					total.innerHTML = totalVotes + ' votes so far in total';
				else
					total.innerHTML = ' no votes so far';
			}
			
			// Set bar heights
			for (index = 2, bar = 1; index < msg.length; index++, bar++)
			{
				barImg = document.getElementById('cdrate_' + arg + '_' + bar);
				if (barImg)
				{
					if (msg[index] > 0 && totalVotes > 0)
						barImg.height = Math.round((msg[index] / totalVotes) * 50);
					else
						barImg.height = 0;
				}
			}
		}
	}
}

/*
	This is called as part of the initialisation and links up the AJAX functionality to the "rate this" box
*/
function initRateThis(articleId)
{
	// Link up the "rate this" box
	var h = document.getElementById('ratethis_' + articleId);
	if (h)
	{
		var l = h.getElementsByTagName('a');
		for (i=0; i<l.length;i++)
		{
			articleId = GetRegexMatch(l[i], '[a-z]+_([1-9]+)_([1-9]+)$', 1);
			if (articleId)
				l[i].href = '#vw' + articleId;
			l[i].onmouseover = function() 
			{ 
				articleId = GetRegexMatch(this, '[a-z]+_([1-9]+)_([1-9]+)$', 1);
				rating = GetRegexMatch(this, '[a-z]+_([1-9]+)_([1-9]+)$', 2);
				if (articleId && rating)
					ShowRate(articleId, rating);
			};
			l[i].onfocus = l[i].onmouseover;
			l[i].onmouseout = function() 
			{ 
				articleId = GetRegexMatch(this, '[a-z]+_([1-9]+)_([1-9]+)$', 1);
				if (articleId)
					ShowRate(articleId, 0);
			};
			l[i].onblur = l[i].onmouseout;
			l[i].onclick = function()
			{
				articleId = GetRegexMatch(this, '[a-z]+_([1-9]+)_([1-9]+)$', 1);
				rating = GetRegexMatch(this, '[a-z]+_([1-9]+)_([1-9]+)$', 2)
				if (articleId && rating)
					SetRate(articleId, rating);
			}
		}
	}
	
	// Link up the spam/offensive
	var s = document.getElementById('spam_' + articleId);
	if (s != null)
	{
		s.onclick = function()
		{
				articleId = GetRegexMatch(this, '[a-z]+_([1-9]+)$', 1);
				if (articleId)
					SetRemove(articleId, 1);
		}
	}
	var o = document.getElementById('offensive_' + articleId);
	if (o != null)
	{
		o.onclick = function()
		{
				articleId = GetRegexMatch(this, '[a-z]+_([1-9]+)$', 1);
				if (articleId)
					SetRemove(articleId, 2);
		}
	}
}

/*
	This updates the star ratings for the "rate this" box
*/
function ShowRate(articleId, rating)
{
	for ( i = 1;  i < 6; i++ ) {
		img = document.getElementById('srate_' + articleId + '_' + i);
		if (img)
			if (i <= rating)
					img.src = "./images/stars/blue_star.gif";
			else
					img.src = "./images/stars/blank_star.gif";
	}
}

/*
	This sets the rating for the user
*/
function SetRate(articleId, rating)
{
	MakeZoomCall("zoom.ashx", {'lclarticleid': articleId, 'lclrating': rating, 'action': 'SetArticleRate'}, HandleSetRate, articleId);
	return false;
}

/*
	This is the callback invoked when the attempt to set the rating returns
*/
function HandleSetRate(ds, arg, success)
{
	if (!success)
		GetRating(arg)
	else
	{
		var record = ds.records[0];
		var msg = record.get('message');
		if (msg)
		{
			var articleId = parseInt(msg[0], 10);
			if (articleId > 0)
			{
				GetRating(articleId);
			}
			else if (articleId < 0)
			{
				alert('Sorry your vote has already been counted please try again tomorrow');
			}
		}
	}
}

/*
	This states that the user believes the item is either spam or offensive
*/
function SetRemove(articleId, rating)
{
	MakeZoomCall("zoom.ashx", {'lclarticleid': articleId, 'lclrating': rating, 'action': 'SetArticleRemove'}, HandleSetRemove, articleId);
}

/*
	This is the callback invoked then the attempt to set the item as either spam or offensive returns
*/
function HandleSetRemove(ds, arg, success)
{
	if (success)
	{
		var record = ds.records[0];
		var msg = record.get('message');
		if (msg != '')
			alert(msg);	
	}
}

/* Simple functions to replace current page rating with set rating (div swap) */
function ratingSwitchOver()
{
	document.getElementById('actualrating').style.visibility = 'hidden';
	document.getElementById('makerating').style.visibility = 'visible';
}

function ratingSwitchOut()
{	
	document.getElementById('makerating').style.visibility = 'hidden';		
	document.getElementById('actualrating').style.visibility = 'visible';
}


