/*-------------------------------------------------
/// Initiate Global Values
--------------------------------------------------*/
var for_has_errors = false; //DEPRICATED, were there any errors during the check ? 
var form_has_errors = false; //were there any errors during the check ?
var serialized_errors = ''; //using this for now to store ?URL like of the errors and then record them
var fa2_nocapture_class = 'nocapture'; //if input element has this class, FA2 will not capture it's value


/*----function---------------------------------------
/// AddEvent Listener Function
--------------------------------------------------*/
function addEvent(obj, evType, fn){ 
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    return false;
  }
}    
    
/*----function---------------------------------------
/// AJAX
--------------------------------------------------*/
function collect(a,f){
  var n=[];
  for(var i=0;i<a.length;i++){
    var v=f(a[i]);
    if(v!=null)n.push(v)
      }
      return n
  };
ajax={};
ajax.x=function(){
  try{
    return new ActiveXObject('Msxml2.XMLHTTP')
    }catch(e){
    try{
      return new ActiveXObject('Microsoft.XMLHTTP')
      }catch(e){
      return new XMLHttpRequest()
      }
    }
};
ajax.serialize=function(f){
  var g=function(n){
    return f.getElementsByTagName(n)
    };

  var nv=function(e){
    if(e.name && !new RegExp('\\b' + fa2_nocapture_class + '\\b').test(e.className) )return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);else return null
      };

  var i=collect(g('input'),function(i){
    if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)
      });
  var s=collect(g('select'),nv);
  var t=collect(g('textarea'),nv);
  return i.concat(s).concat(t).join('&');
};
ajax.send=function(u,f,m,a){
  var x=ajax.x();
  x.open(m,u,true);
  x.onreadystatechange=function(){
    if(x.readyState==4)f(x.responseText)
      };

  if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  x.send(a)
  };
ajax.get=function(url,func){
  ajax.send(url,func,'GET')
  };
ajax.gets=function(url){
  var x=ajax.x();
  x.open('GET',url,false);
  x.send(null);
  return x.responseText
  };
ajax.post=function(url,func,args){
  ajax.send(url,func,'POST',args)
  };
ajax.update=function(url,elm){
  var e=$(elm);
  var f=function(r){
    e.innerHTML=r
    };

  ajax.get(url,f)
  };
ajax.submit=function(url,elm,frm){
  var e=$(elm);
  var f=function(r){
    e.innerHTML=r
    };

  ajax.post(url,f,ajax.serialize(frm))
  };
//end AJAX Functions

/*----function---------------------------------------
/// Peace of Cake, my Dollar Function
--------------------------------------------------*/
function $() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var elid = arguments[i];
    if (typeof elid == 'string') element = document.getElementById(elid);
    if ( !element ){
      if( typeof console != 'undefined'){
        console.error("The element with id: `%s` does not exist", elid)
      }else{
        return false;
      }
    }
    if (arguments.length == 1)
      return element;
    elements.push(element);
  }
  return elements;
}


function $V(elmnt) {
  obj = $(elmnt)
  switch(obj.type){
    case 'radio': case 'checkbox':
      return( obj.checked ? obj.value : null );
    case 'select-one':
      if( ! obj.options || obj.selectedIndex < 0 ){
        return null;
      }
      return obj.options[obj.selectedIndex].value;
  }

  return obj.value;
}



/*----function---------------------------------------
/// Get All elements based on their Class Name
--------------------------------------------------*/
function getElementsByClassName(oElm, strTagName, strClassName){
  var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
  var arrReturnElements = new Array();
  strClassName = strClassName.replace(/\-/g, "\\-");
  var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  var oElement;
  for(var i=0; i<arrElements.length; i++){
    oElement = arrElements[i];
    if(oRegExp.test(oElement.className)){
      arrReturnElements.push(oElement);
    }
  }
  return (arrReturnElements)
}


/*----function---------------------------------------
/// Check if an Email is Valid
--------------------------------------------------*/
function validEmail(email){
    
  var emailRegex = /^[a-zA-Z0-9][a-zA-Z0-9_\-\.\+]*@[a-zA-Z0-9\-\.\+]+?\.[a-zA-Z]{2,6}$/;

  email = email.replace(/[\ ]/g, '')

  if(!emailRegex.test(email))
    return false;
  return true;
}


