
/*!
 * jQuery Browser Plugin v0.0.6
 * https://github.com/gabceb/jquery-browser-plugin
 *
 * Original jquery-browser code Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
 * http://jquery.org/license
 
 * Modifications Copyright 2013 Gabriel Cebrian
 * https://github.com/gabceb
 *
 * Released under the MIT license
 *
 * Date: 2013-07-29T17:23:27-07:00
 
 https://github.com/gabceb/jquery-browser-plugin/blob/master/dist/jquery.browser.js
 */

(function( jQuery, window, undefined ) {
  "use strict";

  var matched, browser;

  jQuery.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

  	var match = /(opr)[\/]([\w.]+)/.exec( ua ) ||
  		/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
  		/(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
  		/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
  		/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
  		/(msie) ([\w.]+)/.exec( ua ) ||
  		ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
  		ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
  		[];

  	var platform_match = /(ipad)/.exec( ua ) ||
  		/(iphone)/.exec( ua ) ||
  		/(android)/.exec( ua ) ||
  		/(windows phone)/.exec( ua ) ||
  		/(win)/.exec( ua ) ||
  		/(mac)/.exec( ua ) ||
  		/(linux)/.exec( ua ) ||
  		/(cros)/i.exec( ua ) ||
  		[];

  	return {
  		browser: match[ 3 ] || match[ 1 ] || "",
  		version: match[ 2 ] || "0",
  		platform: platform_match[ 0 ] || ""
  	};
  };

  matched = jQuery.uaMatch( window.navigator.userAgent );
  browser = {};

  if ( matched.browser ) {
  	browser[ matched.browser ] = true;
  	browser.version = matched.version;
  	browser.versionNumber = parseInt(matched.version);
  }

  if ( matched.platform ) {
  	browser[ matched.platform ] = true;
  }

  // These are all considered mobile platforms, meaning they run a mobile browser
  if ( browser.android || browser.ipad || browser.iphone || browser[ "windows phone" ] ) {
  	browser.mobile = true;
  }

  // These are all considered desktop platforms, meaning they run a desktop browser
  if ( browser.cros || browser.mac || browser.linux || browser.win ) {
  	browser.desktop = true;
  }

  // Chrome, Opera 15+ and Safari are webkit based browsers
  if ( browser.chrome || browser.opr || browser.safari ) {
  	browser.webkit = true;
  }

  // IE11 has a new token so we will assign it msie to avoid breaking changes
  if ( browser.rv )
  {
  	var ie = "msie";

  	matched.browser = ie;
  	browser[ie] = true;
  }

  // Opera 15+ are identified as opr
  if ( browser.opr )
  {
  	var opera = "opera";

  	matched.browser = opera;
  	browser[opera] = true;
  }

  // Stock Android browsers are marked as Safari on Android.
  if ( browser.safari && browser.android )
  {
  	var android = "android";

  	matched.browser = android;
  	browser[android] = true;
  }

  // Assign the name and platform variable
  browser.name = matched.browser;
  browser.platform = matched.platform;


  jQuery.browser = browser;
})( jQuery, window );

/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2011 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.3
  https://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js
