/**
 * STRING Object Extensions
 */
if( !String.upperCaseFirst )
String.prototype.upperCaseFirst = function() {
  t = this.toLowerCase();
  
  alphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  
  start = 0;
  while( alphas.indexOf(t.substr(start,1).toUpperCase()) == -1 )
    start++;
  
  fletter = t.substr(start,1).toUpperCase();
  last = t.substr(start+1, t.length-start);
  
  ret = t.substr(0, start) + fletter + last;

  return ret;
};

if( !String.upperCaseWords )
String.prototype.upperCaseWords = function() {
  ret = new String("");
  aret = new Array();
  
  a = new Array();
  re = /\s\s+/gi;
  
  //Replace Back-to-Back Spaces with a single space
  strPhrase = this.replace( re, " " );

  a = strPhrase.split(" ");
  for(index = 0; index < a.length; index++) {
    aret[index] = a[index].upperCaseFirst();
  };
  
  ret = aret.join(" ");

  return ret;
};

if( !String.trim )
String.prototype.trim = function() {
  re = /(^[\s\t\r\n]+|[\s\t\r\n]+$)+/gi;
  
  ret = this.replace( re, "" );
  
  return ret;
};

if( !Number.trim )
Number.prototype.trim = function() {
  strValue = '' + this;
  
  return parseFloat(strValue.trim());
};

if( !Array.pop )
Array.prototype.pop = function() {
  var b = this[this.length-1];
  this.length--;
  return b;
};

if( !Array.push )
Array.prototype.push = function() {
  for( var i = 0, b = this.length, a = arguments, l = a.length; i<l; i++ ) {
    this[b+i] = a[i];
  }
  
  return this.length;
};

if( !Array.empty )
Array.prototype.empty = function() {
  this.length = 0;
};


if( !window.getObject )
function getObject( obj ) {
  var type = typeof(obj);
  obj = ( type.toLowerCase() == "string" )? document.getElementById(obj) : obj;
  
  return obj;
};

/**
 * FormValidator Object
 */
 
function FormValidator() {
  this.errors = new Array();

};

FormValidator.prototype.STRING_MIN_LENGTH = 3;

FormValidator.prototype.parseErrors = function() {
  ret = this.errors.join("\n");

  return ret;
};

FormValidator.prototype.isValid = function(validatorName, value, bIsRequired) {
  try {
  
    functionName = "isValid" + this._normalizeValidator(validatorName);
  
    if( !this[functionName] ) {
      throw 'Validation Rule Parser Not Found ('+functionName+')';
    };

	isValidValue = this[functionName](value, bIsRequired);
	
	return isValidValue;
	
  } catch(e) {
    alert(e);
  };
};


FormValidator.prototype._normalizeValidator = function(validatorName) { 
  ret = validatorName.upperCaseFirst(); return ret;
};

//Validation Rules

FormValidator.prototype.isValidRequired = function(value, bIsRequired) {
  test = value.trim();
  
  bReturn = true;

  if( bIsRequired == true || bIsRequired == 'true' ) {
    if( test=='' || test.length < 1 ) {
      this.errors.push("is a required field.");
      bReturn = false;
	};
  };

  return bReturn;
};

FormValidator.prototype.isValidNumeric = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  ret = ( isNaN(value) )? false : true;
  
  if( !ret ) {
    this.errors.push("must contain only numeric values.");
	return false;
  };

  return ret;    
};

FormValidator.prototype.isValidString = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  if( value.trim().length > 0 && value.trim().length < this.STRING_MIN_LENGTH ) {
    this.errors.push("must be at least "+this.STRING_MIN_LENGTH+" characters long.");
  
    return false;
  };
  
  return true;
};

FormValidator.prototype.isValidStateprovince = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  SP_MIN_LENGTH = 2;

  if( value.trim().length > 0 && value.trim().length < SP_MIN_LENGTH ) {
    this.errors.push("must be at least "+SP_MIN_LENGTH+" characters long.");
  
    return false;
  };
  
  return true;
};

FormValidator.prototype.isValidPostalcode = function(value, bIsRequired) {

  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  POSTALCODE_MIN_LENGTH = 5;
  POSTALCODE_MAX_LENGTH = 14;
  
  re = /[\s\t\r\n\-\_]+/gi;
  test = value.replace( re, '' );

  if( test.length > 0 && test.length < POSTALCODE_MIN_LENGTH ) {
    this.errors.push("must be at least "+POSTALCODE_MIN_LENGTH+" characters.");
    return false;
  };
  
  if( test.length > POSTALCODE_MAX_LENGTH ) {
    this.errors.push("cannot exceed "+POSTALCODE_MAX_LENGTH+" characters.");
    return false;
  };
  
  return true;
};

FormValidator.prototype.isValidCountry = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  COUNTRY_MIN_LENGTH = 2;

  if( value.trim().length > 0 && value.trim().length < COUNTRY_MIN_LENGTH ) {
    this.errors.push("must be at least "+COUNTRY_MIN_LENGTH+" characters long.");
  
    return false;
  };
  
  return true;
};

