// okay, this is where the magic happens
// this automatically draws the forms when people select stuff
// need to figure out how data is being passed to the submodules
// AHA!
// form generation is driven by directory_config
// which is pased by main directory module 


// Global Killswitch
if (isJsEnabled()) {
  addLoadEvent(directory_search_form);
}

// does something about finding what modules exist
function directory_get_hook(module) {
  var module = arguments[0];
  if (eval('typeof(' + module + '_directory)') == "function") return eval(module + '_directory');
  return false;
}

var directory_fields = []
var last_update = new Date();
var last_query = null;
var query_cache = [];


// creates directory search form based on installed modules and this 'field settings'
// which is part of directory config
function directory_search_form() {
  var fields = [];
  var field_settings = directory_config.field_settings;
  for (var n in field_settings) {
    var field_class = directory_get_hook(field_settings[n].module);
    var weight = field_settings[n].weight;
    directory_fields[n] = new field_class(field_settings[n]);
  }
  var min = 999;
  var max = -999;
  for (var n in fields) {
    if (n < min) min = n;
    if (n > max) max = n;
  }
  
  var search_fields = document.createElement('DIV');
  var title = document.createElement('DIV');
  title.innerHTML = directory_config.label;
  title.className = 'directory_title';
  search_fields.appendChild(title);
  
  var description = document.createElement('DIV');
  description.className = 'directory_description';
  description.innerHTML = directory_config.description;
  search_fields.appendChild(description);
  
  // looks at fields defined when the form loads
  for (var n in directory_fields) {
    var field = document.createElement('DIV');
    field.className = 'directory_field';
    unique_id = field_settings[n].label;
    unique_id = unique_id.replace(/ /,"_");
    unique_id = unique_id.toLowerCase();
    field.id = unique_id;
    var title = document.createElement('H3');
    title.innerHTML = field_settings[n].label;
    field.appendChild(title);
    field.appendChild(directory_fields[n].field());
    search_fields.appendChild(field);
  }
  var search_form = $('directory_search');
  
  while (search_form.hasChildNodes()) {
    search_form.removeChild(search_form.childNodes[0]);
  }
  search_form.appendChild(search_fields);

  //var button = document.createElement('INPUT');
  //button.type = 'button';
  //button.value = 'submit';
  //button.className = 'directory_search_button';
  //button.onclick = function() {
  //  directory_update();
  //}
  //search_form.appendChild(button);
  directory_update();
}

// this is where the magic happens...
function directory_update() {
  var flood_interval = 000;
  var current_time = new Date();
  var query = [];
  for (var n in directory_fields) {
     var temp = directory_fields[n].value();
     if (typeof(temp) != 'undefined') query[n] = temp
  }
  query = obj2query(query);
  // alert(query);
  var loading = false;
  if(current_time - last_update > flood_interval)  {
    if (query != last_query) {
      directory_clear_output(true);
      last_query = query;
      last_update = current_time;
      directory_list(query, 0);
    }
  }
  else {
    if (query != last_query) {
      directory_clear_output(true);
      setTimeout(directory_update, flood_interval - (current_time-last_update));
    }
  }
}

// clears output - perhaps this refers to the results container?
function directory_clear_output(loading) {
  var output = $('directory_output');
  while (output.hasChildNodes()) {
    output.removeChild(output.childNodes[0]);
  }
  if (loading) {
    var loading = document.createElement('span');
    loading.className = 'directory_loading';
    loading.innerHTML = 'loading...';
    $('directory_output').appendChild(loading);
  }
}

// sends a query to drupal, it would appear
function directory_list(query, page) {
  if (!query_cache[query]) query_cache[query] = [];
  if (!query_cache[query][page]) {
  	if(query == ''){
	    string = directory_base_url + 'directory/' + directory_config.directory_name + '/search';
  	} else {
    	string = directory_base_url + 'directory/' + directory_config.directory_name + '/search?' + query + '&page=' + page;
  	}
    // string = directory_base_url + 'directory/' + directory_config.directory_name + '/search?' + query + '&page=' + page;
  	// string = directory_base_url + 'directory/' + directory_config.directory_name + '/search?' + query;

  	// alert(string);
  	
  	//    HTTPGet(directory_base_url + 'directory/' + directory_config.directory_name + '/search?' + query + '&page=' + page, directory_load, {'query' : query, 'page' : page});
    HTTPGet(string, directory_load, {'query' : query, 'page' : page});
		// alert(query);
		// alert(page);
  }
  else {
    directory_output(query_cache[query][page], query, page);
  }
	// alert(query);
}

