var geotype_omraade    = 1;
var geotype_emner      = 2;
var geotype_lokationer = 3;
var geotype_overskrift = 4;

function TGeoItem(geoId, pos, name, parentGeoId, imageUrl, imageMapArea, type, sort, geoImageId, hasChildren, emneGruppeCount, geoImageDefType) {
  var res = new list();
  res.geoId = geoId;
  res.pos = pos;
  res.name = name;
  res.type = type;
  res.sort = sort;
  res.sprogId = '';
  res.ferietypeID = '';
  res.cacheDT = '';
  res.gruppeId = '';
  res.locale = '';
  res.hasChildren = hasChildren;
  res.geoImageId = geoImageId;
  res.parentGeoId = parentGeoId;
  res.imageUrl = imageUrl;
  res.imageMapArea = imageMapArea;
  res.emneGruppeCount = (emneGruppeCount)?emneGruppeCount:0;
  res.geoImageDefType = (geoImageDefType)?geoImageDefType:null;
  res.add = TGeoItem_add;
  res.find = TGeoItem_find;
  res.updateImagemapDefinition = TGeoItem_updateImagemapDefinition;
  res.updateImagemapDefinitionEmner = TGeoItem_updateImagemapDefinitionEmner;
  res.geoList = null;
  res.path = TGeoItem_path;
  res.pathName = TGeoItem_pathName;
  res.hierarchy = TGeoItem_hierarchy;
  res.getchildren = TGeoItem_getchildren;
  res.sortfunction = TGeoItem_sortfunction;
  res.loadChildren = TGeoItem_loadChildren;
  res.parseGeoXML = TGeoItem_parseGeoXML;
  return res;
}

function TGeoItem_sortfunction(a,b) {
  if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
  return 0;
}

function TGeoItem_hierarchy(h) {
  if (!isUndefined(this.parent)) {
    this.parent.hierarchy(h);
  }
  h.add(this);
}

function TGeoItem_path() {
  if (isUndefined(this.parent)) return '';
  return this.parent.path() + ',' + this.geoId;
}

function TGeoItem_pathName() {
  if (isUndefined(this.parent)) return '';
  return this.parent.pathName() + ',' + this.name;
}


function TGeoItem_updateImagemapDefinition(map, children, except) {
  if (children) {
    if(this.geoList.emnerOnMap) this.updateImagemapDefinitionEmner(map);
    for (var i = 0; i < this.length; i++) {
      if (this[i].geoId != except) {
        this[i].updateImagemapDefinition(map,false,'');
      }
    }
    if (this.geoImageDefType != '2' && !isUndefined(this.parent)) {
      this.parent.updateImagemapDefinition(map, true, this.geoId);
    }
  }
    if (this.imageMapArea != '' && this.geoId != except && (this.type == geotype_omraade || this.type == geotype_lokationer)) {
      var ele = document.createElement("AREA");
      ele.shape = 'polygon';
      ele.coords = this.imageMapArea;
      if(this.emneGruppeCount>0)
        ele.href = 'javascript:'+this.geoList.jsName + '.selectGeo(\''+ this.geoId +'\')';
      if(this.geoList.texts && this.emneGruppeCount==1 && this.geoList.texts.productNameSingle) {
        ele.alt = this.name + ': ' + this.emneGruppeCount + ' ' + this.geoList.texts.productNameSingle;
      }else if(this.geoList.texts && this.geoList.texts.productNameMulti) {
        ele.alt = this.name + ': ' + this.emneGruppeCount + ' ' + this.geoList.texts.productNameMulti;
      }else{
        ele.alt = this.name;
      }
      map.appendChild(ele);
    }
}

function TGeoItem_updateImagemapDefinitionEmner(map) {
  if (this.imageMapArea != '' && this.type == geotype_emner) {
    var ele = document.createElement("AREA");
    ele.shape = 'polygon';
    ele.coords = this.imageMapArea;
    if(this.emneGruppeCount>0)
      ele.href = 'javascript:'+this.geoList.jsName + '.selectGeoEmne(\''+ this.geoId +'\')';
    ele.alt = this.name + ': ' + this.emneGruppeCount;
    map.appendChild(ele);
  }
  for (var i = 0; i < this.length; i++) {
    this[i].updateImagemapDefinitionEmner(map);
  }    
}

