/*
TODO: essayer de ne pas refreshLocation quand pas de # dans l'url
*/

var TABULATOR_DIR = 'http://www.teamliquid.net/tlpd/tabulator';

function getHTTPObject() {
  /*
  if (http != null) {
    return http;
  }*/
  if (typeof XMLHttpRequest != 'undefined') {
    return new XMLHttpRequest();
  }
  try {
    return new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      return new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {}
  }
  return false;
}

function remote_query(public_id, internal_id, page, order_col, order_way, search) {
  inner_remote_query(public_id, internal_id, page, order_col, order_way, search, true);
}

function inner_remote_query(public_id, internal_id, page, order_col, order_way, 
                            search, add_to_history) {
  var loadingAnimTop    = document.getElementById(public_id + '_loading_anim_top');
  var loadingAnimBottom = document.getElementById(public_id + '_loading_anim_bottom');
  if (loadingAnimTop) {
    loadingAnimTop.style.visibility    = 'visible';
  }
  if (loadingAnimBottom) {
    loadingAnimBottom.style.visibility = 'visible';
  }

  var tmp = build_path(internal_id, page, order_col, order_way, search, displayProperties[public_id]);
  var url    = tmp[0];
  var params = tmp[1];
  
  var http = getHTTPObject();

  http.open('GET', url + params, true);

  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      if (add_to_history) {
        var location = public_id + '-' + internal_id + '-' + page + '-' 
          + order_col + '-' + order_way;
        if (search.length > 0) {
          location += '-' + search; 
        }
        
        var currentLocation = dhtmlHistory.getCurrentLocation();
        
        if (currentLocation.length > 0) {
          var tblts_info = currentLocation.split(';');
          for (i = 0; i < tblts_info.length; i++) {
            var tblt_info = tblts_info[i];
            var args = tblt_info.split('-');
            var other_public_id = args[0];
            
            if (other_public_id != public_id) {
              location += ';' + tblt_info;
            }
          }
        }
        oldLocation = location;
        dhtmlHistory.add(location, null);
      }
      var tblt_div = document.getElementById(public_id + '_table').parentNode;
      tblt_div.innerHTML = http.responseText;
      if (loadingAnimTop) {
        loadingAnimTop.style.visibility    = 'hidden';
      }
      if (loadingAnimBottom) {
        loadingAnimBottom.style.visibility = 'hidden';
      }
    }
    else if (http.readyState == 4 && http.status == 404) {
      params = params.replace(/tabulator_id=[0-9]+&?/, '');
      window.location = baseHref + params;
    }
  }
  
  http.send(null);
}

function build_path(id, page, order_col, order_way, search, displayProperties) {
  id_arg = 'tabulator_id=' + id;
  page_arg = '&tabulator_page=' + page;
  
  if (order_col != null) {
    order_args = '&tabulator_order_col=' + order_col;
    if (order_way == 'DESC') {
      order_args += '&tabulator_order_desc=1';
    }
  } else {
    order_args = '';
  }
    
  search_arg = '&tabulator_search=' + search;
  
  displayArgs = '';  
  if (typeof displayProperties != 'undefined') {
    for (var propertyName in displayProperties) {
      var propertyValue = displayProperties[propertyName];
      displayArgs += '&' + propertyName + '=' + propertyValue;
    }
  }
      
  args = id_arg + page_arg + order_args + search_arg + displayArgs;
  
  return [TABULATOR_DIR + '/update.php?', args];
}

