
$(document).ready(OnDomLoaded);

var BASE_URL = "./awards.php";
var PROGRESSIVE_LOAD_CHUNK_SIZE = 1;
var STARS ="<div class='user-rating' id='user-rating-'>\
			<div class='label'>Your rating: </div>\
			<div class='stars'>\
			</div></div>";
var BTN_EXPAND = "./img/expand.bmp";
var BTN_COLLAPSE = "./img/collapse.bmp";

var g_offsetRewardColor = false;
var g_offsetDreamColor = false;
			
//**********************************************************************************************************
//*
//*  RatedItems object
//*
//*  Built to house the user ratings (id, rating, hour) in a cookie until they expire
//*
//**********************************************************************************************************
RatedItems = new Object();
RatedItems.cookie = "ratings"
RatedItems.ids = [];
RatedItems.ratings = [];
RatedItems.times = [];
RatedItems.load = function()
{
	var cookieData = getCookie(RatedItems.cookie)
	if (cookieData == null) return;
	
	var data = cookieData.split("~");
	if (data.length > 1)
	{
		this.ids = data[0].split(",");
		this.ratings = data[1].split(",");
		this.times = data[2].split(",");
	}
}
RatedItems.save = function()
{
	var data = [];
	data.push (this.ids.join(","));
	data.push (this.ratings.join(","));
	data.push (this.times.join(","));
	setCookie(RatedItems.cookie, data.join("~"), 365);
}
RatedItems.add = function(id, rating)
{
	currentHour = Math.floor((new Date()).getTime() / 3600000);
	for (var i = 0; i < this.ids.length; i++)
	{
		if (id > this.ids[i]) continue;
		if (id == this.ids[i])
		{
			// just update the time
			this.times[i] = currentHour;
			this.ratings[i] = rating;
			return i;
		}
		if (id < this.ids[i])
		{
			// insert the id into the array at this point
			this.ids.splice(i,0,id);
			this.ratings.splice(i,0,rating);
			this.times.splice(i,0,currentHour);
			return i;
		}
	}
	this.ids.push(id);
	this.ratings.push(rating);
	this.times.push(currentHour);
	return this.ids.length - 1;
}
RatedItems.exists = function(id)
{
	// TODO: implement a binary search
	for (var i = 0; i < this.ids.length && this.ids[i] <= id; i++)
	{
		if (this.ids[i] == id) return true;
	}
	return false;
}
RatedItems.getRating = function(id)
{
	// TODO: implement a binary search
	for (var i = 0; i < this.ids.length && this.ids[i] <= id; i++)
	{
		if (this.ids[i] == id) return this.ratings[i];
	}
	return null;
}
RatedItems.removeExpired = function(hours)
{
	if (!hours) hours = 23;
	
	var changed = false;
	
	var thisHour = Math.floor((new Date()).getTime() / 3600000);
	for (var i = 0; i < this.ids.length; i++)
	{
		if (thisHour - this.times[i] > hours)
		{
			changed = true;
			this.ids.splice(i,1);
			this.times.splice(i,1);
			this.ratings.splice(i,1);
			i--;
		}
	}
	
	return changed;
}

//**********************************************************************************************************
//*
//*  OnDomLoaded
//*
//*  Initializes the page
//*
//**********************************************************************************************************
function OnDomLoaded() 
{
	// preload any images referenced in css files
	$.preloadCssImages();
	
	// remove all older cookies
	for (var i = 0; i < 80; i++)
	{
		removeCookie('user-rating-' + i);
	}
	
	// load the previously-rated items from the cookie
	RatedItems.load();
	if (RatedItems.removeExpired())
	{
		RatedItems.save();
	}
	
	$('#award-submit-btn').click(OnSubmitAward);
	
	$('.stars').quickRating({numStars:5,split:4});
	$('.rating-demo').quickRating({numStars:5,readOnly:true});
	
	// bind clicks on all future expand/collapse buttons
	$('.btn-expand-collapse').live("click", OnExpandCollapseListItem);
	
	// set up the single displayed star rating for each list item
	$('.dis-star').each(function()
	{
		var Data = $(this).metadata();
		$(this).quickRating(
		{
			numStars : 1,
			split : 5,
			value : Math.round(Data.disRating / 4.0), 
			readOnly : true,
			customRatingTips : [(Data.disRating / 4).toFixed(2)]
		});
	});
	
	// set up the user ratings for each list item
	var id = 0;
	var current_user_rating = null;
	$('.reward-list-item').each(function()
	{
		id = $(this).metadata().id;
		current_user_rating = RatedItems.getRating($(this).metadata().id);
		if (current_user_rating != null)
		{
			// the user has already rated this item, so hide the rating control
			$(this).find('.user-rating').hide();
		}
		else
		{
			// the user still hasn't rated this one so hook up the submit button
			$(this).find('.rate-button').click(OnSubmitRating).data('id', id);
		}
	});

	FillUsernameAndEmail();
	
	//FillRewardList();
	//FillDreamList();
}

