// JavaScript Document

var cookie = CF.cookie;

var thisRound = {};
thisRound.count = 6;
thisRound.brackets = 64/Math.pow(2,thisRound.count);
thisRound.voted = false;
/*
thisRound.b1 =  { seed1:  1, seed2: 10, choice: null };
thisRound.b2 =  { seed1: 23, seed2: 31, choice: null };
thisRound.b3 =  { seed1: 34, seed2: 48, choice: null };
thisRound.b4 =  { seed1: 55, seed2: 59, choice: null };


thisRound.b1 =  { seed1: 1, seed2: 23, choice: null };
thisRound.b2 =  { seed1: 34, seed2: 55, choice: null };
*/

thisRound.b1 =  { seed1: 23, seed2: 34, choice: null };


thisRound.complete = function() { 
	for ( var i = 1; i <= thisRound.brackets; i++ ) { 
		if ( !this['b'+i].choice ) { return false; }
	}
	return true;
}

jQuery(document).ready( function() {
	if ( ctx.auth_user ) {
		jQuery(".columns .content .buttons #loginBtn").html('&nbsp;');
		jQuery.get("ajax/checkUser.php", { user: ctx.auth_user.user_name }, handleCheckUser, 'json' );
	}
	if ( cookie.readCookie('cVotes') ) {
		votes = cookie.readCookie('cVotes').split(',');
		for ( var i = 0; i < votes.length; i++ ) {
			var c = votes[i];
			var b = Math.ceil(c/Math.pow(2,thisRound.count));
			pos = (c == thisRound['b' + b].seed1) ? 'first' : 'second'; 
			thisRound['b' + b].choice = c;
			var box = '#R' + thisRound.count + 'B' + b;
			//var bg = 'images/bg_biggerBox'+pos+'_07.gif';
			var bg = 'images/bg_finalsBox'+pos+'_15.gif';
			jQuery(box).css("background","url("+bg+") 0 0 no-repeat");
		}
	}
});

jQuery(window).unload( saveVotes );


/**
 * Handles object o returned from checkUser.php
 * @param o an object with 2 properties
 * 		o.voted = 0 or 1
 * 		o.user = auth_user.user_name
 * If o.voted is true, place message in .buttons div
 */
function handleCheckUser(o) {
	if ( o.voted === 1 ) {
		jQuery(".columns .content .buttons").html('<div class="alreadyVoted">You have already voted this week. Please come back next week to vote again.</div>');
		thisRound.voted = true;
	}
	/*
	else {
		jQuery(".columns .content .buttons").html('<a href="#" onclick="return false;" id="submitVoteBtn">Submit Vote</a>');	
	}
	*/
}

/**
 * Sets a cookie with the values of the ballots cast thus far
 */
function saveVotes() {
	var cValue = [];
	for ( var i = 1; i <= thisRound.brackets; i++ ) {
		if ( thisRound['b'+i].choice ) {
			cValue.push(thisRound['b'+i].choice);
		}
	}
	cookie.createCookie( 'cVotes', cValue.join() );
}

/**
 * Called when user clicks on a bracket
 * @param bracket is a string of pattern 'RxBy'
 *		where x is the round and y is the bracket
 * 
 * Builds html and calls CF.modal
 */
function getBallot( bracket ) {
	var pattern = /R(\d+)B(\d+)/;
	bracket.match(pattern);
	var myRound = RegExp.$1;
	var myBracket = RegExp.$2;
	jQuery.get("ajax/ballot.php", { bracket: bracket }, buildBallot, 'json');
	
	function buildBallot( data ) {
		var html = '';
		jQuery.each( data, function( place, seed ) {
			if ( seed.description === null ) { seed.description = ''; }

			
			html += '<div class="seed ' + place + '">' + 
					'<div style="height:145px; overflow:hidden;">' + 
					'<div class="org">' + seed.display_name + '</div>' + 
					'<a href="' + seed.url + '" class="url" target="_blank">' + seed.url + '</a>' + 
					'<div class="description">' + seed.description + '</div>' + 
					'</div>' + 
					'<a href="profile.php?seed_id=' + seed.seed_id + '" class="profile" onclick="saveVotes();">' + 
						'View Profile Page</a>';
			if ( !ctx.auth_user ) {
				html += '<a href="/account/login.php" class="login">Log In to Vote</a>';
			}
			else if ( !thisRound.voted ) {
				html += '<a href="#" class="vote" onclick="castVote('+myBracket+','+seed.seed_id+',\''+ place +'\');return false;">Vote</a>';
			}
			html += '</div>';
		}); 
		CF.modal.show( html, null, {width:780,height:230} );
	}
}

/**
 * Called when user clicks on vote button on ballot
 * 
 * @param {string} myBracket
 * @param
 * @param
 */
function castVote(myBracket,seed_id,pos) {
	thisRound['b'+myBracket].choice = seed_id;
	var box = '#R' + thisRound.count + 'B' + myBracket;
	//var bg = 'images/bg_bracketBox'+pos+'.gif';
	//var bg = 'images/bg_biggerBox'+pos+'_07.gif';
	var bg = 'images/bg_finalsBox'+pos+'_15.gif';
	jQuery(box).css("background","url("+bg+") 0 0 no-repeat");
	CF.modal.hide();
}

function tallyVotes() {
	if ( !ctx.auth_user ) {
		alert("You must be logged in in order to vote.");
		return;
	}
	if ( !thisRound.complete() ) {
		alert("You must complete all brackets before you submit your votes.");
		return;
	}
	var submitChoices = new Array();
	for ( var i = 1; i <= thisRound.brackets; i++ ) {
		submitChoices[i] = thisRound['b'+i].choice;
	}	
	submitChoices = submitChoices.join(',');
	jQuery.get("ajax/tallyVotes.php", { choices: submitChoices, user: ctx.auth_user.user_name, myRound: thisRound.count }, handleVoteReturn, 'json' );
}

function handleVoteReturn(r) {
	cookie.eraseCookie('cVotes');
	window.location.replace("thankyou.php"); 
}