function TGeoItem_add(item) {
  if (this.geoId == item.parentGeoId) {
    this[this.length] = item;
    item.parent = this;
    item.level = isUndefined(this.level)?0:this.level + 1;
    item.geoList = this.geoList;
    return true;
  }
  for (var i = 0; i < this.length; i++) {
    if (this[i].add(item)) return true; 
  }
  if (this.geoId == null) {
    this[this.length] = item;
    item.parent = this;
    item.level = 0;
    item.geoList = this.geoList;
    return true;
  }
  return false;
}

function TGeoItem_find(id) {
  if (this.geoId == id) {
    this.loadChildren();
    return this;
  }
  //this.loadChildren();
  for (var i = 0; i < this.length; i++) {
    var res = this[i].find(id); 
    if (res != null) {
      return res;
    }
  }
  return null;
}

function TGeoItem_loadChildren() {
  if (this.hasChildren && this.length == 0) {
    //alert('loading : ' + this.name + ' level:'+this.level+ 'getSublevelCount: '+this.geoList.getSublevelCount);
    var xmldom = LoadXML('/geo/data.asp' +
                         '?gruppeid=' + this.gruppeId +
                         '&sprogid='+ this.sprogId + 
                         '&ferietypeid='+ this.ferietypeID +
                         '&locale='+ this.locale + 
                         '&parentgeoid=' + this.geoId +
                         '&AntalSubNiveauer=' + (isUndefined(this.geoList.getSublevelCount)?'0':this.geoList.getSublevelCount(this.level)) +
                         '&cacheDT='+ this.cacheDT,
                         null,
                         'allowCache');
    var nodes = xmldom.responseXML.selectNodes('root/Geo');
    this.parseGeoXML(nodes);
  }
}

function TGeoItem_parseGeoXML(xelGeo) {
  for (var i = 0; i < xelGeo.length; i++) {
    var n = xelGeo[i];
    var item = new TGeoItem( n.getAttribute("Id"), 
                             n.getAttribute("Pos"), 
                             n.getAttribute("Name"), 
                             n.getAttribute("ParentGeoId"),
                             n.getAttribute("ImageUrl"), 
                             n.getAttribute("ImageMapArea"), 
                             n.getAttribute("Type"),
                             n.getAttribute("Sort"), 
                             n.getAttribute("GeoImageId"),
                             ifthen(n.getAttribute("HasChildren") == '1', true, false),
                             n.getAttribute("EmneGruppeCount"),
                             n.getAttribute("GeoImageDefType"));
    item.gruppeId = this.gruppeId;
    item.sprogId = this.sprogId;
    item.ferietypeID = this.ferietypeID;
    item.cacheDT = this.cacheDT;
    item.locale = this.locale;
    this.add(item);
    item.parseGeoXML(n.selectNodes('Geo'));
  }  
}

function TGeoItem_getchildren(list, geoType) {
  this.loadChildren();
  for (var i = 0; i < this.length; i++) {
    if (this[i].type == geoType) {
      list.add(this[i]);
    }
    list = this[i].getchildren(list, geoType);
  }
  return list;
}

//----------------------------------------------------------------------------

function TGeoHeaderText(id, text) {
  this.id = id;
  this.text = text;
}

//----------------------------------------------------------------------------

function TGeoHeaderTextList() {
  var res = new list();
  res.find = TGeoHeaderTextList_find;
  res.findOption = TGeoHeaderTextList_findOption;
  return res;
}

function TGeoHeaderTextList_find(id) {
  id = id.toLowerCase();
  for (var i = 0; i < this.length; i++) {
    if (this[i].id.toLowerCase() == id) return this[i];
  }
  return null;
}

function TGeoHeaderTextList_findOption(id) {
  var h = this.find(id);
  if (h != null)
    return h.text
  else
    return id+' : sprogtekst findes ikke ';
}

//----------------------------------------------------------------------------

function TFilterSelectParam(id,value) {
  this.id = id;
  this.value = value;
}