function OnExpandCollapseListItem()
{
	if ($(this).hasClass("btn-collapse"))
	{
		// toggle the button
		$(this).removeClass("btn-collapse");
		$(this).addClass("btn-expand");
		
		// hide the content
		$(this).nextAll('.expand-box').toggle();
	}
	else
	{
		// toggle the button
		$(this).removeClass("btn-expand");
		$(this).addClass("btn-collapse");
		
		// show the content
		$(this).nextAll('.expand-box').toggle();
	}
}


//**********************************************************************************************************
//*
//*  FillUsernameAndEmail
//*
//*  Fills in default values for the username and email address based on the cookie
//*
//**********************************************************************************************************
function FillUsernameAndEmail()
{
	var user = getCookie('username');
	var email = getCookie('email');
	//$("#input-new-user").val(user == null ? "" : user);
	$("#input-new-email").val(email == null ? "" : email);
}

//**********************************************************************************************************
//*
//*  FillRewardList
//*
//*  Fills in the reward list with the data from the server
//*
//**********************************************************************************************************
function FillRewardList()
{
	$('#rewards-box>.awards-list-cont>.awards-list').text('');
	ajaxGet(BASE_URL, 
			{
				req:"i",
				start:0,
				count:PROGRESSIVE_LOAD_CHUNK_SIZE
			},
			OnRewardsLoaded);
}

//**********************************************************************************************************
//*
//*  FillDreamList
//*
//*  Fills in the dream list with the data from the server
//*
//**********************************************************************************************************
function FillDreamList()
{
	$('#dreams-box>.awards-list-cont>.awards-list').text('');
	ajaxGet(BASE_URL, 
			{
				req:"a",
				start:0,
				count:PROGRESSIVE_LOAD_CHUNK_SIZE
			},
			OnDreamsLoaded);
}

//**********************************************************************************************************
//*
//*  FormatMysqlDate
//*
//*  Converts a date in MySQL format to a more friendly string representation and returns it
//*
//**********************************************************************************************************
function FormatMysqlDate(mysqldate)
{
	var date = String(mysqldate).replace(/\-/g, '/');
	var d = new Date(date);
	var mm = d.getMonth() + 1;
	var dd = d.getDate();
	var yy = d.getFullYear() % 100;
	var str = "" + mm + "/" + (dd < 10 ? "0" : "") + dd + "/" + (yy < 10 ? "0" : "") + yy;
	return str;	
}

//**********************************************************************************************************
//*
//*  OnSubmitAward
//*
//*  Handles posting the new award data to the server
//*
//**********************************************************************************************************
function OnSubmitAward(event)
{
	var title = fast_trim($('#input-new-title').val());
	var desc = fast_trim($('#input-new-desc').val());
	//var user = fast_trim($('#input-new-user').val());
	var email = fast_trim($('#input-new-email').val());
	var radio = $("input[name='awardType']:checked").val();
	var rating = $('#user-rating-new > .stars').data('quickRating');
	if (title == "" || desc == "" || /* user == "" || */ email == "" || radio == undefined)
	{
		DisplaySubmitError();
		return;
	}
	if (rating == undefined) rating = 0;
	
	// basic attempt to verify the email address
	if (!verifyEmail(email, true))
	{
		DisplayEmailError();
		return;
	}
	
	$.facebox.settings.dismissOnEsc = false;
	$.facebox.settings.dismissOnClick = false;
	$.facebox(function($){
				ajaxPost(BASE_URL,
						{
							req:"add",
							title:title,
							desc:desc,
							user:"",
							email:email,
							offered:(radio == "insp" ? 1 : 0),
							rating:rating
						},
						OnAwardAdded);}
			 );
}

//**********************************************************************************************************
//*
//*  DisplaySubmitError
//*
//*  Displays a general error to the user that all fields are required
//*
//**********************************************************************************************************
function DisplaySubmitError()
{
	var s = '<div style="overflow:auto" class="error-popup"><div style="font-weight:bold;padding:3px 0px 0px 70px;color:#555">Oops!</div><div style="font-weight:bold;padding:7px 0px 0px 70px;color:#555">All fields are required for a new award.</div></div>';
	jQuery.facebox(s);
}

