if (!window.PAGEFINDER) (function() {

  PAGEFINDER = {
    countries : null,
    categories : null,
    cities : null,    
    current_country : null,
    current_cat_id : null,
    city : null,
    cat : null,
    type : null,
    
    countryLoad : function(){

      self.current_country = countryCode;    // get from tapestry page vars

      new Ajax.Request('/widgets/homepage_pagefinder/json.php?object=countries', {
        method:'get',
        onSuccess: function(req){
          $$('select.finderCountries').each(function(b){ b.innerHTML='';});
          self.countries = eval('('+req.responseText+')');
          self.countries.each(function(c){
            $$('select.finderCountries').each(function(box){              
              var o = document.createElement('option');
              if (c.code == self.current_country) o.selected = true;
              o.value = c.code;
              o.innerHTML = c.name;
              box.appendChild(o);
            });
          });
          //self.current_country = self.countries[0].code          
          self.getCategories(self.current_country);          
        },
        onFailure: function(){
          //alert('Download failed, retrying...');
          self.countryLoad();
        }
      })
    },

    getCategories : function(cntry_code){
      new Ajax.Request('/widgets/homepage_pagefinder/json.php?object=cats&cntry='+cntry_code, {
        method:'get',
        onSuccess: function(req){
          self.categories = eval('('+req.responseText+')');
          self.loadDefaults();
        },
        onFailure: function(){
          //alert('Download failed, retrying...');
          self.getCategories(cntry_code);
        }
      })
    },

    categoryLoad : function(type){
      datatype = '';      
      if(type=='accom'){
        datatype='accommodation';
      }
      if(type=='todo'){
        datatype='activities';
      }
      if(type=='transport'){
        datatype=type;
      }
      box = $(type+'FinderCat');
      box.innerHTML = '';
      for (catkey in self.categories){
        if(catkey==datatype){
          //alert('Inserting options...'+datatype);
          (self.categories[catkey]).each(function(c){
            var o = document.createElement('option');
            o.value = c.id;
            o.innerHTML = c.name;              
            box.appendChild(o);
          })
        }
      }
    },

    getCities : function(selected_cat){
      new Ajax.Request('/widgets/homepage_pagefinder/json.php?object=cities&cntry='+self.current_country+'&cat='+selected_cat, {
        method:'get',
        onSuccess: function(req){
          self.cities = eval('('+req.responseText+')');
          self.loadCities(self.type);
        },
        onFailure: function(){
          //alert('Download failed, retrying...');
          self.getCities(selected_cat);
        }
      })
    },

    loadCities : function(finder) {
      var box = $(finder+'FinderCity');
      //alert('Inserting options...'+type);
      box.innerHTML = '';
      self.cities.each(function(c){
        var o = document.createElement('option');
        if (c.id == self.city) o.selected = true;
        o.value = c.id;
        o.innerHTML = c.name;
        box.appendChild(o);
      });
      self.doneLoading();
    },

    showLoading : function() {
      $('loading').show();
      $$('input.finderGo').each(function(g){ g.hide() });
      $$('select.finderCountries').each(function(b){ b.disable();});
      $(self.type+'FinderCat').disable();
      if(self.type != 'transport') $(self.type+'FinderCity').disable();      
    },
    
    doneLoading : function(){
      $$('select.finderCountries').each(function(b){ b.enable();});
      $(self.type+'FinderCat').enable();
      if(self.type != 'transport') $(self.type+'FinderCity').enable();
      $('loading').hide();
      $$('input.finderGo').each(function(g){ g.show();});
    },
    
    changeCountry : function(cntry_select) {      
      self.showLoading();
      var new_index = cntry_select.selectedIndex;
      var cntry_code = cntry_select.getValue();
      self.current_country = cntry_code;
      self.getCategories(cntry_code);  // --> loadDefaults()
      $$('select.finderCountries').each(function(box){
        box.selectedIndex = new_index;
      });
    },

    changeCat : function(cat_select) {
      self.showLoading();
      var cat_id = cat_select.getValue();      
      self.getCities(cat_id);
      self.cat = cat_id;
      self.city = $F(self.type+'FinderCity');
    },


    changeFinder : function(type){
      self.type = type;
      self.showLoading();
      if(type == 'transport'){
        self.doneLoading();
      }else{
        var cat_id = $(type+'FinderCat').getValue();
        self.getCities(cat_id);
      }
    },


    loadDefaults : function(){
      self.categoryLoad('accom');
      self.categoryLoad('todo');
      self.categoryLoad('transport');
      if(self.type == 'transport'){
        self.doneLoading();
      }else{
        self.getCities($(self.type+'FinderCat').getValue());
      }
    },

    toSlug : function(str){
      str = str.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/-+$/g,'').replace(/^-+$/g,'');
      return(str);
    },

    go : function(type){
      var city;
      var cntry = self.current_country ;
      var category = $(type+'FinderCat').getValue();
      if(type == 'transport'){
        city = 0;   //fixme -- valid city code needed
      }else{
        city = $(type+'FinderCity').getValue();
      }

      new Ajax.Request('/widgets/homepage_pagefinder/json.php?object=pageurl&cntry='+cntry+'&cat='+category+'&city='+city, {
        method:'get',
        onSuccess: function(req){
          var data = eval('('+req.responseText+')');
          document.location = data.url;
        },
        onFailure: function(){
          //alert('Download failed, retrying...');
          self.go(type);
        }        
      })
    },


    updateUrl :function() {
      var page = TE$('#TEwidgetCategories option:selected').parent().attr("label")
      var city = TE$('#TEwidgetCities option:selected').val();
      var cat = TE$('#TEwidgetCategories option:selected').val();
      if(page=='Accommodation'){page = 'Accommodations';}
      // default form
      var url = self.server + page +'/'+self.country+'/'+city+'/'+cat;
      if(page=='Restaurants'){
        url = self.server + page +'/'+self.country+'/'+city;
      }
      if(page=='Transport'){
        self.isTP=true;
        var slug;
        TE$.each(self.countries, function(key, cntry){
          if(cntry.code==self.country){ slug = cntry.slug;}
        });        
        url = self.server +self.cat+'/'+slug;
      }

      url = url + '?utm_source=<?=$source?>&utm_medium=<?=$medium?>&utm_campaign=<?=$campaign?>';

      TE$('#TEwidgetGo').attr('href', url);
      self.doneLoading();
    },

    init : function() {
      self.countryLoad();
    }

  }
  var self = PAGEFINDER;
  self.init();
})();