FormValidator.prototype.isValidPhone = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  PHONE_MIN_LENGTH = 10;
  PHONE_MAX_LENGTH = 20;

  re = /\D+/gi;
  test = value.replace( re, "");
  
  if( bIsRequired == true && test.trim().length == 0 ) {
    this.errors.push("contains no Numbers");
	return false;
  };
  
  if( test.length > 0 && test.trim().length < PHONE_MIN_LENGTH ) {
    this.errors.push("must contain at least "+PHONE_MIN_LENGTH+" digits.");
	return false;
  };
  
  if( test.trim().length > PHONE_MAX_LENGTH ) {
    this.errors.push("cannot exceed "+PHONE_MIN_LENGTH+" digits.");
	return false;
  };
  
  return true;  
};

FormValidator.prototype.isValidEmail = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  re = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/gi;
  results = value.match( re );

  if( !results && value.length > 0 ) {
    this.errors.push("is formatted invalidly.  please re-enter.");
	return false;
  };

  return true;
};

//Datatype Validation Rules

FormValidator.prototype.isValidInteger = function(value, bIsRequired) {
  INT_MAX = 65535;

  if( !this.isValidNumeric(value, bIsRequired) ) {    
	return false;
  };
  
  tempInt = (value < 0)? value * (-1) : value;
  testInt = INT_MAX - Math.ceil(tempInt);
  
  if( testInt < 0 ) {
    this.errors.push("invalid integer value (passed as 'Double').");
	return false;
  };
  
  return true;
};

FormValidator.prototype.isValidLong = function(value, bIsRequired) {
  if( !this.isValidRequired(value, bIsRequired) )
    return false;

  LNG_MAX = 16777215;
  
  if( !this.isValidNumeric(value, bIsRequired) ) {    
	return false;
  };
  
  tempLng = (value < 0)? value * (-1) : value;
  testLng = LNG_MAX - Math.ceil(tempLng);
  
  if( testLng < 0 ) {
    this.errors.push("invalid integer value (passed as 'Double').");
	return false;
  };
  
  return true;
};

FormValidator.prototype.isValidFloat = function(value, bIsRequired) {
  FLT_MAX = 4294967295;
  
  if( !this.isValidNumeric(value, bIsRequired) ) {    
	return false;
  };
  
  tempFlt = (value < 0)? value * (-1) : value;
  testFlt = FLT_MAX - Math.ceil(tempFlt);
  
  if( testFlt < 0 ) {
    this.errors.push("invalid float value (passed as 'Double').");
	return false;
  };
  
  return true;
};

FormValidator.prototype.isValidDouble = function(value, bIsRequired) {
  DBL_MAX = 18446744073709551615;

  if( !this.isValidNumeric(value, bIsRequired) ) {    
	return false;
  };
  
  tempDbl = (value < 0)? value * (-1) : value;
  testDbl = DBL_MAX - Math.ceil(tempDbl);
  
  if( testDbl < 0 ) {
    this.errors.push("invalid double value (passed as 'Double').");
	return false;
  };
  
  return true;
};

FormValidator.prototype.isValidCurrency = function(value, bIsRequired) {
  if( !this.isValidNumeric( Math.ceil(value) , bIsRequired) ) {    
	return false;
  };
  
  re = /(\.[\d]{3})$/gi;

  str = '' + value;

  if( str.match(re) ) {
    this.errors.push("has too many significant digits (decimal places).");
	return false;
  };
  
  return true;
};

FormValidator.prototype.isValidCreditcard = function(value, bIsRequired) {
  CC_MIN_LENGTH = CC_MAX_LENGTH = 16;

  if( !this.isValidNumeric( value , bIsRequired) ) {    
	return false;
  };
  
  temp = ""+value;
  
  if( temp.length < CC_MIN_LENGTH ) {
    this.errors.push("less than "+CC_MIN_LENGTH+" digits.");
	return false;
  };
  
  if( temp.length > CC_MAX_LENGTH ) {
    this.errors.push("cannot exceed "+CC_MAX_LENGTH+" digits.");
	return false;
  };

  checkCC = new Function('s', 'var i, n, c, r, t; r = ""; for (i = 0; i < s.length; i++) {c = parseInt(s.charAt(i), 10); if (c >= 0 && c <= 9) r = c + r;}; if (r.length <= 1) return false; t = ""; for (i = 0; i < r.length; i++) { c = parseInt(r.charAt(i), 10); if (i % 2 != 0) c *= 2; t = t + c; }; n = 0; for (i = 0; i < t.length; i++) {c = parseInt(t.charAt(i), 10); n = n + c; }; if (n != 0 && n % 10 == 0) return true; else return false;');
  test = checkCC(value);
  
  if( !test ) {
    this.errors.push("is Invalid (Bad Checksum).  Please Re-Enter.");
	return false;
  };
  
  return true;
};/* Floormall.com AJAX Shipping Calculator Functionality */

/**
 * General Utility Functions
 */