/*----function---------------------------------------
/// Check if a Phone is Valid
--------------------------------------------------*/

function isSequence(value){
  var THRESHOLD = 6
  var seq_up = seq_down = seq_same = 1
        
  value = value.replace(/^[0]+/, '');
  value = value.replace(/[^0-9]/, '');
        
  for(i=0; i<value.length; i++){
    curr_val = parseInt( value.charAt(i) )
    prev_val = parseInt( value.charAt(i-1) )

    seq_up   = (curr_val == prev_val+1) ? seq_up+1   : 1;
    seq_down = (curr_val == prev_val-1) ? seq_down+1 : 1;
    seq_same = (curr_val == prev_val)   ? seq_same+1 : 1;
            
    switch(THRESHOLD){
      case seq_up:
      case seq_down:
      case seq_same:
        return true //return true - is some kind of sequence
    }
  }
  return false
}


function validPhone(phone){

  var phone_processed = phone;
  var basicPhoneRegex = /^0?(1|2|3|5|7|8)[0-9]{8,9}/;

  //Replace letter O with digit 0
  phone_processed  = phone_processed.replace(/[oO]/g, '0');

  //Remove non-numerics
  phone_processed = phone_processed.replace(/[^\d]/g, '');

  //Handle International Prefix
  phone_processed = phone_processed.replace(/^0*44/, '0');

  //Basic Phone Validation
  if( ! basicPhoneRegex.test(phone_processed) ){
    return false;
  }
        
  //numbers like 0123456/6543210/5555555 are not valid
  if( isSequence(phone_processed) ){
    return false;
  }
    
  return true;
}
    


/*----function---------------------------------------
/// Check if a Postcode is Valid
--------------------------------------------------*/
function validPostcode(postcode){

  //Remove white space
  var stripped = postcode.replace(/[^0-9a-zA-Z]/g,'');

  //Advanced Postcode Check
  var postcodeRegex =/^[A-Z][A-Z0-9]{4,8}$/i;

  if(!postcodeRegex.test(stripped))
    return false;
		
  return true;
}

/*----function---------------------------------------
/// Check if Amount is Valid
--------------------------------------------------*/
function validMoney(amount){

  var moneyRegex =/^[0-9\,\.\-ko]{1,32}$/i;
	
  //Remove any not digit/comma/dot/space character
  amount = amount.replace(/[^0-9,\.\-ko]/ig, '')
	
  //Remove pence at the end
  amount = amount.replace(/[\.,\-]00$/, '');
  if(moneyRegex.test(amount))
    return true;

  return false
}

/*----function---------------------------------------
/// Check if Date is valid
--------------------------------------------------*/
function validDate(dateValue){
  //Remove white space
  var dateValue = dateValue.replace(/\ /g,'');

  //Initial Basic Check
  var initialRegex =/^[0-3][0-9]\/0|1[0-9]\/19|20[0-9]{2}$/i;
  if(!initialRegex.test(dateValue))
    return false;
        
  //Check if when parsed, the date is valid
  var date_array = dateValue.split('/');
  var day = date_array[0];

  // Attention! Javascript consider months in the range 0 - 11
  var month = date_array[1] - 1;
  var year = date_array[2];

  // This instruction will create a date object
  source_date = new Date(year,month,day);

  if(year != source_date.getFullYear()){
    //Year is not valid!
    return false;
  }

  if(month != source_date.getMonth()){
    //Month is not valid!
    return false;
  }

  if(day != source_date.getDate()){
    //Day is not valid!
    return false;
  }
        
  return true;
}

/*----function---------------------------------------
/// Nicely Display User Errors on Form
--------------------------------------------------*/

function showErrorDelayed(errorId){

  $(errorId).style.display = 'block';
   
}

