String.prototype.isNumeric = function () {
	if (this=='') return false;
	return !isNaN(this);
	};
String.prototype.isEmail = function(){
	emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i
	return emailRe.test(this);
};
function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}
function isdefined( variable){return (typeof(window[variable]) == "undefined")?  false: true;}
function tryit(func){try{func();}catch(e){return;}};
 jQuery.fn.extend({
   check: function() {return this.each(function() { this.checked = true; });},
   uncheck: function() {return this.each(function() { this.checked = false; });}
 });
jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};
NFW={};NFW.External={};NFW.Page={};
NFW.External={Modules:{cluetip:false,validate:false}};
NFW.Page.GlobalLoaded=function(){
	
	(function(){
	    $('.confirm').each(function(){
	    	var _s=$(this).attr('onclick');
	    	$(this).attr('onclick','').bind('click',function(){
	    		if ( ! confirm('The action you are going to take requires confirmation. Are you sure you want to continue?'))
		    		return false;
				$(this).unbind('click').bind('click',_s).click();
	    	});
	    }); 
	    
		$('td','.drow').hover(function(){$(this).parent().addClass('drow_over');},function(){$(this).parent().removeClass('drow_over');});
		//NFW.Helper.InitTips();
	})();
};

NFW.Helper={
	InitTDCheckBoxOnState:function(holder){$('td:has(input[type="checkbox"])',holder).each(function(){NFW.Helper.ToggleTDCheckBoxOnState(this);$(this).click(function(){NFW.Helper.ToggleTDCheckBoxOnState(this);});});},
	ToggleTDCheckBoxOnState:function(obj){if($('input[type="checkbox"]',obj).get(0).checked) $(obj).addClass('on'); else $(obj).removeClass('on');},
	InitTips:function(){if(NFW.External.Modules.cluetip)$('.tip').cluetip({splitTitle: '|',cluetipClass:'getrv',activation: 'hover', mouseOutClose: true});},
	
  months:['January','February','March','April','May','June','July','August','September','October','November','December'],
  
  ShowDiv:
  function(divObj, refObj){
  	refPos=$(refObj).position();
  	$('.__descDiv').parent().hide().end().remove();
  	$(divObj)
  	   .css({
  	   	   position:'absolute',
  	   	   top:refPos.top, 
  	   	   left:refPos.left, 
  	   	   padding: '5px', 
  	   	   backgroundColor: '#FFFFFF',
  	   	   border: '2px solid #336699'
  	   	})
  	   .prepend('' +
  	   		'<div class="__descDiv" style="width:300px; background-color: #336699;text-align: right; padding-right: 5px;">' +
  	   		'<a href="javascript:void(0);" style="color: #FFFFFF; text-decoration: none;" onclick="javascript:;$(this).parent().parent().hide().end().remove();">Close</a>' +
  	   		'</div>')
  	   .show();
  },
  
	ValidateFormSubmit:
	function(json){
		var bCont=true;
		if (typeof CustomForm_OnSubmit == 'function') bCont=CustomForm_OnSubmit();
		
		if(bCont){
				$('[nfwdata="template"]').remove();
				NFW.Helper.ProcessCheckboxes(json.form_id);
				return true;
		}return false;
	},
	
	EnsureCheckReadonly:
	function(obj){
		if ($(obj).attr('readonly')){
			obj.checked=!obj.checked;
		}
	},

 setDefaultOption___:
 function(obj,defaultValue,addSelect,addSelectTitle){
  try{ 
    if (!obj.options) return false;
       if (addSelect){
              var option = document.createElement("option");
              option.setAttribute("selected",true);
              option.appendChild(document.createTextNode(addSelectTitle==undefined?'Select One':addSelectTitle));
              option.setAttribute("value","");
              obj.appendChild(option);
       }
       
       //if($.browser.msie){
       	  for(var i=0; i<obj.options.length; i++){
	          if (obj.options[i].value==defaultValue){
	           obj.options[i].selected=true;
	           break;
	          }
       	  }
       //}
       /*
       for(var i=0;i<obj.options.length;i++){
        if ($.browser.msie){
            if (obj.options[i].value==defaultValue){
              obj.options[i].setAttribute('selected',true);
              obj.selectedIndex=i;
              
              var option = document.createElement("option");
              option.setAttribute("value", defaultValue);
              option.setAttribute("selected",true);
              option.appendChild(document.createTextNode(obj.options[i].innerText));
              obj.appendChild(option);
              break;
            }
        }else{
          if (obj.options[i].value==defaultValue){
           obj.options[i].selected=true;
           break;
          }
        }
      }*/
    }catch(e){};
},
 setDefaultOption:
 function(obj,defaultValue,addSelect,addSelectTitle){
  try{ 
    if (!obj.options) return false;
       if (addSelect){
              var option = document.createElement("option");
              option.setAttribute("selected",true);
              option.appendChild(document.createTextNode(addSelectTitle==undefined?'Select One':addSelectTitle));
              option.setAttribute("value","");
              obj.appendChild(option);
       }
       for(var i=0;i<obj.options.length;i++){
        if ($.browser.msie){
            if (obj.options[i].value==defaultValue){
              obj.options[i].setAttribute('selected',true);
              obj.selectedIndex=i;
              
              var option = document.createElement("option");
              option.setAttribute("value", defaultValue);
              option.setAttribute("selected",true);
              option.appendChild(document.createTextNode(obj.options[i].innerText));
              obj.appendChild(option);
              break;
            }
        }else{
          if (obj.options[i].value==defaultValue){
           obj.options[i].selected=true;
           break;
          }
        }
      }
    }catch(e){};
},
  Toggle:
  function(json){
  	if (typeof json=='string')eval('json='+json);
  	
  	if (json.id==undefined){
  	  var _obj_finder='[name="{t:\''+json.t+'\',f:\''+json.f+'\'}"]';
  	}else{
  		var _obj_finder='#'+json.id;
  	}
  	
  	$(_obj_finder).each(function(i){
  		$(this).get(0).disabled=!$(this).get(0).disabled;
      if (json.nohidden=='undefined' || !json.nohidden){
	  		if ($(this).is(':hidden')){
	  			$(this).show();
	  		}else{
	  			$(this).hide();
	  		}
      }
  	});
  },
  
  GetYearsForSelect2:
  function(start,end,order,defaultValue){
    var _options='';
    if (order=='desc'){
	    for(var i=end;i>=start;i--){
	         _options+='<option value="'+i+'"'+(parseInt(i)==parseInt(defaultValue)?' selected="selected"':'')+'>'+i+'</option>';
	    };
    }else{
      for(var i=start;i<=end;i++){
          _options+='<option value="'+i+'"'+(parseInt(i)==parseInt(defaultValue)?' selected="selected"':'')+'>'+i+'</option>';
      };
    }
    return _options;
  },

  GetMonthsForSelect:
  function(){
  	var _options='';
  	$(this.months).each(function(i){
  		_options+='<option value="'+(i+1)+'">'+NFW.Helper.months[i]+'</option>';
  	});
  	return _options;
  },
  
  GetDaysInMonthForSelect:
  function(){
  	var _options='';
  	for(var i=1;i<=31;i++){
  		_options+='<option value="'+i+'">'+i+'</option>';
  	};
  	return _options;
  },
  
  GetYearsForSelect:
  function(start,num){
    var _options='';
    for(var i=0;i<num;i++){
      _options+='<option value="'+(start+i)+'">'+(start+i)+'</option>';
    };
    return _options;
  },
  
  ProcessCheckboxes:
  function(json){
    $('input[type="checkbox"]',json.form_id).each(function(){
    	if($(this).attr('nfwdata')!==undefined){
	    	eval('nfwdata='+$(this).attr('nfwdata')+';');
	    	var _val=$(this).is(':checked')?nfwdata.on:nfwdata.off;
	    	$(this).val(_val);
	    	//$(this).checked=true;
	    	$(this).get(0).checked=true;
    	};
    });
  },
	
  /**
   * json
   *   .form_action : form action
   *   .form_id : form html id
   */
  SetForm:
  function(json){
    var h
    if (json.form_action)h=NFW.Helper.ReplaceURLParams([{p:'a',v:json.form_action}],true);
    if (json.c && json.s && json.a)h=NFW.Helper.ReplaceURLParams([{p:'c',v:json.c},{p:'s',v:json.s},{p:'a',v:json.a}],true,h);
    if (json.uiid)h=NFW.Helper.ReplaceURLParams([{p:'uiid',v:json.uiid}],true,h);
    if (h.indexOf('?')<0)h=h.replace(/\/&/,'/?');
    $('#'+json.form_id).attr('action',h);
  },
  
  /**
   * ensures that all the checkboxes are accurately checked or unchecked.
   * PHPTAL has an issue with checked parameter. 
   * if checked="" then it should be un-checked
   * if checked="{any_value}" then should be checked.
   * 
   * json
   *   .form_id : the form id where the checkboxes will be searched within
   */
  ValidateCheckboxesWithNFWData:
  function(json){
  	//alert(json.form_id);
  	$('input[type="checkbox"]','#'+json.form_id).each(function(){
  		nfwdata=$(this).attr('nfwdata');
  		if (nfwdata){
  			eval('nfwdata='+nfwdata);
  			$(this).get(0).checked=($(this).val()===nfwdata.on);
  		}
  	});
  },
  
  ProcessFormElementsWithNFWData:
  function(json){
  	$('input[type="checkbox"][nfwdata]','#'+json.form_id).each(function(){
  		nfwdata=$(this).attr('nfwdata');
  		if (nfwdata){
  			eval('nfwdata='+nfwdata);
  			$(this).get(0).checked=($(this).val()===nfwdata.on);
  		}
  	});
  	
  	$('select[nfwdata]','#'+json.form_id).each(function(){
  		nfwdata=$(this).attr('nfwdata');
  		
  		if (nfwdata){
  			eval('nfwdata='+nfwdata);
   			s=$(this).get(0);
  			for(var i=0; i<s.options.length; i++) {
  				if (s.options[i].value==nfwdata.default_value){
  					s.options[i].selected=true;
  					s.selectedIndex=i;
  					i=s.options.length+1;
  				}
  			}
  		}
  	});
  	
  },
  
  ShowPassword:
  function(el){
  	nfwdata=$(el).attr('nfwdata');
	if (nfwdata){
		eval('nfwdata='+nfwdata);
		if(nfwdata.showPassword){
			$(el).html(nfwdata.password);
			$(el).attr('nfwdata',$(el).attr('nfwdata').replace(/showPassword:true/,'showPassword:false'));
		}else{
			$(el).html('[  Show  ]');
			$(el).attr('nfwdata',$(el).attr('nfwdata').replace(/showPassword:false/,'showPassword:true'));
		}
	}
  },
  
  /**
   * returns the thickbox compliant url.
   * if h is supplied then, function will not use the active document href.
   * 
   * @param {string} h 
   */
  GetBoxURL:
  function(h){
  	return NFW.Helper.ReplaceURLParams(
  		[{p:'no_hefo',v:'1'},{p:'KeepThis',v:'true'},{p:'TB_iframe',v:'true'},{p:'height',v:'560'},{p:'width',v:'760'}],
  		true,
  		h);
  },

  ParseGetFromHash:
  function(){
    if((hash=unescape(self.document.location.hash.substring(1)))=='') return {};
    returnValue={};
    arr=hash.split('&');
    for(var i=0;i<arr.length;i++){
    	if (arr[i]!=''){
	      one=arr[i].split('=');
		    eval('returnValue.'+one[0]+'="'+one[1]+'"');
    	}
	  }
	  return returnValue;
  },

  InitLocationTree:
  function(json){
  	
		options={
			location:{defaultValue:json.location_id, container:'cab_location', uiid:'location_id', uiname:"{t:'address',f:'location_id'}", dataprovider:'/ajax_funcs/getLocation.php?',otherLink:false},
			country:{defaultValue:json.country_id, container:'cab_country', uiid:'country_id', uiname:"{t:'address',f:'country_id'}", dataprovider:'/ajax_funcs/getCountry.php?',otherLink:false},
			state:{defaultValue:json.state_id, container:'cab_state', uiid:'state_id', uiname:"{t:'address',f:'state_id'}", dataprovider:'/ajax_funcs/getState.php?',otherLink:false},
			city:{defaultValue:json.city_id, container:'cab_city', uiid:'city_id', uiname:"{t:'address',f:'city_id'}", dataprovider:'/ajax_funcs/getCity.php?',otherLink:false}
		};
		NFW.Helper.InitLocationTreeFreeConf(options);
	},
	  
	InitLocationTreeFreeConf:
	  function(options,idx,filter,company_id){
		hashParams=NFW.Helper.ParseGetFromHash();
		
		var js_dir='/';
		if (idx!==undefined && idx!=='') idx='_'+idx; else idx='';
		
		loc=hashParams.location_id?hashParams.location_id:(NFW.Helper.GUP('location_id'+idx)?NFW.Helper.GUP('location_id'+idx):(options.location_id?options.location_id:'6'));
		cou=hashParams.country_id?hashParams.country_id:(NFW.Helper.GUP('country_id'+idx)?NFW.Helper.GUP('country_id'+idx):(options.country_id?options.country_id:'148'));
		sta=hashParams.state_id?hashParams.state_id:(NFW.Helper.GUP('state_id'+idx)?NFW.Helper.GUP('state_id'+idx):(options.state_id?options.state_id:''));
		cit=hashParams.city_id?hashParams.city_id:(NFW.Helper.GUP('city_id'+idx)?NFW.Helper.GUP('city_id'+idx):(options.city_id?options.city_id:''));
		
		
		var settings=$.extend(true,{
				docroot:'/.',
				location:{defaultValue:loc,container:'cab_location'+idx,uiid:'location_id'+idx,uiname:'location_id'+(idx!==''?'[]':''),dataprovider:'/ajax_funcs/getLocation.php'+(filter?'?all=0':'?all=1')+'&company_id='+company_id,otherLink:false},
				country:{defaultValue:cou,container:'cab_country'+idx,uiid:'country_id'+idx,uiname:'country_id'+(idx!==''?'[]':''),dataprovider:'/ajax_funcs/getCountry.php'+(filter?'?all=0':'?all=1')+'&company_id='+company_id,otherLink:false},
				state:{defaultValue:sta,container:'cab_state'+idx,uiid:'state_id'+idx,uiname:'state_id'+(idx!==''?'[]':''),dataprovider:'/ajax_funcs/getState.php'+(filter?'?all=0':'?all=1')+'&company_id='+company_id,otherLink:false},
				city:{defaultValue:cit,container:'cab_city'+idx,uiid:'city_id'+idx,uiname:'city_id'+(idx!==''?'[]':''),dataprovider:'/ajax_funcs/getCity.php'+(filter?'?all=0':'?all=1')+'&company_id='+company_id,otherLink:false}
			},options);
		
		//alert(settings.country.container);
	
		$('#location_tree'+idx).bindLocationTree(settings);
		
  },
  
  /**
   * Redirects the page to the requested URL.
   */
  GotoURL:
  function(url,new_window,params){
  	if (new_window==undefined) new_window=false;
  	
  	if (!new_window){
		setTimeout(function(){window.location = url;}, 0);
  	}else{
    	var w=window.open(url,'popup',params);
    	w.focus();
  	}
  },
  
  RUP:function(json,bReturn,h){return this.ReplaceURLParams(json,bReturn,h);},
  /**
   * Changes the url paramters that are passed with json object
   * It keeps the other parameters if they are not set in the json string
   * Then it redirects the page with GotoURL function
   * 
   * If the bReturn is set as true, then the function will return the modified URL hash
   * and will not redirect the page.
   * 
   * @param {Object} json
   * @param {boolean} bReturn optional
   */
  ReplaceURLParams:
  function(json,bReturn,h){
  	/* json : [{p:'param1',v:'value1'},{p:'param2',v:'value2'}]*/
  	if (h==undefined || h=='') {
  		h=window.location.href;
  	}
  	if (json.p!==undefined) h=NFW.Helper.SUP(json.p, json.v, h);
  	else {
  		for(var i=0; i<json.length; i++) {
  			var v=json[i].v+'';
  			var p=json[i].p;
  			h=NFW.Helper.SUP(p, escape(v.replace('&','&amp;')), h);
  		}
  	}
  	if(bReturn) return h;
  	else NFW.Helper.GotoURL(h);
  },
  
  /**
   * @param {integer} pnum Page Number
   * @param {integer} tnum Total Page Number
   */
  ChangePagination:
  function(pnum,tnum){
  	var current='';
    if ($('#pnum').get(0)){
      current=$('#pnum').val();
    }else{
      current=NFW.Helper.GUP('pnum');
    }
    if(current=='')current=1;
    switch(pnum){
      case 'prev':
        pnum=parseInt(current)-1;
        if (pnum<1) return;
        break;
      case 'next':
        pnum=parseInt(current)+1;
        if (tnum!==undefined && tnum<pnum) return;
        break;
    }
    window.location=NFW.Helper.SUP('pnum',pnum);
  },
  
  /**
   * Get URL Parameter
   * Returns the requested url parameter.
   * @return (string)
   */
  GUP:
  function(name){
  	var h=window.location.href;var hash='';
  	if (h.indexOf('#')){tmp=h.split('#');hash=tmp[1];h=tmp[0];}
    var name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( h );
    if( results == null )
      return null;
    else
      return results[1];
  },
  
  /**
   * SUP: Set URL Parameter
   * Sets the url parameter
   * If there is a set variable found then updates it
   * otherwise, append the href with name and value
   * 
   * @return (string) href
   */
  SUP:
  function(name,value,h){
  	if (typeof h === 'undefined') h=window.location.href;
  	
  	var hash='';
  	if (h.indexOf('#')){tmp=h.split('#');hash=tmp[1];h=tmp[0];}
    var oldvalue=NFW.Helper.GUP(name);
    if (oldvalue==null){
      if (h.indexOf('?')<0)h+='?';
      h+='&'+name+'='+value;
    }else{
      h=h.replace(name+'='+oldvalue,name+'='+value);
    }
    return h;
  },
  
  /**
   * Duplicates the row given by object id 
   * @return (object) jQuery
   */
  DuplicateRow:
  function(json){
  	if (!$('#'+json.row)) alert('The reference row cannot be found.');
  	var clone=$('#'+json.row).clone();
  	if(json.method=='append'){$(clone).appendTo('#'+json.cab+'>tbody');return clone;}
  	if(json.method=='prepend'){$(clone).prependTo('#'+json.cab+'>tbody');return clone;}
  	return false;
  },
  
  LoadRowData:
  function(json,table_name,row){
		for (property in json){
			
			if(json[property]=='undefined' || json[property]==null) continue;
			
			var obj=$('[name="{t:\''+table_name+'\',f:\''+property+'\'}[]"]',row);
			if($(obj).attr('name')==undefined) {
				obj=$('[name="'+property+'[]"]',row);
			}
			
			
			
			if ($(obj).is('select')){
				//$(obj).children('[value="'+json[property]+'"]')[0].selected=true;
				c=$(obj).children('[value="'+json[property]+'"]')[0];
				if(c !== undefined) c.selected= true;
			}
			else if ($(obj).is('[type="checkbox"]')){
				$(obj).get(0).checked=(json[property]=='1'?true:false);
			}
			else if ($(obj).is('[type="text"]') || $(obj).is('[type="hidden"]')){
				$(obj).val(json[property]);
			}
			else if ($(obj).is('textarea')){
				$(obj).val(json[property]);
			}
			else if ($(obj).is('[type="file"]')){
				NFW.Helper.ToggleFileField(obj.attr('name'),json[property],row);
			}
		}
  },

  ToggleFileField:
  function(objname,value,parent_object){
  	obj=$('[name="'+objname+'"]',$(parent_object));
    $(obj)
    	.hide()
		.attr({disabled:true})
    	.parent()
    	.append('<input type="text" name="'+$(obj).attr('name')+'" readonly="readonly" value="'+value+'" ondblclick="javascript:(function(obj){NFW.Helper.ReloadFileField(obj);})(this)" alt="Double click to change the file." />')
    	.get(0)
    	.disabled=true;
    $('[name="cancel_'+objname+'"]',$(parent_object)).remove();
  },
    
  ReloadFileField:
  function(obj){
  	_name=$(obj).attr('name');
  	_value=$(obj).val();
  	$('[name="'+_name+'"]',$(obj).parent())
  		.show()
  		.attr({disabled:false})
  		.parent()
  		.append('<a style="display:block;" name="cancel_'+_name+'" href="javascript:;" onclick="javascript:NFW.Helper.ToggleFileField(\''+_name.replace(/'/g,'\\\'')+'\',\''+_value+'\',$(this).parent());">cancel</a>')
  		.get(0)
  		.disabled = false;
  	$(obj).remove();
  },
  
  AddRow:
  function(json,_caller){
  	
  		if (json && json.max_row && _caller._total>=json.max_row){
  			alert('You have already reached to the maximum limit of '+ json.max_row);
  			return false;
  		}
		var row=NFW.Helper.DuplicateRow({cab:_caller._key+'_cab',row:_caller._key+'_row',method:(json==undefined || json.method==undefined?'append':json.method)});
		if(!row) {
			alert('Row could not be added.');
			return false;
		}
		//alert(row.html());
		row.show().attr('id',row.attr('id')+'_'+(_caller._row_ctr++));
		row.removeAttr('nfwdata');
		if (json!==undefined) NFW.Helper.LoadRowData(json,_caller._table_name,row);
		_caller._total++;
		//NFW.Helper.InitTips();
		if (typeof NewRow_OnAdd == 'function') NewRow_OnAdd(row);
		return row;
  },
  
  RemoveRow:
  function(el,_caller){$(el).parents('[id*=\''+_caller._key+'_row\']').remove();_caller._total--;},

  printf:
  function printf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }    
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg); 
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg)); 
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg); 
      }
    converters['E'] = function(flags,width,precision,arg) 
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);        
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);        
      }  
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  },
  
  SetHash:function(hash){window.location.hash=hash;},
  GetHash:function(){return window.location.hash},
  ClearHash:function(){window.location.hash='';},
  
  SetFormHistory:
  function(json){
  	//if (no_form_history!==undefined || no_form_history) return;
  	if (isdefined('no_form_history') && no_form_history) return;
  	var hash='';
	  $('input,select,textarea',$('#'+json.form_id)).each(function(){
	  	bcont=true;
	  	if (bcont && $(this).attr('type')=='radio' && $(this).attr('checked')!=='checked') bcont=false;
	  	if (bcont && $(this).attr('name')==undefined) bcont=false;
	  	if (bcont) hash+='&'+$(this).attr('name')+'='+unescape($(this).val());
	  });
	  NFW.Helper.SetHash(hash);
  },
  
  ProtectBackButton:
  function(){
  	if (!postback){
  	   alert('You are about to leave the page. Please use the back button provided in the page?');
  	   return false;
  	   window.location.reload();
  	   return false;
    }
  },
  
  printf2:
  function(){
	  var num = arguments.length; 
	  var oStr = arguments[0];   
	  for (var i = 1; i < num; i++) { 
	    var pattern = "\\{" + (i-1) + "\\}"; 
	    var re = new RegExp(pattern, "g"); 
	    oStr = oStr.replace(re, arguments[i]); 
	  } 
	  return oStr; 
  },
  _:''
};
NFW.H=NFW.Helper;
