function indexCanvas(id, src, cnt, postype){
  this.id = id;
  this.cnt = cnt;
  this.src = src;
  this.type = 0;
  this.postype = postype ? postype : 0;
  
  this.obj = null;
  this.img = false;
}

indexCanvas.prototype.getWindowSize = function(){
  return({
    w : (window.innerWidth ? window.innerWidth : $(window).width()),
    h : (window.innerHeight ? window.innerHeight : $(window).height())
  });
}

indexCanvas.prototype.create = function(){
  if(!document.createElement('canvas').getContext){
    this.obj = document.createElement('DIV');
    this.obj.style.top = '0px';
    this.obj.style.left = '0px';
    this.type = 1;
  }else{
    this.obj = document.createElement('CANVAS');
  }
  this.obj.id = this.id;
  
  return (this.obj);
}


indexCanvas.prototype.calcPosition = function(w, h){
  var nw = w;
  var nh = Math.round(this.img.height * (nw / this.img.width));
  
  if (nh < h) {
    nh = h;
    nw = Math.round(this.img.width * (nh / this.img.height));
  }
  
  var nx = 0;//this.postype ? 0 : -Math.round((nw - w) / 2);
  var ny = 0;//-Math.round((nh - h) / 2);
  
  return ({
    x: nx,
    y: ny,
    w: nw,
    h: nh
  });
}

indexCanvas.prototype.draw = function(w, h){
  if(!w&&!h){var wh=this.getWindowSize();w=wh.w;h=wh.h;}
  switch (this.type) {
    case 1:
      this.cnt.appendChild(this.obj);
      this.obj.style.width = w + 'px';
      this.obj.style.height = h + 'px';
      
      this.obj.style.backgroundImage = "url('" + this.src + "')";
      this.obj.style.backgroundRepeat = 'no-repeat';
      this.obj.style.backgroundPosition = 'bottom left';
      break;
    default:
      this.img = new Image();
      $(this.img).bind('load', {
        refObj: this, w: w, h: h
      }, function(e){
        var refObj = e.data.refObj;
        var pos = refObj.calcPosition(e.data.w, e.data.h);
        refObj.cnt.appendChild(refObj.obj);
        
        refObj.obj.width = w;
        refObj.obj.height = h;
        var ctx = refObj.obj.getContext('2d');
        ctx.width = w;
        ctx.width = h;
        ctx.drawImage(this, pos.x, pos.y, pos.w, pos.h);
      });
      
      this.img.src = this.src;
      break;
  }
  return (this.cnt);
}

indexCanvas.prototype.resize = function(w, h){
  if(!w&&!h){var wh=this.getWindowSize();w=wh.w;h=wh.h;}
  switch (this.type) {
    case 1:
      this.obj.style.width = w + 'px';
      this.obj.style.height = h + 'px';
      break;
    default:
      var ctx = this.obj.getContext('2d');
      ctx.clearRect(0, 0, this.obj.width, this.obj.height);
      
      this.cnt.style.width = w + 'px';
      this.cnt.style.height = h + 'px';
      
      this.obj.width = w;
      this.obj.height = h;
      
      ctx.width = w;
      ctx.height = h;
      
      var pos = this.calcPosition(w, h);
      ctx.drawImage(this.img, pos.x, pos.y, pos.w, pos.h);
      break;
  }
  return (true);
}
