/* ---------------------------------------------------------------
  ui-form-inputs    Action handling for form input elements.

  Purpose     : To provide a consistent set of Form input action handling 
                functions that can be used across all ControlPanel views. 

  Date        : 4/1/07
  Author      : Charles Hunt <cchunt@verio.net>

  Notes       : This relies on Prototype
------------------------------------------------------------------
*/

/* ---------------------------------------------------------------
  container_toggle
 
  Handle the Show|Hide of a DIV section.

  Usage:
    new div_toggle( div_link_id, div_id, dir );

  Params:
    - div_link_id : id of the ele to control the toggle.
    - div_id: id of the div(not always) to toggle.
    - dir: initial state of container.
 
------------------------------------------------------------------
*/
var container_toggle = Class.create();
container_toggle.prototype = 
{
  initialize: function(link_id, container_id, dir, up_css, down_css, remember) 
  {
    var container_state_cookie = (remember == 'false') ? '' : Cookie.get( 'ui_'+container_id+'_toggle' );
    this.ele                   = $(link_id);
    this.container_id          = container_id;
    this.up_css                = up_css;
    this.down_css              = down_css;
    this.direction             = container_state_cookie || dir;
   	this.ele.onclick           = this.toggle.bindAsEventListener(this); 

    this.toggle( this.direction );
  },
  toggle: function(evt) 
  {
    // events take precedence over the current direction
    if ( evt == 'down' ) { this.expand(evt); }
    else if ( evt == 'up' ) { this.collapse(evt); }
    else if ( this.direction == 'up' ) { this.expand(evt); }
    else if ( this.direction == 'down' ) { this.collapse(evt); }
    
    Cookie.set( 'ui_'+this.container_id+'_toggle', this.direction );
  },
  expand: function(evt)
  {
    this.direction = 'down';
    Element.show( this.container_id );
    $(this.ele).removeClassName( this.up_css );
    $(this.ele).addClassName( this.down_css );
  },
  collapse: function(evt)
  {
    this.direction = 'up';
    Element.hide( this.container_id );
    $(this.ele).removeClassName( this.down_css );
    $(this.ele).addClassName( this.up_css );
  }
}; // END container_toggle

/* ---------------------------------------------------------------
  checkbox_watcher
 
  This is to handle the Disabling and enabling of form elements
  based on the status of selected form inputs. 
  for 
 
  This is loaded into the form submit function that is generated for 
  each ui:dialog.
 
------------------------------------------------------------------
*/
var checkbox_watcher = Class.create();
checkbox_watcher.prototype = 
{
  initialize: function( args ) 
  {
    this.ele         = $(args.ele);
    this.disables    = args.disables.split(',');
    this.enables     = args.enables.split(',');
    this.enable_css  = args.enable_css.split(',');
    this.disable_css = args.disable_css.split(',');

    //Assigning our method to the onclick event of the Master checkbox.
    this.ele.onclick = this.toggle.bindAsEventListener(this);

    // Set the initial state of the elements.
    this.toggle();
  },

  toggle: function(evt) 
  {
    for (var i = 0; i < this.disables.length; i++) 
    {
      if ( this.ele.checked  == true )
      {
        Form.Element.disable( this.disables[i] );

        $(this.disables[i]).removeClassName( this.enable_css );
        $(this.disables[i]).addClassName( this.disable_css );
      }
      else
      { 
        Form.Element.enable( this.disables[i] );

        $(this.disables[i]).removeClassName( this.disable_css );
        $(this.disables[i]).addClassName( this.enable_css );
      }
    }

    for (var i = 0; i < this.enables.length; i++)
    {
      if ( this.ele.checked  == true )
      {
        Form.Element.enable( this.enables[i] );

        $(this.enables[i]).removeClassName( this.disable_css );
        $(this.enables[i]).addClassName( this.enable_css );
      }
      else
      {
        Form.Element.disable( this.enables[i] );

        $(this.enables[i]).removeClassName( this.enable_css );
        $(this.enables[i]).addClassName( this.disable_css );
      }
    }
  }
};


var PAGE_CACHE = {
  set_page: function( name, page ) 
  {
    this.pages[ name ] = page;
  },
  get_page: function(page) 
  {
    return this.pages[ page ];
  }
};

