/**
 * provides namespacing for the Fight Log Application PHP version
 */
var logApp = {};

/**
 * Sends an AJAX request to the server to retrieve a list of videos or
 * the video player/metadata.  Sends the request to the specified filePath
 * on the same host, passing the specified params, and filling the specified
 * resultDivName with the resutls upon success.
 * @param {String} filePath The path to which the request should be sent
 * @param {String} params The URL encoded POST params
 * @param {String} resultDivName The name of the DIV used to hold the results
 */
logApp.sendRequest = function(filePath, params, resultDivName) {
  if (window.XMLHttpRequest) {
    var xmlhr = new XMLHttpRequest();
  } else {
    var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0');
  }

  xmlhr.open('POST', filePath);
  xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

  xmlhr.onreadystatechange = function() {
    var resultDiv = document.getElementById(resultDivName);
    if (xmlhr.readyState == 1) {
      //resultDiv.innerHTML = '<b>Loading...</b>'; 
    } else if (xmlhr.readyState == 4 && xmlhr.status == 200) {
      if (xmlhr.responseText) {
        resultDiv.innerHTML = xmlhr.responseText;
      }
    } else if (xmlhr.readyState == 4) {
      alert('Invalid response received - Status: ' + xmlhr.status);
    }
  }
  xmlhr.send(params);
}


logApp.getPlayerList = function(lastName) {
  if (lastName != '' && lastName.length > 1)
  {
	  var params = 'operation=list_players&ln=' + urlencode(lastName);
	  var filePath = 'logops.php';
	  logApp.sendRequest(filePath, params, 'resultsDiv');
  }
  else
  {
  	document.getElementById('resultsDiv').innerHTML = 'Enter more characters or click the search button.';
  }
}

logApp.getPlayerListSubmitted = function(lastName) {
  if (lastName != '')
  {
	  var params = 'operation=list_players&ln=' + urlencode(lastName);
	  var filePath = 'logops.php';
	  logApp.sendRequest(filePath, params, 'resultsDiv');
  }
  else
  {
  	document.getElementById('resultsDiv').innerHTML = "You didn't enter a last name to search for!";
  }
}

/**
 * Create a basic HTML form to use for creating a new playlist.
 */
logApp.prepareNameSearchForm = function() {
  var newNameSearchForm = ['<form id="searchForm" ',
    'onsubmit="logApp.getPlayerListSubmitted(this.lastName.value); return false; ">',
    'Enter last name of player:&nbsp;&nbsp;',
    '<input size="30" name="lastName" type="text" onkeyup="logApp.getPlayerList(this.value);"/>&nbsp;&nbsp;',
    '<input type="submit" value="Search" class="formbutton">',
    '</form>'].join('');
    
  document.getElementById('searchFormDiv').innerHTML = newNameSearchForm;
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function showDetails(logID)
{
	document.getElementById('searchDiv').style.display = 'none';
	HTML_AJAX.replace('detailsDiv', 'fight.php?id=' + logID);
	document.getElementById('detailsWrapper').style.display = '';	
	
}

function hideDetails()
{
	if (document.getElementById('searchDiv') == null)
	{
		parent.history.back();
	}
	else
	{
		document.getElementById('searchDiv').style.display = '';
		document.getElementById('detailsWrapper').style.display = 'none';
		document.getElementById('detailsDiv').innerHTML = '';
	}
}

function showBack()
{
	if (document.getElementById('searchDiv') != null)
	{
		//alert('not null');
		document.getElementById('backDiv').innerHTML = '<center><a title="Back" alt="Back to Search Results" href="javascript:hideDetails();">Back</a></center>';
	}
}

function getURL(url)
{
	location.href = url;
}
