//////////////////////////////////////
//         GLOBAL VARIABLES         //
//////////////////////////////////////

var apiURL = "/XSS/api.php"; // This is the URL to the local XSS API proxy.
var pageToken = "!!";

var registrationRequest = createRequestObject();
var votingRequest = createRequestObject();
var commentsRequest = createRequestObject();

var commentsTimer;
var votingTimer;

var commentState = 0;
var cachedVote = '';

var userToken = readCookie('gcl_userToken');

//////////////////////////////////////
//             PAGE CALLS           //
//////////////////////////////////////

// REGISTERPAGE(...) - registers page with GCL API, generates pageToken/userToken.
function registerPage(pageTitle, pageAuthor, pageVolume, pageIssue, pageURL) {
	
	var registerString = "apiMode=registerPage&pageTitle=" + escape(pageTitle) + 
		"&pageAuthor=" + escape(pageAuthor) + "&pageVolume=" + escape(pageVolume) + 
		"&pageIssue=" + escape(pageIssue) +	"&pageURL=" + escape(pageURL);
		
	if(userToken != null){
		registerString = registerString + "&userToken=" + escape(userToken);
	}
	
	doAjaxPost(apiURL, pageRegistered, registrationRequest, registerString);
}

// SETUPCOMMENTS(...) - retrieves comments from GCL API and puts them in DIV gcl_comments.
function setupComments(expandState){
	if(pageToken == "!!"){
		commentsTimer = setTimeout('setupComments()', 200);
	}else{
		if(expandState){
			expandState = "&commentsExpanded=1";
		}else{
			expandState = "";
		}
		doAjaxGet(apiURL + "?apiMode=setupComments&pageToken=" + pageToken + expandState, commentsResponse, commentsRequest);
	}
}

// SUBMITCOMMENT() - submits comment from gcl_comments_text and gcl_comments_name via GCL API.
function submitComment(){
	var commentText = document.getElementById('gcl_comments_text').value;
	var displayName = document.getElementById('gcl_comments_name').value;
	if(commentText == "" || displayName == ""){
		alert("Error\n------------------------\nYou did not fill in all the required fields. Double check them, and then try again.");
	}else{
		var postString = "apiMode=submitComment&pageToken=" + pageToken + 
			"&commentUsername=&commentPassword=&commentDisplayName=" + escape(displayName) +
			"&commentText=" + escape(commentText);
		doAjaxPost(apiURL, commentsResponse, commentsRequest, postString);
		document.getElementById('gcl_comments').innerHTML = "<img src='http://gamecolalive.net/images/loading.gif'>";
	}
}

// TOGGLECOMMENTS() - toggles the CSS DISPLAY value for gcl_comments.
function toggleComments(){
	if(commentState == 0){
		document.getElementById('gcl_comments_toggle').style.display = "block";
		commentState = 1;
	}else{
		document.getElementById('gcl_comments_toggle').style.display = "none";
		commentState = 0;
	}
}

// PROFILEPOPUP(...) - opens a new window with profile information.
function profilePopup(accountID){
	window.open('http://gamecolalive.net/profile.php?accountID=' + accountID, 
		'profilePopup', 
		'width=450,height=300,resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no'
	);
}

// SETUPVOTING() - retrieves page rating & rating form from GCL API and puts them in DIV gcl_voting.
function setupVoting(){
	if(pageToken == "!!"){
		votingTimer = setTimeout('setupVoting()', 200);
	}else{
		doAjaxGet(apiURL + "?apiMode=setupVoting&pageToken=" + pageToken, votingResponse, votingRequest);
	}
}

// SETVOTE(...) - stores the selected score in var and updates submission form.
function setVote(ratingScore){
	cachedVote = ratingScore;
	document.getElementById('ratingSubmitBtn').value = 'Rate this: ' + ratingScore;
	document.getElementById('ratingSubmitBtn').disabled = false;
}

// RATEPAGE() - submits the selected score and displays updated score.
function ratePage(){
	var rateString = "apiMode=ratePage&pageToken=" + pageToken + "&ratingScore=" + escape(cachedVote) + 
		"&userToken=" + escape(userToken);
	doAjaxPost(apiURL, votingResponse, votingRequest, rateString);
	document.getElementById('gcl_voting').innerHTML = "<img src='http://gamecolalive.net/images/loading.gif'>";
}