/* ---------------------------------------------------------------
  Name      :  ui_post

  Purpose   : 
  Parameters:
  Notes     : To avoid problems with possibly caching pages with
              feedbacks, no view with a feedback is cached and no 
              form posts are retrieved from cache

------------------------------------------------------------------
*/
function ui_post( url, form_id, cache, reg_post )
{
  // if we are not posting, and linking to ourselves, then do nothing.
  if ( url == '#' && form_id == '' ) { return false; }

  // Note that the 'parts' parameter to split isn't properly supported in FF
  var parts = url.split('?');
  var url = decodeURI(encodeURI(parts[0]));
  parts.shift();
  if (parts.length > 0) {
    var params = parts.join('?').split('&');
  
    for (var i = 0; i < params.length; i++) {
      var param = params[i].split('=');
      var name = param[0];
      param.shift();
      if (param.length > 0) {
          params[i] = encodeURIComponent(decodeURIComponent( name )) + '=' + encodeURIComponent(decodeURIComponent( param.join('=') ));
      } else {
          params[i] = encodeURIComponent(decodeURIComponent( name ));
      }
    }
    url += '?' + params.join('&');
  }

  var bypass_ajax = 0;
  var manual_submit = 0;
  var agent = navigator.userAgent.toLowerCase();
  var is_safari_2_0_4 = ( agent.match('safari') && agent.match('419.3') );

  if ( is_safari_2_0_4 )
  {
    bypass_ajax = 1;
  }
  // If a regular post has been requested, then just submit the form
  // or goto the specified url.
  if ( reg_post )
  {
    if ( form_id )
    {
      $(form_id).submit();
    }
    else
    {
      window.location.href = url;
    }
  }

  scroll(0,0);  // Scroll page to the top 

  // Only pull pages from cache, if they have specified that they can be.
  // Default is OFF for all pages.
  cache = ( cache == 'true' ) ? 1 : 0;
  

  var params = '';  // stores form parameter string.

  // create a cache key that identifies this page.
  var re     = new RegExp( '\/ControlPanel\/(.*)' );
  var url_id = url.match(re);
  var key    = url_id[1] || url;

  // If this is a form post, then gather up all the form input values.
  if ( form_id )
  {
    var form = $(form_id);

    // Strip out any button or submit elements that were not actually clicked.
    // This relies on the fact that all submit and buttons set 'document.pressed = this.name'
    // on thier onclick event.
    for ( var i = 0; i < form.elements.length; i++ ) 
    {
      if ( 
        (form.elements[i].type == 'submit' && form.elements[i].name != document.pressed) ||
        (form.elements[i].type == 'button' && form.elements[i].name != document.pressed) 
      )
      {
         $( form.elements[i] ).disable(); 
      } 
	  else if ( 
		( form.elements[i].type == 'button' && form.elements[i].name == document.pressed ) &&
		( bypass_ajax )
	  )
	  {
	    var newEle = document.createElement('INPUT');
	    newEle.type = 'hidden';
	    newEle.name = document.pressed;
	    newEle.value = form.elements[i].value;
	    form.appendChild(newEle);
	    manual_submit = 1;
	  }
    }

    params = $(form_id).serialize() + '&ui_view=1'; 
  }
  else
  {
    params = 'ui_view=1';
  }

  if ( manual_submit )
  {
    $(form_id).submit();
  }
  else if ( document.pressed && ( bypass_ajax ) )
  {
    return true;
  }

  // Reset doc vals used for form posts.
  document.pressed      = '';
  document.validation   = '';


  // See if we have a cached version, caching is enabled, and this is NOT a form post.
  if ( PAGE_CACHE[ key ] && cache && form_id == '' )
  {
    dhtmlHistory.add( key );

    $('innerContentColumn').hide();
    $('innerContentColumn').update( PAGE_CACHE[ key ] );

    Effect.Appear( 'innerContentColumn', {duration:0.1} );

    return false; // always return false to prevent form from actually posting.
  }


  if ( $('innerContentColumn') && ! bypass_ajax )
  {
    dhtmlHistory.add( key );

    var loading_html = '' + 
    '<table>' +
        '<tbody><tr>' +
          '<td align="center">' +
            '<center><img src="/cpimages/loading.gif" border="0"/></center>' +
          '</td>' +
        '</tr>' +
      '</tbody>' +
    '</table>';

    $('innerContentColumn').update( loading_html );


    // GO get the data.
    var myAjax  = new Ajax.Request( url,
      {
        method:'post',
        postBody: params,
        asynchronous:true,
        onSuccess:function(t) 
        {
          $('innerContentColumn').update( t.responseText );
  
          // If there is a feedback in this page, dont store it in the cache.
          // and wipe out any stale cached version that may exist.
          PAGE_CACHE[ key ] = ( $('feedback').empty ) ? t.responseText : '';
  
        },
        onLoaded:function(t) {
           //alert( "Loading" );
        },
        onFailure:function(t) {
        },
        onException:function(t, e) {
          //alert( "JSON Exception: " + e );
        }
      }
    );
  }
  else
  {
    if ( form_id )
	{
      $(form_id).submit(); 
	}
	else
	{
      window.location.href = url;
	}
  }

  return false;

} // END ui_post