function get_location_from_path(path, tblt_ids) {
  if (path.length == 0) {
    return null;
  }
  var values = {}
  var args = path.substring(1).split('&');
  for (var i = 0; i < args.length; i++) {
    var arg = args[i];
    var tmp = arg.split('='), name = tmp[0], value = tmp[1];
    values[name] = value;
  }
  
  var internal_id, public_id;
  for (public_id in tblt_ids) {
    internal_id = tblt_ids[public_id];
    break;
  }
  
  var page      = containsKey(values, 'tabulator_page') 
                  ? values['tabulator_page'] 
                  : 1;
  var order_col = containsKey(values, 'tabulator_order_col') 
                  ? values['tabulator_order_col']
                  : 'default';
  var order_way = containsKey(values, 'tabulator_order_desc') && values['tabulator_order_desc'] 
                  ? 'DESC' 
                  : 'ASC';
          
  var location = public_id + '-' + internal_id + '-' + page + '-' + order_col + '-' + order_way;
  if (containsKey(values, 'tabulator_search')) {
    location += '-' + values['tabulator_search'];
  }
  
  return location;
}

var initial_tblt_ids = null;
var oldLocation = null;
var initialLocation = null;
var baseHref = null;

function initDhtmlHistory(a_BaseHref, tblt_ids) {
  baseHref = a_BaseHref;
  initial_tblt_ids = tblt_ids;
  dhtmlHistory.initialize();
  
  dhtmlHistory.addListener(onHistoryChanged);
  var location = dhtmlHistory.getCurrentLocation();
  if (dhtmlHistory.firstLoad && location.length > 0) {
    refreshLocation(dhtmlHistory.getCurrentLocation());
  } else {
    initialLocation = get_location_from_path(window.location.search, tblt_ids);
    historyStorage.put('', tblt_ids);
  }
}

function onHistoryChanged(historyLocation, historyData) {
  var location = historyLocation.length == 0 ? initialLocation : historyLocation;
  refreshLocation(location);
  oldLocation = location;
} 

function containsKey(hash, key) {
  //alert('value:'+hash[key]);
  return typeof hash[key] != 'undefined';
}

function arrayEquals(array1, array2) {
  if (array1.length != array2.length) {
    return false;
  }
  for (var i = 0; i < array1.length; i++) {
    if (array1[i] != array2[i]) {
      return false;
    }
  }
  return true;
}

function getTbltDataFromLocation(location) {
  var tblt = {};
  var tbltsInLocation = location.split(';');
  for (var i = 0; i < tbltsInLocation.length; i++) {
    var tbltInLocation = tbltsInLocation[i];
    var args = tbltInLocation.split('-');
    if (args.length == 5) {
      args[5] = '';
    }
    tblt[args[0]] = [args[1], args[2], args[3], args[4], args[5]];
  }
  
  return tblt;
}

function getChangedTblts(newLocation) {
  var oldTblts = {};
  if (oldLocation != null && oldLocation.length > 0) {
    oldTblts = getTbltDataFromLocation(oldLocation);
  }
  
  var newTblts = {};
  if (newLocation != null && newLocation.length > 0) {
    newTblts = getTbltDataFromLocation(newLocation);
  }
  
  var changedTblts = {}
  for (var newPublicId in newTblts) {
    if (!containsKey(oldTblts, newPublicId)
     || !arrayEquals(oldTblts[newPublicId], newTblts[newPublicId])) {
      changedTblts[newPublicId] = newTblts[newPublicId];
    }
  } 
  defaultTbltIds = null;
  for (var oldPublicId in oldTblts) {
    if (!containsKey(newTblts, oldPublicId)) {
      if (defaultTbltIds == null) {
        defaultTbltIds = historyStorage.get('');
      }
      var internalId = defaultTbltIds[oldPublicId];
      changedTblts[oldPublicId] = [internalId, 1, '', '', ''];
    } 
  }
  
  return changedTblts;
}

function refreshLocation(newLocation) {  
  var changedTblts = getChangedTblts(newLocation);
  
  for (var publicId in changedTblts) {
    var data = changedTblts[publicId];
    //alert(publicId + ':' + data[1]);
    inner_remote_query(publicId, data[0], data[1], data[2], 
      data[3], data[4], false);
  }
}

var displayProperties = new Object();
function setDisplayProperty(publicId, name, value) {
  if (!containsKey(displayProperties, publicId)) {
    displayProperties[publicId] = new Object();
  }
  displayProperties[publicId][name] = value;
} 