function TFilterSelectParamList() {
  var res = new list();
  res.find = TFilterSelectParamList_find;
  return res;
}

function TFilterSelectParamList_find(id) {
  id = id.toLowerCase();
  for (var i = 0; i < this.length; i++) {
    if (this[i].id.toLowerCase() == id) return this[i];
  }
  return null;
}

//----------------------------------------------------------------------------

function TGeoList() {
  // this.geoItems = undefined;
  this.params = new list();
  this.filterSelectParams = new TFilterSelectParamList();
  this.mapName = '';
  this.elementName = '';
  this.jsName = '';
  this.gruppeId = '';
  this.sprogId ='';
  this.ferietypeID = '';
  this.cacheDT = '';
  this.locale = '';
  
  this.show = TGeoList_Show;
  this.getChildrenOptionList = TGeoList_getChildrenOptionList;
  this.showSelect = TGeoList_ShowSelect;
  this.changeSelect = TGeoList_ChangeSelect;
  this.className = '';
  this.baseFieldName = '';
  this.updateMap = TGeoList_updateMap;
  this.findGeo = TGeoList_findGeo;
  this.updateImageMapDefinition = TGeoList_updateImageMapDefinition;
  this.selectGeo = TGeoList_selectGeo;
  this.selectGeoEmne = TGeoList_selectGeoEmne;
  this.add = TGeoList_add;
  // this.onShow = undefined;
  // this.onBeforeShow = undefined;
  this.createFilteredSelect = TGeolist_createFilteredSelect;
  this.getLastParam = TGeoList_getLastParam;
  this.checkParams = TGeolist_checkParams;
  this.firstOption = new TGeoHeaderTextList();
  // this.onAfterChange = undefined;
  // this.getSublevelCount = undefined;
  this.initializeFromCookie = TGeoList_initializeFromCookie;
  this.texts = new Object();
  this.searchCookieName = 'search';
}

function TGeoList_add(item) {
  item.gruppeId = this.gruppeId;
  item.sprogId = this.sprogId;
  item.ferietypeID = this.ferietypeID;
  item.cacheDT = this.cacheDT;
  item.locale = this.locale;
  if (isUndefined(this.geoItems)) {
    this.geoItems = item;
    this.geoItems.geoList = this;
  } else {
    this.geoItems.add(item);
  }
}

function TGeoList_ShowSelect(name, id) {
  var res = this.getChildrenOptionList(name,id);
  if (res == '') return '';
  var onchange = '';
  if (!isUndefined(this.onAfterChange)) onchange = ';' + this.jsName +'.onAfterChange()';
  return '<select name="'+ name + '" class="'+ this.className +' '+name+'" onChange="'+this.jsName+'.changeSelect(this)'+ onchange +'">' + 
         res +
         '</select><br>';
}

function TGeoList_Show(fireOnAfterChange) {
  if (isUndefined(this.geoItems)) return '';
  var res  = '';
  res += this.showSelect( this.baseFieldName + '_0', this.geoItems.geoId, this.geoItems.geoId);
  for (var i = 0; i < this.params.length; i++) {
    res += this.showSelect( this.baseFieldName + '_' + (i+1), this.params[i], ifthen(i > 0, this.params[i-1], this.params[i]));
  }
  if (!isUndefined(this.onBeforeShow)) {
    res = this.onBeforeShow(res);
  }
  var ele = getElement(this.elementName);
  ele.innerHTML = res;
  if (!isUndefined(this.onShow)) {
    if (this.params.length > 0) {
      var item = this.findGeo(this.params[this.params.length-1]);
      if (item != null) {
        var h = new list();
        item.hierarchy(h);
        this.onShow(h);
      }
    } else {
      this.onShow(Array(this.geoItems))
    }
  }
  this.updateMap();
  if (!isUndefined(this.onAfterChange)) {
    if (!isUndefined(fireOnAfterChange) || fireOnAfterChange) this.onAfterChange();
  }
}


function TGeoList_findGeo(geoId) {
  return this.geoItems.find(geoId);
}