/* ---------------------------------------------------------------
  Name      :  bulk_check

  Purpose   : For checking & unchecking flags of a particular field 
              (helpful in the mail, file, schedule and user sections)

  Parameters:
   
------------------------------------------------------------------
*/
function bulk_check( t, check_items_name ) 
{
  // Assign Default value for check boxes, if none was supplied.
  var item_name = ( check_items_name ) ? check_items_name : 'chk_event';

  var item = document.getElementsByName( item_name );

  if ( t.checked )
  {
      for(var i = 0; i < item.length; i++) 
      {
        item[i].checked = true;
      }
  }
  else
  {
      for(var i = 0; i < item.length; i++) 
      {
        item[i].checked = false;
      }
  }

} // END bulk_check


/* ---------------------------------------------------------------
  Name      :  bulk_submit

  Purpose   : For submitting of bulk actions in a data_table dialog.
              (used in the mail, file, schedule and user sections)

  Parameters:
      item_to_check  -   (required string)
          The name of the form element(s) to check for values
	  before submitting.
      select_string  -    (required string name)
          The name of the string to display if no elements have 
          been selected. 
      confirm_string -   (optional string name)
          The name of the string to display as a confoirmation prompt.
      form_ele       -     (optional string)
          The name of the Form element to be updated, after a confirmation
          has been received. This element will be updated with the value
          specified by form_value
      form_value     -     (optional string)
          The value to be submitted as the FORM named value of 'action'
        
------------------------------------------------------------------
*/
function bulk_submit( 
  item_to_check, 
  select_string, 
  confirm_string, 
  form_ele, 
  form_value 
)
{
  if ( 
    (count_checkboxes( item_to_check ) == 0)
  )
  {
    
    alert( document.js_strings[ select_string ] );

    return false;
  }

  if ( confirm_string )
  {
    if( confirm( document.js_strings[ confirm_string ] ) == false  ) { return false; }
  }

  if ( form_ele )
  {
    document.forms[0].elements[ form_ele ].value = form_value;
  }

  if ($('bulk_select') != null) {
      $('bulk_select').disable();
  }
 
  return ui_post( document.forms[0].action_url.value, document.forms[0].id );

} // END bulk_submit


/* ---------------------------------------------------------------
  Name      :  count_checkboxes

  Purpose   : Used to check how many checkbox input elements have 
              been selected in a form
              Used internally by bulk_submit(); 

  Parameters:
      item_name -   (required string)
          The name of the checkbox form element(s) to check 

------------------------------------------------------------------
*/
function count_checkboxes( item_name ) 
{
  var checks = 0;
  var items  = document.forms[0].elements[item_name];
  
  if ( items && items.length ) 
  {
    for (i = 0; i < items.length; i++) 
    {
      if ( items[i].checked ) 
      {
        checks++;
      }
    }
  } 

  return checks;

} // END count_checkboxes

/* ---------------------------------------

	Name: testPasswordLength
	Purpose: Test the Length of the password, and assign it a score
	Parameters: password
	Returns: Score
 ---------------------------------------
*/