/* Return VIEWPORT WIDTH */
if( !window.getViewportWidth ) {
  function getViewportWidth() {

    /* supported in Mozilla, Opera, and Safari */
     if(window.innerWidth)
         return window.innerWidth;
	
    /* supported in standards mode of IE, but not in any other mode */
     if(window.document.documentElement.clientWidth)
         return document.documentElement.clientWidth;
	
    /* supported in quirks mode, older versions of IE, and mac IE (anything else). */
    return window.document.body.clientWidth;
  };
};

/* Return VIEWPORT HEIGHT */
if( !window.getViewportHeight ) {
  function getViewportHeight() {

    /* supported in Mozilla, Opera, and Safari */
     if(window.innerHeight)
         return window.innerHeight;
	
    /* supported in standards mode of IE, but not in any other mode */
     if(window.document.documentElement.clientHeight)
         return document.documentElement.clientHeight;
	
    /* supported in quirks mode, older versions of IE, and mac IE (anything else). */
    return window.document.body.clientHeight;
  };
};

if( !window.topScrolled ) {
function topScrolled() {
  var y;
  if (self.pageYOffset) {// all except Explorer
	y = self.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop) {// Explorer 6 Strict
	y = document.documentElement.scrollTop;
  }
  else if (document.body) {// all other Explorers
	y = document.body.scrollTop;
  }

  return y;
}
};

if( !window.widthScrolled ) {
function widthScrolled() {
  var x;
  if (self.pageXOffset) // all except Explorer
	x = self.pageXOffset;
  else if (document.documentElement && document.documentElement.scrollLeft) // Explorer 6 Strict
	x = document.documentElement.scrollLeft;
  else if (document.body) // all other Explorers
	x = document.body.scrollLeft;

  return x;
}
};

var AjaxShipping = {
  show: function() {
    this.initform();

    h = getViewportHeight();
    w = getViewportWidth();

    ts = topScrolled();
    ws = widthScrolled();

//    $('frmGetShipping').reset();

    $('ajax_shipping_container').style.left = ( w - $('frmGetShipping').offsetWidth ) / 2 + ws + "px";
    $('ajax_shipping_container').style.top  = ( h - $('frmGetShipping').offsetHeight ) / 2 + ts/1.5 + "px";
    $('ajax_shipping_container').style.visibility = "visible";
  },

  calc: function() {
    // Init Form and Container
    this.initform();

    if( window.FormValidator ) {
      validator = new FormValidator();

      if( !validator.isValidPostalcode( $('frmGetShipping').ZipCode.value, true ) )
      {
        alert( "Zip Code Error:\n\nZip Code " + validator.parseErrors());
        $('frmGetShipping').ZipCode.focus();
        return;
      };

      if( !validator.isValidEmail( $('frmGetShipping').EmailAddress.value, true ) )
      {
        alert( "Email Address Error:\n\nEmail Address " + validator.parseErrors());
        $('frmGetShipping').EmailAddress.focus();
        return;
      };
    };

    $('ajax_shipping_container').addClass('ajax-loading');

    $('frmGetShipping').style.display = 'none';
    $('ajax_shipping_container').style.height = "200px";

    $('ajs_pleasewait_notice').style.display = 'block';

    /**
     * send takes care of encoding and returns the Ajax instance.
     * onComplete removes the spinner from the log.
     */
    qs = [];
    form = $('frmGetShipping');
    for( x=0; x<form.elements.length; x++ ) {
      qs[qs.length] = form.elements[x].name + "=" + form.elements[x].value;
    }
    qs = qs.join("&");

    this.ajax = new Ajax( $('frmGetShipping').getAttribute('action'), {
      method: 'get',
      onComplete: function() {
        $('ajs_pleasewait_notice').style.display = 'none';
        $('ajax_shipping_container').removeClass('ajax-loading');
        $('ajax_shipping_container').style.height = 'auto';

        // Check if an Error Occurred.  If so, Show the Error and the Form Again
        if( this.response.text.indexOf("Error:") > -1 ) {
          $('ajs_err_message').setHTML( this.response.text );
          $('ajs_err_message').style.display = 'block';
          $('frmGetShipping').style.display = 'block';
        }
        else {
          $('ajs_success_message').setHTML( this.response.text );
          $('ajs_success_message').style.display = 'block';
        }
      },
      data: qs
    });

    this.ajax.request();
  },

  initform: function() {
    $('ajax_shipping_container').removeClass('ajax-loading');

    $('ajs_err_message').empty();
    $('ajs_err_message').style.display = 'none';

    $('ajs_success_message').empty();
    $('ajs_success_message').style.display = 'none';

    $('ajs_pleasewait_notice').style.display = 'none';
    $('frmGetShipping').style.display = 'block';
    $('ajax_shipping_container').style.display = "block";
  },

  close: function() {

    $('ajax_shipping_container').style.visibility = "hidden";
    $('ajax_shipping_container').style.left = "-10px";
    $('ajax_shipping_container').style.top = "-10px";
    
    this.cancel();
  },

  cancel: function() {
    if( this.ajax ) { this.ajax.cancel(); }
    this.initform(); 

    // Fully Remove Graphical Space for Window
    $('ajax_shipping_container').style.display = "none";
  }
};