// SHOWLOGINFORM() and REGISTERPOPUP() - this will go away, you'll see.
function showLoginForm(){
	alert("This feature is coming soon, but is not available at this time.\n\nPlease continue to post anonymous as you have been so far. We are pleased to be able to say that this feature will be live before long.");
}
function registerPopup(){
	showLoginForm();
}

//////////////////////////////////////
//           AJAX CALLBACKS         //
//////////////////////////////////////

// PAGEREGISTERED() - receives pageToken/userToken and stores in vars/cookies.
function pageRegistered(){
	if(registrationRequest.readyState == 4){
			var apiData = registrationRequest.responseText;
		var apiSet = apiData.split("|");
		if(apiSet[0] == "ERROR"){
			alert("The following GameCola Live error occured:\n\n" + apiSet[1] + 
				"\n\nAs a result, one or more elements of the page may not load. Additionally, " +
				"any submissions you have made may not have been processed.");
		}else{
			var tokenSet = registrationRequest.responseText;
			var tokenVars = tokenSet.split("//");
			pageToken = tokenVars[0];
			if(tokenVars[1]){
				createCookie('gcl_userToken', tokenVars[1], 30);
				userToken = tokenVars[1];
			}
		}
	}
}

// COMMENTSRESPONSE() - receives comments and comment form and puts it in DIV gcl_comments.
function commentsResponse(){
	if(commentsRequest.readyState == 4){
		var apiData = commentsRequest.responseText;
		var apiSet = apiData.split("|");
		if(apiSet[0] == "ERROR"){
			alert("The following GameCola Live error occured:\n\n" + apiSet[1] + 
				"\n\nAs a result, one or more elements of the page may not load. Additionally, " +
				"any submissions you have made may not have been processed.");
		}else{
			document.getElementById('gcl_comments').innerHTML = commentsRequest.responseText;
		}
	}
}

// VOTINGRESPONSE() - received score & scoring form and puts it in DIV gcl_voting.
function votingResponse(){
	if(votingRequest.readyState == 4){
		var apiData = votingRequest.responseText;
		var apiSet = apiData.split("|");
		if(apiSet[0] == "ERROR"){
			alert("The following GameCola Live error occured:\n\n" + apiSet[1] + 
				"\n\nAs a result, one or more elements of the page may not load. Additionally, " +
				"any submissions you have made may not have been processed.");
		}else{
			document.getElementById('gcl_voting').innerHTML = votingRequest.responseText;
		}
	}
}

//////////////////////////////////////
//           AJAX FUNCTIONS         //
//////////////////////////////////////

// DOAJAXPOST(...) - Setup a POST call with payload to the API server and register callback.
function doAjaxPost(ajaxURL, ajaxCallback, ajaxObject, ajaxPayload) {
	ajaxObject.open('post', ajaxURL);
	ajaxObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	ajaxObject.send(ajaxPayload);
	ajaxObject.onreadystatechange = ajaxCallback;
}

// DOAJAXGET(...) - Setup a GET call to the API server and register callback.
function doAjaxGet(ajaxURL, ajaxCallback, ajaxObject){
	ajaxObject.open('get', ajaxURL);
	ajaxObject.onreadystatechange = ajaxCallback;
	ajaxObject.send(null);
}

// CREATEREQUESTOBJECT() - Return a new XMLHttpRequest() object or ActiveX XMLHTTP object.
function createRequestObject(){
    var requestObject;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        requestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        requestObject = new XMLHttpRequest();
    }
    return requestObject;
}

//////////////////////////////////////
//           COOKIE CALLS           //
//////////////////////////////////////

// CREATECOOKIE(...) - Set a new cookie in the browser with the specified data.
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

// READCOOKIE(...) - Read the specified cookie from the browser.
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// CLEARCOOKIE(...) - Delete the specified cookie from the browser.
function eraseCookie(name) {
	createCookie(name,"",-1);
}
