var ntLookupKey = 113;

(function( $, undefined ) {

// var equates and global variables here/

var tAccordion = 1;
var tTab       = 2;
var tPlain     = 3;
var tRound     = 4;
var tTabXP     = 5;
var tNone      = 6;
var tWizard    = 7;

$.widget("ui.ntform", {
   // default options
	options: {
		defaultButton: '',
		tabType: 0,
		popup:0,
		procedure: ''
   },
//------------------------------------------------------    
		_create: function() {   
			this.ready();
			this.firstFocus();			
		},	
//------------------------------------------------------
  ready: function() {
		this._bindEvents(this);
	},	
//------------------------------------------------------
  _bindEvents: function(){  
		var _this = this;

		$(this.element).find('input').not('.nt-locator')
			.off('keypress.ntform')
			.off('keydown.ntform')
			.off('change.ntform')
			.on('keypress.ntform',function(e){return _this._onKeyPress(e);})
			.on('keydown.ntform',function(e){return _this._onKeyDown(this,e);})
			.on('change.ntform',function(e){return _this.changeField(this);});  
		$(this.element).find('select')
			.off('change.ntform')
			.on('change.ntform',function(e){return _this.changeField(this);});  
		$(this.element).find('[data-do="onclick"]')
		  .off('click.ntform')
		  .on('click.ntform',function(e){return _this.changeField(this);});  			
		$(this.element).find('[data-do="server"]')
		  .off('click.ntform')
		  .on('click.ntform',function(e){return _this.pressButton(this);});  
		},
//------------------------------------------------------      		
		_onKeyPress: function(e) {
			switch (e.which) {
				case 13:{
					return(this._onEnter(e));
					break;
				}  
			}	
		},	
//------------------------------------------------------      		
		_onKeyDown: function(inp,e) {
			if ((e.which == 191) && (e.shiftKey == true)){
				e.which = ntLookupKey;
			}
			switch (e.which) {
			  case 8:{ // explicity handle backspace on readonly fields for benefit of IE.
			    if ($(inp).attr('readonly') == 'readonly'){ 
			      return false;
			    }
			    break;
			  }
				//case 191:  // ?
				case ntLookupKey: {// F2 by default
					$("#"+inp.id+".hasDatepicker").each(
						function(i,v){
							e.preventDefault();
							$(inp).datepicker("show");
							return false;
						}
					);
					$("#"+inp.id).next(':button').each(
						function(i,v){
							$(this).click();
							return false;
						}	
					)
				}
			}	
			return true;
		},			
//------------------------------------------------------      		
		_onEnter: function(e) {
			var _this = this;
			$(this.element).find('[data-nt-default="1"]').each(function(){
				$(this).click();
				e.preventDefault();
				return false;
			})
			return true;	
		},	
//------------------------------------------------------    
		hideTab: function(index){
			var id='';
			switch (this.options.tabType){
			case tNone:
      case tPlain:
			case tRound:
				$('#tab_' + this.options.procedure + index + '_div').hide();
				break;
			case tWizard:
				$('#tab_' + this.options.procedure + '_div').ntwiz("option","hideTab",index);
				break;	
			case tAccordion:
				$('#tab_' + this.options.procedure + '_div').find('h3').eq(index).hide();
				break;	
			case tTab:
				$('#tab_' + this.options.procedure + '_div > ul').find('li').eq(index).hide();
				break;	
			}	
		},
//------------------------------------------------------    		
		showTab: function(index){
			var id='';
			switch (this.options.tabType){
			case tNone:
      case tPlain:
			case tRound:
				$('#tab_' + this.options.procedure + index + '_div').show();
				break;
			case tWizard:
				$('#tab_' + this.options.procedure + '_div').ntwiz("option","unhideTab",index);
			case tAccordion:
				$('#tab_' + this.options.procedure + '_div').find('h3').eq(index).show();
				break;	
			case tTab:
				$('#tab_' + this.options.procedure + '_div > ul').find('li').eq(index).show();
				break;	
			}
		},
//------------------------------------------------------    
		firstFocus: function(){
			var e;
			var t = 4000000000;
			$(this.element).find(' :input').not('[readonly],[disabled],[type="hidden"]').each(function(){
				tx = $(this).offset().top
				if (tx < t && tx != 0){
					e = this;
					t = tx;
				}
			})
			$(e).focus();
		},

//------------------------------------------------------    
  changeField: function(elem){  
    var _this=this;                       
    // in most cases want to send the id first, not the name. The id is unique to the field on
    // the form, hence has a unique validate:: routine. For radios we have to tweak the id to remove
    // the unique suffix.
    var url = $(elem).attr('id');
    if (!url){
      url = $(elem).attr('name');
    } else {
        if ($(elem).attr('type') == 'radio'){
          url = url.slice(0,url.lastIndexOf('_'));
        }
    }   
    var url = this.options.procedure+'_' + url + '_value';
    $.get(url,
          '_popup_='+this.options.popup+'&_event_=1&value='+this.getValue(elem)+'&_ajax_=1&_rnd_='+Math.random(),
          function(data){_this._onAjaxComplete(data);});
    //this.nextFocus(elem);
    return this;
  },

//------------------------------------------------------    
  getValue: function(elem,coded){
    var ans ='';
    var typ = elem.type;
    var i = 0;
    if (typ == undefined){
      typ = elem[0].type;
    }
    switch (typ){
    case "radio":
		ans = $(elem).val();
      break;
    case "checkbox":
      if (elem.checked){                                
        ans = elem.value;                   
      }
      break;
    case "select-multiple":
      for(i = 0; i < elem.length; i++) {
        if(elem.options[i].selected) {
          ans = ans + ';|;' + elem.options[i].value;
        }
      }
      break;
    default: 
      if ($(elem).data('luv')){
        ans = $(elem).data('luv');
      } else {
        ans = elem.value;
      }  
    }
    // if called as a post, do not encode & and %. If called from EIP then do.
    if ( ans && ((coded == 0) || (coded == undefined))){
      ans = ans.replace(/%/,"%25");
      ans = ans.replace(/&/,"%26");
      ans = ans.replace(/#/,"%23");
      ans = ans.replace(/\+/,"%2B");
    }
    return ans;  
  },

	//------------------------------------------------------  
  _onAjaxComplete: function(data) {  
		xmlProcess(data);
		this.ready();
		return this;
  },

	//------------------------------------------------------  
  setTimer: function(fld,t) {      
    setTimeout("$('#"+$(this.element).attr('id')+"').ntform('server','"+this.options.procedure + '_' + fld + '_value'+"','_event_=523');",t);
    return this;
  },

//------------------------------------------------------    
// want to do an ajax call from the form, but with all the form fields included.
		pressButton: function(elem){  
		  var _this=this;
		  var urlA= this.options.procedure+'_' + $(elem).attr('name') + '_value';
    	var options = { 
		    url: urlA,
		    dataType: 'xml',
        success:    function(data) { 
                      _this._onAjaxComplete(data); 
			              },	    
		    data: {	_event_:1,
               value: $(elem).attr("value"),
               _ajax_:1}
	    }; 
      $(elem).closest("form").ajaxSubmit(options);
      return this;
		},
	//------------------------------------------------------  
  server : function(url) {  	// send async request to server procedure
		var parms='';
		var _this=this;
		for(var d = 1; d < arguments.length; d++){
			parms += arguments[d] + '&';
		}
		parms +=  '&_ajax_=1&_rnd_=' + Math.random();
		$.get(url,parms,function(data){_this._onAjaxComplete(data);});
		return this;
  },
  
//------------------------------------------------------    
   destroy: function() {
       $.Widget.prototype.destroy.apply(this, arguments); // default destroy
       // now do other stuff particular to this widget
   }
 });

$.extend( $.ui.ntform, {
	version: "@VERSION"
});

})( jQuery );

// ---------------------------------------------------------------------------------------
// add functionality to "checkbox" button so it has an "on" and "off" text, and icon option.
// ---------------------------------------------------------------------------------------
$.widget("ui.checkboxbutton", $.extend({}, $.ui.button.prototype, {

  _init: function(){
    var _this=this;
    
    this.element.data('button', this.element.data('checkboxbutton'));    
    $(this.element).bind('click',function(e){ _this._clicked()});
    
    var i = $.ui.button.prototype._init.apply(this, arguments);
    this._clicked(); // set initial state    
    return i;
  },

  // Override other methods here.
  _clicked: function(){   
    if($(this.element).attr("checked")){
      this.options.label = this.options.trueText;        
      this.options.icons.primary = this.options.trueIcon;
    } else {
      this.options.label = this.options.falseText;
      this.options.icons.primary = this.options.falseIcon;
    }     
    this._resetButton();
  }

}));

$.ui.checkboxbutton.defaults = $.extend({}, $.ui.button.defaults);