function testPasswordLength(password)
{
	var passwordLengthStrength = 0;

	if ((password.length>4) && (password.length<9))
	{
		passwordLengthStrength += 5;
	}
	if (password.length>8 && password.length<12)
	{
		passwordLengthStrength += 10;
	}
	if (password.length>11)
	{
		passwordLengthStrength += 15;
	}

	return passwordLengthStrength;
}

/* ---------------------------------------
	Name: testPasswordRepeats
	Purpose: Tests to see if a character is repeated
	Parameters: password
	Returns: Score
---------------------------------------
*/
function testPasswordRepeats(password)
{
	var passwordRepeat = 0;

	if (password.match(/([A-Z]|[a-z]|[\d]|[\W])\1/))
	{
		passwordRepeat++;
	}

	return passwordRepeat;
}

/* ---------------------------------------
	Name: testPasswordLowerCase
	Purpose: Tests to see if password contains lower case characters 
	Parameters: password
	Returns: Score
 ---------------------------------------
*/
function testPasswordLowerCase(password)
{
	var passwordLowerCase = 0;

	if (password.match(/[a-z]/))
	{
		passwordLowerCase += 10;
	}

	return passwordLowerCase;
}

/* ---------------------------------------
	Name: testPasswordUpperCase
	Purpose: Tests to see if password contains upper case characters 
	Parameters: password
	Returns: Score
---------------------------------------
*/
function testPasswordUpperCase(password)
{
	var passwordUpperCase = 0;

	if (password.match(/[A-Z]/))
	{
		passwordUpperCase += 10;
	}

	return passwordUpperCase;	
}

/* ---------------------------------------

	Name: testPasswordNumbers
	Purpose: Tests to see if password contains Numbers 
	Parameters: password
	Returns: Score
------------------------------------------
*/
function testPasswordNumbers(password)
{
	var passwordNumbers = 0;

	if (password.match(/[0-9]/))
	{
		passwordNumbers += 10;
	}
	return passwordNumbers;	
}
	
/* ---------------------------------------

	Name: testPasswordChars
	Purpose: Tests to see if password contains SpecialCharacters
	Parameters: password
	Returns: Score
---------------------------------------
*/
function testPasswordChars(password)
{
	var passwordChars = 0;

	if (password.match(/[^a-zA-Z0-9]/))
	{
		passwordChars += 10;
	}
	return passwordChars;	
}

