var Asset = Class.create({
  CLASSDEF: {
      name: 'Asset'
  },
  
  initialize: function A_initialize(options, designer) {
    

    this.id = options.id;
    this.baseUrl = options.bURL; //base url
    this.urlOptions = {
       bURL: options.bURL,
       tURL: options.tURL,
       sURL: options.sURL,
       url: options.url
    };
    
    this.sUrl = this.baseUrl + "/" + options.sURL; //small url
    this.url = this.baseUrl + "/" + options.tURL; //thumb url
    this.wUrl = this.baseUrl + "/" + options.url; //working url
    this.width = options.width;
    this.height = options.height;
    
    this.type = options.type;
    this.usesTransparency = options.trans;
    this.name = options.name;
    this.colors = options.c;
    this.colorWays = options.cw;
    this.defaultColorway = options.dcw;
    this.stitchCount = options.tc;
    this.processes = options.p;
    this.ownerType = options.ot;
    this.imageType = options.it;
    this.defaultColorCount = options.dcc;
    this.metaData = options.meta;
    
    this.aspectRatio = parseFloat(this.width) / parseFloat(this.height);
    var d = this.scale(100,100);
    this.tHeight = d.h;
    this.tWidth = d.w;
    this.workingAssetLoaded = false;
    this.version = 0;
    this.decorationLibraryId = options.dl;
    this.digitizedProcessId = options.dp;
    this.digitizedState = options.dps;
    //NTA: we need to set the "real asset id" which requires asset.to_json to include self.asset_id
    //this will also need LibraryImage to be updated (they duplicate functionality)
    
  },
  
  getUrl: function A_getUrl() {
    //log("getting url");
    if(this.version==0) {
      return this.url;
    }
    return this.addUrlParameter(this.url,this.version);
  },
  
  getWUrl: function A_getWUrl() {
    if(this.version==0) {
      return this.wUrl;
    }
    return this.addUrlParameter(this.wUrl, this.version);
  },
  
  getSUrl: function A_getSUrl() {
    //log("getting url");
    if(this.version==0) {
      return this.sUrl;
    }
    return this.addUrlParameter(this.sUrl,this.version);
  },
  
  addUrlParameter: function A_addUrlParameter(url, param) {
    if(url.indexOf("?") == -1) {
      return url + "?" + param;
    } else {
      return url + "&" + param;
    }
  },
  
  scale: function A_scale(mh,mw) {
    return this.scaleDims(this.height, this.width, mh, mw);
  },
  
  scaleDims: function A_scaleDims(h,w,mh,mw) {
    var s1 = mh / h;
    var s2 = mw / w;
    
    if(s1 > s2) {
      s1 = s2;
    }
    return {h: h * s1, w: w * s1};
  },
  
  getItemType: function A_getItemType() {
    return 0;
  },
  
  loadWorkingAsset: function A_loadWorkingAsset(callback) {
    if(this.workingAssetLoaded) {
      callback();
      return;
    }
    if(this.waCallbacks != null) {
      this.waCallbacks.push(callback);
      return;
    }
    log("building callback img");
    this.waCallbacks = [callback];
    var cbimg = document.createElement("IMG");
    cbimg.style.display = "none";
    //var self = this;
    
    backgroundLoadImage(this.getWUrl(), function(data) {
        
        this.workingAssetLoaded = true;
        for(var i=0;i<this.waCallbacks.length;i++) {
          this.waCallbacks[i]();
        }
        this.waCallbacks = null;
        
    }.bind(this), null);
    
    /*document.body.appendChild(cbimg);
    log("appended img");
    cbimg.src = this.getWUrl();
    if(cbimg.complete) {
      self.workingAssetLoaded = true;
      for(var i=0;i<self.waCallbacks.length;i++) {
        self.waCallbacks[i]();
      }
      self.waCallbacks = null;
      document.body.removeChild(cbimg);
    } else {
      cbimg.onload = function() {
        log("loaded");
        self.workingAssetLoaded = true;
        for(var i=0;i<self.waCallbacks.length;i++) {
          self.waCallbacks[i]();
        }
        self.waCallbacks = null;
        document.body.removeChild(cbimg);
      };
    }*/
  },
  
  refresh: function A_refresh() {
    var a = $("g_0_" + this.id);
    if(a!=null) {
      a.src = this.getUrl();
    }
    a = $("g_1_" + this.id);
    if(a!=null) {
      a.src = this.getUrl();
    }
  },
  
  getMetaData: function A_getMetaData(keys) {
    var curMap = this.metaData; 
    for(var i=0; i < keys.length; i++) {
      if(curMap == null) {
        return null;
      }
      curMap = curMap[keys[i]];
    }
    return curMap;
  },
  
  setMetaData: function A_setMetaData(keys, value) {
    if(this.metaData == null) {
      this.metaData = {};
    }
    var curMap = this.metaData;
    var subMap = null;
    for(var i=0; i < keys.length - 1; i++) {
      subMap = curMap[keys[i]];
      if(subMap == null) {
        subMap = {};
        curMap[keys[i]] = subMap;
      }
      curMap = subMap;
    }
    curMap[keys[keys.length-1]] = value;
    return value;
  },
  
  getColors: function A_getColors(colorCount) {
    if(colorCount == 8 && this.colors != null) {
      return this.colors; //backwards compatability
    }
    if(colorCount == null) {
      colorCount = this.defaultColorCount;
    }
    if(colorCount == null) {
      return;
    }
    return this.getMetaData(["split_colors", colorCount, "colors"]);
  },
  
  getOpacity: function A_getOpacity(transparentColor, callback) {
    if((transparentColor==null) && (!this.usesTransparency)) {
      //no need to check with server....
      callback(1.0);
    } else if((transparentColor==null) && (this.getMetaData("percent_opaque") != null)) {
      //we already have the percent opaque...
      callback(parseFloat(this.getMetaData("percent_opaque")));
    } else {
      var ajax = new Ajax.Request(d.ajaxUrl("/ppr/shared/library/get_percent_opaque/" + this.id + ((transparentColor==null) ? "" : ("?trans_color=" + encodeURIComponent(transparentColor)))) , {
            asynchronous:true, 
            evalScripts:true, 
            onSuccess: function A_onSuccess(transport) {
              var data =  transport.responseText.evalJSON();
              callback(parseFloat(data.percent_opaque));
            },
            onFailure: function A_onFailure(transport) {
              alert(ml("An error occured getting opacity details of image"));
            }
        });
    }
  },
  
  hasCost: function A_hasCost() {
    if(this.decorationLibraryId == 0 || this.decorationLibraryId == null) {
      return false; // we aren't a decorationLibrary so we have no charge
    } else {
      return (d.chargeDecorationLibraries[this.decorationLibraryId].range1price > 0);
    }
  },
  
  // find the unit cost of a decoration library asset
  itemCost: function A_itemCost() {
    log("asset " + this.id + " decorationLibraryId " + this.decorationLibraryId);
    if(this.decorationLibraryId == 0 || this.decorationLibraryId == null) {
      return 0; // we aren't a decorationLibrary so we have no charge
    } else {
      // find all usages of this asset in all products
      var qty = 0;
      for (var i=0; i < d.cart.products.length; i++) {
       product = d.cart.products[i];
       var product_asset_qty = 0;
       for (var view_id in product.views) {
         var view = product.views[view_id];
         for (var area_id in view.areas) {
           var area = view.areas[area_id];
           for (var item_id in area.allItems) {
             var item = area.allItems[item_id];
             if(item.asset.id == this.id ) { //NTA: check asset.real_id as well
               product_asset_qty++;
             }
           };
         };
       };
       qty = product_asset_qty * product.qty;
      };

      dec_price = d.chargeDecorationLibraries[this.decorationLibraryId];
      if(dec_price != null) {
        if(qty >= 0 && qty <= 4) {
          var rangeprice = dec_price.range1price;
        } else if (qty >= 5 && qty <= 12) {
          var rangeprice = dec_price.range2price;
        } else if (qty >= 13 && qty <= 24) {
          var rangeprice = dec_price.range3price;
        } else if (qty >= 25 && qty <= 48) {
          var rangeprice = dec_price.range4price;
        } else if (qty >= 49 && qty <= 72) {
          var rangeprice = dec_price.range5price;
        } else if (qty >= 73 && qty <= 144) {
          var rangeprice = dec_price.range6price;
        } else if (qty >= 145) {
          var rangeprice = dec_price.range7price;
        }
        
        rangeprice = rangeprice + (d.declibMarkup / 100) * rangeprice;
        return rangeprice;
      } else {
        return 0;
      }
    }
  }
});

var TextAsset = Class.create({
  CLASSDEF : {
      name:  'TextAsset',
      parent: Asset
  },
  initialize: function TA_initialize(options) {
    this.height = 16;
    this.width = 14;
    this.url = d.pathPrefix + "/images/mp/text_icon.gif";
  },
  getItemType: function TA_getItemType() {
    return 1;
  }
});

var TeamNameAsset = Class.create({
  CLASSDEF : {
      name:  'TeamNameAsset',
      parent: Asset
  },
  initialize: function TN_initialize(options) {
    this.height = 16;
    this.width = 14;
    this.url = d.pathPrefix + "/images/mp/text_icon.gif";
  },
  getItemType: function TN_getItemType() {
    return 2;
  }
});
