// VacationSpot namespace
var vs = {};
vs.locks = {};
vs.typeAheadProcess = null;
vs.typeAheadQuery = null;
vs.detail = null;
vs.contact = null;
vs.loading = null;
vs.rental = null;
vs.photo = null;
vs.photoIndex = 0;

vs.top = function(data) { 
  if (data && data.locations) {
    var locations = data.locations;
    var geos = $('geos');

    for (var i = 0; i < locations.length; ++i) {
      var geo = locations[i];
      $('geoLink').setProperty('href', 'rentals.html?id=' + geo.locationId);
      $('geoName').innerHTML = geo.name;
      $('geoCount').innerHTML = geo.rentalCount + " rentals";
      var child = $('geo').clone().removeClass('hide');
      child.getElement('img').setProperty('id', "image_" + geo.locationId);
      geos.appendChild(child)
    }
    
    for (var i = 0; i < locations.length; ++i) {
      var geo = locations[i];
      vs.execute('rentals', geo.locationId, {limit:1}, vs.topGeos);
    }
  }
};

vs.topGeos = function(data) {  
  if (data && data.rentals && data.rentals.length > 0) {
    var rental = data.rentals[0];
    if (rental.photo) {
      $("image_" + data.locationId).setProperty('src', rental.photo.mediumUrl);
    }
  }
}

vs.location = function(data) {  
  if (data && data.locationId) {
   $('geo').innerHTML = data.name;
  }
};

vs.rentals = function(data) {
  if (data && data.rentals) {
    var rentals = data.rentals;
    $('rentals').innerHTML = '';    

    for (var i = 0; i < rentals.length; ++i) {
      var rental = rentals[i];            
      
      if (rental.type.length > 0) {
        $('rentalType').innerHTML = rental.type;
      }
      
      if (rental.bedrooms > 0) {
        var beds = rental.bedrooms + " Bedrooms";
        
        if (rental.sleeps > 0)
        {
          beds += ", sleeps " + rental.sleeps;
        }
        
        $('rentalBed').innerHTML = beds;
      }
       
      if (rental.bathrooms > 0) { 
        $('rentalBath').innerHTML = rental.bathrooms + " Bathrooms";
      }
      
      if (rental.overallRating > 0) {
        $('rentalRating').innerHTML = "Rating: " + rental.overallRating  + " (" + rental.reviewCount + " reviews)";
      }
      
      if (rental.photo) {
        $('rentalImage').setProperty('src', rental.photo.largeUrl);
      }
      
      $('rental').setProperty('onclick', '$(this).getElement("div.loading").removeClass("hide");vs.execute("rental", ' + rental.locationId + ', {}, vs.rentalDetail);');
      var child = $('rental').clone().removeClass('hide');
      child.getElement('div.loading').setProperty('id', 'loading_' + rental.locationId);
      
      $('rentals').appendChild(child);
    }
    
    if (data.availableCount > 4) {
      $('paging').removeClass('hide');
      $('count').innerHTML = (data.startOffset + 1) + ' - ' + (data.endOffset + 1)
      $('total').innerHTML = data.availableCount;
      
      if (data.startOffset > 0) {
        $('prevLink').setProperty('href', 'rentals.html?id=' + vs.queryString.id + '&offset=' + (data.startOffset - 4));
        $('prevLink').setProperty('onclick', '');        
        $('prevLink').removeClass('unlink');
      } else {
        $('prevLink').setProperty('onclick', 'return false;');
        $('prevLink').addClass('unlink');
      }
      
      if (data.endOffset + 1 < data.availableCount) {        
        $('nextLink').setProperty('href', 'rentals.html?id=' + vs.queryString.id + '&offset=' + (data.endOffset + 1));
        $('nextLink').setProperty('onclick', '');
        $('nextLink').removeClass('unlink');
      } else {
        $('nextLink').setProperty('onclick', 'return false;');
        $('nextLink').addClass('unlink');
      }
    }
  }
};

vs.typeAheadBegin = function() {
  $('typeAhead').value = '';
  vs.typeAheadProcess = window.setInterval(vs.typeAhead, 1000);
};