//**********************************************************************************************************
//*
//*  DisplayEmailError
//*
//*  Displays an "invalid email" error to the user
//*
//**********************************************************************************************************
function DisplayEmailError()
{
	var s = '<div style="overflow:auto" class="error-popup"><div style="font-weight:bold;padding:3px 0px 0px 70px;color:#555">Oops!</div><div style="font-weight:bold;padding:7px 0px 0px 70px;color:#555">Please enter a valid email address.</div></div>';
	jQuery.facebox(s);
}

//**********************************************************************************************************
//*
//*  AddToList
//*
//*  Takes an award item from the server and adds it to the given list element
//*
//**********************************************************************************************************
function AddToList(listElem, data, listType)
{
	var RecordCount = data[0];
	if (RecordCount == 0) return;
	for (var i = 2; i <= RecordCount + 1; i++)
	{
		var date = String(data[i].date).replace(/\-/g, '/');
		var d = new Date(date);
		var id = data[i].id;
		
		// create the list item element
		var li = $("<li></li>");
		var content =  "<div class='list-item-cont'>\
						<div class='list-item-rating-cont'>\
						<span class='dis-star'></span>\
						<span class='list-item-rating'>";
		content += (data[i].rating / 4.0).toFixed(2) + " / 5.0";
		content += 	   "</span>\
						</div>\
						<div class='btn-expand-collapse btn-expand'></div>\
						<div class='list-item-title'>";
		content += data[i].title;
		content +=     "</div>";
		content += "<div class='expand-box'><div class='list-item-desc'>" + data[i].desc + "</div>";
		//content += "<div class='list-item-date'><div class='list-item-user'>-" + data[i].user + "</div>&nbsp;on " + FormatMysqlDate(data[i].date) + "</div>";
		content += STARS;
		content += "</div></div>";
		li.append(content);
		
		// offset the background color
		var offsetColor = false;
		if (listType == "reward")
		{
			offsetColor = g_offsetRewardColor;
			g_offsetRewardColor = !g_offsetRewardColor;
		}
		else
		{
			offsetColor = g_offsetDreamColor;
			g_offsetDreamColor = !g_offsetDreamColor;
		}
		if (offsetColor)
		{
			li.find('.list-item-cont').css('background-color', '#cccccc');
		}

		// customize the stars for this list item
		var current_user_rating = RatedItems.getRating(id);
		
		li.find('.user-rating').attr('id', 'user-rating-' + id);
		//li.find('.star').attr('name', 'rate'+id);
		if (current_user_rating == null)
		{
			li.find('.label').text("Rate this:");
			li.find('.user-rating').append("<input class='rate-button' type='button' value=' Submit rating! ' />");
			li.find('.rate-button').click(OnSubmitRating).data('id', id);
		}
		
		// convert the radio buttons to a rating
		li.find('.dis-star').quickRating(
		{
			numStars : 1,
			split : 5,
			value : Math.round(data[i].rating / 4.0), 
			readOnly : true,
			customRatingTips : [(data[i].rating / 4).toFixed(2)]
		});
		if (current_user_rating != null)
		{
			li.find('.stars').quickRating(
			{
				numStars : 5,
				split : 4,
				value : current_user_rating,
				readOnly : true
			});
		}	
		else
		{
			li.find('.stars').quickRating(
			{
				numStars : 5,
				split : 4
			});
		}
		
		// add the element to the list		
		listElem.append(li);
		
		// hide the user's previous rating
		if (current_user_rating != null)
		{
			listElem.find('#user-rating-' + data[i].id).hide();
		}
	}
}

//**********************************************************************************************************
//*
//*  OnSubmitRating
//*
//*  Submits the user's rating to the server and sets a cookie so the user can't rate this item again
//*
//**********************************************************************************************************
function OnSubmitRating(event)
{
	// get the current rating
	var rating = $(this).parent().find('.stars').data('quickRating');//:checked').val();
	if (rating == undefined) rating = 0;
	//rating *= 4;
	
	// get the database id for this rating
	var id = $(this).data('id');
	
	// now replace this div with a submitting... label
	var content="<img src='loading.gif' width=14 height=14> <span style='font-size:82.5%;vertical-align:top;'>Submitting rating...</span>";
	$('#user-rating-' + id).html(content);	
	
	// set the rating cookie for this id
	RatedItems.add(id,rating);
	RatedItems.save();
	
	// submit the rating
	ajaxPost(BASE_URL,
			 {
				req:"rate",
				id:id,
				rating:rating
			 },
			 OnRatingSubmitted);
}

