var TextItem = Class.create({
    CLASSDEF: {
        name:  'TextItem',
        parent: ImageItem
    },
  
  initialize: function TxtItem_initialize(id, cViewProcess, asset, options) {
    TextItem.parentClass.constructor().call(this, id, cViewProcess, asset, options);
    this.allowHandleResizing = false;
    this.itemType = 1;
    this.itemTypeName = "Text";
    this.textIsUtf8 = false;
    this.editClickEvent = this.editClick.bindAsEventListener(this);
    this.editSaveClickEvent = this.editSaveClick.bindAsEventListener(this);
    this.editCancelClickEvent = this.editCancelClick.bindAsEventListener(this);
    
    this.sizeFieldChangedEvent = this.sizeFieldChanged.bindAsEventListener(this);

    this.fs = dopt(options, "fs", (10).mm_to_pts());  // fs = Font Size
    
    this.text = dopt(options, "text", "");
    this.fontFace = dopt(this.options, "font", null);
    if(this.fontFace==null) {
      this.fontFace = dopt(this.options, "font", this.isWilcomEMB ? "Alice" : "Arial");
      this.checkUtf8();
    }
    this.fontSpec = pwFontManager.allFonts[this.fontFace];
    if(this.fontSpec != null) {
      this.minFontSize = this.fontSpec.minSize;
    } else {
      this.minFontSize = null;
    }
    this.setName(this.text);
    this.isBold = dopt(options, "b", "1");
    this.isItalics = dopt(options, "i", "0");
    
    this.textColorVal = dopt(options, "tc", "#FF3333");
    this.gradientColorVal = dopt(options, "gc", "#FFFFFF");
    this.strokeColorVal = dopt(options, "sc", "#000000");
    this.effectColorVal = dopt(options, "ec", "#000000");
    this.blurVal = dopt(options, "bl", "2");
    this.glowStrength = dopt(options, "gs", "2");
    this.shadow_x = dopti(options, "sh_x", "2");
    this.shadow_y = dopti(options, "sh_y", "2");
    this.shape = dopt(options, "s", "0");
    this.xAmp = dopt(options, "s_x", "0");  
    this.yAmp = dopt(options, "s_y", "35");

    this.strokeWidth = dopti(this.options, "sw", "0");
    
    this.align = dopti(options, "al", "0");
    
    this.oldTabName = "effects";
    if(d.designerOptions.showTextDims()) {
      this.setFeature("dim", true);
    } else {
      this.setFeature("dim", false);
    }
    if(d.designerOptions.showTextAdvanced()) {
      this.setFeature("adv", true);
    } else {
      this.setFeature("adv", false);
    }
    
  },
  
  initialiseManagePane: function TxtItem_initialiseManagePane() {
    log("TextItem.initialiseManagePane()");
    TextItem.parentClass.method("initialiseManagePane").call(this);
    
    this.editButton = $("mp1_" + this.elId + "_edit");
    this.editButton.style.cursor = "pointer";
    Event.observe(this.editButton, "click", this.editClickEvent);
    
    if(!this.canModifyDesign) {
      this.editButton.hide();
    }
    
    this.editSaveButton = $("mp1_" + this.elId + "_save_edit");
    this.editSaveButton.style.cursor = "pointer";
    Event.observe(this.editSaveButton, "click", this.editSaveClickEvent);
    
    this.editCancelButton = $("mp1_" + this.elId + "_cancel_edit");
    this.editCancelButton.style.cursor = "pointer";
    Event.observe(this.editCancelButton, "click", this.editCancelClickEvent);
    
    this.editContainer = $("mp1_" + this.elId + "_edit_text_container");
    this.editTextArea = $("mp1_" + this.elId + "_edit_text");
    
    var self = this;
    
    if((self.isWilcomEMB)&&(this.canModifyDesign)) {
      this.sizeField = $("mp1_" + this.elId + "_sizefield");
      $("mp1_"+this.elId+"_sizefield_container").show();
      this.setSizeText();
      Event.observe(this.sizeField, "keyup", this.sizeFieldChangedEvent);
    }
    
    if(!this.canModifyDesign) {
      $("mp1_"+this.elId+"_li_arrows").hide();
    }
    
    this.fontButtonDiv = $("mp1_" + this.elId + "_font_button");
    this.fontTextImg = $("mp1_" + this.elId + "_font_text");
    
    this.setFontImage();
    this.fontButtonDiv.onclick= function() {
      if(!self.canModifyDesign) {
        alert(ml("You cannot change the font as it may change the price of your order"));
        return;
      }
			self.checkUtf8();
      pwFontManager.selectFont(self.fontFace,  self.isWilcomEMB ? "Alice" : "Arial", self.isWilcomEMB, function(face, fontData) {
          self.fontFace = face;
          self.fontSpec = fontData;
          self.minFontSize = fontData.minSize;
          if(self.isWilcomEMB) {
            self.checkFontSize();
          }
          self.fontStyleChanged("face");
          self.setFontImage();
          self.setDirty();
          self.setText();
      });
    };
    /*
    this.fontInput = $("mp1_" + this.id + "_fonts");
    this.fontInput.onchange = function(el) { self.setText();};

    this.buildFontDropdown();
    //this.fontInput.value = 
    */
    
    this.aligns = [$("mp1_" + this.elId + "_al"), $("mp1_" + this.elId + "_ac"), $("mp1_" + this.elId + "_ar")];
    this.aligns[0].onclick = function() { self.setAlign(0,true);};
    this.aligns[1].onclick = function() { self.setAlign(1,true);};
    this.aligns[2].onclick = function() { self.setAlign(2,true);};
    
    this.setAlign(this.align, false);
    
    
    this.bButton = $("mp1_" + this.elId + "_b");
    this.iButton = $("mp1_" + this.elId + "_i");
    
    if(this.isBold=="0") {
      this.bButton.className = "button_up";
    } else {
      this.bButton.className = "button_down";
    }
    this.bButton.onclick = function() {
      self.fontStyleChanged("bold");
      if(self.isBold=="1") {
        self.isBold = "0";
        self.bButton.className = "button_up";
      } else {
        self.isBold = "1";
        self.bButton.className = "button_down";
      }
      self.setDirty();
      self.setText();
      //d.itemChanged(true);
    };
    
    if(this.isItalics=="0") {
      this.iButton.className = "button_up";
    } else {
      this.iButton.className = "button_down";
    }
    this.iButton.onclick = function() {
      self.fontStyleChanged("italics");
      if(self.isItalics=="1") {
        self.isItalics = "0";
        self.iButton.className = "button_up";
      } else {
        self.isItalics = "1";
        self.iButton.className = "button_down";
      }
      self.setDirty();
      self.setText();
      //d.itemChanged(true);
    };
 
    
    this.strokePanel = $("ep_stroke_" + this.elId);
    this.gradientPanel = $("ep_gradient_" + this.elId);
    this.effectPanel = $("ep_effect_" + this.elId);
    this.shape_panel = $("ep_shape_" + this.elId);
    
    var tc = $("etc_stroke_" + this.elId);
    tc.onclick = function() { self.selectTab("stroke", self.elId); return false; };
    tc = $("etc_gradient_" + this.elId);
    tc.onclick = function() { self.selectTab("gradient", self.elId); return false; };
    tc = $("etc_effects_" + this.elId);
    tc.onclick = function() { self.selectTab("effects", self.elId); return false; };
    tc = $("etc_shape_" + this.elId);
    tc.onclick = function() { self.selectTab("shape", self.elId); return false; };
    
    
    
    this.gradientType = $("ep_gradienttype_" + this.elId);
    this.gradientType.onchange = function(el) { self.fontStyleChanged("gradient"); self.setDirty(); self.setText(); };
    
    this.textColor = $("mp1_" + this.elId + "_cb");
    this.gradientColor = $("ep_gradient_color_" + this.elId);
    this.effectColor = $("ep_effectcolor_" + this.elId);
    this.strokeColor = $("ep_stroke_color_" + this.elId);
    
    this.textColor.style.backgroundColor = this.textColorVal;
    this.textColor.onclick = function() { self.fontStyleChanged("text-color"); self.setColorClick(self.textColor, 1); };
    this.gradientColor.style.backgroundColor = this.gradientColorVal;
    this.gradientColor.onclick = function() { self.fontStyleChanged("gradient-color"); self.setColorClick(self.gradientColor, 2); };
    this.effectColor.style.backgroundColor = this.effectColorVal;
    this.effectColor.onclick = function() { self.fontStyleChanged("effect-color"); self.setColorClick(self.effectColor, 3); };
    this.strokeColor.style.backgroundColor = this.strokeColorVal;
    this.strokeColor.onclick = function() { self.fontStyleChanged("stroke-color"); self.setColorClick(self.strokeColor, 4); };
    
    
    this.sliderStroke = new Control.Slider('ep_stroke_width_' + this.elId + '_s','ep_stroke_width_' + this.elId + '_t', {
      range:$R(0,20),
      values:$R(0,20),
      sliderValue:this.strokeWidth,
      onChange:function(v){ self.strokeWidth=v; self.fontStyleChanged("stroke-width"); self.setDirty(); self.setText(); }
    });
    
    this.effectType = $("ep_effecttype_" + this.elId);
    this.effectType.onchange = function(el) {  self.fontStyleChanged("effect"); self.setEffectType(true);};
    
    //this.glowStrength = $("ep_glow_strength_" + id);
    //this.glowStrength.onclick = function(el) { _this.setDirty(); _this.setText();};
    
    this.sliderGlow = new Control.Slider('ep_g_str_' + this.elId + '_s','ep_g_str_' + this.elId + '_t', {
      range:$R(0,10),
      sliderValue:this.glowStrength,
      onChange:function(v){ self.glowStrength=v; self.fontStyleChanged("glow"); self.setDirty(); self.setText(); }
    });
    
    this.sliderBlur = new Control.Slider('ep_b_str_' + this.elId + '_s','ep_b_str_' + this.elId + '_t', {
      range:$R(0,10),
      sliderValue:this.blurVal,
      onChange:function(v){ self.blurVal=v;  self.fontStyleChanged("blur"); self.setDirty(); self.setText(); }
    });
    
    this.shadowEffects = $("shadow_effects_" + this.elId); 
    this.glowEffects = $("glow_effects_" + this.elId); 
    
    this.shape_select = $("warp_shape_select_"+this.elId);
//    this.shape

    if(!this.allowFeature("text-warp")) {
      $("et_shape_" + this.elId).hide();
    } else {

      if (this.isWilcomEMB) {
        
        var shapes_li = "<ol class='emb_shapes'>" ;
        for(var k in embShapes) {
          var shape = embShapes[k] ;
          shapes_li += "<li id='emb_shape_"+this.elId+"_"+k+"' value='"+k+"' class='"+shape.code+"'><span>"+shape.c+"</span></li>" ;
        }
        shapes_li += "</ol>" ;
        
        this.shape_select.innerHTML = shapes_li ;
        
        for (var k in embShapes) {
          var emb_ele = $('emb_shape_'+this.elId+'_'+k) ;
          var that = this ;
          if (this.shape == k) emb_ele.addClassName("alt") ;
          emb_ele.observe("click", function(e) {
            var ele = Event.element(e);
            if (ele.tagName.toUpperCase() != "LI") ele = ele.parentNode ;
  //          log("** changing element "+that.elId+", from shape "+that.shape+" to "+ele.value) ;
            $("emb_shape_"+that.elId+"_"+that.shape).removeClassName("alt") ;
            ele.addClassName("alt") ;
            self.shape = ele.value ;
            self.setShapeType(true, true);
          }.bind(that));
        }
        
      } else {
        this.shapes = $("ep_shape_sel_down_" + this.elId);
  
        addSelectOption(this.shapes, "None", "0"); 
        addSelectOption(this.shapes, "Arched", "5"); 
        for(var k in availableShapes) {
          var shape = availableShapes[k];
          addSelectOption(this.shapes, shape["c"], k); 
        }
        this.shapes.value = self.shape; // TODO: test this works in IE.
        this.shapes.onchange = function() {
          self.shape = self.shapes.value;
          self.setShapeType(true);
        };
      }
    
      this.xAmpC = $("ep_s_x_" + this.elId);
      this.yAmpC = $("ep_s_y_" + this.elId);
      
      this.sliderX = new Control.Slider('ep_x_str_' + this.elId + '_s','ep_x_str_' + this.elId + '_t', {
        range:$R(0,100),
        sliderValue:this.xAmp,
        onChange:function(v){self.xAmp=v;   self.setDirty(); self.setText();}
      });
      this.sliderY = new Control.Slider('ep_y_str_' + this.elId + '_s','ep_y_str_' + this.elId + '_t', {
        range:$R(0,100),
        sliderValue:this.yAmp,
        onChange:function(v){self.yAmp=v; self.setDirty(); self.setText(); }
      });
    }
    
    this.offsetWidget = $("mp_" + this.elId + "_offset");
    this.offsetHandleWidget = $("mp_" + this.elId + "_offset_handle");
    
    this.offsetHandleWidget.style.top = (this.shadow_y + 18 - offsetWidgetSize) + "px";
    this.offsetHandleWidget.style.left = (this.shadow_x + 18 - offsetWidgetSize) + "px";
    
    //log("this.offsetHandleWidget.style.top=" + this.offsetHandleWidget.style.top);
    //log(this.shadow_x);
    //log(offsetWidgetSize);
    
    this.eventStartOffset =  this.startOffset.bindAsEventListener(this);
    this.eventOffsetMove =  this.offsetMove.bindAsEventListener(this);
    this.eventOffsetFinish =  this.offsetFinish.bindAsEventListener(this);
    Event.observe(this.offsetHandleWidget, "mousedown", this.eventStartOffset);
    
    //this.fsInput.value = dopt(this.options, "fs", "23");
    //this.b_input.checked = (dopt(this.options, "b", "true")=="true")? true:false;
    //this.i_input.checked = (dopt(this.options, "i", "false")=="true")? true:false;
    
    this.gradientType.value = dopt(this.options, "g", "0");
    this.effectType.value = dopt(this.options, "e", "0");
    this.setEffectType(false);
    if(this.allowFeature("text-warp")) {
      this.setShapeType(false);
    }
    this.setText();

    if(this.isWilcomEMB) {
      $("advanced_pane_tabs_" + this.elId).hide();
      this.selectTab("shape", this.elId);
      
      $("mp1_" + this.elId + "_alc").hide();
    }
    if(!this.allowFeature("text-align")) {
      $("mp1_" + this.elId + "_alc").hide();
    }
    if((d.designerOptions.showTextAdvanced())&&(d.designerOptions.showImageAdvancedOpen())) {
      this.advClick();
    }
  },
  
  fontStyleChanged: function TxtItem_fontStyleChanged(attribute) {
    
  },
  
  setFontImage: function TxtItem_setFontImage() {
    if(this.fontTextImg!=null) {
      var font = pwFontManager.allFonts[this.fontFace];
      if(font == null) {
        alert("Cannot find font definition for '" + this.fontFace + "'");
      }
      setTransPng(this.fontTextImg, font.getSampleURL(this.isWilcomEMB), 70, 20);
    }
  },
  
  buildFontDropdown: function TxtItem_buildFontDropdown() {
    if(this.fontInput==null) {
      return;
    }
    while(this.fontInput.firstChild) {
      this.fontInput.removeChild(this.fontInput.firstChild);
    }
    for(var k in availableFonts) {
      if((!this.textIsUtf8)||(availableFonts[k].u)) {
        var opt = document.createElement("OPTION");
        opt.text = k;
        opt.value = k;
        if(BrowserDetect.browser == "Explorer") {
          this.fontInput.options.add(opt);
        } else {
          this.fontInput.appendChild(opt);
        }
      }
    }
  },
  
  moveToDesigner: function TxtItem_moveToDesigner(cViewProcess, resizeScale, oldLeft, oldTop, offsetLeft, offsetTop) {
    /*if(this.el!=null) {
      this.cViewArea.canvas.removeChild(this.el);
      cViewProcess.configuredViewArea.canvas.appendChild(this.el);
    }
    
    if(this.managePane!=null) {
      this.managePane.parentNode.removeChild(this.managePane);
      
      cViewProcess.managePane.appendChild(this.managePane);
    }
    this.cViewProcess = cViewProcess;
    this.cViewArea = cViewProcess.configuredViewArea;
    this.cView = this.cViewArea.configuredView;
    */
    var scale = this.cViewProcess.productProcess.designScale / resizeScale / cViewProcess.productProcess.designScale;
    log("Text Rescale: " + scale + " will change fs from " + this.fs + " to " + (this.fs * scale));
    this.fs = this.fs * scale;
    TextItem.parentClass.method("moveToDesigner").call(this, cViewProcess, resizeScale, oldLeft, oldTop, offsetLeft, offsetTop);
    
    this.setText();
  },
  //do nothing: text can rescale to desired scale....
  checkScale: function TxtItem_checkScale(desiredScale, process) {
    return desiredScale;
  },
  
  del: function TxtItem_del() {
    if(this.editButton!=null) {
      Event.stopObserving(this.editButton, "click", this.editClickEvent);
      Event.stopObserving(this.editSaveButton, "click", this.editSaveClickEvent);
      Event.stopObserving(this.editCancelButton, "click", this.editCancelClickEvent);
      //Event.stopObserving(this.advButton, "click", this.advClickEvent);
    }
    TextItem.parentClass.method("del").call(this);
  },
  
  //does this item handle its own start positions?
  startPosition: function TxtItem_startPosition() {
    this.doCenter = true;
    return true;
  },
  
  setRolloverStyle: function TxtItem_setRolloverStyle() {
    
  },
  
  setLeaveStyle: function TxtItem_setLeaveStyle() {
    this.el.style.zIndex = this.getElementZIndex();
  },

  setSelectStyle: function TxtItem_setSelectStyle() {
    this.el.style.zIndex = 1000;
  },
  
  setAlign: function TxtItem_setAlign(align, fromGUI) {
    this.aligns[this.align].className = "button_up";
    this.aligns[align].className = "button_down";
    this.align = align;
    if(fromGUI) {
      this.fontStyleChanged("align");
      this.setDirty();
      this.setText();
      //d.itemChanged(true);
    }
  },
  
  setColorClick: function TxtItem_setColorClick(el, type) {
    var self = this;
    var color = null;
    if(type==1) {
      color = this.textColorVal;
    } else if(type==2) {
      color = this.gradientColorVal;
    } else if(type==3) {
      color = this.effectColorVal;
    } else if(type==4) {
      color = this.strokeColorVal;
    }
    
    pwColorPicker.selectColor(this.cViewProcess.productProcess.id, el, color,  function(c) { self.colorCallback(c, el, type); }, {});
    //showColorPicker(el, function(c) { self.colorCallback(c, el, type); });
  },
  
  colorCallback: function TxtItem_colorCallback(color, el, type) {
    el.style.backgroundColor = color;
    if(type==1) {
      this.textColorVal = color;
    } else if(type==2) {
      this.gradientColorVal = color;
    } else if(type==3) {
      this.effectColorVal = color;
    } else if(type==4) {
      this.strokeColorVal = color;
    }
    this.setDirty();
    this.setText();
    
    //d.itemChanged(true);
  },
  
  setSizeText: function TxtItem_setSizeText() {
    this.fontStyleChanged("size");
    var num = parseFloat(this.fs).pts_to_mm() ;
    num = Math.round(num*Math.pow(10,2))/Math.pow(10,2);
    if (this.sizeField) { this.sizeField.value = num; };
  },
  
  quickResize: function TxtItem_quickResize(originalSize) {
    var reScale = parseFloat(originalSize) / parseFloat(this.fs);
    this.width /= reScale;
    this.height /= reScale;
    this.setPosition();
    if(this.selected && !this.isMoving) {
      this.autoRepositionHandles();
    }
  },
  
  checkFontSize: function() {
    var num = parseFloat(this.fs).pts_to_mm() ;
    num = Math.round(num*Math.pow(10,2))/Math.pow(10,2);
    var minSize = (this.minFontSize == null) ? 5 : this.minFontSize;
    if(num < minSize) {
      var originalSize = this.fs;
      this.fs = (minSize).mm_to_pts();
      this.setDirty();
      this.setText(false, 3);
      this.setSizeText() ;
      this.quickResize(originalSize) ;
      this.setSizeText();
    }
  },
  
  sizeUpClick: function TxtItem_sizeUpClick(event) {
    Event.stop(event);
    var originalSize = this.fs;
    var newSize = parseFloat(this.fs).pts_to_mm() + 1 ;
    if(newSize <= 50 || !this.isWilcomEMB) {
      this.fontStyleChanged("size");
      this.fs = (newSize).mm_to_pts() ;
      this.setDirty();
      this.setText(false, 3);
      //d.itemChanged(true);
      this.setSizeText() ;
      this.quickResize(originalSize) ;
    }
  },
  
  sizeDownClick: function TxtItem_sizeDownClick(event) {
    Event.stop(event);
    var originalSize = this.fs;
    var newSize = parseFloat(this.fs).pts_to_mm() - 1 ;
    var minSize = (this.minFontSize == null) ? 5 : this.minFontSize;
    if(newSize >= minSize || !this.isWilcomEMB) {
      this.fontStyleChanged("size");
      this.fs = (newSize).mm_to_pts() ;
      this.setDirty();
      this.setText(false, 3);
      //d.itemChanged(true);
      this.setSizeText() ;
      this.quickResize(originalSize) ;
    }
  },

  sizeFieldChanged:function(event) {
    var val = parseFloat(this.sizeField.getValue()) ;
    log("size changed from "+parseFloat(this.fs).pts_to_mm().round()+" to "+val) ;
    if (val == parseFloat(this.fs).pts_to_mm().round()) return ;
    if (isNaN(val)) {
      if (this.sizeField.getValue() == "") {
        log("Caught empty text, don't do anything") ;
        return ;
      } else {
        this.sizeField.value = parseFloat(this.fs).pts_to_mm().round() ;
        log("Caught some dodgy text, resetting to last known number") ;
        return ;
      }
    }
    var originalSize = this.fs ;
    var minSize = (this.minFontSize == null) ? 5 : this.minFontSize;
    if (val < minSize) return ;
    if (val > 50) {
      this.sizeField.value = 50 ;
      if (this.fs == (50).mm_to_pts()) return ;
      this.fs = (50).mm_to_pts() ;
      log("Got a large number,"+val+" change the size to "+parseFloat(this.fs).pts_to_mm()) ;
    }else {
      this.fs = val.mm_to_pts() ;
      log("Got a new number,"+val+" change the size") ;
    }
    this.fontStyleChanged("size");
    this.quickResize(originalSize) ;
    this.setDirty();
    this.setText(false, 3);
    //d.itemChanged(true);
    //this.setSizeText() ;
  },
  
  startOffset: function TxtItem_startOffset(event) {
    log("starting offset");
    Event.stop(event);
    //start tracking mouse movement
    Event.observe(document, "mousemove", this.eventOffsetMove);
    Event.observe(document, "mouseup", this.eventOffsetFinish);
    
    //store the current location of the rotation widget center
    var pos = Position.cumulativeOffset(this.offsetWidget);
    var mxPos = Event.pointerX(event);
    var myPos = Event.pointerY(event);
    var pos2 = Position.cumulativeOffset(this.offsetHandleWidget);
    
    
    this.offset_x_pos = pos[0] + mxPos - pos2[0];
    this.offset_y_pos = pos[1] + myPos - pos2[1];
    return true;
  },
  
  offsetMove: function TxtItem_offsetMove(event) {
    //determine the angle from center of rotation widget to the mouse
    Event.stop(event);
    var mxPos = Event.pointerX(event);
    var myPos = Event.pointerY(event);
    
    var t = (myPos - this.offset_y_pos);
    var l = (mxPos - this.offset_x_pos);
    
    if(t + offsetWidgetSize >36) {
      t = 36 - offsetWidgetSize;
    }
    if(l + offsetWidgetSize >36) {
      l = 36 - offsetWidgetSize;
    }
    if(t < 0 - offsetWidgetSize ) {
      t = 0 - offsetWidgetSize;
    }
    if(l < 0 - offsetWidgetSize ) {
      l = 0 - offsetWidgetSize;
    }
    this.offsetHandleWidget.style.top = t + "px";
    this.offsetHandleWidget.style.left = l + "px";
  },
  
  offsetFinish: function TxtItem_offsetFinish(event) {
    Event.stopObserving(document, "mousemove", this.eventOffsetMove);
    Event.stopObserving(document, "mouseup", this.eventOffsetFinish);
    
    this.shadow_y = parseInt(this.offsetHandleWidget.style.top, 10) + offsetWidgetSize - 18;
    this.shadow_x = parseInt(this.offsetHandleWidget.style.left, 10) + offsetWidgetSize - 18;

    this.setDirty();
    this.setText();
  },
  
  setEffectType: function TxtItem_setEffectType(fromUI) {
    var val = this.effectType.options[this.effectType.selectedIndex].value;
    if(val==0) {
      this.shadowEffects.style.display='none';
      this.glowEffects.style.display='none';
    } else if(val==1) {
      this.shadowEffects.style.display='';
      this.glowEffects.style.display='none';
    } else {
      this.shadowEffects.style.display='none';
      this.glowEffects.style.display='';
    }
    if(fromUI) {
       this.setDirty();
       this.setText();
    }
  },
  
  setShapeType: function TxtItem_setShapeType(fromUI, emb) {
    if(!emb) emb = false ;
    
    if(this.shape == "5") {
      this.yAmpC.style.display='';
    } else {
      var shape = emb ? embShapes[this.shape] : availableShapes[this.shape];
      if(shape==null) {
        this.xAmpC.style.display='none';
        this.yAmpC.style.display='none';
      } else {
        if(shape["x"]) {
          this.xAmpC.style.display='';
        } else {
          this.xAmpC.style.display='none';
        }
        if(shape["y"]) {
          this.yAmpC.style.display='';
        } else {
          this.yAmpC.style.display='none';
        }
      }
    }
    if(fromUI) {
       this.setDirty();
       this.setText();
    }
  },
                
  selectTab: function TxtItem_selectTab(tab, id) {
    if(this.oldTabName != null) {
      if(this.oldTabName==tab) {
        return;
      }
      var oldTab = $('ep_' + this.oldTabName + "_" + id);
      oldTab.style.display='none';
      oldTab = $('et_' + this.oldTabName + "_" + id);
      oldTab.className = "et_unselected_tab";
    }
    var newTab = $('ep_' + tab + "_" + id);
    newTab.style.display='';
    newTab = $('et_' + tab + "_" + id);
    newTab.className = "et_selected_tab";
    this.oldTabName = tab;
  },
  
  beforeAddNew: function TxtItem_beforeAddNew() {
    popup('new_text_popup');
    $("new_text").focus();
    return true;
  },
  
  continueAdd: function TxtItem_continueAdd() {
    this.text = $("new_text").value;
    $("new_text").value = "";
    this.setName(this.text);
    this.checkUtf8();
  },
  
  buildElement: function TxtItem_buildElement() {
    this.el = document.createElement("IMG");
    this.el.id = "d_" + this.elId;
    this.el.style.display = "none";
    this.el.style.position = "absolute";
    this.el.style.cursor="pointer";
	
    /*
    if(useAlphaHack) {
      this.el.src = d.pathPrefix + "/images/trans.gif";
      this.el.style.fontSize = "1px";
      //el.style.display="inline-block";
      this.el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.asset.url + '", sizingMethod="scale")';
      //this.el.style.filter = 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod="auto expand")\nprogid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.asset.url + '", sizingMethod="scale")';
    } else {
      this.el.src = this.asset.url;
    }*/
    if(useAlphaHack) {
      this.el.src = d.pathPrefix + "/images/trans.gif";
    }
    this.cViewArea.canvas.appendChild(this.el);
    this.el.style.zIndex = this.getElementZIndex();
    
    return this.el;
  },
  
  sizeChanged: function TxtItem_sizeChanged() {
    this.updateTitleSize();
  },
  
  editClick: function TxtItem_editClick(event) {
    Event.stop(event);
    if(!this.canModifyDesign) {
      alert(ml("You cannot edit the text as it may change the price of your order"));
      return;
    }
    this.select();
    this.editTextArea.value = this.text;
    this.editButton.style.display = 'none';
    this.managePaneBody.style.display = 'none';
    this.editContainer.style.display = '';
    return false;
  },
  
  editSaveClick: function TxtItem_editSaveClick(event) {
    if(this.editTextArea.value=="") {
      alert(ml("NO_TEXT"));
      return;
    }
    this.text = this.editTextArea.value;
    this.checkUtf8();
    this.setName(this.text);
    this.editButton.style.display = '';
    this.managePaneBody.style.display = '';
    this.editContainer.style.display = 'none';
    this.setDirty();
    this.setText();
  },
  
  editCancelClick: function TxtItem_editCancelClick(event) {
    this.editButton.style.display = '';
    this.managePaneBody.style.display = '';
    this.editContainer.style.display = 'none';
  },
  
  
  rotationChanged: function TxtItem_rotationChanged(deg) {
    var self = this;
    if(this.rotDelay != null) {
      window.clearTimeout(this.rotDelay);
    }
    this.rotDelay = window.setTimeout( function() { 
      self.setDirty();
      self.setText(false); 
      //d.itemChanged(true);
    }, 100);
    return;
  },
  
  serializeToOptions: function Item_serializeToOptions(o) {
    o = TextItem.parentClass.method("serializeToOptions").call(this,o);
    
    o.font = this.fontFace;

    o.fs = this.fs;
    o.scale = this.cViewProcess.productProcess.designerScale;
                                                      
    o.al = this.align;
                                                                                              
    o.b = this.isBold;
    o.i = this.isItalics;
      
    o.text =  this.text;
                                                      
    o.tc = this.textColorVal;
    o.gc = this.gradientColorVal;
    o.sc = this.strokeColorVal;
    o.ec = this.effectColorVal;
                                                      
    o.sw = this.strokeWidth;
                                                      
    o.g = this.gradientType.value;
                                                      
    o.e = this.effectType.value;
    o.gs = this.glowStrength;
    o.bl = this.blurVal;
                                                      
    o.sh_x = this.shadow_x;
    o.sh_y = this.shadow_y;
                                                      
    o.s = this.shape;
    o.s_x = this.xAmp;
    o.s_y = this.yAmp;
    
    return o;
  },
  
  
  serializeOLD: function TxtItem_serialize(queryComponents, prefix) {
    if(prefix==null) {
      prefix = "t[" + this.id + "]";
    }
    if(queryComponents==null) {
      queryComponents = new Array();
    }
    TextItem.parentClass.method("serialize").call(this,queryComponents,prefix);
    
    //if(this.fontInput != null) {
      //queryComponents.push(encodeURIComponent(prefix + "[font]") + "=" + encodeURIComponent(this.fontInput.value));
      queryComponents.push(encodeURIComponent(prefix + "[font]") + "=" + encodeURIComponent(this.fontFace));
      
      
    //}
    queryComponents.push(encodeURIComponent(prefix + "[fs]") + "=" + encodeURIComponent(this.fs));
    queryComponents.push(encodeURIComponent(prefix + "[scale]") + "=" + encodeURIComponent(this.cViewProcess.productProcess.designerScale));
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[al]") + "=" + encodeURIComponent(this.align));
                                                      
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[b]") + "=" + encodeURIComponent(this.isBold));
    queryComponents.push(encodeURIComponent(prefix + "[i]") + "=" + encodeURIComponent(this.isItalics));
                                                      
    var txt = encodeURIComponent(this.text);          
    queryComponents.push(encodeURIComponent(prefix + "[text]") + "=" + txt);
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[tc]") + "=" + encodeURIComponent(this.textColorVal));
    queryComponents.push(encodeURIComponent(prefix + "[gc]") + "=" + encodeURIComponent(this.gradientColorVal));
    queryComponents.push(encodeURIComponent(prefix + "[sc]") + "=" + encodeURIComponent(this.strokeColorVal));
    queryComponents.push(encodeURIComponent(prefix + "[ec]") + "=" + encodeURIComponent(this.effectColorVal));
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[sw]") + "=" + encodeURIComponent(this.strokeWidth));
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[g]") + "=" + encodeURIComponent(this.gradientType.value));
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[e]") + "=" + encodeURIComponent(this.effectType.value));
    queryComponents.push(encodeURIComponent(prefix + "[gs]") + "=" + encodeURIComponent(this.glowStrength));
    queryComponents.push(encodeURIComponent(prefix + "[bl]") + "=" + encodeURIComponent(this.blurVal));
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[sh_x]") + "=" + encodeURIComponent(this.shadow_x));
    queryComponents.push(encodeURIComponent(prefix + "[sh_y]") + "=" + encodeURIComponent(this.shadow_y));
                                                      
    queryComponents.push(encodeURIComponent(prefix + "[s]") + "=" + encodeURIComponent(this.shape));
    queryComponents.push(encodeURIComponent(prefix + "[s_x]") + "=" + encodeURIComponent(this.xAmp));
    queryComponents.push(encodeURIComponent(prefix + "[s_y]") + "=" + encodeURIComponent(this.yAmp));
    return queryComponents.join('&');
  },
  
  setText: function TxtItem_setText(doDelay, pass) {
    //var updateInfo = this.startUpdating();
    if(doDelay==null) {
      doDelay = true;
    }
    if(pass == null) {
      pass = 1;
    }
    var self = this;
    if(this.textDelay != null) {
      window.clearTimeout(this.textDelay);
      this.textDelay = null;
    }
    if(doDelay) {
      this.textDelay = window.setTimeout( function() { self.setText(false); }, 100);
      return;
    }
    
    var url = "";
    if(pass != 3) {
    //startAsyncAction();
    //if(useAlphaHack) { //we are now always using 2 stage method...
      url =  d.pathPrefix + "/designer/prepare_text?id=" + this.id + "&cp=" + this.cView.configuredProduct.id + "&cpv=" + this.cView.id + "&cpva=" + this.cViewArea.id + "&cpvap=" + this.cViewProcess.id + "&pass=" + pass;
      
      ajaxQueueManager.queueRequest("save_product/" + this.cView.configuredProduct.id, 3, {
          mode: 0,
          subKey: "text_" + this.id,
          url: url,
          options: {asynchronous:true, evalScripts:true, parameters:this.serialize([],"a")}
      });
    }
    if(pass == 1 || pass == 3) { //we gen the preview on first pass, high quality on second...
      this.textDelay = window.setTimeout( function() { self.setText(false, 2); }, 1000);
    }
    /*
    } else {
      url =  d.pathPrefix + "/text/transform_text_bling?" + this.serialize([],"a");
      var _el = this.el;
      this.el.onload = function() {
        _el.style.visibility = "hidden";
        _el.removeAttribute("width");
        _el.removeAttribute("height");
        _el.style.width = null;
        _el.style.height = null;
        self.width = _el.width / self.cViewProcess.productProcess.designScale;
        self.height = _el.height  / self.cViewProcess.productProcess.designScale;
        if(self.doCenter) {
          log("centering");
          self.top = (self.cViewProcess.productProcess.fullHeight - self.height) / 2;
          self.left = (self.cViewProcess.productProcess.fullWidth - self.width) / 2;
          self.doCenter = false;
        } else {
          log("NOT centering");
        }
        log(self.width);                                                   
        self.setPosition();
        _el.style.visibility = "";
        if(self.selected) {
          self.autoRepositionHandles();
        }
        finishAsyncAction();
      };
      this.el.src = url;
    }*/
  },
  
  tbTransformed: function TxtItem_tbTransformed(data) {
    log("tbTransformed" );
    log(data);
    var checkCropIssue = true;
    //finishAsyncAction();
    if(parseInt(data.version, 10) == this.renderVersion) { //we have made more changes just update the image....
      this.width = parseInt(data.width, 10); // / this.layoutManager.layoutData.dScale;
      this.height = parseInt(data.height, 10);  // / this.layoutManager.layoutData.dScale;
    }
    if(this.doCenter) {
      this.top = (this.cViewProcess.productProcess.fullHeight - this.height) / 2;
      this.left = (this.cViewProcess.productProcess.fullWidth - this.width) / 2;
      this.doCenter = false;
    }
    if(this.isWilcomEMB) {
      if(this.stitchCount != parseInt(data.thread_count, 10)) {
        this.stitchCount = parseInt(data.thread_count, 10);
        d.currentProductType.updatePrice();
      }
      if(data.text_quality == "preview") {
        checkCropIssue=false;
      }
    }
    
    this.setPosition();
    //var url = d.pathPrefix + "/text/get_prepared_text_bling?f=" + encodeURIComponent(fname) + "&ts=" + new Date().getTime();
    this.setSrc(data.url, {v: data.version, checkCropIssue:checkCropIssue});
    if(this.selected && !this.isMoving) {
      this.autoRepositionHandles();
    }
    
    this.enablePane();
  },
  
  
  //check if uses utf-8 characters and limit fonts available...
  checkUtf8: function() {
    var usedUtfPages = this.usedUtf8();
		if(usedUtfPages != null) {
      pwFontManager.utf8Pages = usedUtfPages;
			//check the current font supports utf8...
			var f = pwFontManager.allFonts[this.fontFace];
			if(f == null) {
        log("checkUtf8: unable to find font");
        return;
      } else if(f.supportsPages(usedUtfPages)) {
        log("checkUtf8: font supports utf8");
				return;
			}
      log("checkUtf8: font does not support utf8, this.isWilcomEMB=" + this.isWilcomEMB);
			//current font doesnt support it... go set font to first utf8 font...
			for(var k in pwFontManager.allFonts) {
        var f = pwFontManager.allFonts[k];
				if((f.embFont == this.isWilcomEMB)&&(f.supportsPages(usedUtfPages))) {
					this.fontFace = f.name;
          log("Changed font to " + f.name);
					this.setFontImage();
					return;
				}
			}
      log("No Fonts Support UTF8");
		} else {
      pwFontManager.utf8Pages = null;
		}
	},
  
  usedUtf8: function TxtItem_usesUtf8() {
    var usedPages = {};
    var foundLanguage = false;
    for(var i=0;i < this.text.length; i++) {
      var theChar = this.text.charCodeAt(i);
      if(theChar != 32) { //ignore spaces....
        var pages = this.getUtfCodePage(theChar);
        if(pages == null) {
          alert("Unable to get code page for " + theChar);
        } else {
          var codes = pages[3];
          if(codes == null) codes = pages[2];
          usedPages[codes] = true;
          foundLanguage = true;
          //log(theChar + "=" + codes);
        }
      }
    }
    return foundLanguage ? usedPages : null;
  },
  
  getUtfCodePage: function TxtItem_getUtfCodePage(i) {
    var left = 0;
    var right = utf8CodePages.length - 1;
    while (left <= right) {
      var mid = parseInt((left + right)/2);
      var page = utf8CodePages[mid];
      if(page[0] <= i && page[1] >= i)
        return page;
      else if (page[0] < i)
        left = mid + 1;
      else
        right = mid - 1;
    }
    return null;
  },
  
  setHeight: function TxtItem_setHeight(height) {
    this.el.style.height = height + "px";
    return true;
  },
  
  setWidth: function TxtItem_setWidth(width) {
    this.el.style.width = width + "px";
    return true;
  }
  
});