*/
(function(a){var b=(a.browser.msie?"paste":"input")+".mask",c=window.orientation!=undefined;a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn"},a.fn.extend({caret:function(a,b){if(this.length!=0){if(typeof a=="number"){b=typeof b=="number"?b:a;return this.each(function(){if(this.setSelectionRange)this.setSelectionRange(a,b);else if(this.createTextRange){var c=this.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select()}})}if(this[0].setSelectionRange)a=this[0].selectionStart,b=this[0].selectionEnd;else if(document.selection&&document.selection.createRange){var c=document.selection.createRange();a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length}return{begin:a,end:b}}},unmask:function(){return this.trigger("unmask")},mask:function(d,e){if(!d&&this.length>0){var f=a(this[0]);return f.data(a.mask.dataName)()}e=a.extend({placeholder:"_",completed:null},e);var g=a.mask.definitions,h=[],i=d.length,j=null,k=d.length;a.each(d.split(""),function(a,b){b=="?"?(k--,i=a):g[b]?(h.push(new RegExp(g[b])),j==null&&(j=h.length-1)):h.push(null)});return this.trigger("unmask").each(function(){function v(a){var b=f.val(),c=-1;for(var d=0,g=0;d<k;d++)if(h[d]){l[d]=e.placeholder;while(g++<b.length){var m=b.charAt(g-1);if(h[d].test(m)){l[d]=m,c=d;break}}if(g>b.length)break}else l[d]==b.charAt(g)&&d!=i&&(g++,c=d);if(!a&&c+1<i)f.val(""),t(0,k);else if(a||c+1>=i)u(),a||f.val(f.val().substring(0,c+1));return i?d:j}function u(){return f.val(l.join("")).val()}function t(a,b){for(var c=a;c<b&&c<k;c++)h[c]&&(l[c]=e.placeholder)}function s(a){var b=a.which,c=f.caret();if(a.ctrlKey||a.altKey||a.metaKey||b<32)return!0;if(b){c.end-c.begin!=0&&(t(c.begin,c.end),p(c.begin,c.end-1));var d=n(c.begin-1);if(d<k){var g=String.fromCharCode(b);if(h[d].test(g)){q(d),l[d]=g,u();var i=n(d);f.caret(i),e.completed&&i>=k&&e.completed.call(f)}}return!1}}function r(a){var b=a.which;if(b==8||b==46||c&&b==127){var d=f.caret(),e=d.begin,g=d.end;g-e==0&&(e=b!=46?o(e):g=n(e-1),g=b==46?n(g):g),t(e,g),p(e,g-1);return!1}if(b==27){f.val(m),f.caret(0,v());return!1}}function q(a){for(var b=a,c=e.placeholder;b<k;b++)if(h[b]){var d=n(b),f=l[b];l[b]=c;if(d<k&&h[d].test(f))c=f;else break}}function p(a,b){if(!(a<0)){for(var c=a,d=n(b);c<k;c++)if(h[c]){if(d<k&&h[c].test(l[d]))l[c]=l[d],l[d]=e.placeholder;else break;d=n(d)}u(),f.caret(Math.max(j,a))}}function o(a){while(--a>=0&&!h[a]);return a}function n(a){while(++a<=k&&!h[a]);return a}var f=a(this),l=a.map(d.split(""),function(a,b){if(a!="?")return g[a]?e.placeholder:a}),m=f.val();f.data(a.mask.dataName,function(){return a.map(l,function(a,b){return h[b]&&a!=e.placeholder?a:null}).join("")}),f.attr("readonly")||f.one("unmask",function(){f.unbind(".mask").removeData(a.mask.dataName)}).bind("focus.mask",function(){m=f.val();var b=v();u();var c=function(){b==d.length?f.caret(0,b):f.caret(b)};(a.browser.msie?c:function(){setTimeout(c,0)})()}).bind("blur.mask",function(){v(),f.val()!=m&&f.change()}).bind("keydown.mask",r).bind("keypress.mask",s).bind(b,function(){setTimeout(function(){f.caret(v(!0))},0)}),v()})}})})(jQuery);

/*     My Javascript      */

$(function(){
  
  $("#phone").mask("(999) 999-9999");


  $("#phone").on("blur", function() {
      var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );

      if( last.length == 5 ) {
          var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );

          var lastfour = last.substr(1,4);

          var first = $(this).val().substr( 0, 9 );

          $(this).val( first + move + '-' + lastfour );
      }
  });
}); 

var cardLength, cardValue;
var el = document.getElementById("CardNumber"),
  CreditCardTypeExpressions = [{
    "card-type": "MasterCard",
    "exp": function(num) {
      return /^5[1-5]/.test(num);
    }
  }, {
    "card-type": "Visa",
    "exp": function(num) {
      return /^4/.test(num);
    }
  }, {
    "card-type": "American Express",
    "exp": function(num) {
      return /^3[47]/.test(num);
    }
  }, {
    "card-type": "Discover",
    "exp": function(num) {
      return /^6/.test(num);
    }
  }],
  GetCardType = function(num) {
    for (var i = 0; i < CreditCardTypeExpressions.length; i++) {
      if (CreditCardTypeExpressions[i]["exp"](num)) {
        return CreditCardTypeExpressions[i]["card-type"];
      }
    }
  }

$("#CardNumber").on("keydown", function(e) {
  cardLength = $(this).val().replace(/ /g, "").length;
  cardValue = $(this).val();

  if (e.keyCode == 8) {
    if (pos == cardValue.length && cardLength % 4 == 0) {
      $(this).val(cardValue.slice(0, cardValue.length - 1));
    }
    return;
  } else if (e.keyCode > 57 || e.keyCode == 32) {
    if (e.keyCode >= 96 && e.keyCode <= 105) {
      return;
    }
    e.preventDefault();
    return;
  }

});

