/**
* Fusionbox 1.0 - jQuery Plug-in and misc prototyped functions
*
*/

(function($)  {

  //|
  //|  establish fbmvc constants events
  //|
  $(document).ready(function()
  {
    $.fbmvc = {};
    $.fbmvc.App = 'site';
    var admin_app = 'admin';
    var forge_app = 'forge';
    var controller_i = 0;
    $.fbmvc.Controller = 'home';
    $.fbmvc.Action = 'index';
    $.fbmvc.Id = null;

    $( window.location.pathname.replace(/^\//, '').replace(/\/$/, '').split('/') ).each(function(i, val) {
      val = val.raw_url_decode().trim();

      if (val=='')
      {
        controller_i++;
        return;
      }

      if (i==controller_i)
      {
        if (val==admin_app)
        {
          $.fbmvc.App = admin_app;
          controller_i = 1;
        }
        else if (val==forge_app)
        {
          $.fbmvc.App = forge_app;
          controller_i = 1;
        }
        else
        {
          $.fbmvc.Controller = val;
        }
        return true;
      }

      if (i==controller_i + 1)  {  $.fbmvc.Action = val;  return true;  }
      if (i==controller_i + 2)  {  $.fbmvc.Id = val;  return true;  }
    });

  });

  //|
  //|  convert external links
  //|
  $(document).ready(function()
  {
    $("a[rel=external]").each(function()
    {
      $(this).attr('target', "_blank");
    });
  });


  //|
  //|  misc helper functions
  //|
  $.fn.replace_ajax = function(url, data, callback)
  {
    current_element = $(this);
    $.get(url, data, function(response, status) {
      current_element.replaceWith(response);
      if (callback)  callback();
    });

    return this;
  };

  $.fn.one = function()
  {
    if ($(this).length > 0)
    {
      return $(this)[0];
    }

    return null;
  };

  $.fn.first = $.fn.one;
})(jQuery);

if (!String.prototype.htmlentities)
{
  String.prototype.htmlentities = function()
  {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'

    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  }
}
if (!String.prototype.trim)
{
  String.prototype.trim = function()
  {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'

    return this.replace(/^\s*(.*)\s*$/, '$1');
  }
}
if (!String.prototype.regexEscape)
{
  String.prototype.regexEscape = function()
  {
    return this.replace(/([\/\\$^\[\].*(){}|?])/g, '\\$1');
  }
}
/**
 *
 *  modified from:
 *
 *  URL encode / decode
 *  http://www.webtoolkit.info/
 *
 */
if (!String.prototype.raw_url_encode)
{
  String.prototype.raw_url_encode = function ()
  {
    return escape(this);
  };
}
if (!String.prototype.raw_url_decode)
{
  String.prototype.raw_url_decode = function ()
  {
    return unescape(this);
  };
}


/// from
if (!Array.prototype.contains)
{
  Array.prototype.contains = function(v)
  {
    for (i=0; i < this.length; i++)
    {
      if (this[i]==v) return true;
    }
    return false;
  };
}


