/*global Ext, window*/

Ext.ns('Ext.ux.form');

// Class Ext.ux.form.Dimensions extends Ext.form.Field
//
Ext.ux.form.URLField = Ext.extend(Ext.form.Field, {

  defaultAutoCreate: {tag: 'input', type: 'hidden'}, // hidden field to be submitted to server
  
  name: '',
  
  allowBlank: true,
  
  disabled: false,
  
  fieldWidth: 400,        // Width of URL field in pixels (defaults to 40)
  
  urlFieldValue: '',         // Value of URL field (defaults to '')
  
  httpUrlLabel: 'http://',
  
  regex: /^(((http)|(https)):\/\/)?(((\w)|\-)+\.)+([\w\/])*(\.){0,1}\w{2,9}$/i,
  
  regexText: 'This field should be a URL in the format "http://www.domain.com"',
  
  viewButtonText: 'View',    // Text for view button
   
  validUrlCharErrorMessage: 'You must enter a valid URL character!',

  validateUrlErrorMessage: 'You must enter a valid URL in order to view that web page!',   //Error message on click of invalid url
  
  
  // private
  // creates URL TextField and installs the necessary event handlers
  initComponent: function () {
    //local variables
    var urlFieldConfig, viewButtonConfig;
    
    // call parent initComponent
    //Ext.form.TextField.superclass.initComponent.call(this);
    //Ext.Button.superclass.initComponent.call(this);
   
    //forming field name & ids
    this.fieldName = (this.name !== '') ? this.name: this.id;
    this.errorHolderId = this.id + '.ERR';
    
    //To overide key events
    this.keyEventOverride();

    // create url Field
    
    urlFieldConfig = Ext.apply({}, {
      id: this.id + '_url',
      allowBlank: this.allowBlank,
      disabled: this.disabled,
      width: this.fieldWidth,
      selectOnFocus: this.selectOnFocus,
      regex: this.regex,
      regexText: this.regexText,
	    listeners: {
	      keyup: {scope: this, fn: this.onKeyupURL}
	    }
    }, this.urlFieldConfig);

    if (this.focus !== undefined)
    {
      urlFieldConfig.listeners.focus = this.focus;
    }
    this.urlField = new Ext.form.TextField(urlFieldConfig);
    this.urlField.ownerCt = this;

    // The view address button
    viewButtonConfig = Ext.apply({}, {
      id: this.id + '_view-button',
      name: this.id + '_view-button',
      disabled: this.disabled,
      text: this.viewButtonText,
      listeners: {
        click: {scope: this, fn: this.checkUrlField}
      }
    }, this.viewButtonConfig);
    
    this.viewButtonField = new Ext.Button(viewButtonConfig);
    
  },
  
  // private
  onRender: function (ct, position) {
    //local variables
    var domHelperObj;
    // don't run more than once
    if (this.isRendered)
    {
      return;
    }

    // render underlying hidden field
    Ext.form.TextField.superclass.onRender.call(this, ct, position);

    // create bounding table
    domHelperObj = Ext.DomHelper.append(ct, {
      tag: 'table',
      children: [{
        tag: 'tr',
        children: [
          {tag: 'td', valign: 'top', style: 'padding-right:4px', html: this.httpUrlLabel},
          {tag: 'td', valign: 'top', style: 'padding-left:0px;padding-right:4px', cls: this.id + 'ux-url x-form-element'},
          {tag: 'td', valign: 'top', style: 'padding-right:4px', cls: this.id + 'ux-view'}
        ]
      }, {
        tag: 'tr',
        children: [
          {tag: 'td', colspan: 3, id: this.errorHolderId, cls: 'field-error', style: 'display:none', html: ''}
        ]
      }]
    }, true);

    // render url & view fields
    this.urlField.render(domHelperObj.child('td.' + this.id + 'ux-url'));
    this.viewButtonField.render(domHelperObj.child('td.' + this.id + 'ux-view'));

    // prevent helper fields from being submitted
    this.urlField.el.dom.removeAttribute("name");
    
    // setup name for submit
    this.el.dom.name = this.fieldName;

    // we're rendered flag
    this.isRendered = true;
  },
  // private - to update the hidden field
  updateHidden: function () {
    var regX, isMatched, urlValue; 
    if (this.urlField.isValid())
    {
      urlValue = this.urlField.getValue();
      regX = /(http|https):\/\//i;
      isMatched = urlValue.match(regX);
      if (isMatched === null)
      {
        urlValue = "http://" + urlValue;
      }
      this.el.dom.value = urlValue;
    }
    else
    {
      this.el.dom.value = '';
    }    
  },
  //private - to update the hidden field
  onKeyupURL: function () {
    this.updateHidden();
  },
  //private - to check url and open a pop up for the url(if valid)
  checkUrlField: function () {
    //local variables
    var urlField, urlValue, regX, isMatched;
      
    urlField = this.isValid();
    if (urlField === false)
    {
      Ext.Msg.alert("Error!!", this.validateUrlErrorMessage);
    }
    else
    {
      urlValue = this.urlField.getValue();
      regX = /(http|https):\/\//i;
      isMatched = urlValue.match(regX);
      if (isMatched === null)
      {
        urlValue = "http://" + urlValue;
      }
      window.open(urlValue, "url", "height=500,scrollbars=yes,menubar=yes,toolbar=yes,location=yes,width=780,resizable=yes,top=10,left=10");
    }
  },
  //private - to validate url characters
  isValid: function () {
    //local variables
    var url, objRE;
    
    url = this.urlField.getValue();
    objRE = /^(((http)|(https)):\/\/)?(((\w)|\-)+\.)+([\w\/])*(\.){0,1}\w{2,9}$/i;
    if (!objRE.test(url))
    {
      this.urlField.markInvalid();
      return false;
    }
    else
    {
      this.urlField.clearInvalid();
      return true;     
    }  
  },
  //{{{
  /**
    * private
    * function to override the key events
    */
  keyEventOverride: function () {
    Ext.override(Ext.form.Field, {
      fireKey: function (e) {
        if (((Ext.isIE && e.type === 'keydown') || e.type === 'keypress' && e.type === 'keyup') && e.isSpecialKey())
        {
          this.fireEvent('specialkey', this, e);
        }
        else
        {
          this.fireEvent(e.type, this, e);
        }
      },
      initEvents: function () {
        this.el.on("focus", this.onFocus,  this);
        this.el.on("blur", this.onBlur,  this);
        this.el.on("keydown", this.fireKey, this);
        this.el.on("keypress", this.fireKey, this);
        this.el.on("keyup", this.fireKey, this);
                 
        // reference to original value for reset
        this.originalValue = this.getValue();
      }
    });
  },// eo keyEventOverride
  //}}}
  //{{{
  /**
    * private
    * function to enable the component
    */
  enable: function () {
    this.urlField.enable();
    this.viewButtonField.enable();
  },// eo enable
  //}}}
  //{{{
  /**
    * private
    * function to disable the component
    */
  disable: function () {
    this.urlField.disable();
    this.viewButtonField.disable();
  },// eo disable
  //}}}
  //{{{
  /**
    * private
    * function to clear invalid message
    */
  clearInvalid: function () {
    this.urlField.clearInvalid();
  },// eo disable
  //}}}
  //{{{
  /**
    * private
    * function to reset the url field
    */
  reset: function () {
    this.urlField.reset();
  }// eo disable
  //}}}
});

// register xtype
Ext.reg('xurl', Ext.ux.form.URLField);