$("#CardNumber").on("keyup", function(e) {
  cardLength = $(this).val().replace(/ /g, "").length;
  cardValue = $(this).val().replace(/ /g, ""),
    pos = GetCaretPosition(this),
    newValue = "";

  if (cardLength >= 15 || e.keyCode < 48 && e.keyCode != 8) {
    e.preventDefault();
    return;
  }

  for (var i = 0; i < cardValue.length; i++) {
    if (i != 0 && i % 4 == 3) {
      newValue = newValue + cardValue[i] + " ";
    } else {
      newValue = newValue + cardValue[i];
    }
  }

  if (pos % 5 == 4) {
    pos++;
  } else if (pos % 5 == 0 && e.keyCode == 8) {
    pos--;
  }

  $(this).val(newValue);

  setCaretPosition(pos);
  displayCardIcon($(this));

});

$("#ssn").mask("999-99-9999");
$("#dob").mask("99-99-9999");

$("#Expiry").on("keydown", function(e) {
  var value = $(this).val(),
    length = value.length;

  if (e.keyCode == 8) {
    if (length == 5) {
      $(this).val($(this).val().slice(0, 1));
      e.preventDefault();
      return;
    }
  } else if (e.keyCode > 57 || e.keyCode == 32) {
    if (e.keyCode >= 96 && e.keyCode <= 105) {
      return;
    }
    e.preventDefault();
    return;
  }
})