vs.typeAheadEnd = function() {
  if (vs.typeAheadProcess != null) {
    window.clearInterval(vs.typeAheadProcess);
  }
};

vs.typeAhead = function() {
  var query = window.encodeURI($('typeAhead').value);
  
  if (!vs.locks.typeAhead && vs.typeAheadQuery != query && query.length > 0) {
    vs.locks.typeAhead = true;
    vs.typeAheadQuery = query;
    vs.execute('typeahead', query, {}, vs.typeAheadResult);    
  }
};

vs.typeAheadResult = function(data) {  
  if (data && data.geos) {
    var geos = data.geos;
    var results = $('typeAheadResults');
    results.empty();
    
    for (var i = 0; i < geos.length; ++i) {
      var geo = geos[i];
      if (geo.rentalCount > 0) {
        $('typeAheadResultName').innerHTML = geo.displayName + ' (' + geo.rentalCount + ')';
        $('typeAheadResult').setProperty('href', 'rentals.html?id=' + geo.locationId);
        results.appendChild($('typeAheadResult').clone().removeClass('hide'));
      }
    }
    
    $('typeAheadResults').removeClass("hide");    
  }
  
  vs.locks.typeAhead = false;
};

vs.parseQueryString = function() {
  var queryString = window.location.search;
  
  if (queryString && queryString.length > 0) {
    return queryString.substring(1).parseQueryString()
  }
};

vs.rentalDetail = function(data) {
  //  .log(data);    
  if (data && data.general) {        
    vs.clearLightbox();
    
    $('modaldetail').setStyles({
      position: 'absolute',
      left: 0,
      top: 0,
      width: window.getScrollWidth(),
      height: window.getScrollHeight(),
      backgroundColor: '#000',
      zIndex: 9000
    }).setOpacity(0.6);
    $('modaldetail').removeClass('hide');  
    
    vs.rental = data;
    $('loading_' + data.general.locationId).addClass('hide');
    
    // setup
    var rental = data.general;
    $('photos').empty();
    
    // Set new data
    $('rentalName').innerHTML = rental.name;
    $('detailType').innerHTML = rental.type;
    
    if (rental.bedrooms > 0) {
      var beds = rental.bedrooms + " Bedrooms";
      
      if (rental.sleeps > 0)
      {
        beds += ", sleeps " + rental.sleeps;
      }
      
      $('detailBed').innerHTML = beds;
    }
     
    if (rental.bathrooms > 0) { 
      $('detailBath').innerHTML = rental.bathrooms + " Bathrooms";
    }
    
    if (rental.overallRating > 0) {
      $('detailRating').innerHTML = "Rating: " + rental.overallRating  + " (" + rental.reviewCount + " reviews)";
    }    
    
    $('rentalDescription').innerHTML = rental.description.replace('\n', '<br/><br/>');
    
    var url = 'http://www.tripadvisor.com' + rental.webUrl;
    $('trip').setProperty('href', url);
    $('webUrl').setProperty('href', url);
  
    vs.detail = new LightFace({
      width: 900,
      height: 600,
      draggable: false,
      title: 'Property Details - ' + rental.name,
      content: $('rentalDetail').innerHTML,
      buttons: [
        { title: 'Contact', event: function() { window.open(url); }, color: 'blue' },
        { title: 'Close', event: function() { vs.clearLightbox(); }, color: 'white' }
      ],
      resetOnScroll: false
    });
  
    vs.detail.open();
    vs.photoIndex = 0;
    vs.photoSlider(vs.photoIndex);
  }
};

