
/* contains all the data about the pictures (set after the page is
   loaded) */
var search_data;

function get_query_variable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return '';
}
  
/* Remove the loading message and get the search data
 */
function page_loaded() {
  search_data = sd;
  
  if (document.getElementById){
    document.getElementById('loading').style.visibility='hidden';
  } else {
    if (document.layers){ //NS4
      document.loading.visibility = 'hidden';
    } else { //IE4
      document.all.loading.style.visibility = 'hidden';
    }
  }
  search_string = decodeURIComponent(get_query_variable('q'));
  set_search_string(search_string);
  var word_search = get_query_variable('w');
  if (word_search=='1') {
    word_search = true;
  } else {
    word_search = false;
  }
  document.getElementById('search_word').checked = word_search;
  perform_search(search_string, word_search);

  if (document.layers) {
    document.captureEvents(Event.KEYPRESS);
  }
}

/* Return a copy of str, translating all occurrences of each character
   in from to the corresponding character in to
*/
String.prototype.strtr = function(from, to)
{
  var s, p, c1, c2, c3;
  if(! this.length || from.length != to.length) return;
	
  s = this;	
  for(var i=0; i < this.length; i++) {
    c1 = this.substr(i,1);
    for(var j=0; j<from.length; j++) {
      c2 = from.substr(j,1);
      c3 = to.substr(j,1);
      if(c1 == c2) {
	p = new RegExp(c2,'gi');
	s = s.replace(p,c3);
      }
    }
  }
  return s;
};

/* Return a copy of str, removing all accents in it
 */
function remove_accents(string) {
  return string.strtr(
"ÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ",
"AAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy");
}


/* set the string in the query input
 */
function set_search_string(search_string) {
  var input = document.getElementById('search_string');
  input.value = search_string;
}

/* return the string entered by the user, normalized
 */
function get_search_string() {
  var input = document.getElementById('search_string');
  var search_string = remove_accents(input.value.toLowerCase());

  return search_string;
}

/* return a list of keywords from the string entered by user
 */
function get_keywords(search_string, word_search) {
  if (! search_string ) {
    return new Array;
  }
  keywords = search_string.split(/[^a-z0-9]+/i);

  var result = new Array;
  for (var i=0; i<keywords.length; i++) {
    if (keywords[i]) {
      if (word_search) {
	result[result.length] = " " + keywords[i] + " ";	
      } else {
	result[result.length] = keywords[i];
      }
    }
  }
  return result;
}

/* replace a %parameter% in the template by its value
 */
function set_value(template, parameter, value) {
  re = new RegExp("%"+parameter+"%", "g");
  return template.replace(re, value)
}

/* display one found result in the page
 */
function display_result(results, image) {
  result = result_html;
  result = set_value(result, 'url', image.url);
  result = set_value(result, 'thumb_url', image.thumb_url);
  result = set_value(result, 'album_url', image.album_url);
  result = set_value(result, 'album_title', image.album_title);
  result = set_value(result, 'title', image.title);
  result = set_value(result, 'thumb_width', image.width);
  result = set_value(result, 'thumb_height', image.height);
  
  results.innerHTML += result;
}

/* update the status string on the page
 */
function update_status(status, found) {
  status.firstChild.nodeValue = "Search in progress: " + found.toString() +" found";  
}

/* return true if all keywords (array of string) match the string s
 */
function match(keywords, s){
  for (var i=0 ; i<keywords.length ; i++) {
    if (keywords[i] && s.indexOf(keywords[i]) == -1) {
      return false;
    }
  }
  return true;
}
/* perform the search when the page is loaded
 */
function perform_search(search_string, word_search) {

  if (! (document.getElementById || document.createElement)){
    alert("<TMPL_VAR NAME=STRING_NODOM>");
    return;
  }

  var limit = <TMPL_VAR NAME=SEARCH_LIMIT>;
  var found = 0;
  var keywords = get_keywords(search_string, word_search);
  if (keywords.length == 0) {
    return;
  }
  var results = document.getElementById('results');
  results.innerHTML = "";
  var status = document.getElementById('status');

  update_status(status, found);

  for (var i=0 ; i<search_data.length; i++) {
    image = search_data[i];
    if (match(keywords, image.search_string)) {
      if (found >= limit) {
	var status_string = "<TMPL_VAR NAME=STRING_TOOMANYRESULTS>";
	// WTF ? Not sprintf in javascript ? OK, so I code dirty
	status_string = status_string.replace(/%d/, found.toString());
	status.firstChild.nodeValue = status_string;
	return;
      }

      update_status(status, found++);
      display_result(results, image)
    }
  }
  var status_string = "<TMPL_VAR NAME=STRING_SEARCHCOMPLETED>";
  // For dirty hacking remark, see above comment
  status_string = status_string.replace(/%d/, found.toString());
  status.firstChild.nodeValue = status_string;    
  return;
}

/* if user has pressed return in the input field, validate the search
 */
function process_key(e) {
  if (window.event) {
    if (window.event.type == "keypress" & window.event.keyCode == 13)
      reload_page();
  }
  if (e) {
    if (e.type == "keypress" & e.keyCode == 13) {
      reload_page();
    }
  }
}

/* Reload the page when the user click the search button
 */
function reload_page() {
  var search_string = get_search_string();
  var word_search = document.getElementById('search_word').checked;
  if (search_string) {
    search_string = encodeURIComponent(search_string)
    if (word_search) {
      search_string += "&w=1";
    }
    location.href = location.pathname + "?q=" + search_string;
  }
}
