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() {
  if(typeof esi == "undefined") {
    this.esi = {
      version: '0.1beta'
    }
  }

  esi.getcookie = function(name) {
    if (document.cookie.length > 0) {
      var start = document.cookie.indexOf(name + "=");
      if(start != -1) { 
        start = start + name.length + 1; 
        var end = document.cookie.indexOf(";", start);
        if (end == -1) {
          end=document.cookie.length;
        }
        return unescape(document.cookie.substring(start,end));
      } 
    }
    return "";
  }

  esi.setcookie = function(name, value, expiredays) {
    var d=new Date();
    d.setDate(d.getDate()+expiredays);
    document.cookie=name+"="+escape(value)+((expiredays==null) ?"": ";expires="+d.toGMTString()) + "; path=/";
  }

  esi.rollon = function() {
    var s = $(this).attr('src').split('.');
    if(s == undefined || s[0] == undefined || s[1] == undefined) {
      return;
    }
    $(this).attr('src', s[0]+'_over.'+s[1]);
  }

  esi.rolloff = function() {
    var s = $(this).attr('src').split('_over');
    if(s == undefined || s[0] == undefined || s[1] == undefined) {
      return;
    }
    $(this).attr('src', s[0]+s[1]);
  }

  esi.geocode = function(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({address:address}, function(results, status) {
      if(status == google.maps.GeocoderStatus.OK && results.length) {
        var loc = results[0].geometry.location;
        callback(loc.lat(), loc.lng());
      } else {
        callback(0.0, 0.0);
      }
    });
  }

  esi.gmap = function(id, address, zoom, ready) {
    this.map = null;
    this.geocoder = null;
    this.lat = null;
    this.lng = null;
    this.opts = {useStaticMap: false, zoom:zoom, center: null, mapTypeId: google.maps.MapTypeId.ROADMAP};

    if(typeof address === "object") {
      this.lat = address.lat;
      this.lng = address.lng;
    }

    if(this.lat) {
      var latlng = new google.maps.LatLng(this.lat, this.lng);
      this.opts.center = latlng;
      this.map = new google.maps.Map(document.getElementById(id), this.opts);
    } else {
      this.geocoder = new google.maps.Geocoder();
      var m = this;
      this.geocoder.geocode({address:address}, function(results, status) {
        if(status == google.maps.GeocoderStatus.OK && results.length) {
          var loc = results[0].geometry.location;
          m.lat = loc.lat();
          m.lng = loc.lng();
          m.opts.center = loc;
          m.map = new google.maps.Map(document.getElementById(id), m.opts);
        }
        if(typeof ready == "function") {
          ready(m.map ? m : null);
        }
      });
    }

    this.getLat = function() {
      return this.lat;
    };

    this.getLng = function() {
      return this.lng;
    };

    this.marker = function(lat, lng, content, title, image) {
      var latlng = new google.maps.LatLng(lat, lng);
      var infowindow = new google.maps.InfoWindow({content: content});
      var opts = {position: latlng, map: this.map, title: title};

      if(typeof image === "string") {
        opts.icon = image;
      }

      var marker = new google.maps.Marker(opts);

      var m = this;
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(m.map, marker);
      });
    };

    this.icons =  {
      "center":"/images/markers/red_MarkerC.png",
      "rn":"/images/markers/blue_MarkerR.png",
      "lpn":"/images/markers/green_MarkerL.png",
      "clerk":"/images/markers/yellow_MarkerC.png",
      "home":"/images/markers/home.png",
      "h1n1": "/images/markers/orange_MarkerH.png"
    };
  }

  esi.uploader = function(id, url, cb) {
    this.id = id;
    this.posturl = url;
    this.doneCb = cb;
    // defaults
    this.postData = {file:'file'};
    this.size = 500;
    this.types = '*.jpg;*.png;*.gif;*.jpeg';
    this.description = 'Images';
    this.spriteId = id+'_button';
    this.spriteImage = '/images/browse_sprite.png';
    this.spriteWidth = 81;
    this.spriteHeight = 22;

    this.setMaxSize = function(size) {
      this.size = size;
    };
    this.setTypes = function(types) {
      this.types = types;
    };
    this.setDescription = function(description) {
      this.description = description;
    };
    this.setPostData = function(postData) {
      this.postData = postData;
    }
    this.setUploadSprite = function(sprite) {
      this.spriteImage = sprite.image;
      this.spriteHeight = sprite.height;
      this.spriteWidth = sprite.width;
    }

    this.init = function() {
      var sprite = '<div style="float:left;" id="'+this.spriteId+'"></div>';
      var progress = '<div class="progress"><div class="progresswidth"></div></div><div class="progresspct"></div>';
      $('#'+this.id).append(sprite).append(progress);

      var cb = esi.uploader.callbacks;
      var up = new SWFUpload({
        // Backend Settings
        upload_url: this.posturl,
        post_params: this.postData,
    
        // File Upload Settings
        file_size_limit : this.size * 1000,
        file_types : this.types,
        file_types_description : this.description,
        file_upload_limit : "10",
        file_queue_limit : "0",
    
        // Event Handler Settings (all my handlers are in the Handler.js file)
        file_dialog_start_handler : cb.dialog.start,
        file_queued_handler : cb.dialog.queued,
        file_queue_error_handler : cb.dialog.error,
        file_dialog_complete_handler : cb.dialog.complete,
        upload_start_handler : cb.progress.start,
        upload_progress_handler : cb.progress.working,
        upload_error_handler : cb.progress.error,
        upload_success_handler : cb.progress.success,
        upload_complete_handler : cb.progress.complete,
        swfupload_loaded_handler: cb.loaded,
    
        button_image_url : this.spriteImage,
        button_placeholder_id : this.spriteId,
        button_width: this.spriteWidth,
        button_height: this.spriteHeight,
        button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,

        // Flash Settings
        flash_url : "/swf/swfupload.swf",

        // Debug Settings
        debug: false,
        custom_settings: {
          progressTarget: this.id
        }
      });
    }
  }

  esi.uploader.callbacks = {
    loaded: function() {
    },
    dialog: {
      start: function() {
        var p = $('#'+this.customSettings.progressTarget);
        $('.progresswidth', p).width(0);
        $('.progresspct', p).text('');
        $('.progress', p).hide();
      },
      queued: function(file) {
        var p = $('#'+this.customSettings.progressTarget);
        $('.progress', p).show();
        return true;
      },
      error: function(file, errorCode, message) {
        return true;
      },
      complete: function(nSelected, nQueued) {
        this.startUpload();
      }
    },
    progress: {
      start: function(file) {
        var p = $('#'+this.customSettings.progressTarget);
        return true;
      },
      working: function(file, bytesLoaded, bytesTotal) {
        var p = $('#'+this.customSettings.progressTarget);
        var pct = Math.round( (bytesLoaded / bytesTotal) * 100);
        var w = pct;
        $('.progresswidth', p).width(w);
        $('.progresspct', p).text(pct + '%');
      },
      success: function(file, serverResponse) {
        var p = $('#'+this.customSettings.progressTarget);
        $('.progresswidth', p).width(100);
        $('.progresspct', p).text('100%');
        $('.progresswidth>span', p).text('');
        $('.pic', p).attr('src', serverResponse);
      },
      complete: function(file) {
      },
      error: function(file, errorCode, message) {
      }
    }
  }
})();