function toggleUserError (field_id, error_text, serverSide) {
    
  if (typeof(serverSide) == 'undefined'){
    serverSide = false;
  }
	
  var idPrefix = 'error_box_for_';
  if ( serverSide ){
    idPrefix = 'server_error_box_for_'; //FA will not log this as client error
  }
  errorId = idPrefix + $(field_id).id;

  //handle multiple messages for the same input
  if ( serverSide && document.getElementById( errorId ) != null ){
    errorId = idPrefix + error_text.length + '_' + $(field_id).id;
  }
  var theErrorBox = document.createElement('div');

  theErrorBox.setAttribute('class','error_box');
  theErrorBox.setAttribute('id',errorId);
  theErrorBox.style.display = 'none';	//hide it and then show it with delay.
       	

  theErrorBox.className = 'error_box';
  theErrorBox.id = errorId;

  theErrorBox.innerHTML = '&uarr; ' + error_text;

  $(field_id).parentNode.appendChild(theErrorBox);
    
  setTimeout("showErrorDelayed('"+errorId+"')",300);
	
  if (!serverSide){
    //this var appears to be deprecated...
    serialized_errors += '&fields_errors['+field_id+']='+error_text;
  }
    
  for_has_errors = true; //DEPRICATED
  form_has_errors = true;

}

/*----function---------------------------------------
/// Alias function for toggleUserError()
--------------------------------------------------*/
function tur(field_id, error_text, serverSide) {
  return toggleUserError (field_id, error_text, serverSide);
}


/*----function---------------------------------------
/// Check if field is empty and show error
--------------------------------------------------*/
function ifempty (fieldid, errormsg) {

  value_str = $V(fieldid);
  if( ! value_str || value_str.length == 0 || value_str.match(/^Please select/i) ){
    if( typeof errormsg != "undefined" ){
      tur(fieldid, errormsg);
      return true; //return field is empty + show error msg
    }else{
      return true;//return field is empty
    }
  }else{
    return false; //return field is NOT empty
  }
}


/*----function---------------------------------------
/// Clear all errors displayed to the user
--------------------------------------------------*/
function clearOldUserErrors () {
  for_has_errors = false;//DEPRICATED
  form_has_errors = false;
  serialized_errors = '';

  allElements = getElementsByClassName(document, 'div', 'error_box')
  for (i=0; i < allElements.length; i++) {
    allElements[i].style.display = 'none';
    var thisel = allElements[i];
    var parent = thisel.parentNode;
    var removed = parent.removeChild(thisel);
  }
}


/*----function---------------------------------------
/// Format Currency Field
/// this function to be assigned onKeyUp
--------------------------------------------------*/
function formatCurrencyField(field){
  var value         = field.value;
  var decimal_found = false;
  var decimal_count = 0;
  var new_num       = '';
  var new_value     = '';

  // strip non numerical characters, except
  // single decimal point and a maximum of 2 decimal places.
  for (var i=0; i < value.length; i++){
    var charcode = value.charCodeAt(i);

    if ((48 <= charcode) && (charcode <= 57)){
      if (decimal_found == true){
        if (decimal_count > 1){
          alert('only 2 decimal places are allowed.');
          break;
        }else{
          new_num = new_num.concat(value.charAt(i));
          decimal_count++;
        }
      }else{
        new_num = new_num.concat(value.charAt(i));
      }
    }else if ((charcode == 46) && (decimal_found == false)){
      new_num = new_num.concat(value.charAt(i));
      decimal_found = true;
    }
  }

  //Iterate and format with addedd commas
  var current_position = new_num.indexOf('.');
  if (current_position == -1){
    current_position = new_num.length;
  }else{
    new_value = new_num.substring(new_num.indexOf('.'));
  }
  for (var i = current_position; i > 0; i = i - 3){
    if (i > 3){
      new_value = ',' + new_num.substring(i-3,i) + new_value;
    }else{
      new_value = new_num.substring(0,i) + new_value;
    }
  }
  //assign the modified value to the field
  field.value = new_value;
}









/*----function---------------------------------------
/// Format Currency Amount
--------------------------------------------------*/