/* ---------------------------------------

	Name: testPasswordStrength
	Purpose: Tests Strength of a Password, by applyign several checks and giving it a score.   
	Parameters: password
	Returns: Score
 ---------------------------------------
*/
function testPasswordStrength(password,fieldID)
{
	var passwordStrength  = 0;
	var passwordText; 
	var passwordColor;
	var passwordNumbers;
	var passwordChars;
	var passwordLower;
	var passwordUpper;
	var passwordRepeat;

	// Give points based on length of password

	passwordStrength = testPasswordLength(password);

	// Give points based on Lower Case Characters

	passwordLower = testPasswordLowerCase(password);

	// Give points based on Upper Case Characters

	passwordUpper = testPasswordUpperCase(password);

	// Give points based on Numbers

	passwordNumbers = testPasswordNumbers(password);
	
	// Give points based on Special characters

	passwordChars = testPasswordChars(password);

	// Check for Repeated Characters

	passwordRepeat = testPasswordRepeats(password);

	// Give points for Upper and Lower Case
	
	if ((passwordLower) && (passwordUpper))
	{
		passwordStrength += 10;
	}

	// Give Points for Upper, Lower Case and Numbers

	if ((passwordLower) && (passwordUpper) && (passwordNumbers))	
	{
		passwordStrength += 10;
	}

	// Give Points for Upper, Lower case, and Numbers and Special Characters

	if ((passwordLower) && (passwordUpper) && (passwordNumbers) && (passwordChars))	
	{
		passwordStrength += 10;
	}

	// Give Points to Lower, Upper Case, and Special Characters

	if ((passwordLower) && (passwordUpper)  && (passwordChars))	
	{
		passwordStrength += 10;
	}

	// Give Points for Lower Case, Numbers and Special Characters

	if ((passwordLower) && (passwordNumbers)  && (passwordChars))	
	{
		passwordStrength += 10;
	}
	
	// Give Points for Upper Case, Numbers and Special Characters
	
	if ((passwordUpper) && (passwordNumbers)  && (passwordChars))	
	{
		passwordStrength += 10;
	}

	// Give Points for Numbers and Chars
	
	if ((passwordNumbers)  && (passwordChars))	
	{
		passwordStrength += 10;
	}

	passwordStrength += passwordLower;
	passwordStrength += passwordUpper;
	passwordStrength += passwordNumbers;
	passwordStrength += passwordChars;

	// Subtract Points for Repeating Characters
	
	if (passwordRepeat)
	{
		passwordStrength -= 10;
	}

	if ((passwordRepeat < 1) && (password.length > 11))
	{
		passwordStrength = 95;
	}

	if(passwordStrength <= 10)
	{
		passwordText = document.js_strings['msg_password_very_weak'];
	   	$('passwordBar').removeClassName('passwordColorWeak'); 
	   	$('passwordBar').removeClassName('passwordColorOK'); 
	   	$('passwordBar').removeClassName('passwordColorStrong'); 
		$('passwordBar').addClassName('passwordColorVeryWeak' ); 
	}
	else if (passwordStrength >10 && passwordStrength <=40)
	{
		passwordText = document.js_strings['msg_password_weak']
	   	$('passwordBar').removeClassName('passwordColorOK'); 
	   	$('passwordBar').removeClassName('passwordColorStrong'); 
	   	$('passwordBar').removeClassName('passwordColorVeryWeak'); 
		$('passwordBar').addClassName('passwordColorWeak' ); 
	}
	else if (passwordStrength >40 && passwordStrength <=80)
	{
		passwordText = document.js_strings['msg_password_medium']
	   	$('passwordBar').removeClassName('passwordColorStrong'); 
	   	$('passwordBar').removeClassName('passwordColorVeryWeak'); 
	   	$('passwordBar').removeClassName('passwordColorWeak'); 
		$('passwordBar').addClassName('passwordColorOK' ); 
	}
	else if (passwordStrength >80)
	{
		passwordText = document.js_strings['msg_password_strong']
	   	$('passwordBar').removeClassName('passwordColorOK'); 
	   	$('passwordBar').removeClassName('passwordColorVeryWeak'); 
	   	$('passwordBar').removeClassName('passwordColorWeak'); 
		$('passwordBar').addClassName('passwordColorStrong' ); 
	}

	if (passwordStrength > 100) 
	{
		passwordStrength = 100;
	}	
	
	document.getElementById("passwordBar").style.width= passwordStrength + '%';
    document.getElementById("passwordText").innerHTML= (passwordText);	
	document.getElementById("passwordStrength").innerHTML = document.js_strings['msg_password_strength'];
}

// for keeping the two select boxes synchronized.
var orig_select = 0;
function sync_selects( form_id, select_name ) 
{
  var new_index;
  var selector = '[name="' + select_name + '"]';

  var select_elements = $( form_id ).getElementsBySelector( selector );

 
  for ( var i=0; i < select_elements.length; i++ )
  {
    if ( select_elements[i].selectedIndex == orig_select )
    {
      
    }
    else
    {
      new_index = select_elements[i].selectedIndex; 
      orig_select = new_index;
      break;
    }
  }

  for ( var i=0; i < select_elements.length; i++ )
  {
    select_elements[i].selectedIndex = new_index;
  }

} // END

// display or hide the input field 
function showInput(el) {
 var elem = document.getElementById('replyto_string');

 if (el == "to-custom") {
   elem.style.display = "";
 } else {
   elem.style.display = "none";
 }
}

// Convert a passed form reference to a string formatted like
// a JavaScript array of objects
function form2ArrayString( form ) 
{
  var elem, lastName = "";
  var output = "[";
  for (var i = 0; i < form.elements.length; i++) 
  {
    elem = form.elements[i];
    if (elem.name && (elem.name != lastName)) 
    {
      output += formObj2String(form.elements[i]) + ",";
      lastName = elem.name;
    }
  }
  output = output.substring(0, output.length-1) + "]";
  return output;

} // END form2ArrayString


