/* This is a poorly written JS file. The challenge with posting multiple pages
 * is that you need to configure the server to receive multiple pages. I'm
 * not quite ready for that yet.
 */


//Temporary variable to hold the query. We need to use this temporary variable instead of reading it 
//as a parameter from the URL because the home page doesn't have the query as a parameter 
var tempQuery;

/**
 * Called when there is a search. This assumes the search form is called "searchForm"
 * @return
 */
function onSubmit() {
  var query = document.searchForm.query.value;
  queryTwitterApi(query);
}

/**
 * Queries the Twitter API via JSON
 * @param query
 * @return
 */
function queryTwitterApi(query) {
  tempQuery = query;
  var tweetsUrl = "http://search.twitter.com/search.json?lang=en&rpp=100&callback=sendToServer&q=" + query;
  var script = document.createElement("script");
  script.setAttribute('src', tweetsUrl);
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}

/**
 * Posts the JSON results to the server
 * @param json
 * @return
 */
function sendToServer(json) {
  //http://www.json.org/js.html  
  var jsonString = JSON.stringify(json);
  //debug(jsonString);
  //document.searchForm.jsonData.value = jsonString;
  
  var url = "search?query=" + tempQuery;
  
  var params = [];
  params["query"] = tempQuery;
  params["jsonData"] = jsonString;
  
  var aggregationType = gup("aggregationType");
  if(aggregationType != null && aggregationType != "") {
    params["aggregationType"] = aggregationType;
  }
  
  postToUrl(url, params);
}

/**
 * Code from http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
 * @param path
 * @param params
 * @param method
 * @return
 */
function postToUrl(path, params, method) {
  method = method || "post"; // Set method to post by default, if not specified.

  var form = document.createElement("form");
  form.setAttribute("method", method);
  form.setAttribute("action", path);

  for(var key in params) {
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", key);
    hiddenField.setAttribute("value", params[key]);
    form.appendChild(hiddenField);
  }

  document.body.appendChild(form);
  form.submit();
}