function formatCurrencyAmount(amount){
  var value         = amount + '';
  var decimal_found = false;
  var decimal_count = 0;
  var new_num       = '';
  var new_value     = '';

  // strip non numerical characters, except
  // single decimal point and a maximum of 2 decimal places.
  for (var i=0; i < value.length; i++){
    var charcode = value.charCodeAt(i);

    if ((48 <= charcode) && (charcode <= 57)){
      if (decimal_found == true){
        if (decimal_count > 1){
          alert('only 2 decimal places are allowed.');
          break;
        }else{
          new_num = new_num.concat(value.charAt(i));
          decimal_count++;
        }
      }else{
        new_num = new_num.concat(value.charAt(i));
      }
    }else if ((charcode == 46) && (decimal_found == false)){
      new_num = new_num.concat(value.charAt(i));
      decimal_found = true;
    }
  }

  //Iterate and format with addedd commas
  var current_position = new_num.indexOf('.');
  if (current_position == -1){
    current_position = new_num.length;
  }else{
    new_value = new_num.substring(new_num.indexOf('.'));
  }
  for (var i = current_position; i > 0; i = i - 3){
    if (i > 3){
      new_value = ',' + new_num.substring(i-3,i) + new_value;
    }else{
      new_value = new_num.substring(0,i) + new_value;
    }
  }
  //return amount with comma
  return new_value
}

/*----function---------------------------------------
/// Record User Errors
--------------------------------------------------*/
var last_error_time = 0;
function recordUserErrors(){
  //disable any original FA recording, notify FA2
  if( typeof(window.fa2) != "undefined" && typeof(window.fa2.notifyRecordUserError ) != "undefined"){
    window.fa2.notifyRecordUserError();
  }
}
/*----function---------------------------------------
/// Form Analytics 2
--------------------------------------------------*/
window.page_init_timestamp = (new Date()).getTime();

fa2 = function(){
  this.init();
};