// handles return values from db queries
// fires off directory_list
function directory_load(string, ajax, query) {
	// alert('results returned');
  if (ajax.status != 200 && typeof ajax.status != 'undefined') {
    return alert('An HTTP error ' + ajax.status + ' occured.\n' + directory_base_url + 'directory/' + directory_config.directory_name + '/search?' + query.query + '&page=' + query.page);
  }
  //alert(string);
  var data = parseJson(string);
  query_cache[query.query][query.page] = data;
  directory_output(data, query.query, query.page);
}

// parses returned values from drupal
function directory_output(data, query, page) {
	// alert(typeof data);
	// alert(parseInt(data.datalength));
  for (var n in data.settings) {
  	// alright, something is causing this to break. It appears to be related
  	// to the fancy buttons search type
  	// wh00t - got it, this is called within each installed module configured
  	// for the search - without it, there is no search going on...
    directory_fields[data.settings[n].field_id].update(data.settings[n]);
  	// alert(data.settings[n]);
  }
  directory_clear_output();
  var output = $('directory_output');
  var pager_required = false;
  
  // determines if a pager is necessary or not
  if (parseInt(data.datalength) > parseInt(directory_config.page_length)) {
  	pager_required = true;
  }
  
  output.appendChild(directory_total_results(data.datalength));
  if (pager_required) output.appendChild(directory_pager(data.datalength, query, page));
  output.appendChild(directory_page(data.records));
  if (pager_required) output.appendChild(directory_pager(data.datalength, query, page));
}

// adds pager elements in cases where there are a lot of results returned
function directory_pager(length, query, page) {
  // console.log('called with length %o, query %o, page %o', length, query, page);

  var pager = document.createElement('DIV');
  pager.className = 'directory_pager';
  var n = 0;
  // console.log('length %o is something to %o page length', length, directory_config.page_length);
  if (+length > +directory_config.page_length) {
  // console.log('length %o is larger to %o page length', length, directory_config.page_length);
    while (n * directory_config.page_length < length) {
      if (n == page) {
        var link = document.createElement('SPAN');
      }
      else {
        var link = document.createElement('A');
        link.page = n;
        link.onclick = function() {
          directory_list(query, this.page);
        }
      }
      link.className = 'pager';
      link.innerHTML = n+1;
      pager.appendChild(link);
      n++;
    }
  }
  // console.log('pager %o', pager);
  return pager;
}

// displays number of results returned from a search
function directory_total_results(total) {
  var total_results = document.createElement('DIV');
  if (directory_config.type_label == 'All' ) directory_config.type_label = 'result';
  if (directory_config.type_label == 'StoryBank') directory_config.type_label = 'Project';
  var html = 'your search returned <span class="search_total">' + total + '</span> ' + directory_config.type_label;
  if (total != 1) html += 's';
  total_results.innerHTML = html;
  total_results.className = 'search_total_text';
  return total_results;
}

function directory_page(records) {
  var content = document.createElement('DIV');
  for (var n in records) {
    var row = document.createElement('DIV');
    /*var title = document.createElement('H1');
    var link = document.createElement('A');
    link.href = (directory_default_page == '' ? directory_base_url + 'node' : directory_default_page) + '/' + records[n].nid;
    link.innerHTML = records[n].title;
    title.appendChild(link);
    row.appendChild(title);
    var teaser = document.createElement('DIV');
    row.appendChild(teaser);*/
    row.innerHTML = records[n];
    content.appendChild(row);
  }
  return content;
}

// heh, this is a fun one
// unsure what it really does
function obj2query(obj,path,new_path) {
	if (typeof(path)=="undefined") var path=[];
	if (typeof(new_path)!="undefined") path.push(new_path);
	var post_str=[];
	if (typeof(obj)=="array" || typeof(obj)=="object") for (var n in obj) post_str.push(obj2query(obj[n],path,n));
	else {
		var base=path.shift();
		post_str.push(base+(path.length>0?"["+path.join("][")+"]":"")+"="+encodeURI(obj));
		path.unshift(base);
		}
	path.pop();
	return post_str.join("&");
	}

