/*global Ext, escape*/

Ext.ns('Ext.ux.form');

Ext.ux.form.CompanyField = Ext.extend(Ext.ux.form.BaseField, {
  /**
    * @cfg {String/Object} defaultAutoCreate DomHelper element spec
    * Let superclass to create hidden field instead of textbox. Hidden will be submittend to server
    */
  defaultAutoCreate: {tag: 'input', type: 'hidden'},
  
  name: '',
  
  allowBlank: true,
  
  defaultCompanyId: '',                                                 // Default company id
  
  defaultCompanyName: '',                                               // Default company name to be shown as the component get loaded

  personRecordId: '',
  
  companyRecordId: '',  

  isStoreCompanyId: true,

  searchCompanyServiceMethod: 'SearchCompany',                          // Name of the service method to fetch companies

  searchCompanyServiceByURLMethod: 'SearchCompany',                     // Name of the service method to fetch companies

  saveCompanyServiceMethod: 'SaveCompany',                              // Name of the service method for saving company
  
  searchCompanyParam: 'strSearch',                                      // Search parameter  

  companyComboEmptyText: 'Type company name',     
  
  companyComboWidth: 400,
  
  searchFieldWidth: 250,

  searchFieldMaxLength: '',

  searchForText: 'Search for:',

  searchButtonText: 'Search',

  cancelButtonText: 'Cancel',

  companyData: [],
  
  errorMsg: 'This is required field',

  companyGridWindowTitle: 'Company Search',

  companyGridWindowWidth: 727,
  
  companyGridWindowHeight: 350,
  
  companyGridWidth: 600,
  
  companyNameColWidth: 155,
  
  companyLocationColWidth: 140,
  
  companyWebsiteColWidth: 202,
  
  companyDescColWidth: 202,

  companyGridTitle: 'Company List',
  
  addCompanyDialogWidth: 500,
  
  addCompanyDialogHeight: 180,
  
  addCompanyFormWidth: 500,
  
  addCompanyFieldWidth: 300,
    
  addCompanyDialogTitle: 'Add Company',
  
  companyNameLabel: 'Company Name',
  
  companyUrlLabel: 'Primary Company Web Page Address',
  
  // {{{
  /**
    * private
    * creates company component fields
    */
  initComponent: function () {
    //local variables
    var companyConfig, removeCompanyConfig; 
    
    //call parent initComponent
    Ext.form.ComboBox.superclass.initComponent.call(this);
    Ext.form.TextField.superclass.initComponent.call(this);
        
    //forming field name & ids
    this.fieldName = (this.name !== '') ? this.name: this.id;
    this.errorHolderId = this.id + '.ERR';
    
    //setting blank value to the variables companyId & companyName initially
    this.companyId = '';
    this.companyName = '';
    
    
    //Combo Event Override
    Ext.override(Ext.form.ComboBox, {
      initEvents : function () {
        Ext.form.ComboBox.superclass.initEvents.call(this);
        this.queryDelay = Math.max(this.queryDelay || 10, this.mode === 'local' ? 10 : 250);
        this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
        if (this.typeAhead)
        {
          this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
        }
      },
      /*onKeyUp : function (e) {
		//  alert("Ssrr");
        if (this.editable !== false && !e.isSpecialKey())
        {
          this.lastKey = e.getKey();
          this.dqTask.delay(this.queryDelay);
        }
        Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
      },*/
      filter: function (value) {
        if (this.filterFn)
        {
          return this.store.filterBy(this.filterFn.createDelegate(this));
        }
        return this.store.filter(this.displayField, value, this.anyMatch, this.caseSensitive);
      },
      filterFn: function (r) {
        var queryText;
        if (r.data[this.valueField] === '')
        {
          if (this.lastQuery.search(/\S/) !== -1)
          {
            //r.data[this.displayField] = 'Add <b>' + this.lastQuery + '</b> as Company';
          }  
          return true;
        }
        else
        {
          queryText = new RegExp("^" + Ext.escapeRe(this.lastQuery), "i");
          return queryText.test(r.data[this.displayField]); 
        }  
      },
      doQuery : function (q, forceAll) {
        var queryObject;
        q = Ext.isEmpty(q) ? '' : q;
        queryObject = {
          query: q,
          forceAll: forceAll,
          combo: this,
          cancel: false
        };
        if (this.fireEvent('beforequery', queryObject) === false || queryObject.cancel)
        {
          return false;
        }
        q = queryObject.query;
        forceAll = queryObject.forceAll;
        if (forceAll === true || (q.length >= this.minChars))
        {
          if (this.lastQuery !== q)
          {
            this.lastQuery = q;
            if (this.mode === 'local')
            {
              this.selectedIndex = -1;
              if (forceAll)
              {
                this.store.clearFilter();
              }
              else
              {
                this.filter(q);
              }
              this.onLoad();
            }
            else
            {
              this.store.baseParams[this.queryParam] = q;
              this.store.load({
                params: this.getParams(q)
              });
              this.expand();
            }
          }
          else
          {
            this.selectedIndex = -1;
            this.onLoad();
          }
        }
      }
    });
    
    this.companyData =  [];
    if (this.defaultCompanyId.search(/\S/) !== -1 && this.defaultCompanyName.search(/\S/) !== -1)
    {
      this.companyData[0] = [this.defaultCompanyId, this.defaultCompanyName, '', ''];
    }
    else
    {
      this.defaultCompanyId = '';
      this.defaultCompanyName = '';
    }
    //store config
    this.companyStore = {
      fields: ['id', 'name', 'location'],
      data: this.companyData
    };
    this.companyStore = new Ext.data.SimpleStore(this.companyStore); 
    
    this.resultTpl = new Ext.XTemplate(
      '<tpl for="."><div class="' + this.id + '_search-item x-combo-list-item" style="height:auto;white-space:normal">' +
      '<div style="width:200px;float:left;display:block">{name}</div>' +
      '<div style="width:150px;float:left;padding-left:5px;">{location}</div>' +
      '</div><div style="clear:both"></div></tpl>'
    );
    
    companyConfig = Ext.apply({}, {
      id: this.id + '-com-field',
      name: this.id + '-com-field',
      allowBlank: this.allowBlank,
      xtype: 'combo',
      store: this.companyStore,
      mode: 'local',
      displayField: 'name',
      valueField: 'id',
      emptyText: this.companyComboEmptyText,
      width: this.companyComboWidth,
      triggerAction: 'all',
      autoSelect: false,
      selectOnFocus: true,
      forceSelection: true,
      enableKeyEvents: true,
      tpl: this.resultTpl,
      itemSelector: 'div.' + this.id + '_search-item',
      listeners: {
        select: {
          scope: this,
          fn: function (combo) {
            var regX;
            combo.ownerCt.updateHidden();
            regX = new RegExp("Add( )(.*)( )as Company");
            if (combo.getRawValue().match(regX) === null)
            {
              combo.setRawValue(combo.getRawValue().replace(/&amp;/g, "&"));
            }
            else
            {
              combo.setRawValue('Add ' + this.searchText + ' as Company');
              this.openAddCompanyDialog(this.searchText);
            }            
          }
        },
        keyup: {
          scope: this, 
          fn: function (combo) {
            var prevSearchStr = '';
            if (this.searchText !== undefined)
            {
              prevSearchStr = this.searchText;
            }
            if (combo.getRawValue().search(/\S/) !== -1 && prevSearchStr !== combo.getRawValue())
            {
              this.searchText = combo.getRawValue();
              this.updateHidden();
              try{ this.delayObj.cancel(); } catch(ex){}
              this.delayObj = new Ext.util.DelayedTask(function () {
                combo.ownerCt.loadCompanyStore();	
              });
              this.delayObj.delay(1500);
            }  
          } 
        },
        blur: {
          scope: this, 
          fn: function (combo) {
            this.updateHidden();
          } 
        }
      }
    }, this.companyConfig);
    this.companyField = new Ext.form.ComboBox(companyConfig);
    this.companyField.ownerCt = this;
    // to select the default company
    if (this.defaultCompanyId !== '')
    {
      this.companyField.setValue(this.defaultCompanyId);
    }
    
        
    removeCompanyConfig = Ext.apply({}, {
      xtype: 'button',
      id: this.id + '_remove_company',
      name: this.id + '_remove_company',
      text: 'Cancel',
      listeners: {
        click: { scope: this, fn: this.removeCompany }
      }
    }, this.removeCompanyConfig);
           
    this.removeCompanyField = new Ext.Button(removeCompanyConfig);
    this.removeCompanyField.ownerCt = this;
    
  }, // eo initcomponent
  // }}}
  // {{{
  /**
    * private
    * Renders the fields 
    */
  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);
    
    this.ct = ct;
    this.position = position;

    // create bounding table
    domHelperObj = Ext.DomHelper.append(ct, {
      tag: 'table',
      children: [{
        tag: 'tr',
        children: [
          { tag: 'input', type: 'hidden', id: 'CoID' + this.id, name: 'CoID' + this.id},
          { tag: 'input', type: 'hidden', id: this.id + '.D', name: this.id + '.D'},
          { tag: 'td', valign: 'top', cls: this.id + '_ux-company-field' },
          { tag: 'td', valign: 'top', cls: this.id + '_ux-remove-company-btn' },
          {
            tag: 'td',
            id: this.id + '_loading-symbol',
            style: 'display:none;',
            children: [{tag: 'img', src: this.loadingImage}]
          }
        ]
      }, {
        tag: 'tr',
        children: [{tag: 'td', colspan: 3, id: this.errorHolderId, cls: 'field-error',  style: 'display: none', html: ''}]
      }]
    }, true);

    // render buttons
    this.companyField.render(domHelperObj.child('td.' + this.id + '_ux-company-field'));
    this.removeCompanyField.render(domHelperObj.child('td.' + this.id + '_ux-remove-company-btn'));

    // setup name for submit
    this.el.dom.name = this.fieldName;

    // we're rendered flag
    this.isRendered = true;

    //update the underlying hidden field
    this.updateHidden();

  }, // eo onRender
  // }}}
  // {{{
  /**
    * private
    * To set appropriate default value to the combo the fields 
    */
  setComboDefaultValue: function () {
    // to select the default company if companyId & companyName are blank
    if (this.companyId === '' && this.companyName === '')
    {
      if (this.defaultCompanyId !== '' && this.defaultCompanyName !== '')
      {
        this.companyField.setValue(this.defaultCompanyId);
        this.companyField.setRawValue(this.defaultCompanyName);
      }
      else
      {
        this.companyField.setRawValue(this.companyComboEmptyText);
      }
      this.updateHidden();
    }
    else
    {
      this.companyId = '';
      this.companyName = '';
    }
  }, // eo setComboDefaultValue
  // }}}
  // {{{
  /**
    * private
    * To Updates the underlying hidden field value
    */
  updateHidden: function (flag) {
    var selText, companyName, companyId, regX, isMatched, i;
    selText = this.companyField.getRawValue();
    regX = new RegExp("Add( )(.*)( )as Company");
    if (this.isRendered && selText !== this.companyComboEmptyText && selText.match(regX) === null) 
    {
      isMatched = false;
      //to check if selected text is matching with any of the combo option
      for (i = 0; i < this.companyData.length; i = i + 1)
      {
        if (this.companyData[i][1] === selText)
        {
          if (this.companyField.getValue() !== '')
          {
            companyId = this.companyField.getValue();
          }
          else
          {
            companyId = this.companyData[i][0];
          }          
          companyName = this.companyField.getRawValue();
          isMatched = true;
          break;
        }
      }
      if (isMatched)
      {
        if (this.isStoreCompanyId)
	      {
          this.el.dom.value = companyId;
        }
        else
	      {
          this.el.dom.value = companyName;
        }
        Ext.get('CoID' + this.id).dom.value = companyId;
        Ext.get(this.id + '.D').dom.value = companyName;
      }
      else
      {
        this.el.dom.value = '';
        if (flag !== undefined && flag === true)
	    {
          //this.resetCompanyField();
        }
        Ext.get('CoID' + this.id).dom.value = '';
        Ext.get(this.id + '.D').dom.value = '';
      }      
    }
    else
    { 
      this.el.dom.value = '';
      Ext.get('CoID' + this.id).dom.value = '';
      Ext.get(this.id + '.D').dom.value = '';
    }
  }, // eo function updateHidden
  // }}}
   // {{{
  /**
    * private
    * function to reset company field
    */
  resetCompanyField: function () {
    if (this.companyField.getRawValue().search(/\S/) !== -1 && this.companyField.getRawValue() !== this.companyComboEmptyText)
	{
      this.companyField.setValue('');
      this.companyField.setRawValue('');
    }
  }, // eo function resetCompanyField
  // }}}
  // {{{
  /**
    * private
    * function to take necessary action onchange of client combo
    */
  removeCompany: function () {
    this.companyField.setRawValue(this.companyComboEmptyText);
    this.updateHidden();
  }, // eo function onSelect  
  // }}}
  // {{{
  /**
    * private
    * function to display the loading image 
    */
  displayLoadingImage: function () {
    Ext.get(this.id + '_loading-symbol').dom.innerHTML = '<img src="' + this.loadingImage + '" border="0" align="middle" alt="">';
  },
  //}}}
  // {{{
  /**
    * private
    * function to load company store with the fetched companies 
    */
  loadCompanyStore: function () {
    this.showLoadingImage();
    this.ajaxRequest({
      url: this.http + this.serverName + '/' + this.applicationName + '/' + this.handlerName + '/' + this.searchCompanyServiceMethod,
      params: {
        'strSearch': escape(this.searchText)
      },
      method: 'post',
      success: function (result, request) {
        if (request.params.strSearch === escape(request.ownerCt.searchText))
        {
          request.ownerCt.companyString = result.responseText;
          request.ownerCt.populateCompanyData();
        }  
        request.ownerCt.hideLoadingImage();
      },
      failure: function (result, request) {
        if (request.params.strSearch === request.ownerCt.searchText)
        {
          request.ownerCt.companyString = undefined;
          request.ownerCt.populateCompanyData();
        } 
        request.ownerCt.hideLoadingImage(); 
      }
    });
  },
  //}}}
  //{{{
  /**
    * private
    * function to populate company data to the company combo 
    */
  populateCompanyData: function () {
    this.processCompanyData();       // To process the company data fetched via web service
    this.companyStore.removeAll();
    this.companyStore.loadData(this.companyData); // To load te company combo with fetched data
    this.updateHidden(true);
  },
  //}}}
  //{{{
  /**
    * private
    * function to process company data in array format 
    */
  processCompanyData: function () {
    //local variables
    var tempArray, ccount, row;
    this.companyData = [];
    this.companyData[0] = ['', 'Add ' + this.searchText + ' as Company', ''];
    if (this.defaultCompanyId !== '')
    {
      this.companyData[1] = [this.defaultCompanyId, this.defaultCompanyName, ''];
    }
    if (this.companyString)
    {
      tempArray = [];
      tempArray = this.jsonDecoder(this.companyString);
      for (ccount = 0; ccount < tempArray.length; ccount = ccount + 1) {
        row = Ext.util.JSON.decode(tempArray[ccount]);
        this.companyData[this.companyData.length] = [row.ClientId, row.ClientName, row.ClientLocation];
      }
    }  
  },
  //}}}
  //{{{
  /**
    * private
    * function to reload the company combo with new company
    */
  reloadCompanyCombo: function () {
    var i, isMatched;
    isMatched = false;
    if (this.companyId !== '' && this.companyName !== '')
    {
      for (i = 0; i < this.companyData.length; i = i + 1)
      {
        if (this.companyId === this.companyData[i][0])
        {
          isMatched = true;
          break;
        }
      }
      if (!isMatched)
      {
        this.companyData[this.companyData.length] = [this.companyId, this.companyName];
      }  
      this.companyStore.removeAll();
      this.companyStore.loadData(this.companyData);
      this.companyField.setValue(this.companyId);
    }
    else
    {
      this.setComboDefaultValue();
    }
    this.updateHidden();
  },
  //}}}
  // {{{
  /**
    * private
    * This is to update company combo as records are clicked in the company grid 
    */
  updateCompany: function (grid, rowIndex, colIndex, e) {
    //local variables
    var record;
    record = grid.getStore().getAt(rowIndex);
    this.companyId = record.data.id;
    this.companyName = record.data.name;
    this.reloadCompanyCombo();
    if (this.resultWindow !== undefined)
    {
      this.closeDialog(this.resultWindow);
    }
    if (this.companyListWindow !== undefined)
    {
      this.closeDialog(this.companyListWindow);
    } 
    if (this.searchByUrlWindow !== undefined)
    {
      this.closeDialog(this.searchByUrlWindow);
      this.closeDialog(this.cancelDialog);
    }    
  },
  //}}}
  //{{{
  /**
    * private
    * Common function to close dialog
    */
  closeDialog: function (dialog) {
    //for search company dialog
	  if (dialog === this.resultWindow)
	  {
	    if (this.resultWindow !== undefined)
      {
        this.resultWindow.close.defer(20, this.resultWindow);
      }  
	    this.resultWindow = undefined;
	  }
	  //for add company dialog
	  if (dialog === this.addCompanyDialog)
	  {
	    if (this.addCompanyDialog !== undefined)
      {
        this.addCompanyDialog.destroy.defer(20, this.addCompanyDialog);
      }  
	    this.addCompanyDialog = undefined;
	  }
    //for cancel dialog
	  if (dialog === this.cancelDialog)
	  {
	    if (this.cancelDialog !== undefined)
      {
        this.cancelDialog.close.defer(20, this.cancelDialog);
      }  
	    this.cancelDialog = undefined;
	  }
    //for search company by URL dialog
    if (dialog === this.searchByUrlWindow)
	  {
	    if (this.searchByUrlWindow !== undefined)
      {
        this.searchByUrlWindow.close.defer(20, this.searchByUrlWindow);
      }  
	    this.searchByUrlWindow = undefined;
	  }
    if (dialog === this.companyListWindow)
    {
      if (this.companyListWindow !== undefined)
      {
        this.companyListWindow.close.defer(20, this.companyListWindow);
      }
	    this.companyListWindow = undefined;
    }
  },// eo closeDialog function
  //}}}	
  //{{{
  /**
    * private
    * This is to open add company dialog
    */
  saveCompany: function (saveFlag) {
    this.enableBodyMask();
    if (this.companyRecordId.search(/\S/) !== -1 ||  this.personRecordId.search(/\S/) !== -1)
    {
      this.ajaxRequest({
        url: this.http + this.serverName + '/' + this.applicationName + '/' + this.handlerName + '/' + this.saveCompanyServiceMethod + '?strNewCoNoMatch=' + saveFlag + '&strNewCoURL=' + escape(this.newCompanyUrl) +  '&strNewCoName=' + escape(this.newCompanyName) + '&lngPersonRecordID=' + this.personRecordId + '&lngCompanyRecordID=' + this.companyRecordId,
        success: function (result, request) {
          var response;
          response = request.ownerCt.jsonDecoder(result.responseText);
          request.ownerCt.disableBodyMask();
          if (typeof(response) === 'number')
          {
            if (response !== 0)
            {
              request.ownerCt.companyId = response;
              request.ownerCt.companyName = request.ownerCt.newCompanyName;
              //Ext.Msg.alert("Company Saved", "Company is Saved Successfully");
            }
            else
            {
              request.ownerCt.companyId = '';
              request.ownerCt.companyName = '';
              //Ext.Msg.alert("Error", "Unable to add company! Try later.");
            }            
            request.ownerCt.reloadCompanyCombo();
            request.ownerCt.closeDialog(request.ownerCt.addCompanyDialog);
          }
          else
          {
            request.ownerCt.showMatchedCompanyList(response); 
          }
        },
        failure: function (result, request) { 
          var response;
          response = result.responseText;
          Ext.Msg.alert("Error", "Page Request Failed");
          request.ownerCt.setComboDefaultValue();
          request.ownerCt.disableBodyMask();
        }
      });
    }
    else
    {
      this.disableBodyMask();
      Ext.Msg.alert("Error", "Unable to save due to invalid set of parameters!");
    }
  },//eo saveCompany
  //}}}
  //{{{
  /**
    * private
    * This is to open add company dialog
    */
  openAddCompanyDialog: function (inputText) {
	  var saveCompanyButton, cancelButton, companyNameField, companyUrlField, addCompanyForm;
    //to reset companyId & companyName values
    this.companyId = '';
    this.companyName = '';
    //this.closeDialog(this.addCompanyDialog); // to remove the hidden company dialog(if exists)
	  if (this.addCompanyDialog !== undefined)
    {
      if (inputText.search(/\S/) !== -1)
	    {
	      Ext.get('X' + this.id + 'NewCoName').dom.value = inputText;
	    }
	    else
	    {
	      Ext.getCmp('X' + this.id + 'NewCoName').reset();
	    }
      Ext.getCmp('X' + this.id + 'NewCoURL').reset();
      this.addCompanyDialog.show();
      return;
    }
    //Buttons
	  saveCompanyButton = new Ext.Button({
      text: 'Save',
      listeners: {
        click: {
          scope: this, 
          fn: function () {
            if (Ext.getCmp('X' + this.id + 'NewCoName').isValid() && Ext.getCmp('X' + this.id + 'NewCoURL_url').isValid())
            {
              this.newCompanyName = Ext.get('X' + this.id + 'NewCoName').getValue();
              this.newCompanyUrl = Ext.get('X' + this.id + 'NewCoURL').getValue();
              
              if (this.checkCompanyName(this.newCompanyName))
              {
                //this.closeDialog(this.addCompanyDialog);
                this.addCompanyDialog.hide();
                this.saveCompany('');
              }
              else
              { 
                this.addCompanyDialog.hide();
                this.showCompanyNameWarning(this.newCompanyName);
              } 
            }
            else
            {
              Ext.getCmp('X' + this.id + 'NewCoName').isValid();
              Ext.getCmp('X' + this.id + 'NewCoURL_url').isValid();
            }
          }
        }
      }
    });
    
    //Cancel Button
    cancelButton = new Ext.Button({
      text: 'Cancel',
      listeners: {
        click: {
          scope: this,
          fn: function () { 
            //this.closeDialog(this.addCompanyDialog);
            this.addCompanyDialog.hide();
            this.cancelSaveCompany(companyNameField.getValue());
          }  
        }
      }    
    });
    //Company name field
	  companyNameField = new Ext.form.TextField({
	    id: 'X' + this.id + 'NewCoName',
      name: 'X' + this.id + 'NewCoName',
	    fieldLabel: this.companyNameLabel,
	    allowBlank: false
	  });
    
    //Company url field
	  companyUrlField = new Ext.ux.form.URLField({
      id: 'X' + this.id + 'NewCoURL',
      name: 'X' + this.id + 'NewCoURL',
	    fieldWidth: (this.addCompanyFieldWidth - 44),
      fieldLabel: this.companyUrlLabel,
	    allowBlank: false
    });
    
    Ext.form.Field.prototype.msgTarget = 'under';
    //Add Company Form
    addCompanyForm = new Ext.FormPanel({
      frame: true,
      border: true,
      width: this.addCompanyFormWidth,
      defaultType: 'textfield',
      defaults: {labelSeparator: '&nbsp;', width: this.addCompanyFieldWidth},
      items: [companyNameField, companyUrlField],
      buttons: [saveCompanyButton, cancelButton],
      region: 'center'
    });
    
    // Add Company Dialog
    this.addCompanyDialog = new Ext.Window({
      title: this.addCompanyDialogTitle,
      closable: true,
      width: this.addCompanyDialogWidth,
	    height: this.addCompanyDialogHeight,
      border: false,
      plain: true,
      layout: 'border',
	    modal: true,
      items: [addCompanyForm],
      listeners: {
        close: {
          scope: this,
          fn: function () {
            this.setComboDefaultValue();
            this.closeDialog(this.addCompanyDialog);
          }  
        }
      }
    });
    this.addCompanyDialog.show(this); 
    //to set the comapany name field value with the input text
    if (inputText.search(/\S/) !== -1)
    {
		  companyNameField.setValue(inputText);
	  }
  }, // eo function openAddCompanyDialog  
  //}}}
  //{{{
  /**
    * private
    * This is to check company name for the first letter in upper case
    */
  checkCompanyName: function (companyName) {
    var i, companyNameArr, isValid;
    
    companyNameArr = companyName.split(' ');
    isValid = true;
    for (i = 0; i < companyNameArr.length; i = i  + 1)
    {
      if (companyNameArr[i] !== (companyNameArr[i].substr(0, 1).toUpperCase() + companyNameArr[i].substr(1).toLowerCase()))
      {
        isValid = false;
        break;
      }
    }
    return isValid;
  },
  //}}}
  //{{{
  /**
    * private
    * This is show company name warning dialog
    */
  showCompanyNameWarning: function (companyName) {
    var warningMsg, buttonArr;
 
    warningMsg = "This <b>" + companyName + "</b> field will be presented as part of your company's overall record. Generally Company Names are presented in Title Case, where the first letters of each word are capitalized. The Company Name as you entered it is not in this format. Are you sure this is the proper way you wish to display your Company Name?<br><br>";
    
    buttonArr = []; 
    
    buttonArr[0] = new Ext.Button({
      text: 'Ok',
      listeners: {
        click: {
          scope: this,
          fn: function () { 
            this.addCompanyDialog.hide();
            this.warningBox.close.defer(20, this.warningBox);
            this.saveCompany('');
          }
        }  
      }
    });

    buttonArr[1] = new Ext.Button({
      text: 'Cancel',
      listeners: {
        click: {
          scope: this,
          fn: function () { 
            this.warningBox.close.defer(20, this.warningBox);
          }  
        }
      }    
    });

    this.warningBox = new Ext.Window({
      title: 'Warning!',
      width: 600,
      height: 160,
      bodyStyle: 'padding:5px;',
      items: [{
        xtype: 'label',
        html: warningMsg
      }],
      buttons: buttonArr,
      buttonAlign: 'center',
      closable: true,
      draggable: false,
      modal: true,
      listeners: {
        close: {
          scope: this,
          fn: function () {
            this.setComboDefaultValue();
          }
        }
      }
    });
    
    this.warningBox.show();
  },
  //}}}
  //{{{
  /**
    * private
    * This is to show the list of company having with the website entered 
    */
  showMatchedCompanyList: function (matchedCompanyData)
  {
    var i, errMsg, matchedCompanyArray, rowData, matchedCompanyGrid, gridStore;
    matchedCompanyArray = [];
    
    for (i = 0; i < matchedCompanyData.length; i = i + 1)
    {
      rowData = this.jsonDecoder(matchedCompanyData[i]);
      if (rowData.StatusCode !== undefined && parseInt(rowData.StatusCode, 10) === 0) {
        if (rowData.Description !== undefined && rowData.Description.search(/\S/) !== -1)
        {
          errMsg = rowData.Description;
        }
        else
        {
          errMsg = "Database Operation Failed. Try Again!";
        }
        this.setComboDefaultValue();
        Ext.Msg.alert("Error!", errMsg);
        return;
      }
      matchedCompanyArray[matchedCompanyArray.length] = [rowData.ClientId, rowData.ClientName, rowData.ClientLocation, rowData.ClientWebsite, rowData.ClientDescription];
    }
     
    gridStore = new Ext.data.Store({
      ownerCt: this,
      data: matchedCompanyArray,
      reader: new Ext.data.ArrayReader({id: 'id'}, ['id', 'name', 'location', 'website', 'description'])
    });
    
    matchedCompanyGrid = new Ext.grid.GridPanel({
      region: 'center',
      autoScroll: true,
      frame: true,
      //width: 350,
      height: 250,
      store: gridStore,
      columns: [{header: "Name", dataIndex: 'name', width: 180, sortable: true},
        {header: "Website", dataIndex: 'website', width: 223, sortable: true}
      ],
      listeners: {
        cellclick: {scope: this, fn: this.updateCompany}
      }
    });
    
    this.companyListWindow = new Ext.Window({
      title: "Matched Company List",
      closable: true,
      width: 450,
      style: 'padding-bottom:5px;',
      border: false,
      plain: true,
      layout: 'table',
      layoutConfig: {columns: 1},
      modal: true,
      items: [
        {
          html: '<div style="padding:5px 3px;">Following is the list of companies with the website url as <b>' + this.newCompanyUrl + '</b><div>'
        },
        matchedCompanyGrid,
        {
          html: '<div style="padding:5px 3px;">*To select company click any record from above list</div>'
        }, {
			    xtype: 'box',
          autoEl: { 
            tag: 'h2',
            style: 'padding:5px 3px',
            cn: 'What do you want to do?'
          }  
        }, {
			    xtype: 'box',
          autoEl: {
            tag: 'div',
            id: 'company-field-options',
            children: [{
              tag: 'ul',
              children: [{
                tag: 'li',
                children: [{
                  tag: 'a',
					        id: this.id + '_link-option1',
                  cn: 'Want to change what I typed'
                }]
				      }, {
                tag: 'li',
                children: [{
                  tag: 'a',
					        id: this.id + '_link-option2',
                  cn: 'Save the company with the data what I typed'
			          }]
				      }, {
                tag: 'li',
                children: [{
                  tag: 'a',
					        id: this.id + '_link-option3',
                  cn: 'Want to close this window?'
			          }]
				      }]
				    }]
			    }
		    }
      ],
      listeners: {
        close: {
          scope: this,
          fn: function () {
            this.setComboDefaultValue();
            this.closeDialog(this.companyListWindow);
          }
        }
      }
    });
    this.companyListWindow.ownerCt = this;
    if (this.companyListWindow.show())
	  {
      this.bindLinkOption();
	  }
    
  }, //eo function showMatchedCompanyList  
  //}}} 
  //{{{
  /**
    * private
    * This is to open cancel dialog
    */
  cancelSaveCompany: function (inputText) {
	  //Cancel option panel
	  this.cancelOptionPanel = new Ext.Panel({
      frame: true,
		  border: true,
		  plain: true,
		  region: 'center',
      items: [{
			  xtype: 'box',
        autoEl: { 
          tag: 'h2',
          cn: 'What do you want to do?'
        }  
      }, {
			  xtype: 'box',
        autoEl: {
          tag: 'div',
				  id: 'company-field-options',
          children: [{
            tag: 'ul',
            children: [{
              tag: 'li',
              children: [{
                tag: 'a',
					      id: this.id + '_link-option1',
                cn: 'Change what I typed'
              }]
				    }, {
              tag: 'li',
              children: [{
                tag: 'a',
					      id: this.id + '_link-option2',
                cn: 'Try finding my Company by website URL'
			        }]
				    }, {
              tag: 'li',
              children: [{
                tag: 'a',
					      id: this.id + '_link-option3',
                cn: 'Add ' + inputText + ' as a new company'
			        }]
				    }]
				  }]
			  }
		  }]
	  });
	 
	  // Cancel Dialog
    this.cancelDialog = new Ext.Window({
      title: 'Options for You',
      closable: true,
      width: 300,
	    height: 150,
      border: false,
      plain: true,
      layout: 'border',
      modal: true,
      items: [this.cancelOptionPanel],
      listeners: {
        close: {
          scope: this,
          fn: function () { 
            this.setComboDefaultValue();
            this.closeDialog(this.cancelDialog);
          }
        }
      }
    });
    
	  if (this.cancelDialog.show(this))
	  {
      this.bindLinkOption(inputText);
	  }  

  },// eo function cancelSaveCompany  
  //}}}
  // {{{
  /**
    * private
    * This is bind the click event fucntions with the cancel link options
    */
  bindLinkOption: function (inputText) {
    if (inputText !== undefined)
    { 
      Ext.get(this.id + '_link-option1').on(
        'click', 
        function () {
          //this.addCompanyDialog.show();
          this.closeDialog(this.cancelDialog);
        }, 
        this
      );
	    Ext.get(this.id + '_link-option2').on(
        'click',
        function () {
          this.openSearchByUrlDialog();
        },
        this
      );
	    Ext.get(this.id + '_link-option3').on(
        'click',
        function () {
          this.addCompanyDialog.show();
          this.closeDialog(this.cancelDialog);
        },
        this
      );
    }
    else
    {
      Ext.get(this.id + '_link-option1').on(
        'click', 
        function () { 
          this.addCompanyDialog.show();
          this.closeDialog(this.companyListWindow);
        }, 
        this
      );
	    Ext.get(this.id + '_link-option2').on(
        'click',
        function () {
          this.saveCompany('yes');
          this.closeDialog(this.companyListWindow);
        },
        this
      );
	    Ext.get(this.id + '_link-option3').on(
        'click',
        function () {
          this.closeDialog(this.companyListWindow);
        },
        this
      );
    }    
  },// eo function bindLinkOption  
  //}}}
  // {{{
  /**
    * private
    * function to open the search company dialog
    */
  openSearchByUrlDialog: function () {
    var searchToolBar, searchTextBox;
    
	  // don't create the window more than once
    if (this.searchByUrlWindow !== undefined)
    {
      this.searchByUrlWindow.show();
      return;
    }
    this.companyGridData = [];
    
    this.companyGridStore = new Ext.data.Store({
      ownerCt: this,
      data: this.companyGridData,
      reader: new Ext.data.ArrayReader({id: 'id'}, ['id', 'name', 'location', 'website', 'description'])
    }); 
          
    this.companyGrid = new Ext.grid.GridPanel({
      region: 'center',
      autoScroll: true,
      frame: true,
      //width: 350,
      store: this.companyGridStore,
      columns: [{header: "Name", dataIndex: 'name', width: 180, sortable: true},
        {header: "Website", dataIndex: 'website', width: 223, sortable: true}
      ],
      listeners: {
        cellclick: {scope: this, fn: this.updateCompany}  
      }
    });  
   
    searchTextBox = new Ext.form.TextField({
      xtype: 'textfield',
      id: this.id + "_search-text1",
      name: this.id + "_search-text1",
      width: this.searchFieldWidth,
      regex: /^(((http)|(https)):\/\/)?(((\w)|\-)+\.)+([\w\/])*(\.){0,1}\w{2,9}$/i,
      regexText: 'This is not a valid url!',
      allowBlank: false,
      autoCreate: {tag: "input", maxLength: this.searchFieldMaxLength}
    });
    
	  searchToolBar = new Ext.Toolbar({
      items: [
        new Ext.form.Label({
          text: this.searchForText
        }),
        searchTextBox,
        {
          xtype: 'tbspacer'
        },
        new Ext.Button({
          id: this.id + '_search-button1',
          name: this.id + '_search-button1',
          text: this.searchButtonText,
          listeners: {
            click: {
              scope: this,
              fn: function () {
                if (searchTextBox.isValid())
                {
                  this.searchCompanyByUrl(searchTextBox.getValue());
                }
                else
                {
                  Ext.Msg.alert("Invalid Url", "This is not a valid url!"); 
                }                
              }
            }
          }
        }),
		    {
          xtype: 'tbspacer'
        },
        new Ext.Button({
          id: this.id + '_cancel-button1',
          name: this.id + '_cancel-button1',
          text: this.cancelButtonText,
          listeners: {
            click: {
              scope: this, 
              fn: function () {
                this.closeDialog(this.searchByUrlWindow);
				        this.cancelDialog.show();
              }
            }
          }
        })  
      ]
    });
    this.searchByUrlWindow = new Ext.Window({
	    title: this.companyGridWindowTitle + '- Search By Websites',
      closable: true,
      //closeAction: 'hide',
      width: 430,
      height: 400,
      border: false,
      plain: true,
      layout: 'border',
      modal: true,
      tbar: searchToolBar, 
      items: [this.companyGrid],
      listeners: {
        close: {
          scope: this,
          fn: function () {
            this.closeDialog(this.searchByUrlWindow);
            if (this.cancelDialog !== undefined)
            {
              this.cancelDialog.show();
            }  
          }
        }
      }
    });
    this.searchByUrlWindow.show(this);
  },
  //}}}
  // {{{
  /**
    * private
    * function to search company 
    */
  searchCompanyByUrl: function (searchText) {
    this.enableBodyMask();
    this.companyGridStore.removeAll();
    this.ajaxRequest({
      url: this.http + this.serverName + '/' + this.applicationName + '/' + this.handlerName + '/' + this.searchCompanyServiceByURLMethod +'?' + this.searchCompanyParam + '=' + escape(searchText),
      success: function (result, request) {
        request.ownerCt.companyString = result.responseText;
        if (request.ownerCt.companyString !== '[]' && request.ownerCt.companyString !== '')
        {
          request.ownerCt.populateCompanyGrid();
          request.ownerCt.disableBodyMask();
        }
        else
        {
          Ext.Msg.alert("No Match!", "No records were found that match " + "<b>[" + searchText + "]</b>.");
          request.ownerCt.disableBodyMask();
        }
      },
      failure: function (result, request) {
        Ext.Msg.alert("Error", "No Record Found");
        request.ownerCt.disableBodyMask();
      }
    });
  },
  //}}}
  //{{{
  /**
    * private
    * function to populate company data to the company grid 
    */
  populateCompanyGrid: function () {
    this.processCompanyGridData();       // To process the company data fetched via web service
    this.companyGridStore.removeAll();
    this.companyGridStore.loadData(this.companyGridData); // To load te company grid store with fetched data
    this.companyGrid.show();
  },
  //}}}
  //{{{
  /**
    * private
    * function to process company data in array format 
    */
  processCompanyGridData: function () {
    //local variables
    var tempArray, ccount, row;
    this.companyGridData = [];
    tempArray = [];
    tempArray = this.jsonDecoder(this.companyString);
    for (ccount = 0; ccount < tempArray.length; ccount = ccount + 1) {
      row = Ext.util.JSON.decode(tempArray[ccount]);
      this.companyGridData[ccount] = [row.ClientId, row.ClientName, row.ClientLocation, row.ClientWebsite, row.ClientDescription];
    }
  }, //eo function processCompanyGridData
  //}}}
  // {{{
  /**
    * private
    * function to validate the component
    */
  isValid: function () {
    var isValid = true;
    if (!this.allowBlank)
	{
      if (this.companyField.isValid())
      {
        if (this.companyField.getValue() === '')
	    {
          this.companyField.markInvalid();
          isValid = false;
        }
	    else
	    {
          isValid = true;
        }		
      }
      else
      {
        isValid = false;
      }
    }  
    return isValid;
  }//eo function isValid
  //}}}
});

// register xtype
Ext.reg('xcompany', Ext.ux.form.CompanyField);