fa2.prototype = {
  init: function(){
    if( typeof(jQuery) != "undefined"){
      this.recordServerErrors();
    }
  },
  notifyRecordUserError: function(){
    this.recordUserErrors();
  },
  sendRequest: function(data){
    //turn data.form_errors array into FA2 syntax
    var form_errors_fa2_syntax = {};
    var time_since_pageload = Math.round(((new Date()).getTime() - window.page_init_timestamp) / 1000) //convert to seconds
    var data = jQuery.extend(data, {
      'time_since_pageload':time_since_pageload
    });
        
    jQuery.each(data.form_errors, function(i, e){
      form_errors_fa2_syntax['errors['+i+'][error_message]'] = e.message;
      form_errors_fa2_syntax['errors['+i+'][error_field_name]'] = e.field;
    })

    var fa_data = {
      form_name: data.form_name,
      form_error_origin: data.form_error_origin,
      form_errors: jQuery.param(form_errors_fa2_syntax),
      form_data: ajax.serialize(data.form_dom), // using 3rd party serialize() function because jQuery.serialize() (v1.2.3) is broken in IE8
      time_since_pageload: data.time_since_pageload
    };
    if( !fa_data.form_errors || fa_data.form_errors == '') return;
    //important fields: form_name, form_errors, form_data, form_error_origin, time_since_pageload
    //jQuery.post('/formanalytics/ping/capture', fa_data); //DISABLED, using GoogleAnalytics only.
    this.notifyGoogleAnalytics(data);

  },
  notifyGoogleAnalytics: function(data){
    var _get_field_val = function(field_name, context){
      // old versions of jQuery can not find field names containing brackets ([ or ])
      var field_name_compat = (field_name||'').replace(/\[.*$/,'');
      var value = jQuery("[name*="+field_name_compat+"]", context)
      .filter(":text, select, textarea")
      .filter(function(){
        return !! (this.name == field_name && !jQuery(this).hasClass(fa2_nocapture_class));
      })
      .val() || undefined;

      if(value && (value == "-1" || value.match(/^Please select/i)) ){
        return undefined;
      }
      return value;
    }
    //DDDDDDDDDDDDDDDDDDDDDDDDD DEBUG ONLY START DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
    //        window.pageTracker._trackEvent = function(cat,act,label,val){
    //            console.dir([cat,act,label,val]);
    //        }
    //DDDDDDDDDDDDDDDDDDDDDDDDDD END DEBUG DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
    if(typeof(pageTracker) == "undefined" && typeof(_gaq) == "undefined") return;
        
    jQuery.each(data.form_errors, function(i,e){
      //fix problematic field names (e.g claims[update_claim_attributes][6031010][claim_amount] )
      var field = (e.field||'null').replace(/\[[0-9]*\]/, '').replace(/\([a-z0-9]{1,3}\)/,'');
      var message = e.message;
      var form = data.form_name;
      var origin = data.form_error_origin;

      //TODO: data.time_since_pageload could be added as value (4th parameter)
      if(typeof(pageTracker) != "undefined"){
        pageTracker._trackEvent('FA: '+form,
          '['+origin+'] '+field+': '+message
          );
      }else if(typeof(_gaq) != "undefined"){
        _gaq.push([
          '_trackEvent',
          'FA: '+form,
          '['+origin+'] '+field+': '+message
          ]);
      }

    });
  },
  /*---- method --------------------------------------
    /// User-Side Errors
    --------------------------------------------------*/
  recordUserErrors: function(){
    var self = this;
    jQuery.each(document.forms, function(){
      var $form = jQuery(this);
      var $form_errors = null;
      var form_errors = [];
      var form_name = $form.attr('name') || 'unnamed-' + window.location.pathname.replace(/[^a-zA-Z0-9]/gi, '_');

      /*--------------------------------------------------
            /// Paragon Client-Side
            --------------------------------------------------*/
      $form_errors = jQuery('div.error_box[id^=error_box]', $form);
      if( $form_errors.size() ){
        $form_errors.each(function(i){
          var $error_div        = jQuery(this);
          var error_message     = $error_div.text();
          var error_field_id    = $error_div.attr('id').replace('error_box_for_','');
          var $error_field      = jQuery('#'+error_field_id);
          var error_field_name  = $error_field.attr('name');
                    
          form_errors.push({
            'message':error_message,
            'field':error_field_name
          });
        })
      }
      /*--------------------------------------------------
            /// Insurance Client-Side
            /// - insurance client.side uses some weird way of displaying
            ///   the errs, adds .toopen class first & then shows div
            --------------------------------------------------*/
      $form_errors = jQuery('div.error[class*=_error]:visible, div.error[class*=_error].toopen', $form);
      if( $form_errors.size() ){
        $form_errors.each(function(i){
          var $error_div        = jQuery(this);
          var error_message     = $error_div.text();
          var error_field_id    = $error_div.attr('class').match(/([^\s]*)_error/)[1];
          var $error_field      = jQuery('#'+error_field_id);
          var error_field_name  = $error_field.attr('name');

          form_errors.push({
            'message':error_message,
            'field':error_field_name
          });
        })
      }

      // SEND
      self.sendRequest({
        form_name: form_name,
        form_error_origin: 'client',
        form_errors: form_errors,
        form_dom: $form.get(0)
      });
    })
  },
  /*---- method --------------------------------------
    /// Server-Side Errors
    --------------------------------------------------*/
  recordServerErrors: function(){
    var form_name = 'unnamed-' + window.location.pathname.replace(/[^a-zA-Z0-9]/gi, '_');
    var $form = null;
    var form_errors = [];
    var found = false;
        
    /*--------------------------------------------------
        /// Paragon Server-Side
        /// in paragon land, server side errors are sent back as url parameter
        --------------------------------------------------*/
    if(window.location.href.match(/errors=([^:&]*:[^,]*)/)){
      // figuring out the form name here is not easy,
      // will try to find it later using the known field_names
      var form_name_finder_query = '';
      var errors = window.location.href.match(/errors=([^&]*)/)[1].split(',');
      var fields = window.location.href.replace(/errors=[^&]*/,'').match(/\?(.*)$/)[1].split('&');

      jQuery.each(errors, function(i){
        var this_error_arr = this.split(':');
        this_error_arr[1] = this_error_arr[1].replace(/\+/g,' '); // replace '+' as a `space`
        form_errors.push({
          'message':this_error_arr[1],
          'field':this_error_arr[0]
          });

        if( ! this_error_arr[0].match(/(birth|dob|\[)/i) ){
          form_name_finder_query += ':has([name=' + this_error_arr[0] + '])';
        }
      })
            
      jQuery.each(fields, function(i){
        var this_field_arr = this.split('=');
        if( this_field_arr[0] == "form_name" || this_field_arr[0] == "lead_type_id" ){
          form_name_finder_query = ':has([name=' + this_field_arr[0] + '][value=' + this_field_arr[1] + '])';
        }
      })
            
      // Try an find out the original form name
      if(form_name_finder_query){
        form_name_finder_query = 'form' + form_name_finder_query;
        $form = jQuery(form_name_finder_query);
        if( $form.size() == 1 && $form.attr('name').length > 2 ){
          form_name = $form.attr('name');
        }
      }
      found = true;
    }
    /*--------------------------------------------------
        /// RubyOnRails Server-Side
        --------------------------------------------------*/
    var $bk_errors = jQuery("div.bk_err");
    if($bk_errors && $bk_errors.size()){
      form_errors = [];
      $form = $bk_errors.eq(0).parents("form:first");
      if( $form.size() == 1 && ($form.attr('name') || '').length > 2 ){
        form_name = $form.attr('name');
      }

      $bk_errors.each(function(){
        var $bk_error        = jQuery(this);
        var error_field_name = null;
        var error_message    = null;

        error_message    = $bk_error.text();
        error_field_name = $bk_error.parent().find(".fieldWithErrors").find("input[name],select[name],textarea[name]").eq(0).attr('name');
                
        form_errors.push({
          'message':error_message,
          'field':error_field_name
        });
      });

      found = true;
    }
    // SEND
    if( found ){
      this.sendRequest({
        form_name: form_name,
        form_error_origin: 'server',
        form_errors: form_errors,
        form_dom: $form.get(0)
      })
    }
  }
}

function moveServerErrors( context, slideForm ){
  if ( typeof(slideForm) == 'undefined' || slideForm == null ){
    slideForm = false;
  }

  var serverErrors = unescape(window.location.href).match(/errors=([^&]*)/);

  if ( serverErrors && serverErrors[1] ){
    var errorParentFieldsets = [];
    var alreadyActive = false;
    jQuery(serverErrors[1].split(',')).each(function(){
      var err = this.split(':');
      var inputId = 'input[name='+err[0]+'],select[name='+err[0]+']';
      if ( typeof( context ) != 'undefined' && context != null ){
        inputId = jQuery(inputId, context).attr('id');
      } else {
        inputId = jQuery(inputId).attr('id');
      }

      //just one error for dob
      if ( typeof(inputId) != 'undefined' && inputId != 'date_of_birth_month' && inputId != 'date_of_birth_year' ){

        tur(inputId,unescape(err[1].replace(/\+/g,' ')), true);

        if ( slideForm ){
          var $parentFieldset = jQuery('#'+inputId).parents('fieldset');
          if ( !alreadyActive && $parentFieldset.hasClass('active')){
            alreadyActive = true;
          } else {
            var position = $parentFieldset.prevAll('fieldset').length;
            if ( typeof(errorParentFieldsets[position]) == 'undefined' ){
              errorParentFieldsets[position] = $parentFieldset;//save the fieldsets with error, in the order they appear on the page
            }
          }
        }
      }
    });

    //show the first fieldset with error - see slide_form.js for reference
    if ( slideForm && !alreadyActive ){//run only if the fieldset is not already active
      for (var i = 0; i<errorParentFieldsets.length; i++){
        if ( typeof(errorParentFieldsets[i]) != 'undefined' ){
          jQuery('fieldset.active').removeClass('active');
          jQuery(errorParentFieldsets[i]).addClass('active');
          jQuery('.middle_panel').hide();
          jQuery('.mini_form').css('width','710px');//pfuj, ugly constant
          break;
        }
      }
    }
    var $errorBox = jQuery('#form_has_error_box');
    if ( form_has_errors && $errorBox.length > 0){
      $errorBox.show()
      scroll(0,0);
    }
  }
}
/* ad the submitted class to an element when requested */
function submittedFormat(f,action){
  var fid = jQuery('#'+f  );
  if (action=='set'){
    fid.addClass('submitted');
  } else {
    fid.removeClass('submitted');
  }
}

if( typeof(jQuery) != "undefined" ){
  jQuery(document).ready(function(){
    window.fa2 = new fa2();
    var isSlideForm = jQuery('div.basenav div#next').length > 0;
    moveServerErrors(null, isSlideForm);
  });
}else{
  addEvent(window, 'load', function(){
    window.fa2 = new fa2();
  });
}