function formObj2String(obj) 
{
  var output = "{";

  if (obj.name) 
  {
    output += "name:'" + obj.name + "',";
  }
  if (obj.id) 
  {
    output += "id:'" + obj.id + "',";
  }
  output += "type:'" + obj.type + "',";
  switch (obj.type) 
  {
    case "radio":
      if (obj.name) 
      {
        obj = document.forms[0].elements[obj.name];
        var radioVal = "value:false,index:-1";
        for (var i = 0; i < obj.length; i++) 
        {
          if (obj[i].checked) 
          {
            radioVal = "value:true,index:" + i;
            i = obj.length;
          } 
        }
        output += radioVal;
      } 
      else 
      {
        output += "value:" + obj.checked;
      }
      break;
    case "checkbox":
      output += "value:" + obj.checked;
      break;
    case "select-one":
      output += "value:" + obj.selectedIndex;
      break;
    case "select-multiple":
      output += "value:" + obj.selectedIndex;
      break;
    case "text":
      output += "value:'" + escape(obj.value) + "'";
      break;
    case "textarea":
      output += "value:'" + escape(obj.value) + "'";
      break;
    case "password":
      output += "value:'" + escape(obj.value) + "'";
      break;
    case "hidden":
      output += "value:'" + escape(obj.value) + "'";
      break;
    default:
      output += "";
  }
  output += "}"
  return output;

} // END formObj2String


// Distribute form control values from another source to the
// controls in this page's form, whose names/ids match those
// of the original form controls
function string2FormObj(form, str) 
{
  var elem, objArray = eval(str);
  for (var i = 0; i < objArray.length; i++) 
  {
    elem = (objArray[i].name) ? form.elements[objArray[i].name] : document.getElementById(objArray[i].id);
    switch (objArray[i].type) 
    {
      case "radio":
        if (objArray[i].name && objArray[i].value && objArray[i].index >= 0) 
        {
          elem = elem[objArray[i].index];
        }
        elem.checked = objArray[i].value;
        break;
      case "checkbox":
        elem.checked = objArray[i].value;
        break;
      case "select-one":
        elem.selectedIndex = objArray[i].value;
        break;
      case "select-multiple":
        elem.selectedIndex = objArray[i].value;
        break;
      default:
        elem.value = unescape(objArray[i].value);
    }
  }
} // END string2FormObj


function historyChange(newLocation, historyData) 
{
  newLocation     = ( newLocation == '' ) ? 'index.xsl' : newLocation;
  var cached_page = PAGE_CACHE[ newLocation ];

  if ( cached_page )
  { 
    $('innerContentColumn').update( cached_page );

    //Effect.Appear( 'innerContentColumn', {duration:0.1} );
  }

} // END historyChange