function TGeoList_updateImageMapDefinition(geoId) {
  var map = getElement(this.mapName);
  if (map != null) {
    while (map.areas.length > 0) map.removeChild(map.areas[0]);
    var id = this.findGeo(geoId);
    if (id != null) {
      id.updateImagemapDefinition(map,true,'');
    }
  }
}

function TGeoList_updateMap() {
  var map = getElement(this.imageName);
  if (map != null) {
    if(!this.origImageUrl)
      this.origImageUrl = map.src;
    var imageUrl = '';
    if (this.params.length > 0) {
      for (var i = 0; i < this.params.length; i++) {
        var geo = this.findGeo(this.params[i]);
        if (geo != null) {
          if (geo.imageUrl != '') imageUrl = geo.imageUrl;
        }
      }
    } else {
      imageUrl = this.geoItems.imageUrl;
    }
    if (imageUrl != '') {
      map.src = imageUrl;
    } else {
      map.src = this.origImageUrl;
    }
    if (this.params.length > 0 )
      this.updateImageMapDefinition(this.params[this.params.length-1],true,'')
    else
      this.updateImageMapDefinition(this.geoItems.geoId,true,'')
  }
}

function TGeoList_getChildrenOptionList(name, id) {
  var res = '';
  var geo = this.findGeo(id);
  if (geo != null) {
    for (var i = 0; i < geo.length; i++) {
      var item = geo[i];
      if ((item.type == geotype_omraade || item.type == geotype_lokationer) && item.emneGruppeCount>0 ) {
        if (res == '') res = '<option value="">'+ this.firstOption.findOption(name) +'</option>';
        res += '<option value="'+ item.geoId +'" '+ ifthen(this.params.join(',').indexOf(item.geoId) != -1, ' selected ','') +'>'+ item.name + '</option>';
      } else if (item.type == geotype_overskrift) {
        if (res == '') res = '<option value="">'+ this.firstOption.findOption(name) +'</option>';
        res += '<optgroup Label="'+ item.name + '"></optgroup>';
      }
    }
  }
  return res;
}

function TGeoList_ChangeSelect(sel) {
  var no = sel.name.split('_');
  var selname = sel.name;
  var items = '';
  var form = document.forms['searchform'];
  for (var i = 0; i <= no[1]; i++) {
    var ele = eval('form.' + no[0] + '_' + i);
    items += ',' + ele.options[ele.selectedIndex].value;
  }
  items = items.split(',');
  this.params = new list();
  for (var i = 0; i < items.length; i++) {
    if (items[i] != '') {
      this.params.add(items[i]);
    }
  }
  this.filterSelectParams.length = 0;
  
  this.show();
  sel = eval('form.'+selname);
  if (sel != null) sel.focus();
}

function TGeoList_selectGeo(id) {
  var map = getElement(this.imageName);
  if (map != null) if (map.blur) map.blur();

  var geoItem = this.findGeo(id);
  items = geoItem.path().split(',');
  this.params = new list();
  for (var i = 0; i < items.length; i++) {
    if (items[i] != '') {
      this.params.add(items[i]);
    }
  }
  this.filterSelectParams.length = 0;
  this.show();
}

function TGeoList_selectGeoEmne(id) {
  var map = getElement(this.imageName);
  if (map != null) if (map.blur) map.blur();

  var geoItem = this.findGeo(id).parent;
  items = geoItem.path().split(',');
  this.params = new list();
  for (var i = 0; i < items.length; i++) {
    if (items[i] != '') {
      this.params.add(items[i]);
    }
  }
  this.filterSelectParams.length = 0;
  this.filterSelectParams.add(new TFilterSelectParam('geoid_100', id));
  //MBL 20071030 if(this.filterSelectParams[0])this.filterSelectParams[0].value = id
  this.show();
}

function TGeoList_getLastParam() {
  if (this.params.length > 0) {
    return this.params[this.params.length-1];
  }
  return this.geoItems.geoId;
}

function TGeolist_checkParams() {
  var res = new list();  
  var curgeoid = this.geoItems;
  curgeoid.loadChildren();
  for (var i = 0; i < this.params.length; i++) {
    if (curgeoid != null) curgeoid = curgeoid.find(this.params[i]);
    if (curgeoid != null) curgeoid.loadChildren();
    
    var geoId = this.findGeo(this.params[i]);
    if (geoId != null) res.add(this.params[i]);
  }
  this.params = res;
}