vs.photoSlider = function(index) {
  if (vs.rental && vs.rental.photos) {        
    if (index >= 0 && index < vs.rental.photos.length) {
      vs.photoIndex = index;
      var lightBoxPhotos = $$('table.lightface').getElement('div.photos')[0];
      lightBoxPhotos.empty();      
      var photos = vs.rental.photos;      
      
      for (var i = index; i < index + 5 && i < photos.length; ++i) {
        var photo = photos[i];
        var img = null;
        
        img = new Element('img', {src:photo.mediumUrl,width:148,height:111});
        img.setProperty('onclick', 'vs.largePhoto("' + i + '");');
        
       
        lightBoxPhotos.appendChild(img);
      }

      var prevOn = $$('table.lightface').getElement('div.prevPhotoOn')[0];
      var prevOff = $$('table.lightface').getElement('div.prevPhotoOff')[0];
      var nextOn = $$('table.lightface').getElement('div.nextPhotoOn')[0];
      var nextOff = $$('table.lightface').getElement('div.nextPhotoOff')[0];
      
      if (index > 0) {
        prevOn.removeClass('hide');
        prevOff.addClass('hide');
      } else {
        prevOff.removeClass('hide');
        prevOn.addClass('hide');
      }
      
      if (index + 5 < photos.length) {
        nextOn.removeClass('hide');
        nextOff.addClass('hide');
      } else {
        nextOn.addClass('hide');
        nextOff.removeClass('hide');
      }
    }
  }
}

vs.largePhoto = function(index) {
  if (vs.photo && vs.photo != null) {
    vs.photo.close();
    vs.photo.destroy();
    vs.photo = null;
  } 
  
  vs.photo = new LightFace({
    width: 'auto',
    height: 'auto',
    zIndex: 9998,
    draggable: true,
    title: vs.rental.photos[index].caption,
    content: '<div style="text-align:center"><img src="' + vs.rental.photos[index].largeUrl + '" width="320" height="240"/></div>',
    resetOnScroll: true
  });
  
  var windowSize = window.getSize();
  var scrollSize = window.getScrollSize();
  
  $('modalphoto').setStyles({
    position: 'absolute',
    left: 0,
    top: 0,
    width: window.getScrollWidth(),
    height: window.getScrollHeight(),
    backgroundColor: '#000',
    zIndex: 9997
  }).setOpacity(0.6);
  
  $('modalphoto').removeClass('hide');  
  vs.photo.box.addEvent('click', function() {
    var i = parseInt(index);
    if (i + 1 < vs.rental.photos.length) {
      vs.largePhoto(i + 1);
    } else {
      vs.clearLightbox('photo');
    }});
  vs.photo.open();
}

vs.inquiry = function(title, locationId) {
  if (vs.contact && vs.contact != null) {
    vs.contact.close();
    vs.contact.destroy();
    vs.contact = null;
  }
  
  vs.contact = new LightFace({
    width: 400,
    height: 450,
    draggable: true,
    title: title,
    content: $('inquiry').innerHTML,
    buttons: [
      { title: 'Close', event: function() { this.close(); this.destroy(); vs.contact = null; }, color: 'white' },
      { title: 'Submit', event: function() { this.close(); }, color: 'blue' }
    ],
    resetOnScroll: true
  });
  
  vs.contact.open();
};

vs.clearLightbox = function(lightbox) {
  if (lightbox && vs[lightbox]) {  
    vs[lightbox].close();
    vs[lightbox].destroy();
    vs[lightbox] = null;
    
    if ($('modal' + lightbox)) {
      $('modal' + lightbox).addClass('hide');
    }
  } else {
    if (vs.detail && vs.detail != null) {
      vs.detail.close();
      vs.detail.destroy();
      vs.detail = null;
    }
  
    if (vs.contact && vs.contact != null) {
      vs.contact.close();
      vs.contact.destroy();
      vs.contact = null;
    }
  
    if (vs.photo && vs.photo != null) {
      vs.photo.close();
      vs.photo.destroy();
      vs.photo = null;
    }
    
    $('modaldetail').addClass('hide');
    $('modalphoto').addClass('hide');
  }
};

vs.execute = function(method, id, params, callback) {
  var url = 'http://www.tripadvisor.com/api/vacationrentals/1.0/' + method;
  url += (id != null) ? "/" + id : "";  
  params.key = 'e05d1e33-e5ee-44c1-a161-440b42a93325';
  
  new Request.JSONP({
      url: url,
      callbackKey: 'jsoncallback',
      data: params,
      onComplete: callback
  }).send();
};