function init_history ()
{
  var key = 'index.xsl';
  /** Initialize all of our objects now. */
  if ( dhtmlHistory.initialize() ) 
  {
    dhtmlHistory.addListener( historyChange );

    // See if there was a location given and load it up if there was.
    if ( document.location.hash && document.location.hash != '#' )
    {
      key = document.location.hash.replace(/^#/, '');
      var url = '/ControlPanel/' + key;
      var params = 'ui_view=1';

      var loading_html = '' + 
      '<table>' +
          '<tbody><tr>' +
            '<td align="center">' +
              '<center><img src="/cpimages/loading.gif" border="0"/></center>' +
            '</td>' +
          '</tr>' +
        '</tbody>' +
      '</table>';

      $('innerContentColumn').update( loading_html );

      var myAjax  = new Ajax.Request( url,
        {
          method:'post',
          postBody: params,
          asynchronous:false,
          onSuccess:function(t) 
          {
            $('innerContentColumn').update( t.responseText );
    
            if ( $('feedback').empty )
            {
              PAGE_CACHE[ key ] = t.responseText;

              dhtmlHistory.add( key  );
            }
            else
            {
              PAGE_CACHE[ key ] = '';
            }
          },
          onLoaded:function(t) {
             //alert( "Loading" );
          },
          onFailure:function(t) {
            //alert( "Failed to retrieve JSON Table Data: " + t.responseText );
          },
          onException:function(t, e) {
            //alert( "JSON Exception: " + e );
          }
        }
      );
    }
    else
    {
      // Add This page to the cache and register the history event.
     // dhtmlHistory.add( key );

      PAGE_CACHE[ key ] = $('innerContentColumn').innerHTML;
    }

  } // END if ( dhtmlHistory.initialize() ) 

} // END init_history 




function help_link(url) 
{
  var help_url = url;

  if ( document.help_topic )
  {
    help_url = url + '?topic=' + document.help_topic;
  }
  else if ( document.help_category )
  {
    help_url = url + '?category=' + document.help_category;
  }

  window.open( help_url,'','width=800,height=600,scrollbars=yes,menubar=no,resizable=yes');

  return false;
} // END help_link





// This currently is not doing what it was designed for.
// The scripts functions are not accessible from within the page
function ui_add_script( url )
{
  var el = document.createElement('script'); 
  el.src = url;
  el.type='text/javascript';
  document.getElementsByTagName('head')[0].appendChild(el);
} // END ui_add_script

/* ---------------------------------------------------------------
  enter_submit  

  Purpose     : To make an input fiel submit when the enter key 
                is pressed. 
              * 'onsubmit_has_post' is optional for circomstances when you have an
                onsubmit function to your form which later calls ui_post.  This
                stops an infinite loop.  If your 'onsubmit' function contains ui_post
                or the auto-generated 'u_form_submit' function, this is auto-detected

  Example: <input type="text"  onclick="return enter_submit( event, 'chgpasswd')"/>
           This causes the 'chgpasswd' button to be pressed and the form submitted.
               
------------------------------------------------------------------
*/
function enter_submit( evt, button_id, onsubmit_has_post ) 
{
  evt = (evt) ? evt : event;
  var target = (evt.target) ? evt.target : evt.srcElement;
  var form = target.form;
  var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
  if (charCode == 13 || charCode == 3) 
  {
    // This makes sure that the right buttons value is submitted with the form.
    if ( button_id && $(button_id).name )
    {
      document.pressed = $(button_id).name;
    }

    if (form.onsubmit) {
        var val = form.onsubmit;
        var re = /ui_form_submit|ui_post/;
        if (re.match( val ) || onsubmit_has_post) {
            form.onsubmit();
        } else {
            if(form.onsubmit()) {
                ui_post( form.action_url.value, form.id, '' );
            }
        }
    } else {
        ui_post( form.action_url.value, form.id, '' );
    }

    return false;
  }
  else
  {
    return true;
  }
} // END


function block_enter_submit( evt ) 
{
  evt = (evt) ? evt : event;
  var target = (evt.target) ? evt.target : evt.srcElement;
  var form = target.form;
  var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
  if (charCode == 13 || charCode == 3) 
  {
    return false;
  }
  else
  {
    return true;
  }
} // END

/* ---------------------------------------------------------------
  Name      : merge_form_parts

  Purpose   : To take a value that has been broken up into separate 
               input elements and assemble them into one.
  Parameters: parent_ele_id		(required string)
                The ID of the enclosing element that contains all of
                the inputs to join.
              param_id          (required string)
                The id of the Form element to update the value to.
  Notes     : This is used right now for ui:input type="ip" eles.

------------------------------------------------------------------
*/
function merge_form_parts ( parent_ele_id, param_id )
{
	var elements   = $( parent_ele_id ).getElementsBySelector( 'input' );
    var full_value = '';

	elements.each(function(item) {
		full_value += ( full_value ) ? ( '.' + item.value) : item.value; 
	});

	$( param_id ).value = full_value;
} // END

/* ---------------------------------------------------------------
  Name      : get_local_time

  Purpose: Get the client's local timezone information

  Parameters:

------------------------------------------------------------------
*/
function get_local_time( app )
{
    var clientTimezone = new Date();
    var timezoneOffset = -clientTimezone.getTimezoneOffset()/60;
    var elem = document.getElementById('offset');
    elem.href = elem.href + "&clientTimeZoneOffset=" + timezoneOffset;

    return true;

} // END get_local_time