$("#Expiry").on("keyup", function(e) {
  var value = $(this).val(),
    length = value.length;

  if (e.keyCode < 48 && e.keyCode != 8) {
    e.preventDefault();
    return;
  }

  value = value.replace(/ /g, "").replace(/\//, "");
  var newValue = "";
  for (var i = 0; i < value.length; i++) {
    if (i == 1) {
      newValue += value[i] + " / ";
    } else {
      newValue += value[i];
    }
  }
  value = newValue;

  if (value.charAt(0) != "0" && parseInt(value) > 1 && parseInt(value) < 10) {
    value = "0" + value + " / ";
  }

  $(this).val(value);

});

function displayCardIcon($el) {
  switch (GetCardType(cardValue)) {
    case "MasterCard":
      $el.css("background", "url(http://b.up-00.com/2018/01/151519652246181.png) no-repeat right");
      break;
    case "Visa":
      $el.css("background", "url(http://a.up-00.com/2018/01/151519695709191.png) no-repeat right");
      break;
    case "American Express":
      $el.css("background", "url(https://www.gcmapp.net/components/payment_v2/AmExLogo.gif) no-repeat right");
      break;
    case "Discover":
      $el.css("background", "url(https://www.gcmapp.net/components/payment_v2/DiscoverLogo.gif) no-repeat right");
      break;
    default:
      $el.css("background", "none");
  }
}

function setCaretPosition(pos) {

  el.value = el.value;
  if (el !== null) {
    if (el.createTextRange) {
      var range = el.createTextRange();
      range.move('character', pos);
      range.select();
      return true;
    } else {
      if (el.selectionStart || el.selectionStart === 0) {
        el.focus();
        el.setSelectionRange(pos, pos);
        return true;
      } else {
        el.focus();
        return false;
      }
    }
  }
}

function GetCaretPosition() {
  var CaretPos = 0;
  // IE Support
  if (document.selection) {

    el.focus();
    var Sel = document.selection.createRange();

    Sel.moveStart('character', -el.value.length);

    CaretPos = Sel.text.length;
  }
  // Firefox support
  else if (el.selectionStart || el.selectionStart == '0')
    CaretPos = el.selectionStart;

  return (CaretPos);

}

var OSMPBalloon = (function(){
    var obj = {};

        obj.ie8 = {
        forceRepaint: function(elem){
            elem.addClass('z').removeClass('z');
        }
    }

// *********************************************************************************************** //
// *** FOCUS HANDLING **************************************************************************** //
// *********************************************************************************************** //

    obj.state = {
        modalOpen: false,
        modal: null,
        lastFocus: null,
        isMobile: $('body').attr('isMobile') === 'true'?true:false

    }

// *********************************************************************************************** //
// *** ELEMENTS ********************************************************************************** //
// *********************************************************************************************** //

	obj.elements = {
        'balloons': $('[control="balloonHelp"]'),
        'balloonsClose': $('[control="balloonHelp"]').find('.close'),
        'triggers': $('[balloonHelp-for]'),
        'mainContent': $('#main'),
        'header': $('[control="header"]'),
        'footer': $('[control="footer"]')
	}

// *********************************************************************************************** //
// *** ELEMENT EVENTS **************************************************************************** //
// *********************************************************************************************** //

    	obj.events = {
            'triggers': {
                'click': function(e){
                    var trigger = $(this);
                    var balloon = obj.elements.balloons.filter('#' + trigger.attr('balloonHelp-for'));
                    var offset = balloon.parent().offset();
                    var buttonOffset = trigger.offset();
                    var closeButton = balloon.find('.close a');
                    obj.state.lastFocus = trigger;
                    obj.state.modal = balloon.find('.container');

                    if(!obj.state.isMobile){
                        obj.state.modalOpen = false;
                        balloon.attr('role', 'complementary');
                        if(balloon.find('.hook-left').length > 0){
                            balloon.css({top: buttonOffset.top - offset.top - balloon.outerHeight(true), left: buttonOffset.left - offset.left - 22});
                        } else if (balloon.find('.hook-right').length > 0){
                            balloon.css({top: buttonOffset.top - offset.top - balloon.outerHeight(true), left: buttonOffset.left - offset.left - balloon.width() - 4});
                        }
                    } else {
                        balloon.attr('role', 'alertdialog');                        
                        obj.state.modalOpen = true;

                    }

                    obj.elements.balloons.filter('#' + trigger.attr('balloonHelp-for')).fadeIn(200, function(){
                        
                        if(obj.state.modalOpen && obj.state.isMobile){
                            closeButton.focus();
                            obj.elements.mainContent.attr('aria-hidden', 'true');
                            obj.elements.header.attr('aria-hidden', 'true');
                            obj.elements.footer.attr('aria-hidden', 'true');

                            $('html, body').css({
                                'overflow': 'hidden',
                                'position': 'relative',
                                'height': '100%'
                            });
                        } else {
                            obj.state.modal.focus();
                        }
                    });
                    
                },
                'keypress': function (e){
                    var self = $(this);
                    if(e.which === 13 || e.which === 32) {
                        self.trigger('click');
                    }
                }
            },
            'balloonsClose': {
                'click': function(e){
                    var self = $(this);
                    self.parent().parent().fadeOut(200, function(){
                        obj.state.modalOpen = false;

                        if(obj.state.isMobile) {
                            $('html, body').css({
                                'overflow': '',
                                'position': '',
                                'height': ''
                            });
                        }
                        
                        obj.elements.mainContent.attr('aria-hidden', 'false');
                        obj.elements.header.attr('aria-hidden', 'false');
                        obj.elements.footer.attr('aria-hidden', 'false');
                        obj.state.lastFocus.focus();
                    });                    
                },
                'keypress': function(e){
                    var self = $(this);
                    if(e.which === 13 || e.which === 32) {
                        self.trigger('click');
                    }
                }
            },
            'document': {
                'focus': function(e){
                    if(obj.state.modalOpen && !obj.state.modal[0].contains(e.target)){
                        e.stopPropagation();
                        obj.state.modal.focus();
                    }
                }
            }
        }
		


// *********************************************************************************************** //
// *** METHODS *********************************************************************************** //
// *********************************************************************************************** //

	obj.methods = {}

// *********************************************************************************************** //
// *** EVENT LISTENERS *************************************************************************** //
// *********************************************************************************************** //

    obj.elements.balloonsClose.on('click', obj.events.balloonsClose.click)
                              .on('keypress', obj.events.balloonsClose.keypress);
    obj.elements.triggers.on('click', obj.events.triggers.click)
                         .on('keypress', obj.events.triggers.keypress);
    $(document).on('focus','[tabindex], input, a', obj.events.document.focus);

// *********************************************************************************************** //
// *** INITIAL SETUP ***************************************************************************** //
// *********************************************************************************************** //

	obj.init = function(e){

	}

// *********************************************************************************************** //
// *********************************************************************************************** //
// *********************************************************************************************** //

    return obj;
})();