function TGeolist_createFilteredSelect( name, geoType ) {
  var g = new list();
  var geoId = this.findGeo(this.getLastParam());
  if (geoId == null) geoId = this.geoItems;
  if (geoId.type == geotype_emner && geoId.parent) {
    geoId = geoId.parent;
  }
  g = geoId.getchildren(g, geoType);
  if (g.length == 0) return '';
  g.sort(TGeoItem_sortfunction);
  
  for (var i = 0; i < g.length; i++) {
    if (g[i].emneGruppeCount == 0) {
      g[i] = null;
    }
  }
  
  for(var i=0;i<g.length;i++) {
    for(var j=i; j<g.length;j++) {
      if (g[i] != null && g[j] != null && j != i)
        if (g[i].name.toLowerCase() == g[j].name.toLowerCase()) {
          g[j]=null;
        }
    }
  }
  var res = '';
  var onchange = ""
  if (!isUndefined(this.onAfterChange)) onchange = this.jsName +'.onAfterChange()';
  var resoptions = ''
  var selvalue = this.filterSelectParams.find(name);
  if (selvalue != null) selvalue = selvalue.value;
  for (var i = 0; i < g.length; i++) {
    var item = g[i];
    if (item != null && item.emneGruppeCount>0) {
      resoptions += '<option value="'+ item.geoId +'" '+ ifthen(item.geoId == selvalue, ' selected ','') +'>'+ item.name + '</option>';
    }
  }
  if(resoptions!='') {
    res = '<select name="'+ name + '" class="'+ this.className +' '+ name +'" onChange="'+ onchange +'">';
    res += '<option value="">'+ this.firstOption.findOption(name) +'</option>';
    res += resoptions;
    res += '</select><br>';
  }
  return res;
}

function ShowGeoNameWithParents(hierarchy) {
  var res = '';
  for(var i = 0; i < hierarchy.length; i++) {
    var cur = hierarchy[i];
    if (i < hierarchy.length-1) {
      res += '<a href="javascript:'+ cur.geoList.jsName + '.selectGeo(\''+ cur.geoId +'\')">' + cur.name + '</a>&nbsp;'
    } else {  
      res += cur.name;  
    }
  }
  var ele = getElement('geo_information');
  if (ele != null) ele.innerHTML = res;
  DisplayResetLink(hierarchy);
}

function ShowGeoName(hierarchy) {
  var res = '';
  if (hierarchy.length > 0) {
    res =  hierarchy[hierarchy.length-1].name;
  }
  var ele = getElement('geo_information');
  if (ele != null) ele.innerHTML = res;
  DisplayResetLink(hierarchy);
}

function DisplayResetLink(hierarchy) {
  var ele = getElement('geo_reset');
  if (ele != null) {
    if (hierarchy.length > 1) 
      ele.style.display = 'block';
    else 
      ele.style.display = 'none';
  }
}

function insertExtraDropDown(res) {
  res += geo.createFilteredSelect('geoid_100', geotype_emner);
  return res;
}

function TGeoList_initializeFromCookie() {
  if(Cookies && Cookies.getValue) {
    var search = Cookies.getValue(this.searchCookieName);
    if(search.length>0) {
      search="&"+search+"&";
      var matches = search.match(/&(geoid\d+=[^&]*)&/gi);
      if (matches != null) {
        var regex = /&geoid(\d+)=([^&]*)&/i;
        var params = new Array(matches.length);
        for(var i=0;i<matches.length;i++){
          var match = regex.exec(matches[i]);
          params[i]={id:parseInt(match[1]),geoid:match[2]};
        }
        this.params.length=this.filterSelectParams.length=0;
        params.sort(function(a,b){return a.id-b.id});
        for(i=0;i<params.length;i++){
          if(params[i].id==100){
            this.filterSelectParams.add(new TFilterSelectParam('geoid_100',params[i].geoid));
          }else{
            this.params.add(params[i].geoid);
          }
        }
      }
    }
  }
}
