function strip(string) {
  return string.replace(/^\s+/, '').replace(/\s+$/, '');
}

function downcase(string) {
  return string.toLowerCase();
}

function slugify(string) {
  return downcase(strip(string)).replace(/[^-a-z0-9~\s\.:;+=_]/g, '').replace(/[\s\.:;=+]+/g, '-');
}

// http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery
$.preloadImages = function(files) {
  for(var i = 0; i < files.length; i++) {
    $("<img>").attr("src", files[i]);
  }
}

// Fix IE's lack of indexOf, courtesy of http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj) {
    for(var i=0; i<this.length; i++) {
      if(this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
}

function showPackages(tag) {
  $.ajax({
    type: "POST",
    url: "/specials-packages/filter",
    data: "tag=" + tag,
    success: function(msg){
      $("#specials-display").html(msg);
    }
  });
}

function filterActionByTag(tag, url, id) {
  // Get the current height of the #specials-display div
  height = $("div.inner")[0].offsetHeight;
  
  // Set that height as the minimum.
  $("#specials-display").css("minHeight",height+"px");
  
  // Fade out the current data
  $("div.inner").animate({opacity:0.01});
  
  // Get the new data
  $.ajax({
    type: "POST",
    url: url,
    data: "tag=" + tag + "&id=" + id,
    success: function(msg){
      // Insert the new data
      $("div.inner").html(msg);
      
      // Get the new height of the inner div
      newHeight = $("div.inner")[0].offsetHeight;
      
      // Increase the size of the container
      $("#specials-display").css("height",height+"px").css("minHeight","0px").animate({duration:2000,height:newHeight+"px"}, function(){
        // Make the inner container appear
        $("div.inner").animate({opacity:1.0},function(){
          if(jQuery.browser.msie) {
            this.style.removeAttribute('filter');
          }
        });
      });
    }
  });
}

function filterPackages(tag, id) {
  filterActionByTag(tag, '/specials-packages/filter', id);
}

function filterEvents(tag, id) {
  filterActionByTag(tag, '/activities/calendar/filter', id);
}

function detectActionToLoad(method) {
  loc = window.location.href;
  hashtag = loc.indexOf("#");
  if(hashtag >= 0) {
    sub = loc.substr(hashtag + 1);
    split = sub.indexOf('|');
    if(split >= 0) {
      tag = sub.substr(0,split);
      id = sub.substr(split + 1);
    } else {
      tag = sub;
      id = 0;
    }
    
    if(tag != null && tag != '') {
      method(tag, id);
    }
  }
}

function detectEventToLoad() {
  detectActionToLoad(filterEvents);
}

function detectPackageToLoad() {
  detectActionToLoad(filterPackages);
}