//|
//|  validation functions
//|
String.prototype.validateNotBlank = function()
{
  return this.match(/\S/);
};
String.prototype.validateNotNull = function()
{
  return this.length != 0;
};
String.prototype.validateNoSpace = function()
{
  return (! this.match(/\s/));
};
String.prototype.validateMaxValue = function(max) {
  if (typeof max == 'number')
  {
    return (parseFloat(this) <= max);
  }
  else
  {
    return (this <= max);
  }
};
String.prototype.validateMinValue = function(min) {
  if (typeof min == 'number')
  {
    return (parseFloat(this) >= min);
  }
  else
  {
    return (this >= min);
  }
};
String.prototype.validateMaxLength = function(length) {
  return this.length <= length;
};
String.prototype.validateMinLength = function(length) {
  return this.length >= length;
};
String.prototype.validateCreditCard = function()
{
  var credit_card_regex = /^([0-9][-. ]?){13,16}$/;
  return this.replace(/[^0-9]/g, '').match(credit_card_regex);
};
String.prototype.validatePastDate = function(date) {

};
String.prototype.validateFutureDate = function(date) {

};
String.prototype.validateBeforeTime = function(time) {

};
String.prototype.validateAfterTime = function(time) {

};
String.prototype.validateInArray = function(values) {
  return values.contains(this);
};
var countries_array = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CS', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TP', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UK', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW'];
String.prototype.validateInCountry = function(or_value) {
  if (typeof or_value != 'undefined' && this==or_value)  return true;
  return countries_array.contains(this);
};
var states_array = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'];
String.prototype.validateInState = function(or_value) {
  if (typeof or_value != 'undefined' && this==or_value)  return true;
  return states_array.contains(this);
};
String.prototype.validateRange = function(min, max) {
  if (typeof min == 'number' && typeof max == 'number')
  {
    return (parseFloat(this) >= min && parseFloat(this) <= max);
  }
  else
  {
    return (this >= min && this <= max);
  }
};
String.prototype.validateRegex = function(regex) {
  return this.match(regex);
};
String.prototype.validateCurrency = function(symbol, comma, decimal, symbol_at_start, number_between_commas) {
  symbol = (typeof symbol=='undefined') ? '$' : symbol;
  comma = (typeof comma=='undefined') ? ',' : comma;
  decimal = (typeof decimal=='undefined') ? '.' : decimal;
  symbol_at_start = (typeof symbol_at_start=='undefined') ? true : symbol_at_start;
  number_between_commas = (typeof number_between_commas=='undefined') ? 3 : number_between_commas;

  var regex = '^'+(symbol_at_start && symbol ? symbol.regexEscape()+'?' : '') + '([0-9]{1,'+number_between_commas+'}('+comma.regexEscape()+'[0-9]{'+number_between_commas+'})*|[0-9]+)('+decimal.regexEscape()+'[0-9]*)?' + (!symbol_at_start && symbol ? symbol.regexEscape()+'?' : '') + '$';
  if (this.match(new RegExp(regex)))
  {
    return this;
  }
  else
  {
    return false;
  }
};
String.prototype.parseCurrency = function()
{
  return this.replace(/[^0-9.]/g, '').match(/[0-9.]+/)[0];
};
function parseCurrency(value)
{
  return value.parseCurrency();
}
String.prototype.validateEmail = function()
{
  var email_regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return this.match(email_regex);
};
String.prototype.validateZip = function()
{
  var zip_regex = /^[0-9]{5}(-?[0-9]{4})?$/;
  return this.match(zip_regex);
};
String.prototype.validateDate = function()
{

};
String.prototype.validateTime = function()
{

};
String.prototype.validateIp = function()
{
  var ip_regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  return this.match(ip_regex);
};
String.prototype.validatePhoneNumber = function()
{
  var phone_number_regex = /^\+?([0-9().-]+)$/;
  var phone_number_length = this.replace(/[^0-9]/g, '').length;
  return this.match(phone_number_regex) && (phone_number_length >= 10);
}
String.prototype.validateUsPhoneNumber = function(area_code_required)
{
  area_code_required = (typeof area_code_required=='undefined') ? true : area_code_required;
  if (area_code_required)
  {
    var phone_number_regex = /^(\(?[0-9]{3}\)?-? *)([0-9]{3})-? *([0-9]{4})$/;
  }
  else
  {
    var phone_number_regex = /^(\(?[0-9]{3}\)?-? *)?([0-9]{3})-? *([0-9]{4})$/;
  }
  return this.match(phone_number_regex);
}
String.prototype.validateNumber = function(comma, decimal, number_between_commas) {
  comma = (typeof comma=='undefined') ? ',' : comma;
  decimal = (typeof decimal=='undefined') ? '.' : decimal;
  number_between_commas = (typeof number_between_commas=='undefined') ? '3' : number_between_commas;
  var number_regex = new RegExp('^([0-9]{1,' + number_between_commas + '}(' + comma.regexEscape() + '[0-9]{' + number_between_commas + '})*|[0-9]+)(' + decimal.regexEscape() + '[0-9]*)?$');
  return this.match(number_regex);
};
String.prototype.parseNumber = function() {
  if (this.match(/^[0-9.]+/)) return parseInt(this.match(/^[0-9.]+/)[0]);
  return 0;
};
String.prototype.validateDigits = function(digits, precision)
{

};
String.prototype.validateInteger = function()
{
  var contender = this.match(/[0-9]+/);
  return (contender[0] == this) ? true : false;
};