//**********************************************************************************************************
//*
//*  OnRatingSubmitted
//*
//**********************************************************************************************************
function OnRatingSubmitted(success, data, textStatus)
{
	// replace the div with the user's rating
	if (data)
	{
		var id = data['id'];
		var new_rating = data['db-rating'];
		new_rating /= 4.0;
		
		$('#user-rating-' + id).html(STARS);
		$('#user-rating-' + id + ' .stars').quickRating(
		{
			numStars : 5,
			split : 4,
			value : parseInt(RatedItems.getRating(id)),
			readOnly : true
		});
		
		// for now, hide the user's rating
		$('#user-rating-' + id).hide();

		// update the rating for this list item
		$('#user-rating-' + id).parent().find('.dis-star').quickRating({value:Math.round(new_rating)});
		$('#user-rating-' + id).parent().find('.list-item-rating').text(new_rating.toFixed(2) + ' / 5.0');
	}
}

//**********************************************************************************************************
//*
//*  OnRewardsLoaded
//*
//**********************************************************************************************************
function OnRewardsLoaded(success, data, textStatus)
{
	AddToList($('#rewards-box>.awards-list-cont>.awards-list'), data, "reward");

	// if there's more data to load, fire off another request
	if (data && data[0] == PROGRESSIVE_LOAD_CHUNK_SIZE)
	{
		var last_starting_row = parseInt(data[1]);
		ajaxGet(BASE_URL, 
				{
					req:"i",
					start:last_starting_row + PROGRESSIVE_LOAD_CHUNK_SIZE,
					count:PROGRESSIVE_LOAD_CHUNK_SIZE
				},
				OnRewardsLoaded);
	}
}

//**********************************************************************************************************
//*
//*  OnDreamsLoaded
//*
//**********************************************************************************************************
function OnDreamsLoaded(success, data, textStatus)
{
	AddToList($('#dreams-box>.awards-list-cont>.awards-list'), data, "dream");

	// if there's more data to load, fire off another request
	if (data && data[0] == PROGRESSIVE_LOAD_CHUNK_SIZE)
	{
		var last_starting_row = parseInt(data[1]);
		ajaxGet(BASE_URL, 
				{
					req:"a",
					start:last_starting_row + PROGRESSIVE_LOAD_CHUNK_SIZE,
					count:PROGRESSIVE_LOAD_CHUNK_SIZE
				},
				OnDreamsLoaded);
	}
}

//**********************************************************************************************************
//*
//*  OnAwardAdded
//*
//**********************************************************************************************************
function OnAwardAdded(success, data, textStatus)
{
	$.facebox.settings.dismissOnEsc = true;
	$.facebox.settings.dismissOnClick = true;
	if (!success)
	{
		// oops!  just show an error and bail out
		var s = '<div style="overflow:auto" class="error-popup"><div style="font-weight:bold;padding:0px 0px 0px 70px;color:#555">Oops!</div><div style="font-weight:bold;padding:8px 0px 0px 70px;color:#555">Something, somewhere, went wrong!  Please try again later.</div></div>';
		jQuery.facebox(s);
		return;
	}

	var s = '<div style="overflow:auto" class="success-popup"><div style="font-weight:bold;padding:23px 0px 0px 85px;color:#555">Thank you for submitting a reward!</div></div>';
	jQuery.facebox(s);
	
	var radio = $("input[name='awardType']:checked").val();
	var rating = $('#user-rating-new > .stars').data('quickRating');
	if (rating == undefined) rating = 0;
	
	$("#input-new-title").val("");
	$("#input-new-desc").val("");
	$("input[name='awardType']").attr("checked", false);
	$('#user-rating-new > .stars').quickRating({value:0});
	
	// set the accepted username and email in a cookie
	// setCookie('username', fast_trim($('#input-new-user').val()), 365);
	setCookie('email', fast_trim($('#input-new-email').val()), 365);
	
	// set the fact that they already rated their own item in a cookie
	RatedItems.add(data['id'],rating);
	RatedItems.save();
	
	// reload the lists
	if (radio == 'insp')
	{
		FillRewardList();
	}
	else
	{
		FillDreamList();
	}
}

