/* Minification failed. Returning unminified contents.
(2188,5-6): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: $
 */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : e("object" == typeof exports ? require("jquery") : jQuery) }(function (e) { function n(e) { return u.raw ? e : encodeURIComponent(e) } function o(e) { return u.raw ? e : decodeURIComponent(e) } function i(e) { return n(u.json ? JSON.stringify(e) : String(e)) } function r(e) { 0 === e.indexOf('"') && (e = e.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\")); try { return e = decodeURIComponent(e.replace(c, " ")), u.json ? JSON.parse(e) : e } catch (n) { } } function t(n, o) { var i = u.raw ? n : r(n); return e.isFunction(o) ? o(i) : i } var c = /\+/g, u = e.cookie = function (r, c, f) { if (void 0 !== c && !e.isFunction(c)) { if (f = e.extend({}, u.defaults, f), "number" == typeof f.expires) { var a = f.expires, d = f.expires = new Date; d.setTime(+d + 864e5 * a) } return document.cookie = [n(r), "=", i(c), f.expires ? "; expires=" + f.expires.toUTCString() : "", f.path ? "; path=" + f.path : "", f.domain ? "; domain=" + f.domain : "", f.secure ? "; secure" : ""].join("") } for (var p = r ? void 0 : {}, s = document.cookie ? document.cookie.split("; ") : [], m = 0, x = s.length; x > m; m++) { var v = s[m].split("="), k = o(v.shift()), l = v.join("="); if (r && r === k) { p = t(l, c); break } r || void 0 === (l = t(l)) || (p[k] = l) } return p }; u.defaults = {}, e.removeCookie = function (n, o) { return void 0 === e.cookie(n) ? !1 : (e.cookie(n, "", e.extend({}, o, { expires: -1 })), !e.cookie(n)) } });;
//     Underscore.js 1.6.0
//     http://underscorejs.org
//     (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var
    push             = ArrayProto.push,
    slice            = ArrayProto.slice,
    concat           = ArrayProto.concat,
    toString         = ObjProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.6.0';

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
      }
    }
    return obj;
  };

  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results.push(iterator.call(context, value, index, list));
    });
    return results;
  };

  var reduceError = 'Reduce of empty array with no initial value';

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduce && obj.reduce === nativeReduce) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
    }
    each(obj, function(value, index, list) {
      if (!initial) {
        memo = value;
        initial = true;
      } else {
        memo = iterator.call(context, memo, value, index, list);
      }
    });
    if (!initial) throw new TypeError(reduceError);
    return memo;
  };

  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
    }
    var length = obj.length;
    if (length !== +length) {
      var keys = _.keys(obj);
      length = keys.length;
    }
    each(obj, function(value, index, list) {
      index = keys ? keys[--length] : --length;
      if (!initial) {
        memo = obj[index];
        initial = true;
      } else {
        memo = iterator.call(context, memo, obj[index], index, list);
      }
    });
    if (!initial) throw new TypeError(reduceError);
    return memo;
  };

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, predicate, context) {
    var result;
    any(obj, function(value, index, list) {
      if (predicate.call(context, value, index, list)) {
        result = value;
        return true;
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, predicate, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
    each(obj, function(value, index, list) {
      if (predicate.call(context, value, index, list)) results.push(value);
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, predicate, context) {
    return _.filter(obj, function(value, index, list) {
      return !predicate.call(context, value, index, list);
    }, context);
  };

  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, predicate, context) {
    predicate || (predicate = _.identity);
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
    each(obj, function(value, index, list) {
      if (!(result = result && predicate.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, predicate, context) {
    predicate || (predicate = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
    each(obj, function(value, index, list) {
      if (result || (result = predicate.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if the array or object contains a given value (using `===`).
  // Aliased as `include`.
  _.contains = _.include = function(obj, target) {
    if (obj == null) return false;
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
    return any(obj, function(value) {
      return value === target;
    });
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    var isFunc = _.isFunction(method);
    return _.map(obj, function(value) {
      return (isFunc ? method : value[method]).apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, _.property(key));
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function(obj, attrs) {
    return _.filter(obj, _.matches(attrs));
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function(obj, attrs) {
    return _.find(obj, _.matches(attrs));
  };

  // Return the maximum element or (element-based computation).
  // Can't optimize arrays of integers longer than 65,535 elements.
  // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
  _.max = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
      return Math.max.apply(Math, obj);
    }
    var result = -Infinity, lastComputed = -Infinity;
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      if (computed > lastComputed) {
        result = value;
        lastComputed = computed;
      }
    });
    return result;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
      return Math.min.apply(Math, obj);
    }
    var result = Infinity, lastComputed = Infinity;
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      if (computed < lastComputed) {
        result = value;
        lastComputed = computed;
      }
    });
    return result;
  };

  // Shuffle an array, using the modern version of the
  // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  _.shuffle = function(obj) {
    var rand;
    var index = 0;
    var shuffled = [];
    each(obj, function(value) {
      rand = _.random(index++);
      shuffled[index - 1] = shuffled[rand];
      shuffled[rand] = value;
    });
    return shuffled;
  };

  // Sample **n** random values from a collection.
  // If **n** is not specified, returns a single random element.
  // The internal `guard` argument allows it to work with `map`.
  _.sample = function(obj, n, guard) {
    if (n == null || guard) {
      if (obj.length !== +obj.length) obj = _.values(obj);
      return obj[_.random(obj.length - 1)];
    }
    return _.shuffle(obj).slice(0, Math.max(0, n));
  };

  // An internal function to generate lookup iterators.
  var lookupIterator = function(value) {
    if (value == null) return _.identity;
    if (_.isFunction(value)) return value;
    return _.property(value);
  };

  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, iterator, context) {
    iterator = lookupIterator(iterator);
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value: value,
        index: index,
        criteria: iterator.call(context, value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
  };

  // An internal function used for aggregate "group by" operations.
  var group = function(behavior) {
    return function(obj, iterator, context) {
      var result = {};
      iterator = lookupIterator(iterator);
      each(obj, function(value, index) {
        var key = iterator.call(context, value, index, obj);
        behavior(result, key, value);
      });
      return result;
    };
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = group(function(result, key, value) {
    _.has(result, key) ? result[key].push(value) : result[key] = [value];
  });

  // Indexes the object's values by a criterion, similar to `groupBy`, but for
  // when you know that your index values will be unique.
  _.indexBy = group(function(result, key, value) {
    result[key] = value;
  });

  // Counts instances of an object that group by a certain criterion. Pass
  // either a string attribute to count by, or a function that returns the
  // criterion.
  _.countBy = group(function(result, key) {
    _.has(result, key) ? result[key]++ : result[key] = 1;
  });

  // Use a comparator function to figure out the smallest index at which
  // an object should be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator, context) {
    iterator = lookupIterator(iterator);
    var value = iterator.call(context, obj);
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >>> 1;
      iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Safely create a real, live array from anything iterable.
  _.toArray = function(obj) {
    if (!obj) return [];
    if (_.isArray(obj)) return slice.call(obj);
    if (obj.length === +obj.length) return _.map(obj, _.identity);
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    if ((n == null) || guard) return array[0];
    if (n < 0) return [];
    return slice.call(array, 0, n);
  };

  // Returns everything but the last entry of the array. Especially useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N. The **guard** check allows it to work with
  // `_.map`.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array. The **guard** check allows it to work with `_.map`.
  _.last = function(array, n, guard) {
    if (array == null) return void 0;
    if ((n == null) || guard) return array[array.length - 1];
    return slice.call(array, Math.max(array.length - n, 0));
  };

  // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  // Especially useful on the arguments object. Passing an **n** will return
  // the rest N values in the array. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = _.drop = function(array, n, guard) {
    return slice.call(array, (n == null) || guard ? 1 : n);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, _.identity);
  };

  // Internal implementation of a recursive `flatten` function.
  var flatten = function(input, shallow, output) {
    if (shallow && _.every(input, _.isArray)) {
      return concat.apply(output, input);
    }
    each(input, function(value) {
      if (_.isArray(value) || _.isArguments(value)) {
        shallow ? push.apply(output, value) : flatten(value, shallow, output);
      } else {
        output.push(value);
      }
    });
    return output;
  };

  // Flatten out an array, either recursively (by default), or just one level.
  _.flatten = function(array, shallow) {
    return flatten(array, shallow, []);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Split an array into two arrays: one whose elements all satisfy the given
  // predicate, and one whose elements all do not satisfy the predicate.
  _.partition = function(array, predicate) {
    var pass = [], fail = [];
    each(array, function(elem) {
      (predicate(elem) ? pass : fail).push(elem);
    });
    return [pass, fail];
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iterator, context) {
    if (_.isFunction(isSorted)) {
      context = iterator;
      iterator = isSorted;
      isSorted = false;
    }
    var initial = iterator ? _.map(array, iterator, context) : array;
    var results = [];
    var seen = [];
    each(initial, function(value, index) {
      if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
        seen.push(value);
        results.push(array[index]);
      }
    });
    return results;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(_.flatten(arguments, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function(array) {
    var rest = slice.call(arguments, 1);
    return _.filter(_.uniq(array), function(item) {
      return _.every(rest, function(other) {
        return _.contains(other, item);
      });
    });
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
    return _.filter(array, function(value){ return !_.contains(rest, value); });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    var length = _.max(_.pluck(arguments, 'length').concat(0));
    var results = new Array(length);
    for (var i = 0; i < length; i++) {
      results[i] = _.pluck(arguments, '' + i);
    }
    return results;
  };

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function(list, values) {
    if (list == null) return {};
    var result = {};
    for (var i = 0, length = list.length; i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i = 0, length = array.length;
    if (isSorted) {
      if (typeof isSorted == 'number') {
        i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
      } else {
        i = _.sortedIndex(array, item);
        return array[i] === item ? i : -1;
      }
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
    for (; i < length; i++) if (array[i] === item) return i;
    return -1;
  };

  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item, from) {
    if (array == null) return -1;
    var hasIndex = from != null;
    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
      return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
    }
    var i = (hasIndex ? from : array.length);
    while (i--) if (array[i] === item) return i;
    return -1;
  };

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(length);

    while(idx < length) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Reusable constructor function for prototype setting.
  var ctor = function(){};

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  // available.
  _.bind = function(func, context) {
    var args, bound;
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError;
    args = slice.call(arguments, 2);
    return bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
      ctor.prototype = func.prototype;
      var self = new ctor;
      ctor.prototype = null;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if (Object(result) === result) return result;
      return self;
    };
  };

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context. _ acts
  // as a placeholder, allowing any combination of arguments to be pre-filled.
  _.partial = function(func) {
    var boundArgs = slice.call(arguments, 1);
    return function() {
      var position = 0;
      var args = boundArgs.slice();
      for (var i = 0, length = args.length; i < length; i++) {
        if (args[i] === _) args[i] = arguments[position++];
      }
      while (position < arguments.length) args.push(arguments[position++]);
      return func.apply(this, args);
    };
  };

  // Bind a number of an object's methods to that object. Remaining arguments
  // are the method names to be bound. Useful for ensuring that all callbacks
  // defined on an object belong to it.
  _.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length === 0) throw new Error('bindAll must be passed function names');
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memo = {};
    hasher || (hasher = _.identity);
    return function() {
      var key = hasher.apply(this, arguments);
      return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
    };
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){ return func.apply(null, args); }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time. Normally, the throttled function will run
  // as much as it can, without ever going more than once per `wait` duration;
  // but if you'd like to disable the execution on the leading edge, pass
  // `{leading: false}`. To disable execution on the trailing edge, ditto.
  _.throttle = function(func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    options || (options = {});
    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      context = args = null;
    };
    return function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0) {
        clearTimeout(timeout);
        timeout = null;
        previous = now;
        result = func.apply(context, args);
        context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function() {
      var last = _.now() - timestamp;
      if (last < wait) {
        timeout = setTimeout(later, wait - last);
      } else {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
          context = args = null;
        }
      }
    };

    return function() {
      context = this;
      args = arguments;
      timestamp = _.now();
      var callNow = immediate && !timeout;
      if (!timeout) {
        timeout = setTimeout(later, wait);
      }
      if (callNow) {
        result = func.apply(context, args);
        context = args = null;
      }

      return result;
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return _.partial(wrapper, func);
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

  // Object Functions
  // ----------------

  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = function(obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var values = new Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  };

  // Convert an object into a list of `[key, value]` pairs.
  _.pairs = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var pairs = new Array(length);
    for (var i = 0; i < length; i++) {
      pairs[i] = [keys[i], obj[keys[i]]];
    }
    return pairs;
  };

  // Invert the keys and values of an object. The values must be serializable.
  _.invert = function(obj) {
    var result = {};
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      result[obj[keys[i]]] = keys[i];
    }
    return result;
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function(obj) {
    var copy = {};
    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
    each(keys, function(key) {
      if (key in obj) copy[key] = obj[key];
    });
    return copy;
  };

   // Return a copy of the object without the blacklisted properties.
  _.omit = function(obj) {
    var copy = {};
    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
    for (var key in obj) {
      if (!_.contains(keys, key)) copy[key] = obj[key];
    }
    return copy;
  };

  // Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          if (obj[prop] === void 0) obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Internal recursive comparison function for `isEqual`.
  var eq = function(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) return a !== 0 || 1 / a == 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className != toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b);
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a == +b;
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') return false;
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = aStack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] == a) return bStack[length] == b;
    }
    // Objects with different constructors are not equivalent, but `Object`s
    // from different frames are.
    var aCtor = a.constructor, bCtor = b.constructor;
    if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
                             _.isFunction(bCtor) && (bCtor instanceof bCtor))
                        && ('constructor' in a && 'constructor' in b)) {
      return false;
    }
    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);
    var size = 0, result = true;
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length;
      result = size == b.length;
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          if (!(result = eq(a[size], b[size], aStack, bStack))) break;
        }
      }
    } else {
      // Deep compare objects.
      for (var key in a) {
        if (_.has(a, key)) {
          // Count the expected number of properties.
          size++;
          // Deep compare each member.
          if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (_.has(b, key) && !(size--)) break;
        }
        result = !size;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return result;
  };

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b, [], []);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
    for (var key in obj) if (_.has(obj, key)) return false;
    return true;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType === 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    return obj === Object(obj);
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) == '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return !!(obj && _.has(obj, 'callee'));
    };
  }

  // Optimize `isFunction` if appropriate.
  if (typeof (/./) !== 'function') {
    _.isFunction = function(obj) {
      return typeof obj === 'function';
    };
  }

  // Is a given object a finite number?
  _.isFinite = function(obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

  // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  _.isNaN = function(obj) {
    return _.isNumber(obj) && obj != +obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  _.has = function(obj, key) {
    return hasOwnProperty.call(obj, key);
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iterators.
  _.identity = function(value) {
    return value;
  };

  _.constant = function(value) {
    return function () {
      return value;
    };
  };

  _.property = function(key) {
    return function(obj) {
      return obj[key];
    };
  };

  // Returns a predicate for checking whether an object has a given set of `key:value` pairs.
  _.matches = function(attrs) {
    return function(obj) {
      if (obj === attrs) return true; //avoid comparing an object to itself.
      for (var key in attrs) {
        if (attrs[key] !== obj[key])
          return false;
      }
      return true;
    }
  };

  // Run a function **n** times.
  _.times = function(n, iterator, context) {
    var accum = Array(Math.max(0, n));
    for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
    return accum;
  };

  // Return a random integer between min and max (inclusive).
  _.random = function(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  };

  // A (possibly faster) way to get the current timestamp as an integer.
  _.now = Date.now || function() { return new Date().getTime(); };

  // List of HTML entities for escaping.
  var entityMap = {
    escape: {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;'
    }
  };
  entityMap.unescape = _.invert(entityMap.escape);

  // Regexes containing the keys and values listed immediately above.
  var entityRegexes = {
    escape:   new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
    unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  };

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  _.each(['escape', 'unescape'], function(method) {
    _[method] = function(string) {
      if (string == null) return '';
      return ('' + string).replace(entityRegexes[method], function(match) {
        return entityMap[method][match];
      });
    };
  });

  // If the value of the named `property` is a function then invoke it with the
  // `object` as context; otherwise, return it.
  _.result = function(object, property) {
    if (object == null) return void 0;
    var value = object[property];
    return _.isFunction(value) ? value.call(object) : value;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function(obj) {
    each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result.call(this, func.apply(_, args));
      };
    });
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'":      "'",
    '\\':     '\\',
    '\r':     'r',
    '\n':     'n',
    '\t':     't',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(text, data, settings) {
    var render;
    settings = _.defaults({}, settings, _.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = new RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset)
        .replace(escaper, function(match) { return '\\' + escapes[match]; });

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      }
      if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      }
      if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }
      index = offset + match.length;
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + "return __p;\n";

    try {
      render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    if (data) return render(data, _);
    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled function source as a convenience for precompilation.
    template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function, which will delegate to the wrapper.
  _.chain = function(obj) {
    return _(obj).chain();
  };

  // OOP
  // ---------------
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.

  // Helper function to continue chaining intermediate results.
  var result = function(obj) {
    return this._chain ? _(obj).chain() : obj;
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      var obj = this._wrapped;
      method.apply(obj, arguments);
      if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
      return result.call(this, obj);
    };
  });

  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      return result.call(this, method.apply(this._wrapped, arguments));
    };
  });

  _.extend(_.prototype, {

    // Start chaining a wrapped Underscore object.
    chain: function() {
      this._chain = true;
      return this;
    },

    // Extracts the result from a wrapped and chained object.
    value: function() {
      return this._wrapped;
    }

  });

  // AMD registration happens at the end for compatibility with AMD loaders
  // that may not enforce next-turn semantics on modules. Even though general
  // practice for AMD registration is to be anonymous, underscore registers
  // as a named module because, like jQuery, it is a base library that is
  // popular enough to be bundled in a third party lib, but not be part of
  // an AMD load request. Those cases could generate an error when an
  // anonymous define() is called outside of a loader request.
  if (typeof define === 'function' && define.amd) {
    define('underscore', [], function() {
      return _;
    });
  }
}).call(this);
;
/* ========================================================================
 * Bootstrap: tooltip.js v3.3.0
 * http://getbootstrap.com/javascript/#tooltip
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // TOOLTIP PUBLIC CLASS DEFINITION
  // ===============================

  var Tooltip = function (element, options) {
    this.type       =
    this.options    =
    this.enabled    =
    this.timeout    =
    this.hoverState =
    this.$element   = null

    this.init('tooltip', element, options)
  }

  Tooltip.VERSION  = '3.3.0'

  Tooltip.TRANSITION_DURATION = 150

  Tooltip.DEFAULTS = {
    animation: true,
    placement: 'top',
    selector: false,
    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
    trigger: 'hover focus',
    title: '',
    delay: 0,
    html: false,
    container: false,
    viewport: {
      selector: 'body',
      padding: 0
    }
  }

  Tooltip.prototype.init = function (type, element, options) {
    this.enabled   = true
    this.type      = type
    this.$element  = $(element)
    this.options   = this.getOptions(options)
    this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)

    var triggers = this.options.trigger.split(' ')

    for (var i = triggers.length; i--;) {
      var trigger = triggers[i]

      if (trigger == 'click') {
        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
      } else if (trigger != 'manual') {
        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
        var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'

        this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
        this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
      }
    }

    this.options.selector ?
      (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
      this.fixTitle()
  }

  Tooltip.prototype.getDefaults = function () {
    return Tooltip.DEFAULTS
  }

  Tooltip.prototype.getOptions = function (options) {
    options = $.extend({}, this.getDefaults(), this.$element.data(), options)

    if (options.delay && typeof options.delay == 'number') {
      options.delay = {
        show: options.delay,
        hide: options.delay
      }
    }

    return options
  }

  Tooltip.prototype.getDelegateOptions = function () {
    var options  = {}
    var defaults = this.getDefaults()

    this._options && $.each(this._options, function (key, value) {
      if (defaults[key] != value) options[key] = value
    })

    return options
  }

  Tooltip.prototype.enter = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (self && self.$tip && self.$tip.is(':visible')) {
      self.hoverState = 'in'
      return
    }

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    clearTimeout(self.timeout)

    self.hoverState = 'in'

    if (!self.options.delay || !self.options.delay.show) return self.show()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'in') self.show()
    }, self.options.delay.show)
  }

  Tooltip.prototype.leave = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    clearTimeout(self.timeout)

    self.hoverState = 'out'

    if (!self.options.delay || !self.options.delay.hide) return self.hide()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'out') self.hide()
    }, self.options.delay.hide)
  }

  Tooltip.prototype.show = function () {
    var e = $.Event('show.bs.' + this.type)

    if (this.hasContent() && this.enabled) {
      this.$element.trigger(e)

      var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
      if (e.isDefaultPrevented() || !inDom) return
      var that = this

      var $tip = this.tip()

      var tipId = this.getUID(this.type)

      this.setContent()
      $tip.attr('id', tipId)
      this.$element.attr('aria-describedby', tipId)

      if (this.options.animation) $tip.addClass('fade')

      var placement = typeof this.options.placement == 'function' ?
        this.options.placement.call(this, $tip[0], this.$element[0]) :
        this.options.placement

      var autoToken = /\s?auto?\s?/i
      var autoPlace = autoToken.test(placement)
      if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

      $tip
        .detach()
        .css({ top: 0, left: 0, display: 'block' })
        .addClass(placement)
        .data('bs.' + this.type, this)

      this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

      var pos          = this.getPosition()
      var actualWidth  = $tip[0].offsetWidth
      var actualHeight = $tip[0].offsetHeight

      if (autoPlace) {
        var orgPlacement = placement
        var $container   = this.options.container ? $(this.options.container) : this.$element.parent()
        var containerDim = this.getPosition($container)

        placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top'    :
                    placement == 'top'    && pos.top    - actualHeight < containerDim.top    ? 'bottom' :
                    placement == 'right'  && pos.right  + actualWidth  > containerDim.width  ? 'left'   :
                    placement == 'left'   && pos.left   - actualWidth  < containerDim.left   ? 'right'  :
                    placement

        $tip
          .removeClass(orgPlacement)
          .addClass(placement)
      }

      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

      this.applyPlacement(calculatedOffset, placement)

      var complete = function () {
        var prevHoverState = that.hoverState
        that.$element.trigger('shown.bs.' + that.type)
        that.hoverState = null

        if (prevHoverState == 'out') that.leave(that)
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        $tip
          .one('bsTransitionEnd', complete)
          .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
        complete()
    }
  }

  Tooltip.prototype.applyPlacement = function (offset, placement) {
    var $tip   = this.tip()
    var width  = $tip[0].offsetWidth
    var height = $tip[0].offsetHeight

    // manually read margins because getBoundingClientRect includes difference
    var marginTop = parseInt($tip.css('margin-top'), 10)
    var marginLeft = parseInt($tip.css('margin-left'), 10)

    // we must check for NaN for ie 8/9
    if (isNaN(marginTop))  marginTop  = 0
    if (isNaN(marginLeft)) marginLeft = 0

    offset.top  = offset.top  + marginTop
    offset.left = offset.left + marginLeft

    // $.fn.offset doesn't round pixel values
    // so we use setOffset directly with our own function B-0
    $.offset.setOffset($tip[0], $.extend({
      using: function (props) {
        $tip.css({
          top: Math.round(props.top),
          left: Math.round(props.left)
        })
      }
    }, offset), 0)

    $tip.addClass('in')

    // check to see if placing tip in new offset caused the tip to resize itself
    var actualWidth  = $tip[0].offsetWidth
    var actualHeight = $tip[0].offsetHeight

    if (placement == 'top' && actualHeight != height) {
      offset.top = offset.top + height - actualHeight
    }

    var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)

    if (delta.left) offset.left += delta.left
    else offset.top += delta.top

    var isVertical          = /top|bottom/.test(placement)
    var arrowDelta          = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
    var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'

    $tip.offset(offset)
    this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
  }

  Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) {
    this.arrow()
      .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
      .css(isHorizontal ? 'top' : 'left', '')
  }

  Tooltip.prototype.setContent = function () {
    var $tip  = this.tip()
    var title = this.getTitle()

    $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
    $tip.removeClass('fade in top bottom left right')
  }

  Tooltip.prototype.hide = function (callback) {
    var that = this
    var $tip = this.tip()
    var e    = $.Event('hide.bs.' + this.type)

    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      that.$element
        .removeAttr('aria-describedby')
        .trigger('hidden.bs.' + that.type)
      callback && callback()
    }

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    $tip.removeClass('in')

    $.support.transition && this.$tip.hasClass('fade') ?
      $tip
        .one('bsTransitionEnd', complete)
        .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
      complete()

    this.hoverState = null

    return this
  }

  Tooltip.prototype.fixTitle = function () {
    var $e = this.$element
    if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
      $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
    }
  }

  Tooltip.prototype.hasContent = function () {
    return this.getTitle()
  }

  Tooltip.prototype.getPosition = function ($element) {
    $element   = $element || this.$element

    var el     = $element[0]
    var isBody = el.tagName == 'BODY'

    var elRect    = el.getBoundingClientRect()
    if (elRect.width == null) {
      // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
      elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
    }
    var elOffset  = isBody ? { top: 0, left: 0 } : $element.offset()
    var scroll    = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
    var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null

    return $.extend({}, elRect, scroll, outerDims, elOffset)
  }

  Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2  } :
           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2  } :
           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width   }

  }

  Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
    var delta = { top: 0, left: 0 }
    if (!this.$viewport) return delta

    var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
    var viewportDimensions = this.getPosition(this.$viewport)

    if (/right|left/.test(placement)) {
      var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
      var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
      if (topEdgeOffset < viewportDimensions.top) { // top overflow
        delta.top = viewportDimensions.top - topEdgeOffset
      } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
        delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
      }
    } else {
      var leftEdgeOffset  = pos.left - viewportPadding
      var rightEdgeOffset = pos.left + viewportPadding + actualWidth
      if (leftEdgeOffset < viewportDimensions.left) { // left overflow
        delta.left = viewportDimensions.left - leftEdgeOffset
      } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
        delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
      }
    }

    return delta
  }

  Tooltip.prototype.getTitle = function () {
    var title
    var $e = this.$element
    var o  = this.options

    title = $e.attr('data-original-title')
      || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

    return title
  }

  Tooltip.prototype.getUID = function (prefix) {
    do prefix += ~~(Math.random() * 1000000)
    while (document.getElementById(prefix))
    return prefix
  }

  Tooltip.prototype.tip = function () {
    return (this.$tip = this.$tip || $(this.options.template))
  }

  Tooltip.prototype.arrow = function () {
    return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
  }

  Tooltip.prototype.enable = function () {
    this.enabled = true
  }

  Tooltip.prototype.disable = function () {
    this.enabled = false
  }

  Tooltip.prototype.toggleEnabled = function () {
    this.enabled = !this.enabled
  }

  Tooltip.prototype.toggle = function (e) {
    var self = this
    if (e) {
      self = $(e.currentTarget).data('bs.' + this.type)
      if (!self) {
        self = new this.constructor(e.currentTarget, this.getDelegateOptions())
        $(e.currentTarget).data('bs.' + this.type, self)
      }
    }

    self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
  }

  Tooltip.prototype.destroy = function () {
    var that = this
    clearTimeout(this.timeout)
    this.hide(function () {
      that.$element.off('.' + that.type).removeData('bs.' + that.type)
    })
  }


  // TOOLTIP PLUGIN DEFINITION
  // =========================

  function Plugin(option) {
    return this.each(function () {
      var $this    = $(this)
      var data     = $this.data('bs.tooltip')
      var options  = typeof option == 'object' && option
      var selector = options && options.selector

      if (!data && option == 'destroy') return
      if (selector) {
        if (!data) $this.data('bs.tooltip', (data = {}))
        if (!data[selector]) data[selector] = new Tooltip(this, options)
      } else {
        if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
      }
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tooltip

  $.fn.tooltip             = Plugin
  $.fn.tooltip.Constructor = Tooltip


  // TOOLTIP NO CONFLICT
  // ===================

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(jQuery);
;
// list of current browsers
// http://fresh-browsers.com/
; (function (window, document, undefined) {
	"use strict";

	var getBrowser = function () {
		// initial values for checks
		var
			nAgt = navigator.userAgent,                         // store user agent [Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0]
			browser = navigator.appName,                        // browser string [Netscape]
			version = '' + parseFloat(navigator.appVersion),    // version string (5) [5.0 (Windows)]
			majorVersion = parseInt(navigator.appVersion, 10)   // version number (5) [5.0 (Windows)]
		;

		var nameOffset, // used to detect other browsers name
			verOffset,  // used to trim out version
			ix          // used to trim string
		;

		// Opera
		if ((verOffset = nAgt.indexOf('Opera')) !== -1) {
			browser = 'Opera';
			version = nAgt.substring(verOffset + 6);
			if ((verOffset = nAgt.indexOf('Version')) !== -1) {
				version = nAgt.substring(verOffset + 8);
			}

			// MSIE
		} else if ((verOffset = nAgt.indexOf('MSIE')) !== -1) {
			browser = 'Microsoft Internet Explorer';
			version = nAgt.substring(verOffset + 5);

			//IE 11 no longer identifies itself as MS IE, so trap it
			//http://stackoverflow.com/questions/17907445/how-to-detect-ie11
		} else if ((browser === 'Netscape') && (nAgt.indexOf('Trident/') !== -1)) {
			browser = 'Microsoft Internet Explorer';
			version = nAgt.substring(verOffset + 5);
			if ((verOffset = nAgt.indexOf('rv:')) !== -1) {
				version = nAgt.substring(verOffset + 3);
			}

			// Chrome
		} else if ((verOffset = nAgt.indexOf('Chrome')) !== -1) {
			browser = 'Chrome';
			version = nAgt.substring(verOffset + 7);

			// Chrome on iPad identifies itself as Safari. However it does mention CriOS.
		} else if ((verOffset = nAgt.indexOf('CriOS')) !== -1) {
			browser = 'Chrome';
			version = nAgt.substring(verOffset + 6);

			// Safari
		} else if ((verOffset = nAgt.indexOf('Safari')) !== -1) {
			browser = 'Safari';
			version = nAgt.substring(verOffset + 7);
			if ((verOffset = nAgt.indexOf('Version')) !== -1) {
				version = nAgt.substring(verOffset + 8);
			}

			// Firefox
		} else if ((verOffset = nAgt.indexOf('Firefox')) !== -1) {
			browser = 'Firefox';
			version = nAgt.substring(verOffset + 8);

			// Other browsers
		} else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
			browser = nAgt.substring(nameOffset, verOffset);
			version = nAgt.substring(verOffset + 1);
			if (browser.toLowerCase() === browser.toUpperCase()) {
				browser = navigator.appName;
			}
		}

		// trim the version string
		if ((ix = version.indexOf(';')) !== -1) version = version.substring(0, ix);
		if ((ix = version.indexOf(' ')) !== -1) version = version.substring(0, ix);
		if ((ix = version.indexOf(')')) !== -1) version = version.substring(0, ix);

		// why is this here?
		majorVersion = parseInt('' + version, 10);
		if (isNaN(majorVersion)) {
			version = '' + parseFloat(navigator.appVersion);
			majorVersion = parseInt(navigator.appVersion, 10);
		}

		return {
			name: browser,
			version: majorVersion,
			versionString: version
		};
	},
    getDevice = function () {
    	var i,
            nVer = navigator.appVersion,
            nAgt = navigator.userAgent,
            tabletStrings = [
				{ s: 'iPad', r: /iPad/ },
                { s: 'Samsung Galaxy', r: /SCH-I800/ },
                { s: 'Motorola', r: /xoom/ },
                { s: 'Kindle', r: /kindle/ }
            ],
            phoneStrings = [
                 { s: 'iPhone', r: /iPhone/ },
                 { s: 'iPod', r: /iPod/ },
                 { s: 'blackberry', r: /blackberry/ },
                 { s: 'android 0.5', r: /android 0.5/ },
                 { s: 'htc', r: /htc/ },
                 { s: 'lg', r: /lg/ },
                 { s: 'midp', r: /midp/ },
                 { s: 'mmp', r: /mmp/ },
                 { s: 'mobile', r: /mobile/ },
                 { s: 'nokia', r: /nokia/ },
                 { s: 'opera mini', r: /opera mini/ },
                 { s: 'palm', r: /palm|PalmSource/ },
                 { s: 'pocket', r: /pocket/ },
                 { s: 'psp', r: /psp|Playstation Portable/ },
                 { s: 'sgh', r: /sgh/ },
				 { s: 'smartphone', r: /smartphone/ },
                 { s: 'symbian', r: /symbian/ },
                 { s: 'treo mini', r: /treo mini/ },
                 { s: 'SonyEricsson', r: /SonyEricsson/ },
                 { s: 'Samsung', r: /Samsung/ },
                 { s: 'MobileExplorer', r: /MobileExplorer/ },
                 { s: 'Benq', r: /Benq/ },
                 { s: 'Windows Phone', r: /Windows Phone/ },
                 { s: 'Windows Mobile', r: /Windows Mobile/ },
                 { s: 'IEMobile', r: /IEMobile/ },
                 { s: 'Windows CE', r: /Windows CE/ },
                 { s: 'Nintendo Wii', r: /Nintendo Wii/ }
            ];

    	var is_tablet = false,
			is_phone = false,
			device = "";

    	for (i in tabletStrings) {
    		if (!!tabletStrings[i].r && tabletStrings[i].r.test(nAgt)) {
    			device = tabletStrings[i].s;
    			is_tablet = true;
    			break;
    		}
    	}

    	if (device === "") {
    		for (i in phoneStrings) {
    			if (!!phoneStrings[i].r && phoneStrings[i].r.test(nAgt)) {
    				device = phoneStrings[i].s;
    				is_phone = true;
    				break;
    			}
    		}
    	}

    	// if they are on tablet or phone
    	var is_mobile = is_tablet || is_phone;
    	if (!is_mobile) {
    		is_mobile = /Mobile|mini|Fennec|Android/.test(nVer);
    	}

    	return {
    		screen: {
    			width: screen.width,
    			height: screen.height
    		},
    		device: device,
    		isTable: is_tablet,
    		isMobile: is_mobile,
    		isPhone: is_phone
    	};
    },
    getOS = function () {
      	var nVer = navigator.appVersion;
       	var nAgt = navigator.userAgent;
       	var osVersion = "unknown";
       	var os = "unknown";
       	// system

       	var clientStrings = [
		    { s: 'Windows 3.11', r: /Win16/ },
            { s: 'Windows 95', r: /(Windows 95|Win95|Windows_95)/ },
            { s: 'Windows ME', r: /(Win 9x 4.90|Windows ME)/ },
            { s: 'Windows 98', r: /(Windows 98|Win98)/ },
            { s: 'Windows CE', r: /Windows CE/ },
            { s: 'Windows 2000', r: /(Windows NT 5.0|Windows 2000)/ },
            { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ },
            { s: 'Windows Server 2003', r: /Windows NT 5.2/ },
            { s: 'Windows Vista', r: /Windows NT 6.0/ },
            { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ },
            { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ },
			{ s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ },
            { s: 'Windows NT 4.0', r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ },
            { s: 'Windows ME', r: /Windows ME/ },
            { s: 'Android', r: /Android/ },
            { s: 'Open BSD', r: /OpenBSD/ },
            { s: 'Sun OS', r: /SunOS/ },
            { s: 'Linux', r: /(Linux|X11)/ },
            { s: 'iOS', r: /(iPhone|iPad|iPod)/ },
            { s: 'Mac OS X', r: /Mac OS X/ },
            { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
            { s: 'QNX', r: /QNX/ },
            { s: 'UNIX', r: /UNIX/ },
            { s: 'BeOS', r: /BeOS/ },
            { s: 'OS/2', r: /OS\/2/ },
            { s: 'Search Bot', r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/ }
       	];
        	
       	for (var id in clientStrings) {
       		var cs = clientStrings[id];
       		if (cs.r.test(nAgt)) {
       			os = cs.s;
       			break;
       		}
       	}

       	if (/Windows/.test(os)) {
       		osVersion = /Windows (.*)/.exec(os)[1];
       		os = 'Windows';
       	}
        
        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
                break;
            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
                break;
            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                if (!!osVersion && osVersion.length >= 3) {
                    osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                }
                break;
        }    

       	return {
       		name: os,
       		versionString: osVersion
       	};
    },
    getBrowserFeatures = function () {
      	// cookie support
       	var cookieEnabled = false;
       	try {
       		// Create cookie
       		document.cookie = 'cookietest=1';
       		var ret = document.cookie.indexOf('cookietest=') != -1;
       		// Delete cookie
       		document.cookie = 'cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
       		cookieEnabled = ret;
       	}
       	catch (e) {
       	}

       	return {
       		window: {
       			width: window.innerWidth,
       			height: window.innerHeight
       		},
       		allowsCookies: cookieEnabled
       	}
    }

	window.browserInfo = {
		userAgent: navigator.userAgent,
		browser: getBrowser(),
		browserFeatures: getBrowserFeatures(),
		device: getDevice(),
		os: getOS()
	};
})(window, document);;
/*! jQuery Validation Plugin - v1.17.0 - 7/29/2017
 * https://jqueryvalidation.org/
 * Copyright (c) 2017 Jörn Zaefferer; Licensed MIT */
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : "object" == typeof module && module.exports ? module.exports = a(require("jquery")) : a(jQuery) }(function (a) { a.extend(a.fn, { validate: function (b) { if (!this.length) return void (b && b.debug && window.console && console.warn("Nothing selected, can't validate, returning nothing.")); var c = a.data(this[0], "validator"); return c ? c : (this.attr("novalidate", "novalidate"), c = new a.validator(b, this[0]), a.data(this[0], "validator", c), c.settings.onsubmit && (this.on("click.validate", ":submit", function (b) { c.submitButton = b.currentTarget, a(this).hasClass("cancel") && (c.cancelSubmit = !0), void 0 !== a(this).attr("formnovalidate") && (c.cancelSubmit = !0) }), this.on("submit.validate", function (b) { function d() { var d, e; return c.submitButton && (c.settings.submitHandler || c.formSubmitted) && (d = a("<input type='hidden'/>").attr("name", c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)), !c.settings.submitHandler || (e = c.settings.submitHandler.call(c, c.currentForm, b), d && d.remove(), void 0 !== e && e) } return c.settings.debug && b.preventDefault(), c.cancelSubmit ? (c.cancelSubmit = !1, d()) : c.form() ? c.pendingRequest ? (c.formSubmitted = !0, !1) : d() : (c.focusInvalid(), !1) })), c) }, valid: function () { var b, c, d; return a(this[0]).is("form") ? b = this.validate().form() : (d = [], b = !0, c = a(this[0].form).validate(), this.each(function () { b = c.element(this) && b, b || (d = d.concat(c.errorList)) }), c.errorList = d), b }, rules: function (b, c) { var d, e, f, g, h, i, j = this[0]; if (null != j && (!j.form && j.hasAttribute("contenteditable") && (j.form = this.closest("form")[0], j.name = this.attr("name")), null != j.form)) { if (b) switch (d = a.data(j.form, "validator").settings, e = d.rules, f = a.validator.staticRules(j), b) { case "add": a.extend(f, a.validator.normalizeRule(c)), delete f.messages, e[j.name] = f, c.messages && (d.messages[j.name] = a.extend(d.messages[j.name], c.messages)); break; case "remove": return c ? (i = {}, a.each(c.split(/\s/), function (a, b) { i[b] = f[b], delete f[b] }), i) : (delete e[j.name], f) }return g = a.validator.normalizeRules(a.extend({}, a.validator.classRules(j), a.validator.attributeRules(j), a.validator.dataRules(j), a.validator.staticRules(j)), j), g.required && (h = g.required, delete g.required, g = a.extend({ required: h }, g)), g.remote && (h = g.remote, delete g.remote, g = a.extend(g, { remote: h })), g } } }), a.extend(a.expr.pseudos || a.expr[":"], { blank: function (b) { return !a.trim("" + a(b).val()) }, filled: function (b) { var c = a(b).val(); return null !== c && !!a.trim("" + c) }, unchecked: function (b) { return !a(b).prop("checked") } }), a.validator = function (b, c) { this.settings = a.extend(!0, {}, a.validator.defaults, b), this.currentForm = c, this.init() }, a.validator.format = function (b, c) { return 1 === arguments.length ? function () { var c = a.makeArray(arguments); return c.unshift(b), a.validator.format.apply(this, c) } : void 0 === c ? b : (arguments.length > 2 && c.constructor !== Array && (c = a.makeArray(arguments).slice(1)), c.constructor !== Array && (c = [c]), a.each(c, function (a, c) { b = b.replace(new RegExp("\\{" + a + "\\}", "g"), function () { return c }) }), b) }, a.extend(a.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", pendingClass: "pending", validClass: "valid", errorElement: "label", focusCleanup: !1, focusInvalid: !0, errorContainer: a([]), errorLabelContainer: a([]), onsubmit: !0, ignore: ":hidden", ignoreTitle: !1, onfocusin: function (a) { this.lastActive = a, this.settings.focusCleanup && (this.settings.unhighlight && this.settings.unhighlight.call(this, a, this.settings.errorClass, this.settings.validClass), this.hideThese(this.errorsFor(a))) }, onfocusout: function (a) { this.checkable(a) || !(a.name in this.submitted) && this.optional(a) || this.element(a) }, onkeyup: function (b, c) { var d = [16, 17, 18, 20, 35, 36, 37, 38, 39, 40, 45, 144, 225]; 9 === c.which && "" === this.elementValue(b) || a.inArray(c.keyCode, d) !== -1 || (b.name in this.submitted || b.name in this.invalid) && this.element(b) }, onclick: function (a) { a.name in this.submitted ? this.element(a) : a.parentNode.name in this.submitted && this.element(a.parentNode) }, highlight: function (b, c, d) { "radio" === b.type ? this.findByName(b.name).addClass(c).removeClass(d) : a(b).addClass(c).removeClass(d) }, unhighlight: function (b, c, d) { "radio" === b.type ? this.findByName(b.name).removeClass(c).addClass(d) : a(b).removeClass(c).addClass(d) } }, setDefaults: function (b) { a.extend(a.validator.defaults, b) }, messages: { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date (ISO).", number: "Please enter a valid number.", digits: "Please enter only digits.", equalTo: "Please enter the same value again.", maxlength: a.validator.format("Please enter no more than {0} characters."), minlength: a.validator.format("Please enter at least {0} characters."), rangelength: a.validator.format("Please enter a value between {0} and {1} characters long."), range: a.validator.format("Please enter a value between {0} and {1}."), max: a.validator.format("Please enter a value less than or equal to {0}."), min: a.validator.format("Please enter a value greater than or equal to {0}."), step: a.validator.format("Please enter a multiple of {0}.") }, autoCreateRanges: !1, prototype: { init: function () { function b(b) { !this.form && this.hasAttribute("contenteditable") && (this.form = a(this).closest("form")[0], this.name = a(this).attr("name")); var c = a.data(this.form, "validator"), d = "on" + b.type.replace(/^validate/, ""), e = c.settings; e[d] && !a(this).is(e.ignore) && e[d].call(c, this, b) } this.labelContainer = a(this.settings.errorLabelContainer), this.errorContext = this.labelContainer.length && this.labelContainer || a(this.currentForm), this.containers = a(this.settings.errorContainer).add(this.settings.errorLabelContainer), this.submitted = {}, this.valueCache = {}, this.pendingRequest = 0, this.pending = {}, this.invalid = {}, this.reset(); var c, d = this.groups = {}; a.each(this.settings.groups, function (b, c) { "string" == typeof c && (c = c.split(/\s/)), a.each(c, function (a, c) { d[c] = b }) }), c = this.settings.rules, a.each(c, function (b, d) { c[b] = a.validator.normalizeRule(d) }), a(this.currentForm).on("focusin.validate focusout.validate keyup.validate", ":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']", b).on("click.validate", "select, option, [type='radio'], [type='checkbox']", b), this.settings.invalidHandler && a(this.currentForm).on("invalid-form.validate", this.settings.invalidHandler) }, form: function () { return this.checkForm(), a.extend(this.submitted, this.errorMap), this.invalid = a.extend({}, this.errorMap), this.valid() || a(this.currentForm).triggerHandler("invalid-form", [this]), this.showErrors(), this.valid() }, checkForm: function () { this.prepareForm(); for (var a = 0, b = this.currentElements = this.elements(); b[a]; a++)this.check(b[a]); return this.valid() }, element: function (b) { var c, d, e = this.clean(b), f = this.validationTargetFor(e), g = this, h = !0; return void 0 === f ? delete this.invalid[e.name] : (this.prepareElement(f), this.currentElements = a(f), d = this.groups[f.name], d && a.each(this.groups, function (a, b) { b === d && a !== f.name && (e = g.validationTargetFor(g.clean(g.findByName(a))), e && e.name in g.invalid && (g.currentElements.push(e), h = g.check(e) && h)) }), c = this.check(f) !== !1, h = h && c, c ? this.invalid[f.name] = !1 : this.invalid[f.name] = !0, this.numberOfInvalids() || (this.toHide = this.toHide.add(this.containers)), this.showErrors(), a(b).attr("aria-invalid", !c)), h }, showErrors: function (b) { if (b) { var c = this; a.extend(this.errorMap, b), this.errorList = a.map(this.errorMap, function (a, b) { return { message: a, element: c.findByName(b)[0] } }), this.successList = a.grep(this.successList, function (a) { return !(a.name in b) }) } this.settings.showErrors ? this.settings.showErrors.call(this, this.errorMap, this.errorList) : this.defaultShowErrors() }, resetForm: function () { a.fn.resetForm && a(this.currentForm).resetForm(), this.invalid = {}, this.submitted = {}, this.prepareForm(), this.hideErrors(); var b = this.elements().removeData("previousValue").removeAttr("aria-invalid"); this.resetElements(b) }, resetElements: function (a) { var b; if (this.settings.unhighlight) for (b = 0; a[b]; b++)this.settings.unhighlight.call(this, a[b], this.settings.errorClass, ""), this.findByName(a[b].name).removeClass(this.settings.validClass); else a.removeClass(this.settings.errorClass).removeClass(this.settings.validClass) }, numberOfInvalids: function () { return this.objectLength(this.invalid) }, objectLength: function (a) { var b, c = 0; for (b in a) void 0 !== a[b] && null !== a[b] && a[b] !== !1 && c++; return c }, hideErrors: function () { this.hideThese(this.toHide) }, hideThese: function (a) { a.not(this.containers).text(""), this.addWrapper(a).hide() }, valid: function () { return 0 === this.size() }, size: function () { return this.errorList.length }, focusInvalid: function () { if (this.settings.focusInvalid) try { a(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus().trigger("focusin") } catch (b) { } }, findLastActive: function () { var b = this.lastActive; return b && 1 === a.grep(this.errorList, function (a) { return a.element.name === b.name }).length && b }, elements: function () { var b = this, c = {}; return a(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function () { var d = this.name || a(this).attr("name"); return !d && b.settings.debug && window.console && console.error("%o has no name assigned", this), this.hasAttribute("contenteditable") && (this.form = a(this).closest("form")[0], this.name = d), !(d in c || !b.objectLength(a(this).rules())) && (c[d] = !0, !0) }) }, clean: function (b) { return a(b)[0] }, errors: function () { var b = this.settings.errorClass.split(" ").join("."); return a(this.settings.errorElement + "." + b, this.errorContext) }, resetInternals: function () { this.successList = [], this.errorList = [], this.errorMap = {}, this.toShow = a([]), this.toHide = a([]) }, reset: function () { this.resetInternals(), this.currentElements = a([]) }, prepareForm: function () { this.reset(), this.toHide = this.errors().add(this.containers) }, prepareElement: function (a) { this.reset(), this.toHide = this.errorsFor(a) }, elementValue: function (b) { var c, d, e = a(b), f = b.type; return "radio" === f || "checkbox" === f ? this.findByName(b.name).filter(":checked").val() : "number" === f && "undefined" != typeof b.validity ? b.validity.badInput ? "NaN" : e.val() : (c = b.hasAttribute("contenteditable") ? e.text() : e.val(), "file" === f ? "C:\\fakepath\\" === c.substr(0, 12) ? c.substr(12) : (d = c.lastIndexOf("/"), d >= 0 ? c.substr(d + 1) : (d = c.lastIndexOf("\\"), d >= 0 ? c.substr(d + 1) : c)) : "string" == typeof c ? c.replace(/\r/g, "") : c) }, check: function (b) { b = this.validationTargetFor(this.clean(b)); var c, d, e, f, g = a(b).rules(), h = a.map(g, function (a, b) { return b }).length, i = !1, j = this.elementValue(b); if ("function" == typeof g.normalizer ? f = g.normalizer : "function" == typeof this.settings.normalizer && (f = this.settings.normalizer), f) { if (j = f.call(b, j), "string" != typeof j) throw new TypeError("The normalizer should return a string value."); delete g.normalizer } for (d in g) { e = { method: d, parameters: g[d] }; try { if (c = a.validator.methods[d].call(this, j, b, e.parameters), "dependency-mismatch" === c && 1 === h) { i = !0; continue } if (i = !1, "pending" === c) return void (this.toHide = this.toHide.not(this.errorsFor(b))); if (!c) return this.formatAndAdd(b, e), !1 } catch (k) { throw this.settings.debug && window.console && console.log("Exception occurred when checking element " + b.id + ", check the '" + e.method + "' method.", k), k instanceof TypeError && (k.message += ".  Exception occurred when checking element " + b.id + ", check the '" + e.method + "' method."), k } } if (!i) return this.objectLength(g) && this.successList.push(b), !0 }, customDataMessage: function (b, c) { return a(b).data("msg" + c.charAt(0).toUpperCase() + c.substring(1).toLowerCase()) || a(b).data("msg") }, customMessage: function (a, b) { var c = this.settings.messages[a]; return c && (c.constructor === String ? c : c[b]) }, findDefined: function () { for (var a = 0; a < arguments.length; a++)if (void 0 !== arguments[a]) return arguments[a] }, defaultMessage: function (b, c) { "string" == typeof c && (c = { method: c }); var d = this.findDefined(this.customMessage(b.name, c.method), this.customDataMessage(b, c.method), !this.settings.ignoreTitle && b.title || void 0, a.validator.messages[c.method], "<strong>Warning: No message defined for " + b.name + "</strong>"), e = /\$?\{(\d+)\}/g; return "function" == typeof d ? d = d.call(this, c.parameters, b) : e.test(d) && (d = a.validator.format(d.replace(e, "{$1}"), c.parameters)), d }, formatAndAdd: function (a, b) { var c = this.defaultMessage(a, b); this.errorList.push({ message: c, element: a, method: b.method }), this.errorMap[a.name] = c, this.submitted[a.name] = c }, addWrapper: function (a) { return this.settings.wrapper && (a = a.add(a.parent(this.settings.wrapper))), a }, defaultShowErrors: function () { var a, b, c; for (a = 0; this.errorList[a]; a++)c = this.errorList[a], this.settings.highlight && this.settings.highlight.call(this, c.element, this.settings.errorClass, this.settings.validClass), this.showLabel(c.element, c.message); if (this.errorList.length && (this.toShow = this.toShow.add(this.containers)), this.settings.success) for (a = 0; this.successList[a]; a++)this.showLabel(this.successList[a]); if (this.settings.unhighlight) for (a = 0, b = this.validElements(); b[a]; a++)this.settings.unhighlight.call(this, b[a], this.settings.errorClass, this.settings.validClass); this.toHide = this.toHide.not(this.toShow), this.hideErrors(), this.addWrapper(this.toShow).show() }, validElements: function () { return this.currentElements.not(this.invalidElements()) }, invalidElements: function () { return a(this.errorList).map(function () { return this.element }) }, showLabel: function (b, c) { var d, e, f, g, h = this.errorsFor(b), i = this.idOrName(b), j = a(b).attr("aria-describedby"); h.length ? (h.removeClass(this.settings.validClass).addClass(this.settings.errorClass), h.html(c)) : (h = a("<" + this.settings.errorElement + ">").attr("id", i + "-error").addClass(this.settings.errorClass).html(c || ""), d = h, this.settings.wrapper && (d = h.hide().show().wrap("<" + this.settings.wrapper + "/>").parent()), this.labelContainer.length ? this.labelContainer.append(d) : this.settings.errorPlacement ? this.settings.errorPlacement.call(this, d, a(b)) : d.insertAfter(b), h.is("label") ? h.attr("for", i) : 0 === h.parents("label[for='" + this.escapeCssMeta(i) + "']").length && (f = h.attr("id"), j ? j.match(new RegExp("\\b" + this.escapeCssMeta(f) + "\\b")) || (j += " " + f) : j = f, a(b).attr("aria-describedby", j), e = this.groups[b.name], e && (g = this, a.each(g.groups, function (b, c) { c === e && a("[name='" + g.escapeCssMeta(b) + "']", g.currentForm).attr("aria-describedby", h.attr("id")) })))), !c && this.settings.success && (h.text(""), "string" == typeof this.settings.success ? h.addClass(this.settings.success) : this.settings.success(h, b)), this.toShow = this.toShow.add(h) }, errorsFor: function (b) { var c = this.escapeCssMeta(this.idOrName(b)), d = a(b).attr("aria-describedby"), e = "label[for='" + c + "'], label[for='" + c + "'] *"; return d && (e = e + ", #" + this.escapeCssMeta(d).replace(/\s+/g, ", #")), this.errors().filter(e) }, escapeCssMeta: function (a) { return a.replace(/([\\!"#$%&'()*+,.\/:;<=>?@\[\]^`{|}~])/g, "\\$1") }, idOrName: function (a) { return this.groups[a.name] || (this.checkable(a) ? a.name : a.id || a.name) }, validationTargetFor: function (b) { return this.checkable(b) && (b = this.findByName(b.name)), a(b).not(this.settings.ignore)[0] }, checkable: function (a) { return /radio|checkbox/i.test(a.type) }, findByName: function (b) { return a(this.currentForm).find("[name='" + this.escapeCssMeta(b) + "']") }, getLength: function (b, c) { switch (c.nodeName.toLowerCase()) { case "select": return a("option:selected", c).length; case "input": if (this.checkable(c)) return this.findByName(c.name).filter(":checked").length }return b.length }, depend: function (a, b) { return !this.dependTypes[typeof a] || this.dependTypes[typeof a](a, b) }, dependTypes: { "boolean": function (a) { return a }, string: function (b, c) { return !!a(b, c.form).length }, "function": function (a, b) { return a(b) } }, optional: function (b) { var c = this.elementValue(b); return !a.validator.methods.required.call(this, c, b) && "dependency-mismatch" }, startRequest: function (b) { this.pending[b.name] || (this.pendingRequest++ , a(b).addClass(this.settings.pendingClass), this.pending[b.name] = !0) }, stopRequest: function (b, c) { this.pendingRequest-- , this.pendingRequest < 0 && (this.pendingRequest = 0), delete this.pending[b.name], a(b).removeClass(this.settings.pendingClass), c && 0 === this.pendingRequest && this.formSubmitted && this.form() ? (a(this.currentForm).submit(), this.submitButton && a("input:hidden[name='" + this.submitButton.name + "']", this.currentForm).remove(), this.formSubmitted = !1) : !c && 0 === this.pendingRequest && this.formSubmitted && (a(this.currentForm).triggerHandler("invalid-form", [this]), this.formSubmitted = !1) }, previousValue: function (b, c) { return c = "string" == typeof c && c || "remote", a.data(b, "previousValue") || a.data(b, "previousValue", { old: null, valid: !0, message: this.defaultMessage(b, { method: c }) }) }, destroy: function () { this.resetForm(), a(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur") } }, classRuleSettings: { required: { required: !0 }, email: { email: !0 }, url: { url: !0 }, date: { date: !0 }, dateISO: { dateISO: !0 }, number: { number: !0 }, digits: { digits: !0 }, creditcard: { creditcard: !0 } }, addClassRules: function (b, c) { b.constructor === String ? this.classRuleSettings[b] = c : a.extend(this.classRuleSettings, b) }, classRules: function (b) { var c = {}, d = a(b).attr("class"); return d && a.each(d.split(" "), function () { this in a.validator.classRuleSettings && a.extend(c, a.validator.classRuleSettings[this]) }), c }, normalizeAttributeRule: function (a, b, c, d) { /min|max|step/.test(c) && (null === b || /number|range|text/.test(b)) && (d = Number(d), isNaN(d) && (d = void 0)), d || 0 === d ? a[c] = d : b === c && "range" !== b && (a[c] = !0) }, attributeRules: function (b) { var c, d, e = {}, f = a(b), g = b.getAttribute("type"); for (c in a.validator.methods) "required" === c ? (d = b.getAttribute(c), "" === d && (d = !0), d = !!d) : d = f.attr(c), this.normalizeAttributeRule(e, g, c, d); return e.maxlength && /-1|2147483647|524288/.test(e.maxlength) && delete e.maxlength, e }, dataRules: function (b) { var c, d, e = {}, f = a(b), g = b.getAttribute("type"); for (c in a.validator.methods) d = f.data("rule" + c.charAt(0).toUpperCase() + c.substring(1).toLowerCase()), this.normalizeAttributeRule(e, g, c, d); return e }, staticRules: function (b) { var c = {}, d = a.data(b.form, "validator"); return d.settings.rules && (c = a.validator.normalizeRule(d.settings.rules[b.name]) || {}), c }, normalizeRules: function (b, c) { return a.each(b, function (d, e) { if (e === !1) return void delete b[d]; if (e.param || e.depends) { var f = !0; switch (typeof e.depends) { case "string": f = !!a(e.depends, c.form).length; break; case "function": f = e.depends.call(c, c) }f ? b[d] = void 0 === e.param || e.param : (a.data(c.form, "validator").resetElements(a(c)), delete b[d]) } }), a.each(b, function (d, e) { b[d] = a.isFunction(e) && "normalizer" !== d ? e(c) : e }), a.each(["minlength", "maxlength"], function () { b[this] && (b[this] = Number(b[this])) }), a.each(["rangelength", "range"], function () { var c; b[this] && (a.isArray(b[this]) ? b[this] = [Number(b[this][0]), Number(b[this][1])] : "string" == typeof b[this] && (c = b[this].replace(/[\[\]]/g, "").split(/[\s,]+/), b[this] = [Number(c[0]), Number(c[1])])) }), a.validator.autoCreateRanges && (null != b.min && null != b.max && (b.range = [b.min, b.max], delete b.min, delete b.max), null != b.minlength && null != b.maxlength && (b.rangelength = [b.minlength, b.maxlength], delete b.minlength, delete b.maxlength)), b }, normalizeRule: function (b) { if ("string" == typeof b) { var c = {}; a.each(b.split(/\s/), function () { c[this] = !0 }), b = c } return b }, addMethod: function (b, c, d) { a.validator.methods[b] = c, a.validator.messages[b] = void 0 !== d ? d : a.validator.messages[b], c.length < 3 && a.validator.addClassRules(b, a.validator.normalizeRule(b)) }, methods: { required: function (b, c, d) { if (!this.depend(d, c)) return "dependency-mismatch"; if ("select" === c.nodeName.toLowerCase()) { var e = a(c).val(); return e && e.length > 0 } return this.checkable(c) ? this.getLength(b, c) > 0 : b.length > 0 }, email: function (a, b) { return this.optional(b) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a) }, url: function (a, b) { return this.optional(b) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[\/?#]\S*)?$/i.test(a) }, date: function (a, b) { return this.optional(b) || !/Invalid|NaN/.test(new Date(a).toString()) }, dateISO: function (a, b) { return this.optional(b) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a) }, number: function (a, b) { return this.optional(b) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a) }, digits: function (a, b) { return this.optional(b) || /^\d+$/.test(a) }, minlength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(b, c); return this.optional(c) || e >= d }, maxlength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(b, c); return this.optional(c) || e <= d }, rangelength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(b, c); return this.optional(c) || e >= d[0] && e <= d[1] }, min: function (a, b, c) { return this.optional(b) || a >= c }, max: function (a, b, c) { return this.optional(b) || a <= c }, range: function (a, b, c) { return this.optional(b) || a >= c[0] && a <= c[1] }, step: function (b, c, d) { var e, f = a(c).attr("type"), g = "Step attribute on input type " + f + " is not supported.", h = ["text", "number", "range"], i = new RegExp("\\b" + f + "\\b"), j = f && !i.test(h.join()), k = function (a) { var b = ("" + a).match(/(?:\.(\d+))?$/); return b && b[1] ? b[1].length : 0 }, l = function (a) { return Math.round(a * Math.pow(10, e)) }, m = !0; if (j) throw new Error(g); return e = k(d), (k(b) > e || l(b) % l(d) !== 0) && (m = !1), this.optional(c) || m }, equalTo: function (b, c, d) { var e = a(d); return this.settings.onfocusout && e.not(".validate-equalTo-blur").length && e.addClass("validate-equalTo-blur").on("blur.validate-equalTo", function () { a(c).valid() }), b === e.val() }, remote: function (b, c, d, e) { if (this.optional(c)) return "dependency-mismatch"; e = "string" == typeof e && e || "remote"; var f, g, h, i = this.previousValue(c, e); return this.settings.messages[c.name] || (this.settings.messages[c.name] = {}), i.originalMessage = i.originalMessage || this.settings.messages[c.name][e], this.settings.messages[c.name][e] = i.message, d = "string" == typeof d && { url: d } || d, h = a.param(a.extend({ data: b }, d.data)), i.old === h ? i.valid : (i.old = h, f = this, this.startRequest(c), g = {}, g[c.name] = b, a.ajax(a.extend(!0, { mode: "abort", port: "validate" + c.name, dataType: "json", data: g, context: f.currentForm, success: function (a) { var d, g, h, j = a === !0 || "true" === a; f.settings.messages[c.name][e] = i.originalMessage, j ? (h = f.formSubmitted, f.resetInternals(), f.toHide = f.errorsFor(c), f.formSubmitted = h, f.successList.push(c), f.invalid[c.name] = !1, f.showErrors()) : (d = {}, g = a || f.defaultMessage(c, { method: e, parameters: b }), d[c.name] = i.message = g, f.invalid[c.name] = !0, f.showErrors(d)), i.valid = j, f.stopRequest(c, j) } }, d)), "pending") } } }); var b, c = {}; return a.ajaxPrefilter ? a.ajaxPrefilter(function (a, b, d) { var e = a.port; "abort" === a.mode && (c[e] && c[e].abort(), c[e] = d) }) : (b = a.ajax, a.ajax = function (d) { var e = ("mode" in d ? d : a.ajaxSettings).mode, f = ("port" in d ? d : a.ajaxSettings).port; return "abort" === e ? (c[f] && c[f].abort(), c[f] = b.apply(this, arguments), c[f]) : b.apply(this, arguments) }), a });;
(function (window) {
    "use strict";
    window.OAApp = {};
    OAApp.appsettings = {
        appId: 1001,
        desktopAppId: 1002,
        apiUrl: "https://www.californiapsychics.com",
        apiUrlOldBrowserSupport: "https://www.californiapsychics.com",
        OATrackingCookieDomain: ".californiapsychics.com",
        defaultMasNumber: "8005734784",
        defaultFormattedMasNumber: "800.573.4784",
        desktopSiteUrl: "https://www.californiapsychics.com/",
        MobileResolution: 740,
        isSupportSubmitted: false,
        isSupportLinkOpen: false,
        getIPAddressURL: "https://api.ipify.org?format=jsonp&callback=?",
        RecaptchaSitekey: "6LftJiUUAAAAAO5bUD-zH__aTFKO2tXFTTOLEpxR",
        Facebookappkey: "1466311480052203",
        facebookVersion: "v3.1",
        ReaderLineNumber: "800.785.7667",
        TalkButtonNumber: "8004569918",
        refreshPsychicStatusInterval: 10000,
        psychicsInfoURL: '/psychics',
        psychicsStatusURL: '/psychic/getstatus',
        currentView: "",        
        defaultCTMPhoneNumber: "800.573.4784",
        MASReferrerExclusionList: ["paypal.com"],
        isCTMEnabled: true,
        psychicListPageSize: 12,
        psychicsCookieExpiryMin: 720,
        
        pauseDurationDesktop: 5000,
        pauseDurationMobile: 5000,       
        isOptitrackEnabled: true,
        isChatShow: true,
        sourceCookie: "sitesource",
        twilioSyncEnabled: false,
        queueSize: 6
    };

    OAApp.featureConfig = {
        isPurchaseReadingsEnabled: false
    };
    OAApp.getAppId = function () {
        if (window.innerWidth >= OAApp.appsettings.MobileResolution)
            return OAApp.appsettings.desktopAppId;
        return OAApp.appsettings.appId;
    };
}(window));;
/* globals Backbone, _ , $ , OA */
(function (window) {
    "use strict";

    // Expose OA to Window Object (Global)
    window.OA = {};

    // Register view instances on this object
    OA.app = {};

    OA.baseUrl = OAApp.appsettings.apiUrl;

    // Utilities
    OA.utils = {};

    // Services
    OA.services = {};

    // Authentication
    OA.auth = {};

    // Backbone
    OA.views = {
        common: {}
    };
    OA.models = {
        common: {}
    };
    OA.collections = {};

    OA.pollers = {};
    OA.queue = {};
    OA.favoriteManager = {};
    OA.callback = {};
    OA.cookie = {};

    // Paths
    OA.paths = {};
    
    // workaround for jQuery null reference
    $ = jQuery;
    
    //jQuery Cookie
    $.cookie.json = true;

    // Specific Global Settings
    OA.settings = {};

    OA.cookie = {
        SetCookieValue: function (keyname, keyvalue, expirationDate, domain) {
            //console.log("Inside SetCookieValue method of OA.cookie")
            var options = {};
            if (expirationDate != undefined) {
                options.expires = expirationDate;
            }
            if (domain != undefined) {
                options.domain = domain;
                //options.path = '/';
            }

            //Set cookie path to root so it will be accessible via all pages in the domain
            options.path = '/';
            $.cookie(keyname, keyvalue, options);
            var cookie = $.cookie(keyname);

            if (!cookie && navigator.cookieEnabled) {
                //if (!cookie) {
                //console.log("Inside if cookie not set");
                keyvalue = JSON.stringify(keyvalue);

                try {
                    localStorage.setItem(keyname, keyvalue);
                }
                catch (excp) {
                    console.log(excp.message);
                }

                var value = localStorage.getItem(keyname);

                if (!value) {
                    try {
                        sessionStorage.setItem(keyname, keyvalue);
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            }
        },
        GetCookieValue: function (keyname) {
            //console.log("Inside GetCookieValue method of OA.cookie")

            var cookie = $.cookie(keyname);

            if (!cookie && navigator.cookieEnabled) {
                //if (!cookie) {
                //console.log("Inside if cookie not get");
                cookie = localStorage.getItem(keyname);
                if (!cookie) {
                    cookie = sessionStorage.getItem(keyname);
                }
                cookie = JSON.parse(cookie);
            }

            return cookie;
        },
        ManageCookieValue: function (keyname, keyvalue, expirationDate, domain) {
            //console.log("Inside ManageCookieValue method of OA.cookie")

            if (keyvalue != undefined) {
                OA.cookie.SetCookieValue(keyname, keyvalue, expirationDate, domain);
            } else {
                return OA.cookie.GetCookieValue(keyname);
            }
        },
        RemoveCookieValue: function (keyname) {
            try {
                $.removeCookie(keyname);
                $.removeCookie(keyname, { path: '/' });
                $.cookie(keyname, null, { path: '/', domain: '.californiapsychics.com' });
                $.removeCookie(keyname, { path: '/', domain: '.californiapsychics.com' });
                sessionStorage.removeItem(keyname);
            } catch (e) {
            }
        },
        GetRawCookieValue: function (keyname) {
            var name = keyname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1);
                if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
            }
            return "";
        }
    };

    OA.endpoints = {
        Authenticate: {
            auth: "/auth",
            authProvider: function (provider) {
                return '/auth/' + provider;
            },
            authenticate: "/authenticate",
            authenticateProvider: function (provider) {
                return '/auth/' + provider;
            }
        },
        AddCustomer: function () {
            return '/newc';
        },
        GetCustomerCreditCard: function (CustId, CCId) {
            return '/customers/' + CustId + '/creditcards/' + CCId + '?t=' + new Date().getTime();
        },
        GetCustomerCreditCards: function (CustId) {
            return '/customers/' + CustId + '/creditcardslist?t=' + new Date().getTime();
        },
        GetCustomerDetails: function (CustId) {
            return '/customers/' + CustId + '/details';
        },
        GetSiteInfo: function () {
            return "/site";
        },
        GetSubscriptionSetting: function (CustId) {
            return '/customers/' + CustId + '/subscription';
        },
        SignOut: function () {
            return '/auth/logout';
        },
        ValidateEmail: function () {
            return '/utils/validateemail';
        },
        GetCustomerReadingCount: function (CustId, visitTime) {
            return '/customers/' + CustId + '/readingcount/' + visitTime;
        },
        SearchPsychicName: function () {
            return "/psychics/search";
        },
        FacebookAuthentication: function () {
            return '/Facebook';
        },
        FacebookAccessLog: function () {
            return '/FacebookAccessLog';
        },
        GooglereCAPTCHA_Responce: function () {
            return '/GooglereCAPTCHA';
        },
        CheckSigninAttempt: function () {
            return '/CheckSigninAttempt';
        },
        AddSupportLinkXML: function () {
            return "/site/supportlink";
        },
        getPsychicsAvailableScheduleSlot: function (ExtId) {
            return '/psychics/timeslots/' + ExtId;
        },
        ReserveCustomerCallback: function (CustId) {
            return '/customers/' + CustId + '/callbacks/reserve';
        },
        ReserveCallback: function () {
            return '/chat/customers/callbacks/reserve';
        },
        AddFavoritePsychic: function (CustId) {
            return '/mpsychics/' + CustId + '/favorite/add';
        },
        RemoveFavoritePsychic: function (CustId) {
            return '/mpsychics/' + CustId + '/favorite/remove';
        },
        AddAffiliate: function () {
            return '/AddAffiliate';
        },
        GetCountryList: "/site/countrylist",
        GetSignupCountryList: "/site/signupcountrylist",
        GetPsychics: '/psychics?t=' + new Date().getTime(),
        GetStates: function (CountryCode) {
            var url = '/site/states/' + CountryCode;
            return url;
        },
        GetCityState: function (CountryCode, PostalCode) {
            var url = '/site/citystate/' + CountryCode + '/' + PostalCode;
            return url;
        },
        GetStickyOffer: function (CustId) {
            return '/offers/sticky/' + CustId;
        },
        CreateCustomerAccount: function () {
            return '/createaccount';
        },
        CreateHoroscopeSignup: "/mhoroscope/signup",
        GetTestimonials: function (extId, pageIndex, pageSize) {
            return '/psychics/' + extId + '/testimonials?PageIndex=' + pageIndex + '&PageSize=' + pageSize + '&t=' + new Date().getTime();
        },
        GetDiscountedOfferPageContent: "/DiscountedOfferPageContent",
        GetPsychicDetails: function (ExtId) {
            return '/psychics/' + ExtId;
        },
        ChatReservationRelease: function () {
            return '/chat/reserve/release';
        },
        GetChatAllowance: function () {
            return '/chat/allowance';
        },
        ChatReservation: function () {
            return '/chat/reserve';
        },
        ChatStart: function () {
            return '/chat/start';
        },
        ChatChargeOnetime: function () {
            return '/Chat/Charge/Onetime';
        },
        GetChatCustomerRecurringPayment: function (CustId) {
            return '/chat/' + CustId + '/recurring/payment';
        },
        ChatChargeRecurring: function () {
            return '/chat/charge/recurring';
        },
        CustomerSession: function (CustId) {
            return '/customers/' + CustId + '/CustomerSession';
        },
        UpdateCallbackNumber: function (CustId) {
            return "/customers/" + CustId + "/updateCallbackNumber";
        },
        GetIPCountryGeolocationInfo: function () {
            return '/ipgeocountry';
        },
        GetGDPRCustomer: function (CustId) {
            return '/customers/' + CustId + '/GDPRCustomer';
        },
        ValidateNewCustomer: function () {
            return '/newc/validate';
        },
        UpdateSubscriptions: function () {
            return '/customers/subscriptions';
        },
        AddCustomerCallback: function (CustId) {
            return '/customers/' + CustId + '/callbacks';
        },
        CreateCustomerRequest: function () {
            return '/slot/customerrequest';
        },
        RedeemKRPoints: function (CustId) {
            return '/customers/' + CustId + '/redeemkrpoints';
        },
        GetUpdatedStatus: function () {
            return '/psychic/getstatus';
        },
        GetPsychicStatus: function () {
            return '/psychicstatus';
        },
        CancelCustomerCallback: function (CustId, CallbackId) {
            return '/customers/' + CustId + '/callbacks/' + CallbackId;
        },
        AddPsychicInCircle: function () {
            return '/customers/psychiccircle/add';
        },
        GetPsychicInCircle: function (CustId) {
            return '/customers/psychiccircle?CustId=' + CustId;
        },
        DeletePsychicInCircle: function () {
            return '/customers/psychiccircle/delete';
        },
        UpdatePsychicPlaceInCircle: function () {
            return '/customers/psychiccircle/update';
        },
        GetSimilarPsychic: function () {
            return '/similarpsychics';
        },
        CustomerBenefits: function (CustId) {
            return '/customers/benefits';
        },
        StartExtendCallbackQueueExtension: function (CustId) {
            return '/customers/callbackqextend/start';
        },
        RedeemCallbackQueue: function () {
            return '/customers/callbackqueue/redeemkrpoints';
        },
        JoinKarmaRewards: function (CustId) {
            return '/customers/' + CustId + '/joinkarmarewards';
        },
        FreeReadingRedeemKRPoints: function () {
            return '/customers/freereading/redeemkrpoints';        
        },
        posttestimonial: function () {
            return '/customers/posttestimonial';
        },
        KarmaHubPointsActivity: function (data) {
            return '/customers/pointsactivity?custId=' + data.CustId + '&PageIndex=' + data.PageIndex + '&PageSize=' + data.PageSize;
        },
        CustomerBirthChart: function () {
            return '/customers/birthchart';
        },
        GetCustomerGifts: function (CustId) {
            return '/customers/gifts?CustId=' + CustId;
        },
        GetCustomerBirthChartForecast: function (data) {          
            return '/birthchart/mhoroscope?CustId=' + data.CustId + '&Type=' + data.Type;
        },
    };

    // Set URLs via JS
    OA.paths = {
        home: "/",
        mobileHome: '/',
        psychicReading: "/psychic-readings",
        searchPsychic: "/psychic-product/{0}/{1}",
        searchPsychicByText: "/psychic-product/{0}",
        psychic: {
            list: "psychic-readings"
        },
        signIn: {
            main: "sign-in"
        },
        askNcCheckout: {
            createAccount: "ask-question-signup",
            createAccount2: "/ask-question-signup2",
            checkout: "ask-question-checkout",
            checkout2: "/ask-question-checkout2",
            offers: "ask-question-offers",
            offers2: "/ask-question-offers2",
            question: "ask-free-question",
            question2: "/ask-free-question2",
            receipt: "/ask-question-receipt",
            receipt2: "/ask-question-receipt2",
            afqHomepage: "/ghomepage"
        },
        buyOfferPackage: {
            main: "/buy-package"
        },
        unsubscribeConfirm: '/unsubscribeconfirm',
        karmaRewards: {
            redeem: "karma-rewards",
            congratulations: "karma-rewards-congratulations",
            welcome: "karma-rewards-welcome",
            error: "karma-rewards-error",
            join: "karma-rewards-join",
            karmaRedeem: "karma-rewards",
            karmaJoin: "karma-rewards-join"
        }
    };

    OA.chatCommon = {
        auth: OA.cookie.ManageCookieValue('auth'),
        extIdCommon: null,
        chatWindow: null,
        psychicNameCommon: null,
        basePrice: null,
        chatStarted: function (chatStartResponse) {

            console.log('3/3 chatStarted ' + JSON.stringify(chatStartResponse));
            OA.chatCommon.chatWindow.location.href = '/ChatFrame?' + $.param(chatStartResponse);
            return false;
        },
        chatFailed: function (retVal) {
            console.log('chatFailed ' + JSON.stringify(retVal));
            if (retVal.status == 403 && OA.chatCommon.chatWindow != null) {
                OA.chatCommon.chatWindow.close();
                OA.chatCommon.psychicUnavailable();
            }
            return false;

        },
        chatStartFailed: function (retVal) {
            console.log('chatFailed ' + JSON.stringify(retVal));

            //403 thrown when reservation expired inside chat/start
            //This is called from only Purchase/NC Flow Receipt Chat button fail, attempt reservation again.
            if (retVal.status == 403)
                OA.chatCommon.makeReservation();

            return false;
        },
        psychicUnavailable: function () {
            var popupDialogObj = $("#psychicUnavailableModal");
            var url = window.location.href;

            url = url.substring(url.indexOf('com') + 3);
            console.log("OACPChatPsychNA", url);
            dataLayer.push({
                'event': 'OACPChatPsychNA',
                'pageURL': url
            });

            popupDialogObj.removeClass("hidden");
            popupDialogObj.trigger('create');
            popupDialogObj.find("#psychicName").text(OA.chatCommon.psychicNameCommon);
            popupDialogObj.show();
            popupDialogObj.popup();

            popupDialogObj.popup('open');

            popupDialogObj.find(".optionCancel").first().on('click', function () {
                //OA.chatCommon.chatWindow.close();
                popupDialogObj.attr('data-confirmed', 'no');
            });
            popupDialogObj.find("#close").first().on('click', function () {

                popupDialogObj.attr('data-confirmed', 'no');
            });

        },
        sucChat: function (retVal) {
            console.log('inside sucChat-Post CHAT2-1543-MVC');

            var sucessSample = {
                "success": true,
                "errorCode": 0,
                "errorMessage": "",
                "reservationID": "2239914",
                "allowance": {
                    "allowedMinutes": 7,
                    "rechargingMinute": 2,
                    "minimumCharge": 50,
                    "directMessageBillableMinutes": 10
                }
            };

            console.log('Original /chat/reserve return value ' + JSON.stringify(retVal));

            //console.log('****************Forcing success object...revert back when done testing******************');
            //if (!retVal.success)
            //    retVal=sucessSample;    //uncomment to see successful call value

            if (retVal.success) {
                console.log('2/3 Reserving Psychic-Successful');
                var initMsg = {
                    "deviceId": "browser", //change per desktop requirement
                    "customerId": OA.chatCommon.auth.custId,
                    "extId": OA.chatCommon.extIdCommon,
                    "requestType": "RealTime",
                    "reservationID": retVal.reservationID,
                    "message": "Chat reading requested...",
                    "sourcePlatform": (window.screen.width <= 740) ? "WebMobile" : "WebDesktop"
                };

                console.log('chat start params ' + JSON.stringify(initMsg));

                OA.services.ChatStart(initMsg).done(OA.chatCommon.chatStarted).fail(OA.chatCommon.chatFailed);
            }
            else {
                OA.chatCommon.psychicUnavailable();
            }
        },
        errChat: function (retVal) {
            console.log('Reserving Psychic- Failed ' + JSON.stringify(retVal));
            //console.log(retVal);
        },
        makeReservation: function () {
            console.log('1/3 Reserving Psychic...');

            var reserve = {
                "custId": OA.chatCommon.auth.custId, //to simulate errChat replace with 123 to throw argument exception
                "extId": OA.chatCommon.extIdCommon,
                "requestType": "RealTime"
            };

            OA.services.ChatReservation(reserve).done(OA.chatCommon.sucChat).fail(OA.chatCommon.errChat);
        },
        insufficientFundsCheck: function (basePr, psychicName) {
            OA.chatCommon.chatWindow = window.open('/ChatFrame?lineName=' + psychicName + '&insufficient=1', 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=385px,height=480px');
            window.location.href = "/purchase-reading?extid=" + OA.chatCommon.extIdCommon + "&ischat=1";
        },
        recurringPayment: function (autoReloadDetails) {
            var minAmtForChat = 0

            if (OA.chatCommon.basePrice != null && OA.chatCommon.basePrice > 0)
                minAmtForChat = OA.chatCommon.basePrice * 10

            if (autoReloadDetails.isEnabled) {
                var data = {
                    CustId: OA.chatCommon.auth.custId,
                    PaymentType: autoReloadDetails.paymentType,
                    ExtId: OA.chatCommon.extIdCommon,
                    Amount: minAmtForChat
                };

                OA.services.ChatChargeRecurring(data).done(
                    function (recChargeRes) {
                        console.log('Auto Reload Charge Recurring Response-' + JSON.stringify(recChargeRes));

                        if (recChargeRes != null && recChargeRes.isSuccess && recChargeRes.allowance.allowedMinutes >= 10)
                            OA.chatCommon.makeReservation();
                        else {
                            console.log('Unable to reserve....see above');
                            if (recChargeRes.isSuccess == false) {
                                if (recChargeRes.reason.indexOf('You have exceeded') > -1) {
                                    OA.chatCommon.chatWindow = window.open('/ChatFrame?lineName=' + psychicName + '&exceededlimt=1', 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=385px,height=480px');
                                }
                            }
                        }
                    }
                );
            }
            else {
                //insufficient funds popup
                //call insuff funds
                //TODO: pass discount price
                console.log('Insufficient Funds');
                OA.chatCommon.insufficientFundsCheck(OA.chatCommon.basePrice, OA.chatCommon.psychicNameCommon);
            }
        },
        allowanceCheck: function (allowance) {
            if (allowance.allowedMinutes >= 10)   //show dialog only if has sufficient funds for 10 min reading
            {
                console.log('more than 10 allowed minutes.....resp');
                OA.chatCommon.makeReservation();
            }
            else {
                OA.services.GetChatCustomerRecurringPayment(OA.chatCommon.auth.custId).done(OA.chatCommon.recurringPayment);
            }
        },
        confirmChatSuccess: function (psychicDetails) {
            //Get psychic base price
            OA.chatCommon.basePrice = psychicDetails.basePrice;
            OA.chatCommon.psychicNameCommon = psychicDetails.lineName;

            OA.services.getChatAllowance({
                ExtId: OA.chatCommon.extIdCommon,
                CustId: OA.chatCommon.auth.custId
            }).done(OA.chatCommon.allowanceCheck)
                .fail(OA.chatCommon.errChat);
        },
        confirmChat: function (extId, psychicName) {
            console.log('in confirmChat');

            OA.chatCommon.chatWindow = window.open('', 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=385px,height=480px'); //open or find 'targetWindow'
            try {
                if (OA.chatCommon.chatWindow.location.href.indexOf('ChatFrame') == -1) {
                    OA.chatCommon.chatWindow.location.href = '/ChatFrame?lineName=' + psychicName;
                } else {
                    alert('Please close your open chat window before starting another chat.');
                    return;
                }    
            } catch (e) {
                console.error('error openning ChatFrame in confirmChat', e);
                return;
            }

            OA.chatCommon.extIdCommon = extId;

            //show confirm chat popup
            if (OA.chatCommon.auth != undefined) //user should be logged in to show confirm popup
            {
                OA.services.getPsychicDetails({
                    ExtId: OA.chatCommon.extIdCommon,
                    CustId: OA.chatCommon.auth.custId
                }).done(OA.chatCommon.confirmChatSuccess)
                    .fail(OA.chatCommon.errChat);

            }
            return false;
        }
    };

    if (!window.console) window.console = {};
    if (!window.console.log)
        window.console.log = function () { };
}(window));;
OA.ctm = {
	ctmPhoneNumber: '',  // call track metrics number
	MASDisabled: function () {
		return true;
	}
}

window.CTMSourceEvent = function (event) {
	
	var masCookie = OA.cookie.ManageCookieValue('MASPhoneNumber');
	if (masCookie) {
		OA.ctm.ctmPhoneNumber = masCookie;
		return;
	}

	switch (event.state) {
		case 'before':
			break;

		case 'after':
			var masCookie = OA.cookie.ManageCookieValue('MASPhoneNumber');
			if (!masCookie) {
				OA.ctm.ctmPhoneNumber = event.new_number;
				var ExpDate = new Date();
				ExpDate.setDate(ExpDate.getDate() + 365);
				document.cookie = 'MASPhoneNumber=' + event.new_number + ';path=/;domain=.californiapsychics.com;expires=' + ExpDate;
			}
			OA.auth.getMasNumber();
			break;

		default: break;
	}
};
(function (window) {
    "use strict";
    var whichpage = "";
    var isFacebookSignup = false;
    var custid = "";
    OA.LoginWithFacebookInit = {
        successfulAuthfacebook: function (data) {
            var self = this;
            OA.auth.successfulAuth(data).done(function () {
                if (data != "") {
                    OA.cookie.RemoveCookieValue('sign-out');
                    //Remove five free cookie because on talk click always follow the ask flow - TO-4569
                    OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");
                    if (data.custGroup && data.custGroup == OA.utils.enum.NCCustomerGroupType.NewCustomerLead || data.custGroup < 0) {
                        OA.utils.leadCustomer.checkCustomerCreditCardData();
                        $.cookie("freeLeadCustomer", 1, { path: '/' });
                        $(".optbardiv").empty();
                    } else {
                        OA.LoginWithFacebookInit.redirectAfterLoginFacebook();
                    }
                }
            }).fail(function (res) {
                $('p.err').html('<label for="fields" class="error">* Couldn\'t get user information. Please Try Again.</label>');
                $(".sign-in #submit-6").removeAttr("disabled");
            }).always(function () {
                OA.utils.ajaxHelpers.closeJQMLoader();
                $(".sign-in #submit-6").removeAttr("disabled");
            });
        },
        authenticateDesktopFacebook: function (username, password, res) {
            var self = this;
            $.mobile.loading("show");
            $(".sign-in #submit-6").attr("disabled", "disabled");
            self.successfulAuthfacebook(res);
        },
        redirectAfterLoginFacebook: function () {
            var self = this;
            $.mobile.loading("show");
            var redirectURL = OA.cookie.ManageCookieValue('redirect');

            if (!redirectURL)
                redirectURL = OA.paths.home;
            else
                redirectURL = redirectURL;

            window.location.href = redirectURL;
        },
        LoadFacebookSDK: function (whichpage) {


        },
        GetfacebookUserDetail: function (whichpage, saleLocation) {

            var FacebookSigningLogID = 0,
                Custid = 0,
                clientID = OA.utils.OAGA.getGAClientID(),
                auth = OA.cookie.ManageCookieValue('auth');

            if (!!auth) {
                Custid = auth.custId;
            }
            OA.services.FacebookAccessLog({
                ID: 0,
                CustId: Custid,
                PINLogin: 2,
                ApplicationID: 2,
                LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.FacebookLogin),
                Email: '', clientID: clientID, saleLocation: saleLocation, password: ''
            }).done(function (res) {
                OA.cookie.ManageCookieValue('FacebookSigningLogID', res);
                FacebookSigningLogID = res;
            })

            FB.login(function (response) {
                if (response.status === "connected") {

                    var uID = response.authResponse.userID;

                    FB.api('/me?fields=id,email,birthday,first_name,last_name', function (response) {
                        OA.cookie.ManageCookieValue('AccountCreateUsingFacebook', true);
                        var EmailID = response.email;
                        console.log('Emailid', EmailID);
                        var access_token = FB.getAuthResponse()['accessToken'];
                        OA.cookie.ManageCookieValue('FacebooAccessToken', access_token);
                        OA.cookie.ManageCookieValue('FacebookUserID', response.id);
                        OA.cookie.ManageCookieValue('isFacebookSignup', true);
                        var length = 6,
                                 charset = "abcdefghijklmnopqrstuvwxyz0123456789",
                                 tempPassword = "";

                        for (var i = 0, n = charset.length; i < length; ++i) {
                            tempPassword += charset.charAt(Math.floor(Math.random() * n));
                        }
                        tempPassword = response.first_name + tempPassword;

                        OA.cookie.ManageCookieValue('femail', EmailID);
                        OA.cookie.ManageCookieValue('ffirst_name', response.first_name);
                        OA.cookie.ManageCookieValue('flast_name', response.last_name);
                        if (response.birthday != undefined) {
                            OA.cookie.ManageCookieValue('fbirthday', response.birthday);
                        }

                        if (whichpage == "signup") {
                            var self = this;
                            if (response.email != undefined) {
                                if (response.birthday != undefined) {
                                    $("#first-name").val(response.first_name);
                                    $("#last-name").val(response.last_name);
                                    $("#email").val(response.email);
                                    $("#password").val(tempPassword);
                                    $("#cpassword").val(tempPassword);

                                    var date = response.birthday;
                                    if (date != "" && date != undefined) {
                                        var d = new Date(date);
                                        date = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + ('0' + d.getDate()).slice(-2);
                                    }
                                    else {
                                        date = "";

                                    }
                                    if (!OA.utils.device.Android()) {
                                        $('.dob_control').html('').html('<label id="lbl_dob" for="dob">DATE OF BIRTH</label><input tabindex="6" name="dob" type="date" value="' + date + '" id="dob" class="ask-nc-funnel-add-customer-dob dob unstyled">').trigger('create');
                                    }
                                    else {
                                        $("#dob").val(response.birthday);
                                    }

                                    var fields = response.birthday.split("/");
                                    var month = fields[0];
                                    var day = fields[1];
                                    var year = fields[2];
                                    $(".month").val(month);
                                    $(".day").val(day);
                                    $(".year").val(year);
                                    var form = $("#frm-create-account");
                                    if (!form.valid()) {
                                        $('.tooltip').removeClass("in");
                                        OA.utils.ajaxHelpers.closeJQMLoader();
                                        return;
                                    }
                                    isFacebookSignup = true;
                                    OA.services.FacebookAccessLog({
                                        ID: FacebookSigningLogID,
                                        CustId: Custid,
                                        PINLogin: 2,
                                        ApplicationID: 2,
                                        LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.Success),
                                        Email: response.email, clientID: clientID, saleLocation: saleLocation, password: ''
                                    }).done(function (res) {
                                        console.log("FacebookAccessLog AccessDenyDOB", res);
                                        OA.cookie.ManageCookieValue('FacebookSigningLogID', res);
                                    })
                                    $("#saveaccount").trigger("click");
                                }
                                else {
                                    $("#first-name").val(response.first_name);
                                    $("#last-name").val(response.last_name);
                                    $("#email").val(response.email);
                                    $("#password").addClass("pass");
                                    $("#password").val(tempPassword);
                                    $("#cpassword").val(tempPassword);

                                    OA.services.FacebookAccessLog({
                                        ID: FacebookSigningLogID,
                                        CustId: Custid,
                                        PINLogin: 2,
                                        ApplicationID: 2,
                                        LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.AccessDenyDOB),
                                        Email: response.email, clientID: clientID, saleLocation: saleLocation, password: ''
                                    }).done(function (res) {
                                        console.log("FacebookAccessLog AccessDenyDOB", res);
                                        OA.cookie.ManageCookieValue('FacebookSigningLogID', res);
                                    })
                                    var self = this;
                                    var form = $("#frm-create-account");
                                    if (!form.valid()) {
                                        $('.tooltip').removeClass("in");
                                        OA.utils.ajaxHelpers.closeJQMLoader();
                                        return;
                                    }
                                    OA.services.FacebookAccessLog({
                                        ID: FacebookSigningLogID,
                                        CustId: Custid,
                                        PINLogin: 2,
                                        ApplicationID: 2,
                                        LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.Success),
                                        Email: response.email, clientID: clientID, saleLocation: saleLocation, password: ''
                                    }).done(function (res) {
                                        console.log("FacebookAccessLog AccessDenyDOB", res);
                                        OA.cookie.ManageCookieValue('FacebookSigningLogID', res);
                                    })
                                    $("#saveaccount").trigger("click");
                                }
                            }
                            else {
                                $("#first-name").val(response.first_name);
                                $("#last-name").val(response.last_name);

                                var self = this;
                                var form = $("#frm-create-account");

                                OA.services.FacebookAccessLog({
                                    ID: FacebookSigningLogID,
                                    CustId: Custid,
                                    PINLogin: 2,
                                    ApplicationID: 2,
                                    LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.AccessDenyEmail),
                                    Email: "",
                                    clientID: clientID, saleLocation: saleLocation, password: ''
                                }).done(function (res) {
                                    console.log("FacebookAccessLog", res);
                                    OA.cookie.ManageCookieValue('FacebookSigningLogID', res);
                                })
                                if (!form.valid()) {
                                    $('.tooltip').removeClass("in");
                                    OA.utils.ajaxHelpers.closeJQMLoader();
                                    return;
                                }
                                $("#saveaccount").trigger("click");
                            }
                        }
                        else {
                            EmailID = response.email;
                            OA.services.FacebookAuthentication({
                                FacebooAccessToken: access_token,
                                EmailId: response.email,
                                FacebookUserID: response.id
                            }).done(function (res) {
                                $.mobile.loading("show");
                                custid = res.custid;
                                OA.services.getCustomerDetails(res.custid).done(function (custResponce) {
                                    console.log("custResponce.........", custResponce);
                                    OA.services.FacebookAccessLog({
                                        ID: FacebookSigningLogID,
                                        CustId: res.custid,
                                        PINLogin: 2,
                                        ApplicationID: 2,
                                        LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.Success),
                                        Email: EmailID, clientID: clientID, saleLocation: saleLocation, password: ''
                                    }).done(function (res) {
                                        console.log("FacebookAccessLog", res);
                                    })


                                    if (custResponce.pin == "") {
                                        var offerDict = OA.utils.purchases.fillOffersDictionary('20');
                                        var info = {
                                            firstName: custResponce.firstName,
                                            lastName: custResponce.lastName,
                                            email: custResponce.email,
                                            dob: custResponce.birthDate,
                                            password: '',
                                            sendFreeHoroAndNewsLetter: '',
                                            offerDuration: '',
                                            cardHolderName: '',
                                            cardNumber: '',
                                            expMonth: '',
                                            expYear: '',
                                            cvv: '',
                                            cardType: '',
                                            billingCountry: '',
                                            billingCountryName: '',
                                            zipCode: '',
                                            state: '',
                                            stateRegion: '',
                                            city: '',
                                            address1: '',
                                            address2: '',
                                            phoneCountry: '',
                                            phoneNumber: '',
                                            masId: '',
                                            custId: custid,
                                            callbackId: '',
                                            extId: '',
                                            offerId: '',
                                            priceId: '',
                                            transactionId: '',
                                            transactionAmount: '',
                                            statusCode: '',
                                            errorMessage: '',
                                            subscriptionId: '',
                                            package: offerDict["1"],
                                            questionText: ''
                                        };
                                        var authCookie = OA.cookie.ManageCookieValue('auth');
                                        OA.cookie.RemoveCookieValue('FiveFreeAccountInfo');
                                        OA.cookie.ManageCookieValue('askAccountInfo', info);

                                        console.log('askAccountInfo........', info);



                                        window.location.href = "../" + OA.paths.askNcCheckout.checkout + "?nc=1";

                                    }
                                    if (custResponce.pin != "") {

                                        OA.services.auth(undefined, {
                                            Authorization: "Basic " + OA.utils.stringHelpers.base64Encode(custResponce.email + ':' + custResponce.pin)
                                        }, clientID, saleLocation).done(function (res) {
                                            if (res.pin != "") {

                                                var self = this;

                                                $.mobile.loading("show");
                                                if (OAApp.featureConfig.isOldDesktopSiteLoginEnabled) {

                                                    $.mobile.loading("show");
                                                    var loginTimer = $.timer(function () {
                                                        $.mobile.loading("show");
                                                        //Create Desktop user session
                                                        if (OAApp.featureConfig.isOldDesktopSiteLoginEnabled) {
                                                            $.mobile.loading("show");
                                                            $(".sign-in-desktop #btnSignindesktop").attr("disabled", "disabled");

                                                            OA.LoginWithFacebookInit.authenticateDesktopFacebook(res.email, res.pin, res);
                                                        }
                                                        loginTimer.stop();
                                                    });
                                                    loginTimer.set({ time: 100, autostart: true });
                                                }

                                                else {
                                                    $(".sign-in-desktop #btnSignindesktop").attr("disabled", "disabled");
                                                    OA.LoginWithFacebookInit.successfulAuthfacebook(res);
                                                }
                                            }

                                            else {
                                                $.mobile.loading("hide");
                                                var auth = OA.cookie.ManageCookieValue('auth');
                                                if (auth == "" || auth == undefined || auth == null) {
                                                    $(".Facebook-sign-in-error-content").empty();
                                                    $('div.Facebook-sign-in-error-content').text('The email address associated with your Facebook account does not match an existing California Psychics account. Please sign in using your email and password to continue, or create a new account.');
                                                    $('.Facebook-sign-in-error').css("height", "180px");
                                                }
                                                else {
                                                    $(".Facebook-sign-in-error-content").empty();
                                                    $('div.Facebook-sign-in-error-content').text('The email address associated with your Facebook account does not match your California Psychics account email.The email address must match in order for you to link the two accounts. Please sign in using your email and password to continue.');

                                                }

                                                if (whichpage == "signin_Header") {

                                                    $.mobile.loading('show');
                                                    $('.sign-in-popup-main').show();
                                                    $('.sign-in-error').hide();
                                                    $('.Facebook-sign-in-error').show();
                                                    $(".sign-in-header-popup").css('max-height', '555px');
                                                    $('.FacebookDesktop').hide();

                                                }
                                                if (whichpage == "signin-DeskTop") {
                                                    $('.sign-in-error').hide();
                                                    $('.sign-in-error-desktop-display').hide();
                                                    $('.Facebook-sign-in-error').show();
                                                    $(' .page-wrap').css('height', '887px');
                                                    $(' .sign-in-main').css('height', '620px');
                                                    $('.FacebookCPHeader').hide();
                                                    $('.ui-panel-wrapper').css('height', '1214');

                                                }
                                                if (whichpage == "signin-mobile") {
                                                    $('#fields-error').hide();
                                                    $('.sign-in-error-desktop-display').hide();
                                                    $('.Facebook-sign-in-error').show();
                                                    var windowSize = $(window).width();
                                                    if (windowSize <= 740) {
                                                        $('.ui-panel-wrapper').addClass('MobileSigninWindow');
                                                        $('.MobileSigninWindow').css('height', '900px');
                                                        $('p.err').text('');
                                                    }

                                                }
                                            }
                                        }).fail(function (res) {
                                            window.location.href = "/ask-question-signup?fromaskitself=true&login=true";
                                            $.mobile.loading("hide");
                                            //var auth = OA.cookie.ManageCookieValue('auth');
                                            //if (auth == "" || auth == undefined || auth == null) {
                                            //    $(".Facebook-sign-in-error-content").empty();
                                            //    $('div.Facebook-sign-in-error-content').text('The email address associated with your Facebook account does not match an existing California Psychics account. Please sign in using your email and password to continue, or create a new account.');
                                            //    $('.Facebook-sign-in-error').css("height", "180px");
                                            //}
                                            //else {
                                            //    $(".Facebook-sign-in-error-content").empty();
                                            //    $('div.Facebook-sign-in-error-content').text('The email address associated with your Facebook account does not match your California Psychics account email.The email address must match in order for you to link the two accounts. Please sign in using your email and password to continue.');

                                            //}

                                            //if (whichpage == "signin_Header") {
                                            //    $.mobile.loading('show');
                                            //    $('.sign-in-popup-main').show();
                                            //    $('.sign-in-error').hide();
                                            //    $('.Facebook-sign-in-error').show();
                                            //    $('.FacebookDesktop').hide();
                                            //    $(".sign-in-header-popup").css('max-height', '555px');
                                            //}
                                            //if (whichpage == "signin-DeskTop") {
                                            //    $('.sign-in-error').hide();
                                            //    $('.sign-in-error-desktop-display').hide();
                                            //    $('.Facebook-sign-in-error').show();
                                            //    $(' .page-wrap').css('height', '887px');
                                            //    $(' .sign-in-main').css('height', '620px');
                                            //    $('.FacebookCPHeader').hide();
                                            //    $('.ui-panel-wrapper').css('height', '1214');


                                            //}
                                            //if (whichpage == "signin-mobile") {
                                            //    $('#fields-error').hide();
                                            //    $('.sign-in-error-desktop-display').hide();
                                            //    $('.Facebook-sign-in-error').show();
                                            //    var windowSize = $(window).width();
                                            //    if (windowSize <= 740) {
                                            //        $('.ui-panel-wrapper').addClass('MobileSigninWindow');
                                            //        $('.MobileSigninWindow').css('height', '900px');
                                            //        $('p.err').text('');
                                            //    }
                                            //}


                                        })
                                    }
                                }).fail(function (res) {

                                });
                            }).fail(function (res) {
                                //$.mobile.loading("hide");                              
                                OA.services.FacebookAccessLog({
                                    ID: FacebookSigningLogID,
                                    CustId: Custid,
                                    PINLogin: 2,
                                    ApplicationID: 2,
                                    LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.LoginMismatch),
                                    Email: EmailID, clientID: clientID, saleLocation: saleLocation, password: ''
                                }).done(function (res) {
                                    console.log("LoginMismatch done", res);
                                })
                                window.location.href = "/ask-question-signup?fromaskitself=true&login=true";
                                //var auth = OA.cookie.ManageCookieValue('auth');
                                //if (auth == "" || auth == undefined || auth == null) {
                                //    $(".Facebook-sign-in-error-content").empty();
                                //    $('div.Facebook-sign-in-error-content').text('The email address associated with your Facebook account does not match an existing California Psychics account. Please sign in using your email and password to continue, or create a new account.');
                                //    $('.Facebook-sign-in-error').css("height", "180px");
                                //}
                                //else {
                                //    $(".Facebook-sign-in-error-content").empty();
                                //    $('div.Facebook-sign-in-error-content').text('The email address associated with your Facebook account does not match your California Psychics account email.The email address must match in order for you to link the two accounts. Please sign in using your email and password to continue.');

                                //}

                                //if (whichpage == "signin_Header") {
                                //    //$.mobile.loading('show');
                                //    $('.sign-in-popup-main').show();
                                //    $('.sign-in-error').hide();
                                //    $('.Facebook-sign-in-error').show();
                                //    $(".sign-in-header-popup").css('max-height', '555px');
                                //    $('.FacebookDesktop').hide();

                                //}
                                //if (whichpage == "signin-DeskTop") {
                                //    $('.sign-in-error').hide();
                                //    $('.sign-in-error-desktop-display').hide();
                                //    $('.Facebook-sign-in-error').show();

                                //    $('.ui-panel-wrapper').css('height', '1214');
                                //    $(' .sign-in-main').css('height', '620px');
                                //    $('.FacebookCPHeader').hide();


                                //}
                                //if (whichpage == "signin-mobile") {

                                //    $('#fields-error').hide();
                                //    $('.sign-in-error-desktop-display').hide();
                                //    $('.Facebook-sign-in-error').show();
                                //    var windowSize = $(window).width();
                                //    if (windowSize <= 740) {
                                //        $('.ui-panel-wrapper').addClass('MobileSigninWindow');
                                //        $('.MobileSigninWindow').css('height', '900px');
                                //        $('p.err').text('');
                                //    }
                                //}
                            })

                        }
                    }), ({ auth_type: 'reauthenticate' });
                } else if (response.status == undefined || response.status === "not_authorized") {
                    OA.services.FacebookAccessLog({
                        ID: FacebookSigningLogID,
                        CustId: Custid,
                        PINLogin: 2,
                        ApplicationID: 2,
                        LoginResultID: parseInt(OA.utils.enum.FacebookLoginId.Failed),
                        Email: '', clientID: clientID, saleLocation: saleLocation, password: ''
                    }).done(function (res) {
                        console.log("Failed", res);
                    })
                }
            },
            {
                scope: 'email,user_birthday'
            }
    );
        }
    }
}(window));;
/**
 * jquery.timer.js
 *
 * Copyright (c) 2011 Jason Chavannes <jason.chavannes@gmail.com>
 *
 * http://jchavannes.com/jquery-timer
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

;(function($) {
	$.timer = function(func, time, autostart) {	
	 	this.set = function(func, time, autostart) {
	 		this.init = true;
	 	 	if(typeof func == 'object') {
		 	 	var paramList = ['autostart', 'time'];
	 	 	 	for(var arg in paramList) {if(func[paramList[arg]] != undefined) {eval(paramList[arg] + " = func[paramList[arg]]");}};
 	 			func = func.action;
	 	 	}
	 	 	if(typeof func == 'function') {this.action = func;}
		 	if(!isNaN(time)) {this.intervalTime = time;}
		 	if(autostart && !this.isActive) {
			 	this.isActive = true;
			 	this.setTimer();
		 	}
		 	return this;
	 	};
	 	this.once = function(time) {
			var timer = this;
	 	 	if(isNaN(time)) {time = 0;}
			window.setTimeout(function() {timer.action();}, time);
	 		return this;
	 	};
		this.play = function(reset) {
			if(!this.isActive) {
				if(reset) {this.setTimer();}
				else {this.setTimer(this.remaining);}
				this.isActive = true;
			}
			return this;
		};
		this.pause = function() {
			if(this.isActive) {
				this.isActive = false;
				this.remaining -= new Date() - this.last;
				this.clearTimer();
			}
			return this;
		};
		this.stop = function() {
			this.isActive = false;
			this.remaining = this.intervalTime;
			this.clearTimer();
			return this;
		};
		this.toggle = function(reset) {
			if(this.isActive) {this.pause();}
			else if(reset) {this.play(true);}
			else {this.play();}
			return this;
		};
		this.reset = function() {
			this.isActive = false;
			this.play(true);
			return this;
		};
		this.clearTimer = function() {
			window.clearTimeout(this.timeoutObject);
		};
	 	this.setTimer = function(time) {
			var timer = this;
	 	 	if(typeof this.action != 'function') {return;}
	 	 	if(isNaN(time)) {time = this.intervalTime;}
		 	this.remaining = time;
	 	 	this.last = new Date();
			this.clearTimer();
			this.timeoutObject = window.setTimeout(function() {timer.go();}, time);
		};
	 	this.go = function() {
	 		if(this.isActive) {
	 			this.action();
	 			this.setTimer();
	 		}
	 	};
	 	
	 	if(this.init) {
	 		return new $.timer(func, time, autostart);
	 	} else {
			this.set(func, time, autostart);
	 		return this;
	 	}
	};
})(jQuery);;
//! moment.js
//! version : 2.6.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com

(function (undefined) {

    /************************************
        Constants
    ************************************/

    var moment,
        VERSION = "2.6.0",
        // the global-scope this is NOT the global object in Node.js
        globalScope = typeof global !== 'undefined' ? global : this,
        oldGlobalMoment,
        round = Math.round,
        i,

        YEAR = 0,
        MONTH = 1,
        DATE = 2,
        HOUR = 3,
        MINUTE = 4,
        SECOND = 5,
        MILLISECOND = 6,

        // internal storage for language config files
        languages = {},

        // moment internal properties
        momentProperties = {
            _isAMomentObject: null,
            _i : null,
            _f : null,
            _l : null,
            _strict : null,
            _isUTC : null,
            _offset : null,  // optional. Combine with _isUTC
            _pf : null,
            _lang : null  // optional
        },

        // check for nodeJS
        hasModule = (typeof module !== 'undefined' && module.exports),

        // ASP.NET json date format regex
        aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
        aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,

        // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
        // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
        isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,

        // format tokens
        formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
        localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,

        // parsing token regexes
        parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
        parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
        parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
        parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
        parseTokenDigits = /\d+/, // nonzero number of digits
        parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic.
        parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
        parseTokenT = /T/i, // T (ISO separator)
        parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
        parseTokenOrdinal = /\d{1,2}/,

        //strict parsing regexes
        parseTokenOneDigit = /\d/, // 0 - 9
        parseTokenTwoDigits = /\d\d/, // 00 - 99
        parseTokenThreeDigits = /\d{3}/, // 000 - 999
        parseTokenFourDigits = /\d{4}/, // 0000 - 9999
        parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
        parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf

        // iso 8601 regex
        // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
        isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,

        isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',

        isoDates = [
            ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
            ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
            ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
            ['GGGG-[W]WW', /\d{4}-W\d{2}/],
            ['YYYY-DDD', /\d{4}-\d{3}/]
        ],

        // iso time formats and regexes
        isoTimes = [
            ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
            ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
            ['HH:mm', /(T| )\d\d:\d\d/],
            ['HH', /(T| )\d\d/]
        ],

        // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
        parseTimezoneChunker = /([\+\-]|\d\d)/gi,

        // getter and setter names
        proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
        unitMillisecondFactors = {
            'Milliseconds' : 1,
            'Seconds' : 1e3,
            'Minutes' : 6e4,
            'Hours' : 36e5,
            'Days' : 864e5,
            'Months' : 2592e6,
            'Years' : 31536e6
        },

        unitAliases = {
            ms : 'millisecond',
            s : 'second',
            m : 'minute',
            h : 'hour',
            d : 'day',
            D : 'date',
            w : 'week',
            W : 'isoWeek',
            M : 'month',
            Q : 'quarter',
            y : 'year',
            DDD : 'dayOfYear',
            e : 'weekday',
            E : 'isoWeekday',
            gg: 'weekYear',
            GG: 'isoWeekYear'
        },

        camelFunctions = {
            dayofyear : 'dayOfYear',
            isoweekday : 'isoWeekday',
            isoweek : 'isoWeek',
            weekyear : 'weekYear',
            isoweekyear : 'isoWeekYear'
        },

        // format function strings
        formatFunctions = {},

        // tokens to ordinalize and pad
        ordinalizeTokens = 'DDD w W M D d'.split(' '),
        paddedTokens = 'M D H h m s w W'.split(' '),

        formatTokenFunctions = {
            M    : function () {
                return this.month() + 1;
            },
            MMM  : function (format) {
                return this.lang().monthsShort(this, format);
            },
            MMMM : function (format) {
                return this.lang().months(this, format);
            },
            D    : function () {
                return this.date();
            },
            DDD  : function () {
                return this.dayOfYear();
            },
            d    : function () {
                return this.day();
            },
            dd   : function (format) {
                return this.lang().weekdaysMin(this, format);
            },
            ddd  : function (format) {
                return this.lang().weekdaysShort(this, format);
            },
            dddd : function (format) {
                return this.lang().weekdays(this, format);
            },
            w    : function () {
                return this.week();
            },
            W    : function () {
                return this.isoWeek();
            },
            YY   : function () {
                return leftZeroFill(this.year() % 100, 2);
            },
            YYYY : function () {
                return leftZeroFill(this.year(), 4);
            },
            YYYYY : function () {
                return leftZeroFill(this.year(), 5);
            },
            YYYYYY : function () {
                var y = this.year(), sign = y >= 0 ? '+' : '-';
                return sign + leftZeroFill(Math.abs(y), 6);
            },
            gg   : function () {
                return leftZeroFill(this.weekYear() % 100, 2);
            },
            gggg : function () {
                return leftZeroFill(this.weekYear(), 4);
            },
            ggggg : function () {
                return leftZeroFill(this.weekYear(), 5);
            },
            GG   : function () {
                return leftZeroFill(this.isoWeekYear() % 100, 2);
            },
            GGGG : function () {
                return leftZeroFill(this.isoWeekYear(), 4);
            },
            GGGGG : function () {
                return leftZeroFill(this.isoWeekYear(), 5);
            },
            e : function () {
                return this.weekday();
            },
            E : function () {
                return this.isoWeekday();
            },
            a    : function () {
                return this.lang().meridiem(this.hours(), this.minutes(), true);
            },
            A    : function () {
                return this.lang().meridiem(this.hours(), this.minutes(), false);
            },
            H    : function () {
                return this.hours();
            },
            h    : function () {
                return this.hours() % 12 || 12;
            },
            m    : function () {
                return this.minutes();
            },
            s    : function () {
                return this.seconds();
            },
            S    : function () {
                return toInt(this.milliseconds() / 100);
            },
            SS   : function () {
                return leftZeroFill(toInt(this.milliseconds() / 10), 2);
            },
            SSS  : function () {
                return leftZeroFill(this.milliseconds(), 3);
            },
            SSSS : function () {
                return leftZeroFill(this.milliseconds(), 3);
            },
            Z    : function () {
                var a = -this.zone(),
                    b = "+";
                if (a < 0) {
                    a = -a;
                    b = "-";
                }
                return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
            },
            ZZ   : function () {
                var a = -this.zone(),
                    b = "+";
                if (a < 0) {
                    a = -a;
                    b = "-";
                }
                return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
            },
            z : function () {
                return this.zoneAbbr();
            },
            zz : function () {
                return this.zoneName();
            },
            X    : function () {
                return this.unix();
            },
            Q : function () {
                return this.quarter();
            }
        },

        lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];

    function defaultParsingFlags() {
        // We need to deep clone this object, and es5 standard is not very
        // helpful.
        return {
            empty : false,
            unusedTokens : [],
            unusedInput : [],
            overflow : -2,
            charsLeftOver : 0,
            nullInput : false,
            invalidMonth : null,
            invalidFormat : false,
            userInvalidated : false,
            iso: false
        };
    }

    function deprecate(msg, fn) {
        var firstTime = true;
        function printMsg() {
            if (moment.suppressDeprecationWarnings === false &&
                    typeof console !== 'undefined' && console.warn) {
                console.warn("Deprecation warning: " + msg);
            }
        }
        return extend(function () {
            if (firstTime) {
                printMsg();
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }

    function padToken(func, count) {
        return function (a) {
            return leftZeroFill(func.call(this, a), count);
        };
    }
    function ordinalizeToken(func, period) {
        return function (a) {
            return this.lang().ordinal(func.call(this, a), period);
        };
    }

    while (ordinalizeTokens.length) {
        i = ordinalizeTokens.pop();
        formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
    }
    while (paddedTokens.length) {
        i = paddedTokens.pop();
        formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
    }
    formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);


    /************************************
        Constructors
    ************************************/

    function Language() {

    }

    // Moment prototype object
    function Moment(config) {
        checkOverflow(config);
        extend(this, config);
    }

    // Duration Constructor
    function Duration(duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;

        // representation for dateAddRemove
        this._milliseconds = +milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 36e5; // 1000 * 60 * 60
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months +
            quarters * 3 +
            years * 12;

        this._data = {};

        this._bubble();
    }

    /************************************
        Helpers
    ************************************/


    function extend(a, b) {
        for (var i in b) {
            if (b.hasOwnProperty(i)) {
                a[i] = b[i];
            }
        }

        if (b.hasOwnProperty("toString")) {
            a.toString = b.toString;
        }

        if (b.hasOwnProperty("valueOf")) {
            a.valueOf = b.valueOf;
        }

        return a;
    }

    function cloneMoment(m) {
        var result = {}, i;
        for (i in m) {
            if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
                result[i] = m[i];
            }
        }

        return result;
    }

    function absRound(number) {
        if (number < 0) {
            return Math.ceil(number);
        } else {
            return Math.floor(number);
        }
    }

    // left zero fill a number
    // see http://jsperf.com/left-zero-filling for performance comparison
    function leftZeroFill(number, targetLength, forceSign) {
        var output = '' + Math.abs(number),
            sign = number >= 0;

        while (output.length < targetLength) {
            output = '0' + output;
        }
        return (sign ? (forceSign ? '+' : '') : '-') + output;
    }

    // helper function for _.addTime and _.subtractTime
    function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = duration._days,
            months = duration._months;
        updateOffset = updateOffset == null ? true : updateOffset;

        if (milliseconds) {
            mom._d.setTime(+mom._d + milliseconds * isAdding);
        }
        if (days) {
            rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
        }
        if (months) {
            rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            moment.updateOffset(mom, days || months);
        }
    }

    // check if is an array
    function isArray(input) {
        return Object.prototype.toString.call(input) === '[object Array]';
    }

    function isDate(input) {
        return  Object.prototype.toString.call(input) === '[object Date]' ||
                input instanceof Date;
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    function normalizeUnits(units) {
        if (units) {
            var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
            units = unitAliases[units] || camelFunctions[lowered] || lowered;
        }
        return units;
    }

    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;

        for (prop in inputObject) {
            if (inputObject.hasOwnProperty(prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }

        return normalizedInput;
    }

    function makeList(field) {
        var count, setter;

        if (field.indexOf('week') === 0) {
            count = 7;
            setter = 'day';
        }
        else if (field.indexOf('month') === 0) {
            count = 12;
            setter = 'month';
        }
        else {
            return;
        }

        moment[field] = function (format, index) {
            var i, getter,
                method = moment.fn._lang[field],
                results = [];

            if (typeof format === 'number') {
                index = format;
                format = undefined;
            }

            getter = function (i) {
                var m = moment().utc().set(setter, i);
                return method.call(moment.fn._lang, m, format || '');
            };

            if (index != null) {
                return getter(index);
            }
            else {
                for (i = 0; i < count; i++) {
                    results.push(getter(i));
                }
                return results;
            }
        };
    }

    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;

        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            if (coercedNumber >= 0) {
                value = Math.floor(coercedNumber);
            } else {
                value = Math.ceil(coercedNumber);
            }
        }

        return value;
    }

    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }

    function weeksInYear(year, dow, doy) {
        return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
    }

    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    function checkOverflow(m) {
        var overflow;
        if (m._a && m._pf.overflow === -2) {
            overflow =
                m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
                m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
                m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
                m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
                m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
                m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
                -1;

            if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }

            m._pf.overflow = overflow;
        }
    }

    function isValid(m) {
        if (m._isValid == null) {
            m._isValid = !isNaN(m._d.getTime()) &&
                m._pf.overflow < 0 &&
                !m._pf.empty &&
                !m._pf.invalidMonth &&
                !m._pf.nullInput &&
                !m._pf.invalidFormat &&
                !m._pf.userInvalidated;

            if (m._strict) {
                m._isValid = m._isValid &&
                    m._pf.charsLeftOver === 0 &&
                    m._pf.unusedTokens.length === 0;
            }
        }
        return m._isValid;
    }

    function normalizeLanguage(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }

    // Return a moment from input, that is local/utc/zone equivalent to model.
    function makeAs(input, model) {
        return model._isUTC ? moment(input).zone(model._offset || 0) :
            moment(input).local();
    }

    /************************************
        Languages
    ************************************/


    extend(Language.prototype, {

        set : function (config) {
            var prop, i;
            for (i in config) {
                prop = config[i];
                if (typeof prop === 'function') {
                    this[i] = prop;
                } else {
                    this['_' + i] = prop;
                }
            }
        },

        _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
        months : function (m) {
            return this._months[m.month()];
        },

        _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
        monthsShort : function (m) {
            return this._monthsShort[m.month()];
        },

        monthsParse : function (monthName) {
            var i, mom, regex;

            if (!this._monthsParse) {
                this._monthsParse = [];
            }

            for (i = 0; i < 12; i++) {
                // make the regex if we don't have it already
                if (!this._monthsParse[i]) {
                    mom = moment.utc([2000, i]);
                    regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                    this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
                }
                // test the regex
                if (this._monthsParse[i].test(monthName)) {
                    return i;
                }
            }
        },

        _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
        weekdays : function (m) {
            return this._weekdays[m.day()];
        },

        _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
        weekdaysShort : function (m) {
            return this._weekdaysShort[m.day()];
        },

        _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
        weekdaysMin : function (m) {
            return this._weekdaysMin[m.day()];
        },

        weekdaysParse : function (weekdayName) {
            var i, mom, regex;

            if (!this._weekdaysParse) {
                this._weekdaysParse = [];
            }

            for (i = 0; i < 7; i++) {
                // make the regex if we don't have it already
                if (!this._weekdaysParse[i]) {
                    mom = moment([2000, 1]).day(i);
                    regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                    this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
                }
                // test the regex
                if (this._weekdaysParse[i].test(weekdayName)) {
                    return i;
                }
            }
        },

        _longDateFormat : {
            LT : "h:mm A",
            L : "MM/DD/YYYY",
            LL : "MMMM D YYYY",
            LLL : "MMMM D YYYY LT",
            LLLL : "dddd, MMMM D YYYY LT"
        },
        longDateFormat : function (key) {
            var output = this._longDateFormat[key];
            if (!output && this._longDateFormat[key.toUpperCase()]) {
                output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
                    return val.slice(1);
                });
                this._longDateFormat[key] = output;
            }
            return output;
        },

        isPM : function (input) {
            // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
            // Using charAt should be more compatible.
            return ((input + '').toLowerCase().charAt(0) === 'p');
        },

        _meridiemParse : /[ap]\.?m?\.?/i,
        meridiem : function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'pm' : 'PM';
            } else {
                return isLower ? 'am' : 'AM';
            }
        },

        _calendar : {
            sameDay : '[Today at] LT',
            nextDay : '[Tomorrow at] LT',
            nextWeek : 'dddd [at] LT',
            lastDay : '[Yesterday at] LT',
            lastWeek : '[Last] dddd [at] LT',
            sameElse : 'L'
        },
        calendar : function (key, mom) {
            var output = this._calendar[key];
            return typeof output === 'function' ? output.apply(mom) : output;
        },

        _relativeTime : {
            future : "in %s",
            past : "%s ago",
            s : "a few seconds",
            m : "a minute",
            mm : "%d minutes",
            h : "an hour",
            hh : "%d hours",
            d : "a day",
            dd : "%d days",
            M : "a month",
            MM : "%d months",
            y : "a year",
            yy : "%d years"
        },
        relativeTime : function (number, withoutSuffix, string, isFuture) {
            var output = this._relativeTime[string];
            return (typeof output === 'function') ?
                output(number, withoutSuffix, string, isFuture) :
                output.replace(/%d/i, number);
        },
        pastFuture : function (diff, output) {
            var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
            return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
        },

        ordinal : function (number) {
            return this._ordinal.replace("%d", number);
        },
        _ordinal : "%d",

        preparse : function (string) {
            return string;
        },

        postformat : function (string) {
            return string;
        },

        week : function (mom) {
            return weekOfYear(mom, this._week.dow, this._week.doy).week;
        },

        _week : {
            dow : 0, // Sunday is the first day of the week.
            doy : 6  // The week that contains Jan 1st is the first week of the year.
        },

        _invalidDate: 'Invalid date',
        invalidDate: function () {
            return this._invalidDate;
        }
    });

    // Loads a language definition into the `languages` cache.  The function
    // takes a key and optionally values.  If not in the browser and no values
    // are provided, it will load the language file module.  As a convenience,
    // this function also returns the language values.
    function loadLang(key, values) {
        values.abbr = key;
        if (!languages[key]) {
            languages[key] = new Language();
        }
        languages[key].set(values);
        return languages[key];
    }

    // Remove a language from the `languages` cache. Mostly useful in tests.
    function unloadLang(key) {
        delete languages[key];
    }

    // Determines which language definition to use and returns it.
    //
    // With no parameters, it will return the global language.  If you
    // pass in a language key, such as 'en', it will return the
    // definition for 'en', so long as 'en' has already been loaded using
    // moment.lang.
    function getLangDefinition(key) {
        var i = 0, j, lang, next, split,
            get = function (k) {
                if (!languages[k] && hasModule) {
                    try {
                        require('./lang/' + k);
                    } catch (e) { }
                }
                return languages[k];
            };

        if (!key) {
            return moment.fn._lang;
        }

        if (!isArray(key)) {
            //short-circuit everything else
            lang = get(key);
            if (lang) {
                return lang;
            }
            key = [key];
        }

        //pick the language from the array
        //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
        //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
        while (i < key.length) {
            split = normalizeLanguage(key[i]).split('-');
            j = split.length;
            next = normalizeLanguage(key[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                lang = get(split.slice(0, j).join('-'));
                if (lang) {
                    return lang;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return moment.fn._lang;
    }

    /************************************
        Formatting
    ************************************/


    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, "");
        }
        return input.replace(/\\/g, "");
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = "";
            for (i = 0; i < length; i++) {
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {

        if (!m.isValid()) {
            return m.lang().invalidDate();
        }

        format = expandFormat(format, m.lang());

        if (!formatFunctions[format]) {
            formatFunctions[format] = makeFormatFunction(format);
        }

        return formatFunctions[format](m);
    }

    function expandFormat(format, lang) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return lang.longDateFormat(input) || input;
        }

        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }

        return format;
    }


    /************************************
        Parsing
    ************************************/


    // get the regex to find the next token
    function getParseRegexForToken(token, config) {
        var a, strict = config._strict;
        switch (token) {
        case 'Q':
            return parseTokenOneDigit;
        case 'DDDD':
            return parseTokenThreeDigits;
        case 'YYYY':
        case 'GGGG':
        case 'gggg':
            return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
        case 'Y':
        case 'G':
        case 'g':
            return parseTokenSignedNumber;
        case 'YYYYYY':
        case 'YYYYY':
        case 'GGGGG':
        case 'ggggg':
            return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
        case 'S':
            if (strict) { return parseTokenOneDigit; }
            /* falls through */
        case 'SS':
            if (strict) { return parseTokenTwoDigits; }
            /* falls through */
        case 'SSS':
            if (strict) { return parseTokenThreeDigits; }
            /* falls through */
        case 'DDD':
            return parseTokenOneToThreeDigits;
        case 'MMM':
        case 'MMMM':
        case 'dd':
        case 'ddd':
        case 'dddd':
            return parseTokenWord;
        case 'a':
        case 'A':
            return getLangDefinition(config._l)._meridiemParse;
        case 'X':
            return parseTokenTimestampMs;
        case 'Z':
        case 'ZZ':
            return parseTokenTimezone;
        case 'T':
            return parseTokenT;
        case 'SSSS':
            return parseTokenDigits;
        case 'MM':
        case 'DD':
        case 'YY':
        case 'GG':
        case 'gg':
        case 'HH':
        case 'hh':
        case 'mm':
        case 'ss':
        case 'ww':
        case 'WW':
            return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
        case 'M':
        case 'D':
        case 'd':
        case 'H':
        case 'h':
        case 'm':
        case 's':
        case 'w':
        case 'W':
        case 'e':
        case 'E':
            return parseTokenOneOrTwoDigits;
        case 'Do':
            return parseTokenOrdinal;
        default :
            a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
            return a;
        }
    }

    function timezoneMinutesFromString(string) {
        string = string || "";
        var possibleTzMatches = (string.match(parseTokenTimezone) || []),
            tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
            parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
            minutes = +(parts[1] * 60) + toInt(parts[2]);

        return parts[0] === '+' ? -minutes : minutes;
    }

    // function to convert string input to date
    function addTimeToArrayFromToken(token, input, config) {
        var a, datePartArray = config._a;

        switch (token) {
        // QUARTER
        case 'Q':
            if (input != null) {
                datePartArray[MONTH] = (toInt(input) - 1) * 3;
            }
            break;
        // MONTH
        case 'M' : // fall through to MM
        case 'MM' :
            if (input != null) {
                datePartArray[MONTH] = toInt(input) - 1;
            }
            break;
        case 'MMM' : // fall through to MMMM
        case 'MMMM' :
            a = getLangDefinition(config._l).monthsParse(input);
            // if we didn't find a month name, mark the date as invalid.
            if (a != null) {
                datePartArray[MONTH] = a;
            } else {
                config._pf.invalidMonth = input;
            }
            break;
        // DAY OF MONTH
        case 'D' : // fall through to DD
        case 'DD' :
            if (input != null) {
                datePartArray[DATE] = toInt(input);
            }
            break;
        case 'Do' :
            if (input != null) {
                datePartArray[DATE] = toInt(parseInt(input, 10));
            }
            break;
        // DAY OF YEAR
        case 'DDD' : // fall through to DDDD
        case 'DDDD' :
            if (input != null) {
                config._dayOfYear = toInt(input);
            }

            break;
        // YEAR
        case 'YY' :
            datePartArray[YEAR] = moment.parseTwoDigitYear(input);
            break;
        case 'YYYY' :
        case 'YYYYY' :
        case 'YYYYYY' :
            datePartArray[YEAR] = toInt(input);
            break;
        // AM / PM
        case 'a' : // fall through to A
        case 'A' :
            config._isPm = getLangDefinition(config._l).isPM(input);
            break;
        // 24 HOUR
        case 'H' : // fall through to hh
        case 'HH' : // fall through to hh
        case 'h' : // fall through to hh
        case 'hh' :
            datePartArray[HOUR] = toInt(input);
            break;
        // MINUTE
        case 'm' : // fall through to mm
        case 'mm' :
            datePartArray[MINUTE] = toInt(input);
            break;
        // SECOND
        case 's' : // fall through to ss
        case 'ss' :
            datePartArray[SECOND] = toInt(input);
            break;
        // MILLISECOND
        case 'S' :
        case 'SS' :
        case 'SSS' :
        case 'SSSS' :
            datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
            break;
        // UNIX TIMESTAMP WITH MS
        case 'X':
            config._d = new Date(parseFloat(input) * 1000);
            break;
        // TIMEZONE
        case 'Z' : // fall through to ZZ
        case 'ZZ' :
            config._useUTC = true;
            config._tzm = timezoneMinutesFromString(input);
            break;
        case 'w':
        case 'ww':
        case 'W':
        case 'WW':
        case 'd':
        case 'dd':
        case 'ddd':
        case 'dddd':
        case 'e':
        case 'E':
            token = token.substr(0, 1);
            /* falls through */
        case 'gg':
        case 'gggg':
        case 'GG':
        case 'GGGG':
        case 'GGGGG':
            token = token.substr(0, 2);
            if (input) {
                config._w = config._w || {};
                config._w[token] = input;
            }
            break;
        }
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function dateFromConfig(config) {
        var i, date, input = [], currentDate,
            yearToUse, fixYear, w, temp, lang, weekday, week;

        if (config._d) {
            return;
        }

        currentDate = currentDateArray(config);

        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            fixYear = function (val) {
                var intVal = parseInt(val, 10);
                return val ?
                  (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
                  (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
            };

            w = config._w;
            if (w.GG != null || w.W != null || w.E != null) {
                temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
            }
            else {
                lang = getLangDefinition(config._l);
                weekday = w.d != null ?  parseWeekday(w.d, lang) :
                  (w.e != null ?  parseInt(w.e, 10) + lang._week.dow : 0);

                week = parseInt(w.w, 10) || 1;

                //if we're parsing 'd', then the low day numbers may be next week
                if (w.d != null && weekday < lang._week.dow) {
                    week++;
                }

                temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
            }

            config._a[YEAR] = temp.year;
            config._dayOfYear = temp.dayOfYear;
        }

        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];

            if (config._dayOfYear > daysInYear(yearToUse)) {
                config._pf._overflowDayOfYear = true;
            }

            date = makeUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }

        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }

        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }

        // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
        input[HOUR] += toInt((config._tzm || 0) / 60);
        input[MINUTE] += toInt((config._tzm || 0) % 60);

        config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
    }

    function dateFromObject(config) {
        var normalizedInput;

        if (config._d) {
            return;
        }

        normalizedInput = normalizeObjectUnits(config._i);
        config._a = [
            normalizedInput.year,
            normalizedInput.month,
            normalizedInput.day,
            normalizedInput.hour,
            normalizedInput.minute,
            normalizedInput.second,
            normalizedInput.millisecond
        ];

        dateFromConfig(config);
    }

    function currentDateArray(config) {
        var now = new Date();
        if (config._useUTC) {
            return [
                now.getUTCFullYear(),
                now.getUTCMonth(),
                now.getUTCDate()
            ];
        } else {
            return [now.getFullYear(), now.getMonth(), now.getDate()];
        }
    }

    // date from string and format string
    function makeDateFromStringAndFormat(config) {

        config._a = [];
        config._pf.empty = true;

        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var lang = getLangDefinition(config._l),
            string = '' + config._i,
            i, parsedInput, tokens, token, skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;

        tokens = expandFormat(config._f, lang).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    config._pf.unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    config._pf.empty = false;
                }
                else {
                    config._pf.unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            }
            else if (config._strict && !parsedInput) {
                config._pf.unusedTokens.push(token);
            }
        }

        // add remaining unparsed input length to the string
        config._pf.charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            config._pf.unusedInput.push(string);
        }

        // handle am pm
        if (config._isPm && config._a[HOUR] < 12) {
            config._a[HOUR] += 12;
        }
        // if is 12 am, change hours to 0
        if (config._isPm === false && config._a[HOUR] === 12) {
            config._a[HOUR] = 0;
        }

        dateFromConfig(config);
        checkOverflow(config);
    }

    function unescapeFormat(s) {
        return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        });
    }

    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function regexpEscape(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    // date from string and array of format strings
    function makeDateFromStringAndArray(config) {
        var tempConfig,
            bestMoment,

            scoreToBeat,
            i,
            currentScore;

        if (config._f.length === 0) {
            config._pf.invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = extend({}, config);
            tempConfig._pf = defaultParsingFlags();
            tempConfig._f = config._f[i];
            makeDateFromStringAndFormat(tempConfig);

            if (!isValid(tempConfig)) {
                continue;
            }

            // if there is any input that was not parsed add a penalty for that format
            currentScore += tempConfig._pf.charsLeftOver;

            //or tokens
            currentScore += tempConfig._pf.unusedTokens.length * 10;

            tempConfig._pf.score = currentScore;

            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    // date from iso format
    function makeDateFromString(config) {
        var i, l,
            string = config._i,
            match = isoRegex.exec(string);

        if (match) {
            config._pf.iso = true;
            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(string)) {
                    // match[5] should be "T" or undefined
                    config._f = isoDates[i][0] + (match[6] || " ");
                    break;
                }
            }
            for (i = 0, l = isoTimes.length; i < l; i++) {
                if (isoTimes[i][1].exec(string)) {
                    config._f += isoTimes[i][0];
                    break;
                }
            }
            if (string.match(parseTokenTimezone)) {
                config._f += "Z";
            }
            makeDateFromStringAndFormat(config);
        }
        else {
            moment.createFromInputFallback(config);
        }
    }

    function makeDateFromInput(config) {
        var input = config._i,
            matched = aspNetJsonRegex.exec(input);

        if (input === undefined) {
            config._d = new Date();
        } else if (matched) {
            config._d = new Date(+matched[1]);
        } else if (typeof input === 'string') {
            makeDateFromString(config);
        } else if (isArray(input)) {
            config._a = input.slice(0);
            dateFromConfig(config);
        } else if (isDate(input)) {
            config._d = new Date(+input);
        } else if (typeof(input) === 'object') {
            dateFromObject(config);
        } else if (typeof(input) === 'number') {
            // from milliseconds
            config._d = new Date(input);
        } else {
            moment.createFromInputFallback(config);
        }
    }

    function makeDate(y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);

        //the date constructor doesn't accept years < 1970
        if (y < 1970) {
            date.setFullYear(y);
        }
        return date;
    }

    function makeUTCDate(y) {
        var date = new Date(Date.UTC.apply(null, arguments));
        if (y < 1970) {
            date.setUTCFullYear(y);
        }
        return date;
    }

    function parseWeekday(input, language) {
        if (typeof input === 'string') {
            if (!isNaN(input)) {
                input = parseInt(input, 10);
            }
            else {
                input = language.weekdaysParse(input);
                if (typeof input !== 'number') {
                    return null;
                }
            }
        }
        return input;
    }

    /************************************
        Relative Time
    ************************************/


    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
        return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function relativeTime(milliseconds, withoutSuffix, lang) {
        var seconds = round(Math.abs(milliseconds) / 1000),
            minutes = round(seconds / 60),
            hours = round(minutes / 60),
            days = round(hours / 24),
            years = round(days / 365),
            args = seconds < 45 && ['s', seconds] ||
                minutes === 1 && ['m'] ||
                minutes < 45 && ['mm', minutes] ||
                hours === 1 && ['h'] ||
                hours < 22 && ['hh', hours] ||
                days === 1 && ['d'] ||
                days <= 25 && ['dd', days] ||
                days <= 45 && ['M'] ||
                days < 345 && ['MM', round(days / 30)] ||
                years === 1 && ['y'] || ['yy', years];
        args[2] = withoutSuffix;
        args[3] = milliseconds > 0;
        args[4] = lang;
        return substituteTimeAgo.apply({}, args);
    }


    /************************************
        Week of Year
    ************************************/


    // firstDayOfWeek       0 = sun, 6 = sat
    //                      the day of the week that starts the week
    //                      (usually sunday or monday)
    // firstDayOfWeekOfYear 0 = sun, 6 = sat
    //                      the first week is the week that contains the first
    //                      of this day of the week
    //                      (eg. ISO weeks use thursday (4))
    function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
        var end = firstDayOfWeekOfYear - firstDayOfWeek,
            daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
            adjustedMoment;


        if (daysToDayOfWeek > end) {
            daysToDayOfWeek -= 7;
        }

        if (daysToDayOfWeek < end - 7) {
            daysToDayOfWeek += 7;
        }

        adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
        return {
            week: Math.ceil(adjustedMoment.dayOfYear() / 7),
            year: adjustedMoment.year()
        };
    }

    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
        var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;

        weekday = weekday != null ? weekday : firstDayOfWeek;
        daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
        dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;

        return {
            year: dayOfYear > 0 ? year : year - 1,
            dayOfYear: dayOfYear > 0 ?  dayOfYear : daysInYear(year - 1) + dayOfYear
        };
    }

    /************************************
        Top Level Functions
    ************************************/

    function makeMoment(config) {
        var input = config._i,
            format = config._f;

        if (input === null || (format === undefined && input === '')) {
            return moment.invalid({nullInput: true});
        }

        if (typeof input === 'string') {
            config._i = input = getLangDefinition().preparse(input);
        }

        if (moment.isMoment(input)) {
            config = cloneMoment(input);

            config._d = new Date(+input._d);
        } else if (format) {
            if (isArray(format)) {
                makeDateFromStringAndArray(config);
            } else {
                makeDateFromStringAndFormat(config);
            }
        } else {
            makeDateFromInput(config);
        }

        return new Moment(config);
    }

    moment = function (input, format, lang, strict) {
        var c;

        if (typeof(lang) === "boolean") {
            strict = lang;
            lang = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c = {};
        c._isAMomentObject = true;
        c._i = input;
        c._f = format;
        c._l = lang;
        c._strict = strict;
        c._isUTC = false;
        c._pf = defaultParsingFlags();

        return makeMoment(c);
    };

    moment.suppressDeprecationWarnings = false;

    moment.createFromInputFallback = deprecate(
            "moment construction falls back to js Date. This is " +
            "discouraged and will be removed in upcoming major " +
            "release. Please refer to " +
            "https://github.com/moment/moment/issues/1407 for more info.",
            function (config) {
        config._d = new Date(config._i);
    });

    // creating with utc
    moment.utc = function (input, format, lang, strict) {
        var c;

        if (typeof(lang) === "boolean") {
            strict = lang;
            lang = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c = {};
        c._isAMomentObject = true;
        c._useUTC = true;
        c._isUTC = true;
        c._l = lang;
        c._i = input;
        c._f = format;
        c._strict = strict;
        c._pf = defaultParsingFlags();

        return makeMoment(c).utc();
    };

    // creating with unix timestamp (in seconds)
    moment.unix = function (input) {
        return moment(input * 1000);
    };

    // duration
    moment.duration = function (input, key) {
        var duration = input,
            // matching against regexp is expensive, do it on demand
            match = null,
            sign,
            ret,
            parseIso;

        if (moment.isDuration(input)) {
            duration = {
                ms: input._milliseconds,
                d: input._days,
                M: input._months
            };
        } else if (typeof input === 'number') {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
            sign = (match[1] === "-") ? -1 : 1;
            duration = {
                y: 0,
                d: toInt(match[DATE]) * sign,
                h: toInt(match[HOUR]) * sign,
                m: toInt(match[MINUTE]) * sign,
                s: toInt(match[SECOND]) * sign,
                ms: toInt(match[MILLISECOND]) * sign
            };
        } else if (!!(match = isoDurationRegex.exec(input))) {
            sign = (match[1] === "-") ? -1 : 1;
            parseIso = function (inp) {
                // We'd normally use ~~inp for this, but unfortunately it also
                // converts floats to ints.
                // inp may be undefined, so careful calling replace on it.
                var res = inp && parseFloat(inp.replace(',', '.'));
                // apply sign while we're at it
                return (isNaN(res) ? 0 : res) * sign;
            };
            duration = {
                y: parseIso(match[2]),
                M: parseIso(match[3]),
                d: parseIso(match[4]),
                h: parseIso(match[5]),
                m: parseIso(match[6]),
                s: parseIso(match[7]),
                w: parseIso(match[8])
            };
        }

        ret = new Duration(duration);

        if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
            ret._lang = input._lang;
        }

        return ret;
    };

    // version number
    moment.version = VERSION;

    // default format
    moment.defaultFormat = isoFormat;

    // Plugins that add properties should also add the key here (null value),
    // so we can properly clone ourselves.
    moment.momentProperties = momentProperties;

    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    moment.updateOffset = function () {};

    // This function will load languages and then set the global language.  If
    // no arguments are passed in, it will simply return the current global
    // language key.
    moment.lang = function (key, values) {
        var r;
        if (!key) {
            return moment.fn._lang._abbr;
        }
        if (values) {
            loadLang(normalizeLanguage(key), values);
        } else if (values === null) {
            unloadLang(key);
            key = 'en';
        } else if (!languages[key]) {
            getLangDefinition(key);
        }
        r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
        return r._abbr;
    };

    // returns language data
    moment.langData = function (key) {
        if (key && key._lang && key._lang._abbr) {
            key = key._lang._abbr;
        }
        return getLangDefinition(key);
    };

    // compare moment object
    moment.isMoment = function (obj) {
        return obj instanceof Moment ||
            (obj != null &&  obj.hasOwnProperty('_isAMomentObject'));
    };

    // for typechecking Duration objects
    moment.isDuration = function (obj) {
        return obj instanceof Duration;
    };

    for (i = lists.length - 1; i >= 0; --i) {
        makeList(lists[i]);
    }

    moment.normalizeUnits = function (units) {
        return normalizeUnits(units);
    };

    moment.invalid = function (flags) {
        var m = moment.utc(NaN);
        if (flags != null) {
            extend(m._pf, flags);
        }
        else {
            m._pf.userInvalidated = true;
        }

        return m;
    };

    moment.parseZone = function () {
        return moment.apply(null, arguments).parseZone();
    };

    moment.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };

    /************************************
        Moment Prototype
    ************************************/


    extend(moment.fn = Moment.prototype, {

        clone : function () {
            return moment(this);
        },

        valueOf : function () {
            return +this._d + ((this._offset || 0) * 60000);
        },

        unix : function () {
            return Math.floor(+this / 1000);
        },

        toString : function () {
            return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
        },

        toDate : function () {
            return this._offset ? new Date(+this) : this._d;
        },

        toISOString : function () {
            var m = moment(this).utc();
            if (0 < m.year() && m.year() <= 9999) {
                return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            } else {
                return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        },

        toArray : function () {
            var m = this;
            return [
                m.year(),
                m.month(),
                m.date(),
                m.hours(),
                m.minutes(),
                m.seconds(),
                m.milliseconds()
            ];
        },

        isValid : function () {
            return isValid(this);
        },

        isDSTShifted : function () {

            if (this._a) {
                return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
            }

            return false;
        },

        parsingFlags : function () {
            return extend({}, this._pf);
        },

        invalidAt: function () {
            return this._pf.overflow;
        },

        utc : function () {
            return this.zone(0);
        },

        local : function () {
            this.zone(0);
            this._isUTC = false;
            return this;
        },

        format : function (inputString) {
            var output = formatMoment(this, inputString || moment.defaultFormat);
            return this.lang().postformat(output);
        },

        add : function (input, val) {
            var dur;
            // switch args to support add('s', 1) and add(1, 's')
            if (typeof input === 'string') {
                dur = moment.duration(+val, input);
            } else {
                dur = moment.duration(input, val);
            }
            addOrSubtractDurationFromMoment(this, dur, 1);
            return this;
        },

        subtract : function (input, val) {
            var dur;
            // switch args to support subtract('s', 1) and subtract(1, 's')
            if (typeof input === 'string') {
                dur = moment.duration(+val, input);
            } else {
                dur = moment.duration(input, val);
            }
            addOrSubtractDurationFromMoment(this, dur, -1);
            return this;
        },

        diff : function (input, units, asFloat) {
            var that = makeAs(input, this),
                zoneDiff = (this.zone() - that.zone()) * 6e4,
                diff, output;

            units = normalizeUnits(units);

            if (units === 'year' || units === 'month') {
                // average number of days in the months in the given dates
                diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
                // difference in months
                output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
                // adjust by taking difference in days, average number of days
                // and dst in the given months.
                output += ((this - moment(this).startOf('month')) -
                        (that - moment(that).startOf('month'))) / diff;
                // same as above but with zones, to negate all dst
                output -= ((this.zone() - moment(this).startOf('month').zone()) -
                        (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
                if (units === 'year') {
                    output = output / 12;
                }
            } else {
                diff = (this - that);
                output = units === 'second' ? diff / 1e3 : // 1000
                    units === 'minute' ? diff / 6e4 : // 1000 * 60
                    units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
                    units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
                    units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
                    diff;
            }
            return asFloat ? output : absRound(output);
        },

        from : function (time, withoutSuffix) {
            return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
        },

        fromNow : function (withoutSuffix) {
            return this.from(moment(), withoutSuffix);
        },

        calendar : function () {
            // We want to compare the start of today, vs this.
            // Getting start-of-today depends on whether we're zone'd or not.
            var sod = makeAs(moment(), this).startOf('day'),
                diff = this.diff(sod, 'days', true),
                format = diff < -6 ? 'sameElse' :
                    diff < -1 ? 'lastWeek' :
                    diff < 0 ? 'lastDay' :
                    diff < 1 ? 'sameDay' :
                    diff < 2 ? 'nextDay' :
                    diff < 7 ? 'nextWeek' : 'sameElse';
            return this.format(this.lang().calendar(format, this));
        },

        isLeapYear : function () {
            return isLeapYear(this.year());
        },

        isDST : function () {
            return (this.zone() < this.clone().month(0).zone() ||
                this.zone() < this.clone().month(5).zone());
        },

        day : function (input) {
            var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
            if (input != null) {
                input = parseWeekday(input, this.lang());
                return this.add({ d : input - day });
            } else {
                return day;
            }
        },

        month : makeAccessor('Month', true),

        startOf: function (units) {
            units = normalizeUnits(units);
            // the following switch intentionally omits break keywords
            // to utilize falling through the cases.
            switch (units) {
            case 'year':
                this.month(0);
                /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
                /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
                this.hours(0);
                /* falls through */
            case 'hour':
                this.minutes(0);
                /* falls through */
            case 'minute':
                this.seconds(0);
                /* falls through */
            case 'second':
                this.milliseconds(0);
                /* falls through */
            }

            // weeks are a special case
            if (units === 'week') {
                this.weekday(0);
            } else if (units === 'isoWeek') {
                this.isoWeekday(1);
            }

            // quarters are also special
            if (units === 'quarter') {
                this.month(Math.floor(this.month() / 3) * 3);
            }

            return this;
        },

        endOf: function (units) {
            units = normalizeUnits(units);
            return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
        },

        isAfter: function (input, units) {
            units = typeof units !== 'undefined' ? units : 'millisecond';
            return +this.clone().startOf(units) > +moment(input).startOf(units);
        },

        isBefore: function (input, units) {
            units = typeof units !== 'undefined' ? units : 'millisecond';
            return +this.clone().startOf(units) < +moment(input).startOf(units);
        },

        isSame: function (input, units) {
            units = units || 'ms';
            return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
        },

        min: function (other) {
            other = moment.apply(null, arguments);
            return other < this ? this : other;
        },

        max: function (other) {
            other = moment.apply(null, arguments);
            return other > this ? this : other;
        },

        // keepTime = true means only change the timezone, without affecting
        // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
        // It is possible that 5:31:26 doesn't exist int zone +0200, so we
        // adjust the time as needed, to be valid.
        //
        // Keeping the time actually adds/subtracts (one hour)
        // from the actual represented time. That is why we call updateOffset
        // a second time. In case it wants us to change the offset again
        // _changeInProgress == true case, then we have to adjust, because
        // there is no such time in the given timezone.
        zone : function (input, keepTime) {
            var offset = this._offset || 0;
            if (input != null) {
                if (typeof input === "string") {
                    input = timezoneMinutesFromString(input);
                }
                if (Math.abs(input) < 16) {
                    input = input * 60;
                }
                this._offset = input;
                this._isUTC = true;
                if (offset !== input) {
                    if (!keepTime || this._changeInProgress) {
                        addOrSubtractDurationFromMoment(this,
                                moment.duration(offset - input, 'm'), 1, false);
                    } else if (!this._changeInProgress) {
                        this._changeInProgress = true;
                        moment.updateOffset(this, true);
                        this._changeInProgress = null;
                    }
                }
            } else {
                return this._isUTC ? offset : this._d.getTimezoneOffset();
            }
            return this;
        },

        zoneAbbr : function () {
            return this._isUTC ? "UTC" : "";
        },

        zoneName : function () {
            return this._isUTC ? "Coordinated Universal Time" : "";
        },

        parseZone : function () {
            if (this._tzm) {
                this.zone(this._tzm);
            } else if (typeof this._i === 'string') {
                this.zone(this._i);
            }
            return this;
        },

        hasAlignedHourOffset : function (input) {
            if (!input) {
                input = 0;
            }
            else {
                input = moment(input).zone();
            }

            return (this.zone() - input) % 60 === 0;
        },

        daysInMonth : function () {
            return daysInMonth(this.year(), this.month());
        },

        dayOfYear : function (input) {
            var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
            return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
        },

        quarter : function (input) {
            return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
        },

        weekYear : function (input) {
            var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
            return input == null ? year : this.add("y", (input - year));
        },

        isoWeekYear : function (input) {
            var year = weekOfYear(this, 1, 4).year;
            return input == null ? year : this.add("y", (input - year));
        },

        week : function (input) {
            var week = this.lang().week(this);
            return input == null ? week : this.add("d", (input - week) * 7);
        },

        isoWeek : function (input) {
            var week = weekOfYear(this, 1, 4).week;
            return input == null ? week : this.add("d", (input - week) * 7);
        },

        weekday : function (input) {
            var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
            return input == null ? weekday : this.add("d", input - weekday);
        },

        isoWeekday : function (input) {
            // behaves the same as moment#day except
            // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
            // as a setter, sunday should belong to the previous week.
            return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
        },

        isoWeeksInYear : function () {
            return weeksInYear(this.year(), 1, 4);
        },

        weeksInYear : function () {
            var weekInfo = this._lang._week;
            return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
        },

        get : function (units) {
            units = normalizeUnits(units);
            return this[units]();
        },

        set : function (units, value) {
            units = normalizeUnits(units);
            if (typeof this[units] === 'function') {
                this[units](value);
            }
            return this;
        },

        // If passed a language key, it will set the language for this
        // instance.  Otherwise, it will return the language configuration
        // variables for this instance.
        lang : function (key) {
            if (key === undefined) {
                return this._lang;
            } else {
                this._lang = getLangDefinition(key);
                return this;
            }
        }
    });

    function rawMonthSetter(mom, value) {
        var dayOfMonth;

        // TODO: Move this out of here!
        if (typeof value === 'string') {
            value = mom.lang().monthsParse(value);
            // TODO: Another silent failure?
            if (typeof value !== 'number') {
                return mom;
            }
        }

        dayOfMonth = Math.min(mom.date(),
                daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }

    function rawGetter(mom, unit) {
        return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
    }

    function rawSetter(mom, unit, value) {
        if (unit === 'Month') {
            return rawMonthSetter(mom, value);
        } else {
            return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }

    function makeAccessor(unit, keepTime) {
        return function (value) {
            if (value != null) {
                rawSetter(this, unit, value);
                moment.updateOffset(this, keepTime);
                return this;
            } else {
                return rawGetter(this, unit);
            }
        };
    }

    moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
    moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
    moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
    // moment.fn.month is defined separately
    moment.fn.date = makeAccessor('Date', true);
    moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
    moment.fn.year = makeAccessor('FullYear', true);
    moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));

    // add plural methods
    moment.fn.days = moment.fn.day;
    moment.fn.months = moment.fn.month;
    moment.fn.weeks = moment.fn.week;
    moment.fn.isoWeeks = moment.fn.isoWeek;
    moment.fn.quarters = moment.fn.quarter;

    // add aliased format methods
    moment.fn.toJSON = moment.fn.toISOString;

    /************************************
        Duration Prototype
    ************************************/


    extend(moment.duration.fn = Duration.prototype, {

        _bubble : function () {
            var milliseconds = this._milliseconds,
                days = this._days,
                months = this._months,
                data = this._data,
                seconds, minutes, hours, years;

            // The following code bubbles up values, see the tests for
            // examples of what that means.
            data.milliseconds = milliseconds % 1000;

            seconds = absRound(milliseconds / 1000);
            data.seconds = seconds % 60;

            minutes = absRound(seconds / 60);
            data.minutes = minutes % 60;

            hours = absRound(minutes / 60);
            data.hours = hours % 24;

            days += absRound(hours / 24);
            data.days = days % 30;

            months += absRound(days / 30);
            data.months = months % 12;

            years = absRound(months / 12);
            data.years = years;
        },

        weeks : function () {
            return absRound(this.days() / 7);
        },

        valueOf : function () {
            return this._milliseconds +
              this._days * 864e5 +
              (this._months % 12) * 2592e6 +
              toInt(this._months / 12) * 31536e6;
        },

        humanize : function (withSuffix) {
            var difference = +this,
                output = relativeTime(difference, !withSuffix, this.lang());

            if (withSuffix) {
                output = this.lang().pastFuture(difference, output);
            }

            return this.lang().postformat(output);
        },

        add : function (input, val) {
            // supports only 2.0-style add(1, 's') or add(moment)
            var dur = moment.duration(input, val);

            this._milliseconds += dur._milliseconds;
            this._days += dur._days;
            this._months += dur._months;

            this._bubble();

            return this;
        },

        subtract : function (input, val) {
            var dur = moment.duration(input, val);

            this._milliseconds -= dur._milliseconds;
            this._days -= dur._days;
            this._months -= dur._months;

            this._bubble();

            return this;
        },

        get : function (units) {
            units = normalizeUnits(units);
            return this[units.toLowerCase() + 's']();
        },

        as : function (units) {
            units = normalizeUnits(units);
            return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
        },

        lang : moment.fn.lang,

        toIsoString : function () {
            // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
            var years = Math.abs(this.years()),
                months = Math.abs(this.months()),
                days = Math.abs(this.days()),
                hours = Math.abs(this.hours()),
                minutes = Math.abs(this.minutes()),
                seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);

            if (!this.asSeconds()) {
                // this is the same as C#'s (Noda) and python (isodate)...
                // but not other JS (goog.date)
                return 'P0D';
            }

            return (this.asSeconds() < 0 ? '-' : '') +
                'P' +
                (years ? years + 'Y' : '') +
                (months ? months + 'M' : '') +
                (days ? days + 'D' : '') +
                ((hours || minutes || seconds) ? 'T' : '') +
                (hours ? hours + 'H' : '') +
                (minutes ? minutes + 'M' : '') +
                (seconds ? seconds + 'S' : '');
        }
    });

    function makeDurationGetter(name) {
        moment.duration.fn[name] = function () {
            return this._data[name];
        };
    }

    function makeDurationAsGetter(name, factor) {
        moment.duration.fn['as' + name] = function () {
            return +this / factor;
        };
    }

    for (i in unitMillisecondFactors) {
        if (unitMillisecondFactors.hasOwnProperty(i)) {
            makeDurationAsGetter(i, unitMillisecondFactors[i]);
            makeDurationGetter(i.toLowerCase());
        }
    }

    makeDurationAsGetter('Weeks', 6048e5);
    moment.duration.fn.asMonths = function () {
        return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
    };


    /************************************
        Default Lang
    ************************************/


    // Set default language, other languages will inherit from English.
    moment.lang('en', {
        ordinal : function (number) {
            var b = number % 10,
                output = (toInt(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    /* EMBED_LANGUAGES */

    /************************************
        Exposing Moment
    ************************************/

    function makeGlobal(shouldDeprecate) {
        /*global ender:false */
        if (typeof ender !== 'undefined') {
            return;
        }
        oldGlobalMoment = globalScope.moment;
        if (shouldDeprecate) {
            globalScope.moment = deprecate(
                    "Accessing Moment through the global scope is " +
                    "deprecated, and will be removed in an upcoming " +
                    "release.",
                    moment);
        } else {
            globalScope.moment = moment;
        }
    }

    // CommonJS module is defined
    if (hasModule) {
        module.exports = moment;
    } else if (typeof define === "function" && define.amd) {
        define("moment", function (require, exports, module) {
            if (module.config && module.config() && module.config().noGlobal === true) {
                // release the global variable
                globalScope.moment = oldGlobalMoment;
            }

            return moment;
        });
        makeGlobal(true);
    } else {
        makeGlobal();
    }
}).call(this);
;
/*!
  hey, [be]Lazy.js - v1.8.2 - 2016.10.25
  A fast, small and dependency free lazy load script (https://github.com/dinbror/blazy)
  (c) Bjoern Klinggaard - @bklinggaard - http://dinbror.dk/blazy
*/
  (function(q,m){"function"===typeof define&&define.amd?define(m):"object"===typeof exports?module.exports=m():q.Blazy=m()})(this,function(){function q(b){var c=b._util;c.elements=E(b.options);c.count=c.elements.length;c.destroyed&&(c.destroyed=!1,b.options.container&&l(b.options.container,function(a){n(a,"scroll",c.validateT)}),n(window,"resize",c.saveViewportOffsetT),n(window,"resize",c.validateT),n(window,"scroll",c.validateT));m(b)}function m(b){for(var c=b._util,a=0;a<c.count;a++){var d=c.elements[a],e;a:{var g=d;e=b.options;var p=g.getBoundingClientRect();if(e.container&&y&&(g=g.closest(e.containerClass))){g=g.getBoundingClientRect();e=r(g,f)?r(p,{top:g.top-e.offset,right:g.right+e.offset,bottom:g.bottom+e.offset,left:g.left-e.offset}):!1;break a}e=r(p,f)}if(e||t(d,b.options.successClass))b.load(d),c.elements.splice(a,1),c.count--,a--}0===c.count&&b.destroy()}function r(b,c){return b.right>=c.left&&b.bottom>=c.top&&b.left<=c.right&&b.top<=c.bottom}function z(b,c,a){if(!t(b,a.successClass)&&(c||a.loadInvisible||0<b.offsetWidth&&0<b.offsetHeight))if(c=b.getAttribute(u)||b.getAttribute(a.src)){c=c.split(a.separator);var d=c[A&&1<c.length?1:0],e=b.getAttribute(a.srcset),g="img"===b.nodeName.toLowerCase(),p=(c=b.parentNode)&&"picture"===c.nodeName.toLowerCase();if(g||void 0===b.src){var h=new Image,w=function(){a.error&&a.error(b,"invalid");v(b,a.errorClass);k(h,"error",w);k(h,"load",f)},f=function(){g?p||B(b,d,e):b.style.backgroundImage='url("'+d+'")';x(b,a);k(h,"load",f);k(h,"error",w)};p&&(h=b,l(c.getElementsByTagName("source"),function(b){var c=a.srcset,e=b.getAttribute(c);e&&(b.setAttribute("srcset",e),b.removeAttribute(c))}));n(h,"error",w);n(h,"load",f);B(h,d,e)}else b.src=d,x(b,a)}else"video"===b.nodeName.toLowerCase()?(l(b.getElementsByTagName("source"),function(b){var c=a.src,e=b.getAttribute(c);e&&(b.setAttribute("src",e),b.removeAttribute(c))}),b.load(),x(b,a)):(a.error&&a.error(b,"missing"),v(b,a.errorClass))}function x(b,c){v(b,c.successClass);c.success&&c.success(b);b.removeAttribute(c.src);b.removeAttribute(c.srcset);l(c.breakpoints,function(a){b.removeAttribute(a.src)})}function B(b,c,a){a&&b.setAttribute("srcset",a);b.src=c}function t(b,c){return-1!==(" "+b.className+" ").indexOf(" "+c+" ")}function v(b,c){t(b,c)||(b.className+=" "+c)}function E(b){var c=[];b=b.root.querySelectorAll(b.selector);for(var a=b.length;a--;c.unshift(b[a]));return c}function C(b){f.bottom=(window.innerHeight||document.documentElement.clientHeight)+b;f.right=(window.innerWidth||document.documentElement.clientWidth)+b}function n(b,c,a){b.attachEvent?b.attachEvent&&b.attachEvent("on"+c,a):b.addEventListener(c,a,{capture:!1,passive:!0})}function k(b,c,a){b.detachEvent?b.detachEvent&&b.detachEvent("on"+c,a):b.removeEventListener(c,a,{capture:!1,passive:!0})}function l(b,c){if(b&&c)for(var a=b.length,d=0;d<a&&!1!==c(b[d],d);d++);}function D(b,c,a){var d=0;return function(){var e=+new Date;e-d<c||(d=e,b.apply(a,arguments))}}var u,f,A,y;return function(b){if(!document.querySelectorAll){var c=document.createStyleSheet();document.querySelectorAll=function(a,b,d,h,f){f=document.all;b=[];a=a.replace(/\[for\b/gi,"[htmlFor").split(",");for(d=a.length;d--;){c.addRule(a[d],"k:v");for(h=f.length;h--;)f[h].currentStyle.k&&b.push(f[h]);c.removeRule(0)}return b}}var a=this,d=a._util={};d.elements=[];d.destroyed=!0;a.options=b||{};a.options.error=a.options.error||!1;a.options.offset=a.options.offset||100;a.options.root=a.options.root||document;a.options.success=a.options.success||!1;a.options.selector=a.options.selector||".b-lazy";a.options.separator=a.options.separator||"|";a.options.containerClass=a.options.container;a.options.container=a.options.containerClass?document.querySelectorAll(a.options.containerClass):!1;a.options.errorClass=a.options.errorClass||"b-error";a.options.breakpoints=a.options.breakpoints||!1;a.options.loadInvisible=a.options.loadInvisible||!1;a.options.successClass=a.options.successClass||"b-loaded";a.options.validateDelay=a.options.validateDelay||25;a.options.saveViewportOffsetDelay=a.options.saveViewportOffsetDelay||50;a.options.srcset=a.options.srcset||"data-srcset";a.options.src=u=a.options.src||"data-src";y=Element.prototype.closest;A=1<window.devicePixelRatio;f={};f.top=0-a.options.offset;f.left=0-a.options.offset;a.revalidate=function(){q(a)};a.load=function(a,b){var c=this.options;void 0===a.length?z(a,b,c):l(a,function(a){z(a,b,c)})};a.destroy=function(){var a=this._util;this.options.container&&l(this.options.container,function(b){k(b,"scroll",a.validateT)});k(window,"scroll",a.validateT);k(window,"resize",a.validateT);k(window,"resize",a.saveViewportOffsetT);a.count=0;a.elements.length=0;a.destroyed=!0};d.validateT=D(function(){m(a)},a.options.validateDelay,a);d.saveViewportOffsetT=D(function(){C(a.options.offset)},a.options.saveViewportOffsetDelay,a);C(a.options.offset);l(a.options.breakpoints,function(a){if(a.width>=window.screen.width)return u=a.src,!1});setTimeout(function(){q(a)})}});;
(function () {
    "use strict";
    var Utils = OA.utils;
    OA.utils.ajaxHelpers = {
        ajaxDefault: function (options) {
            var base, dat;
            // Options
            // defaultURL, url, data, type, dataType, contentType, stringify
            if (!_.isEmpty(options)) {
                options.stringify = !!options.stringify;
                base = !!options.defaultURL ? '' : OA.baseUrl;
                dat = (!options.type) ? options.data : Utils.objectHelpers.jsonStringify(options.data);
            }

            //IE 9 doesn't support cross-domain service calls. Redirect all the calls to apiUrlOldBrowserSupport url instead.
            if (Utils.browser.isIE9()) {
                base = OAApp.appsettings.apiUrlOldBrowserSupport;
            }
            if (options.url.indexOf("?") > -1) {
                options.url = options.url + "&ts=ts_" + new Date().getTime();
            }
            else {
                options.url = options.url + "?ts=ts_" + new Date().getTime();
            }

            return $.ajax({
                url: base + options.url,
                data: dat,
                method: options.type || "GET",
                headers: options.headers,
                dataType: options.dataType || "json",
                contentType: options.contentType || 'application/json',
                async: !(options.sync === true)
            }).fail(function (xhr, status, error) {
                if (xhr.status === 401) {

                    if (!options || !options.authOptional)
                        if (options.url.indexOf("/auth") == -1) {
                            Utils.RESTHelpers.statusCodes[xhr.status]();
                        }
                }
            });
        },
        closeJQMLoader: function () {
            setTimeout(function () {
                $.mobile.loading('hide');
            }, 500);
        },
        getError: function (xhr) {
            if (!!xhr.responseJSON && !!xhr.responseJSON.responseStatus)
                return xhr.responseJSON.responseStatus.message;
            return xhr.statusText;
        },
    };
    OA.utils.RESTHelpers = {
        statusCodes: {
            401: function () {
                var loc = window.location.href,
                    authCookie = OA.cookie.ManageCookieValue('auth');
                if (_.isEmpty(authCookie))
                    OA.cookie.RemoveCookieValue('auth');
                else {
                    authCookie.loggedIn = false;
                    OA.cookie.ManageCookieValue('auth', authCookie, undefined, OAApp.appsettings.OATrackingCookieDomain);
                }
                OA.cookie.ManageCookieValue('redirect', loc);
                $.mobile.changePage(OA.paths.signIn.main);
                window.location.href = OA.paths.signIn.main;
                if (window.location.href.indexOf('/sign-in') < 0) {
                    window.location.href = '../' + OA.paths.signIn.main;
                }
            }
        }
    };

    OA.utils.Logging = {
        SaveCookie: function (obj) {
            try {
                OA.cookie.ManageCookieValue('Logging.BuyPackage', JSON.stringify(obj));
            }
            catch (err) {
            }
        },
        Push: function (obj) {
            try {
                var saveData = JSON.parse(OA.cookie.ManageCookieValue('Logging.BuyPackage'));
                var currentDate = new Date();
                var pushData =
                {
                    RequestTime: saveData.RequestTime,
                    CustID: obj.CustID,
                    TransactionID: obj.TransactionID,
                    ResponseTime: currentDate,
                    FunnelID: obj.FunnelID,
                };

                OA.services.TransactionEventPerformanceLog(pushData);
                OA.cookie.RemoveCookieValue('Logging.BuyPackage');
                return;
            }
            catch (err) { }
        }
    };

    OA.utils.objectHelpers = {
        jsonStringify: function (data) {
            if (_.isEmpty(data)) {
                return undefined;
            }
            return JSON.stringify(data);
        }
    };

    OA.utils.stringHelpers = {
        getQueryString: function () {
            var qs_array = [],
                hash;
            var q = document.URL.split('?')[1];
            if (q != undefined) {
                q = q.replace('#', '').split('&');
                for (var i = 0; i < q.length; i++) {
                    hash = q[i].split('=');
                    qs_array.push(hash[1]);
                    qs_array[hash[0]] = hash[1];
                }
            }
            return qs_array;
        },
        getParameterByName: function (name) {
            var results = null;
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");

            if (location.search != '') {
                results = regex.exec(location.search);
            }
            else if (location.href.indexOf("?") > 0) {
                // location.search is empty, but a query string exists
                // This issue occurs on Chrome for iOS
                results = regex.exec(location.href.substring(location.href.indexOf("?")));
            }

            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        },
        parsePhoneNumber: function (phone) {
            var szPhone = typeof phone === 'number' ? phone.toString() : phone;
            if (szPhone && szPhone.length === 10) {
                return szPhone.substring(0, 3).concat(".", szPhone.substring(3, 6), ".", szPhone.substring(6, 10));
            }
            return szPhone;
        },
        formatCurrency: function (value) {
            if (isNaN(value)) {
                return;
            }
            if (value < 0) {
                return "-$" + Math.abs(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
            } else {
                return "$" + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
            }
        },
        formatDollarAmount: function (value) {
            if (isNaN(value)) {
                return;
            }
            return "$" + Math.abs(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
        },
        formatKarma: function (value) {
            if (isNaN(value)) {
                return;
            }
            return numeral(value).format('0,0');
        },
        formatKarmaPts: function (value) {
            if (isNaN(value)) {
                return;
            }
            return numeral(value).format('0,0') + ' pts';
        },
        base64Encode: function (str) {
            var result = '';
            if (window.btoa) {
                result = btoa(unescape(encodeURIComponent(str)));
            }
            else {
                result = $.base64.btoa(unescape(encodeURIComponent(str)));
            }
            return result;
        },
        getMasPhone: function () {
            var phoneNumber = OA.utils.stringHelpers.parsePhoneNumber(OA.cookie.ManageCookieValue('MASPhoneNumber'));
            if (!phoneNumber) {
                if (OA.ctm.ctmPhoneNumber != '')
                    phoneNumber = OA.utils.stringHelpers.parsePhoneNumber(OA.ctm.ctmPhoneNumber);
                else
                    phoneNumber = OA.utils.stringHelpers.parsePhoneNumber(OAApp.appsettings.defaultCTMPhoneNumber);
            }
            return phoneNumber;
        },
        getOriginalPhoneNumber: function (phone) {
            return phone.replace('.', '');
        }
    };

    OA.utils.UpdateReadingCount = function () {
        var auth = OA.cookie.ManageCookieValue('auth'),
            authToken = !_.isEmpty(auth) ? auth.authToken : undefined,
            custId = !_.isEmpty(auth) ? auth.custId : undefined,
            visitTimeCookie = OA.cookie.ManageCookieValue('ReadingVisitTime'),
            visitTime = !_.isEmpty(visitTimeCookie) ? visitTimeCookie : null;
        if (auth) {
            OA.services.getCustomerReadingCount({
                CustId: custId,
                LastVisitTime: new Date().toDateString()
            }, {
                    "Authorization": authToken
                }).done(function (res) {
                    if (parseInt(res) > 0) {
                        $('[data-role="header"]').find('.header-my-Readings').find('.circle-count').html(res);

                        if (window.location.href.indexOf('/my-account/readings') < 0) {
                            $('[data-role="header"]').find('.header-my-Readings').find('.circle-count').show();
                        } else {
                            $('[data-role="header"]').find('.header-my-Readings').find('.circle-count').hide();
                        }
                        $("#upcoming-reading-count").text(res);
                        $(".my-account-inner-div #upcoming-reading-count").text(res);
                    } else {
                        $('[data-role="header"]').find('.header-my-Readings').find('.circle-count').hide();
                        $("#upcoming-reading-count").text(0);
                        $(".my-account-inner-div #upcoming-reading-count").text(0);
                    }
                    $("#DesktopHeader .upcoming-readings a").attr("href", OAApp.appsettings.desktopSiteUrl + "my-account/readings ");
                }).fail(function (err) {
                });
        }
    }
    OA.utils.page = {
        getCopyrightText: function () {
            var element = $(".copyrighttext"),
                currDate = new Date(),
                currYear = currDate.getFullYear();

            if (element.length > 0) {
                element.empty().append("<p>&copy; 2002-" + currYear + " Outlook Amusements, Inc. All Rights Reserved.<br />For entertainment purposes only. Must be 18 years or older.</p>");
            }
        },
    };
    OA.utils.device = {
        Android: function () {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function () {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function () {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function () {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function () {
            return navigator.userAgent.match(/IEMobile/i);
        },
        iPad: function () {
            return navigator.userAgent.match(/iPad/i);
        },
        iPod: function () {
            return navigator.userAgent.match(/iPod/i);
        },
        any: function () {
            //return window.browserInfo.device.isMobile;
            return (window.innerWidth <= OAApp.appsettings.MobileResolution);
        },
        getAllDevice: function () {
            var device = new Object();
            device.Android = OA.utils.device.Android() != null ? OA.utils.device.Android() : false;
            device.BlackBerry = OA.utils.device.BlackBerry() != null ? OA.utils.device.BlackBerry() : false;
            device.iOS = OA.utils.device.iOS() != null ? OA.utils.device.iOS() : false;
            device.Opera = OA.utils.device.Opera() != null ? OA.utils.device.Opera() : false;
            device.Windows = OA.utils.device.Windows() != null ? OA.utils.device.Windows() : false;
            device.iPad = OA.utils.device.iPad() != null ? OA.utils.device.iPad() : false;;
            device.iPod = OA.utils.device.iPod() != null ? OA.utils.device.iPod() : false;
            device.any = OA.utils.device.any() != null ? OA.utils.device.any() : false;
            return device;
        },
        deviceType: function () {
            return (window.innerWidth <= OAApp.appsettings.MobileResolution ? "mobile" : "desktop");
        }
    };

    OA.utils.facebook = {
        init: function () {
            var _fbq = window._fbq || (window._fbq = []);
            if (!_fbq.loaded) {
                var fbds = document.createElement('script');
                fbds.async = true;
                fbds.src = '//connect.facebook.net/en_US/fbds.js';
                var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(fbds, s);
                _fbq.loaded = true;
            }
        },
        trackPurchase: function (orderTotal) {
            if (orderTotal != null) {
                setTimeout(function () {
                    //fbq('track', 'Purchase', { value: orderTotal.toFixed(2).toString(), currency: 'USD' });
                    //fbq('track', 'CompleteRegistration');
                    window._fbq = window._fbq || [];
                    window._fbq.push(['track', 'Purchase', { value: orderTotal.toFixed(2).toString(), currency: 'USD' }]);
                    window._fbq.push(['track', 'CompleteRegistration']);
                }, 5000);

                console.log('Facebook Tag pixel - EventName: Purchase (value=' + orderTotal.toFixed(2).toString() + ')');
                console.log('Facebook Tag pixel - EventName: CompleteRegistration');
            }
        },
    };
    OA.utils.browser = {
        isMSIE: function () {
            var myNav = navigator.userAgent.toLowerCase();
            return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
        },
        isIE: function () {
            var myNav = window.navigator.userAgent;
            var msie = myNav.indexOf("MSIE ");
            if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))
                return true
            else
                return false;
        },
        isIE9: function () {
            return (Utils.browser.isMSIE() && Utils.browser.isMSIE() == 9);
        },
        isIOS8: function () {
            var deviceAgent = navigator.userAgent.toLowerCase();
            return /(iphone|ipod|ipad).* os 8_/.test(deviceAgent);
        },
        isSafari: function () {
            return (/Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor));
        },
        isFirefox: function () {
            return /firefox/.test(navigator.userAgent.toLowerCase());
        },
        isChrome: function () {
            return /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
        },
        GetWindowWidth: function () {
            return window.innerWidth;
        },
        isEdge: function () {
            var ua = navigator.userAgent.toLowerCase();
            return ua.indexOf('edge') >= 0;
        },
        GetAllBrowser: function () {
            var browser = new Object();
            browser.IsMSIE = OA.utils.browser.isMSIE();
            browser.IsIE = OA.utils.browser.isIE();
            browser.IsIE9 = OA.utils.browser.isIE9();
            browser.IsIOS8 = OA.utils.browser.isIOS8();
            browser.IsSafari = OA.utils.browser.isSafari();
            browser.IsFirefox = OA.utils.browser.isFirefox();
            browser.IsChrome = OA.utils.browser.isChrome();
            browser.isEdge = OA.utils.browser.isEdge();
            return browser;
        }
    };
    OA.utils.enum = {
        NCCustomerGroupType: {
            NewCustomerLead: 16,
            FreeLead15: -15,
            FreeLead11: -11,
            FreeLead14: -14,
            FreeLead17: -17,
            FreeLead12: -12,
            FreeLead16: -16,
            FreeLead13: -13,
            DiscountRate: 33
        },
        FacebookLoginId: {
            Success: 1,
            Failed: 2,
            AccessDeny: 3,
            AccessDenyEmail: 4,
            AccessDenyDOB: 5,
            FacebookLogin: 6,
            IncorrectPassword: 7,
            EmailDoesNotExistsInDB: 8,
            LoginMismatch: 9
        },
        PointsActivity:
        {
            RedeemPoints : 27,
            CallbackQExtention : 41,
            SeventhSpot : 43,
            FreeReading : 42
        }
    };
    OA.utils.tooltips = {
        showTooltip: function ($el, txt, placement) {
            if (!$el || !$el.length)
                return;
            var $tooltip = $el.next();
            if ($tooltip.length && $tooltip.hasClass('tooltip')) {
                if ($tooltip.text() == txt)
                    return;
                $el.tooltip('destroy');
            }
            $el.tooltip({ "placement": placement, "trigger": "focus", "title": txt }).tooltip('show');
        },
        hideTooltip: function ($el) {
            if (!$el || !$el.length)
                return;
            if ($el.next().hasClass('tooltip'))
                $el.tooltip('destroy');
        },
        showDesktopTooltip: function ($el, txt) {
            if (!$el || !$el.length)
                return;
            var $tooltip = $el.next();
            if ($tooltip.length && $tooltip.hasClass('tooltip')) {
                if ($tooltip.text() == txt)
                    return;
                $el.tooltip('destroy');
            }
            $el.tooltip({ "placement": "top", "trigger": "focus", "title": txt }).tooltip('show');
        },
        hideDesktopTooltip: function ($el) {
            if (!$el || !$el.length)
                return;
            if ($el.next().hasClass('tooltip'))
                $el.tooltip('destroy');
        },
    };
    OA.utils.purchases = {
        fillOffersDictionary: function (duration) {
            var basePrice = "$100", offerPrice = "$20", saveAmount = "$80";
            var objOffers = {};
            var offersDictionary = {};
            objOffers.packageName = "Popular";
            objOffers.packageType = "1";
            objOffers.packageBasePrice = basePrice;
            objOffers.packageOfferPrice = offerPrice;
            objOffers.saveAmount = saveAmount;
            objOffers.duration = duration;
            offersDictionary["1"] = objOffers;
            if (duration == 10) {
                basePrice = "$65";
                offerPrice = "$20";
                saveAmount = "$45";
            } else if (duration == 20) {
                basePrice = "$130";
                offerPrice = "$40";
                saveAmount = "$90";
            } else if (duration == 30) {
                basePrice = "$195";
                offerPrice = "$60";
                saveAmount = "$135";
            }
            var objOffers = {};
            objOffers.packageName = "Preferred";
            objOffers.packageType = "2";
            objOffers.packageBasePrice = basePrice;
            objOffers.packageOfferPrice = offerPrice;
            objOffers.saveAmount = saveAmount;
            objOffers.duration = duration;
            offersDictionary["2"] = objOffers;
            if (duration == 10) {
                basePrice = "$85";
                offerPrice = "$40";
                saveAmount = "$45";
            } else if (duration == 20) {
                basePrice = "$170";
                offerPrice = "$80";
                saveAmount = "$90";
            } else if (duration == 30) {
                basePrice = "$255";
                offerPrice = "$120";
                saveAmount = "$135";
            }
            var objOffers = {};
            objOffers.packageName = "Premium";
            objOffers.packageType = "3";
            objOffers.packageBasePrice = basePrice;
            objOffers.packageOfferPrice = offerPrice;
            objOffers.saveAmount = saveAmount;
            objOffers.duration = duration;
            offersDictionary["3"] = objOffers;
            return offersDictionary;
        },
        fillFiveFreeOffersDictionary: function (duration) {
            var basePrice = "$20", offerPrice = "$0", saveAmount = "$20";
            var objOffers = {};
            var offersDictionary = {};
            objOffers.packageName = "Promoted";
            objOffers.packageType = "0";
            objOffers.packageBasePrice = basePrice;
            objOffers.packageOfferPrice = offerPrice;
            objOffers.saveAmount = saveAmount;
            objOffers.duration = "5";
            offersDictionary["1"] = objOffers;
            if (duration == 5) {
                duration = 20;
            }
            if (duration == 10) {
                basePrice = "$50";
                offerPrice = "$10";
                saveAmount = "$40";
            } else if (duration == 20) {
                basePrice = "$100";
                offerPrice = "$20";
                saveAmount = "$80";
            } else if (duration == 30) {
                basePrice = "$150";
                offerPrice = "$30";
                saveAmount = "$120";
            }
            var objOffers = {};
            objOffers.packageName = "Popular";
            objOffers.packageType = "1";
            objOffers.packageBasePrice = basePrice;
            objOffers.packageOfferPrice = offerPrice;
            objOffers.saveAmount = saveAmount;
            objOffers.duration = duration;
            offersDictionary["2"] = objOffers;
            if (duration == 10) {
                basePrice = "$65";
                offerPrice = "$20";
                saveAmount = "$45";
            } else if (duration == 20) {
                basePrice = "$130";
                offerPrice = "$40";
                saveAmount = "$90";
            } else if (duration == 30) {
                basePrice = "$195";
                offerPrice = "$60";
                saveAmount = "$135";
            }
            var objOffers = {};
            objOffers.packageName = "Preferred";
            objOffers.packageType = "2";
            objOffers.packageBasePrice = basePrice;
            objOffers.packageOfferPrice = offerPrice;
            objOffers.saveAmount = saveAmount;
            objOffers.duration = duration;
            offersDictionary["3"] = objOffers;
            return offersDictionary;
        }
    }
    OA.utils.leadCustomer = {
        checkCustomerCreditCardData: function (popupID) {
            var authCookie = OA.cookie.ManageCookieValue('auth');
            if (authCookie) {
                var custGrp = authCookie.custGroup;
                OA.utils.leadCustomer.getCreditCardData(authCookie, custGrp, popupID);
            }
        },
        createAskInfoCookie: function (offerDict, data) {
            var info = {
                firstName: data.firstName,
                lastName: data.lastName,
                email: data.userEmail,
                dob: data.userDob,
                password: '',
                sendFreeHoroAndNewsLetter: '',
                offerDuration: '',
                cardHolderName: '',
                cardNumber: '',
                expMonth: '',
                expYear: '',
                cvv: '',
                cardType: '',
                billingCountry: '',
                billingCountryName: '',
                zipCode: '',
                state: '',
                stateRegion: '',
                city: '',
                address1: '',
                address2: '',
                phoneCountry: '',
                phoneNumber: '',
                masId: '',
                custId: data.custId,
                callbackId: '',
                extId: '',
                offerId: '',
                priceId: '',
                transactionId: '',
                transactionAmount: '',
                statusCode: '',
                errorMessage: '',
                subscriptionId: '',
                package: offerDict["1"],
                questionText: ''
            };
            if (data.custGroup == OA.utils.enum.NCCustomerGroupType.FreeLead17) {
                OA.cookie.RemoveCookieValue('askAccountInfo');
                OA.cookie.ManageCookieValue('FiveFreeAccountInfo', info);
            }
            else {
                OA.cookie.RemoveCookieValue('FiveFreeAccountInfo');
                OA.cookie.ManageCookieValue('askAccountInfo', info);
            }
        },
        getCreditCardData: function (authCookie, custGrp, popupID) {
            OA.services.getCustomerCreditCards(authCookie.custId, {
                "Authorization": authCookie.authToken
            }).done(function (ccData) {

                if (custGrp == OA.utils.enum.NCCustomerGroupType.NewCustomerLead) {
                    OA.utils.leadCustomer.createAskInfoCookie(OA.utils.purchases.fillOffersDictionary('20'), authCookie);
                    if (popupID != undefined) {
                        window.location.href = "../" + OA.paths.askNcCheckout.offers + "?nc=1";
                    }
                    else {
                        window.location.reload();
                    }
                }
                else if (custGrp == OA.utils.enum.NCCustomerGroupType.FreeLead17
                    || custGrp == OA.utils.enum.NCCustomerGroupType.FreeLead16
                    || custGrp == OA.utils.enum.NCCustomerGroupType.FreeLead15
                    || custGrp == OA.utils.enum.NCCustomerGroupType.FreeLead14
                    || custGrp == OA.utils.enum.NCCustomerGroupType.FreeLead13
                    || custGrp == OA.utils.enum.NCCustomerGroupType.FreeLead11) {
                    OA.utils.leadCustomer.createAskInfoCookie(OA.utils.purchases.fillFiveFreeOffersDictionary('5'), authCookie);
                    // window.location.href = "../" + OA.paths.fiveFreeCheckout.offers + "?nc=1";
                    if (popupID != undefined) {
                        window.location.href = "../" + OA.paths.askNcCheckout.offers + "?nc=1";
                    }
                    else {
                        window.location.reload();
                    }
                }
                else if (custGrp < 0) {
                    if (window.location.href.indexOf("/buy-package") > 0) {
                        $(popupID).show();
                        $(".buy-offer-package .page-wrap").hide();
                    }
                    else if (window.location.href.indexOf("/purchase-reading") > 0) {
                        $(popupID).show();
                        $(".purchase-reading .page-wrap").hide();
                    }
                    else if (window.location.href.indexOf("schedule-appointment") > 0) {
                        $(popupID).show();
                        $(".schedule-appointment .page-wrap").hide();
                    }
                    else {
                        var redirectURL = OA.cookie.ManageCookieValue('redirect');
                        if (redirectURL != null && redirectURL != "" && redirectURL != undefined) {
                            window.location.href = redirectURL;
                        } else {
                            window.location.reload();
                        }
                    }
                }
            }).fail(function (error) {
                
            });
        }
    };
    OA.utils.tracking = {
        sendSearchToGA: function (searchText) {
            dataLayer.push({ 'event': 'OAGASearch', 'url': window.location.pathname, 'searchText': searchText });
        }
    };

    OA.utils.OAGA = {
        getGAClientID: function () {
            var clientID = OA.cookie.ManageCookieValue('OAGAClientId');
            if (clientID != undefined && clientID != null && clientID != "") {
                console.log("clientID : " + clientID);
                return clientID;
            }
            else {
                var ga = OA.cookie.GetRawCookieValue('_ga');
                if (ga != undefined && ga != "") {
                    var gaArray = ga.split('.');
                    if (gaArray.length > 0) {
                        clientID = gaArray[gaArray.length - 2] + "." + gaArray[gaArray.length - 1];
                    }
                }
            }
            return clientID;
        }
    };

    OA.utils.timeHelpers = {
        getTimezoneName: function () {
            var tz = jstz.determine(); // Determines the time zone of the browser client
            return tz.name();
        },
        getMonthDigitsArr: function () {
            return ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
        },
        getRelevantCreditCardYears: function () {
            var i, ccYrs = [], currentYr;
            currentYr = parseInt(moment().format('YYYY'), 10);
            for (i = 0; i < 21; i += 1) {
                ccYrs.push(currentYr + i);
            }
            return ccYrs;
        },
        populateExpYearDropdown: function (dd) {
            try {
                var ccYrs = this.getRelevantCreditCardYears();
                $.each(ccYrs, function (key, value) {
                    dd.append($('<option></option>').val(value).text(value));
                });
                dd.selectmenu("refresh");
            } catch (e) {
            }
        },
        getFriendlyDateTime: function (dd) {
            var d = moment(moment(dd).format("MM-DD-YYYY"));
            var today = moment(moment().format("MM-DD-YYYY"));
            var t = moment(dd).format("h:mm a");

            if (d.isSame(today))
                return t;
            else if (d.isSame(today.subtract(1, 'days')))
                return "Yesterday";
            else
                return d.format("M/D/YYYY");
        }
    };

    OA.utils.talkButtonHelper = {
        clickedCustId: '',
        clickedPsychicId: '',
        clickedTimestamp: 0,
        offersDictionary: OA.utils.purchases.fillOffersDictionary('20'),
        reservationRequested: false,
        talkWithPsychics: function (e) {
            $.mobile.loading("show");
            var extId = e.target.getAttribute("data-extid"),
                name = e.target.getAttribute("data-name"),
                auth = OA.cookie.ManageCookieValue('auth'),
                talkToPsychic = e.target.getAttribute("data-talk") === 'true',
                custId = '',
                userInQueue = e.target.getAttribute("data-inqueue"),
                prtappenabled = e.target.getAttribute("data-prtappenabled"),
                btnText = e.target.innerText.toLowerCase(),
                self = this;
            
            OA.cookie.ManageCookieValue("CTAType", btnText);


            e.preventDefault();
            e.stopPropagation();

            // only 1 talk click permitted at once
            if (self.reservationRequested === false && OA.chatCommon.chatWindow === null) {
                self.reservationRequested = true;
            }
            else if (self.reservationRequested === true || OA.chatCommon.chatWindow !== null) {
                return;
            }

            if (auth != undefined && auth.customerPhoneNumber == "" && window.innerWidth <= 740) {
                OA.utils.callback.initialize($('#addNewCallback'), e);
            }
            else {
                OA.utils.talkButtonHelper.talkWithPsychicsClickHandler(e, extId, name, talkToPsychic, userInQueue, prtappenabled);
                }
        },
        getTimeSlots: function (scheduleList, extId, psychicName) {
            var formattedDate = moment().format("YYYY-MM-DD");

            for (var i = 0; i < scheduleList.availableScheduleSlots.length; i++) {
                var item = scheduleList.availableScheduleSlots[i];
                var date = moment.utc(scheduleList.availableScheduleSlots[i].slotTimeString).local().format("YYYY-MM-DD");

                if (date == formattedDate) {
                    if (moment.utc(scheduleList.availableScheduleSlots[i].slotTimeString) >= moment.utc()) {
                        var selectedSlot = item.slotTimeString;
                        var selectedDay = formattedDate;
                        var fromDate = formattedDate;
                        var toDate = formattedDate;
                        var appType = 'req';
                        var duration = selectedSlot;

                        switch (selectedSlot.toString()) {
                            case 'M':
                                fromDate.setHours(4);
                                toDate.setHours(11, 59);
                                break;
                            case 'A':
                                fromDate.setHours(12);
                                toDate.setHours(18, 59);
                                break;
                            case 'N':
                                fromDate.setHours(19);
                                toDate.setDate(fromDate.getDate() + 1);
                                toDate.setHours(3, 59);
                                break;
                            case '-1':
                                duration = 'Anytime';
                                fromDate = new Date();
                                toDate.setDate(fromDate.getDate() + 1);
                                break;
                            case '1':
                                fromDate = new Date();
                                toDate = new Date().setTime(fromDate.getTime() + (1 * 60 * 60 * 1000))
                                break;
                            case '4':
                                fromDate = new Date();
                                toDate = new Date().setTime(fromDate.getTime() + (4 * 60 * 60 * 1000))
                                break;
                            default:
                                appType = 'app';
                                duration = '20';
                                fromDate = new Date(selectedSlot);
                                toDate = new Date(selectedSlot);;
                                toDate.setMinutes(toDate.getMinutes() + 20);
                                break;
                        }

                        window.location.href = '/call-request?extId=' + extId + "&from=" + encodeURIComponent(fromDate.toJSON()) + "&to=" + encodeURIComponent(new Date(toDate).toJSON()) + "&type=" + appType + "&dr=" + duration;
                        return;
                    }
                }
            }

            window.location.href = "/psychics/" + psychicName.toLowerCase() + "-" + extId;
        },
        talkWithPsychicsHandler: function (dataObj, oPackage) {
            var extId = dataObj.ExtId,
                name = dataObj.Name,
                talkToPsychic = dataObj.TalkToPsychic,
                auth = OA.cookie.ManageCookieValue('auth'),
                status = "2",
                self = this;

            var info = {
                firstName: '',
                lastName: '',
                email: '',
                dob: '',
                password: '',
                sendFreeHoroAndNewsLetter: true,
                offerDuration: '',
                cardHolderName: '',
                cardNumber: '',
                expMonth: '',
                expYear: '',
                cvv: '',
                cardType: '',
                billingCountry: '',
                billingCountryName: '',
                zipCode: '',
                state: '',
                stateRegion: '',
                city: '',
                address1: '',
                address2: '',
                phoneCountry: '',
                phoneNumber: '',
                masId: '',
                custId: '',
                callbackId: '',
                extId: extId,
                offerId: '',
                priceId: '',
                transactionId: '',
                transactionAmount: '',
                statusCode: '',
                errorMessage: '',
                subscriptionId: '',
                package: oPackage,
                questionText: ''
            };
            OA.cookie.ManageCookieValue("askAccountInfo", info);

            if (!auth && !OA.auth.isECCookied()) {
                window.location.href = "/ask-question-signup?extid=" + extId;
                return;
            }
            else if (!auth && (OA.auth.isECCookied() && OAApp.featureConfig.isPurchaseReadingsEnabled)) {
                var cookieValue = { ExtId: extId, Name: name };
                OA.cookie.ManageCookieValue("PsychicTalkCookie", cookieValue);
                window.location.href = "/sign-in?c=1";
            }
            else if (auth || OA.auth.isECCookied()) {
                if (!OAApp.featureConfig.isPurchaseReadingsEnabled && !talkToPsychic) {
                    window.location.href = "/ask-question-signup?extid=" + extId;
                    return;
                }
                if (auth.isLeadCustomer) {
                    var acctInfo = OA.cookie.ManageCookieValue("askAccountInfo");
                    if (acctInfo != null) {
                        if (acctInfo.package == null) {
                            acctInfo.extId = extId;
                            acctInfo.package = oPackage;
                        }
                        acctInfo.firstName = auth.firstName;
                        acctInfo.lastName = auth.lastName;
                        acctInfo.email = auth.userEmail;
                        acctInfo.dob = auth.userDob;
                        acctInfo.custId = auth.custId;
                        OA.cookie.ManageCookieValue("askAccountInfo", acctInfo);
                    }

                    window.location.href = "/ask-question-signup?extid=" + extId;
                    return;
                }

                $.mobile.loading('show');

                var custId = '';
                var header = '';

                if (auth && !_.isEmpty(auth)) {
                    custId = auth.custId;
                    header = OA.services.basicAuth(auth.authToken);
                }

                var data = { CustID: custId, ExtId: extId };

                // Do not reserve psychic if user is on tablet/desktop resolution
                data.statusOnly = (window.innerWidth > OAApp.appsettings.MobileResolution);

                OA.services.reserveCustomerCallback(header, data).done(function (res) {
                    OA.utils.talkButtonHelper.callPsychics(res, name, extId);
                }).fail(function () {
                    OA.utils.ajaxHelpers.closeJQMLoader();
                    self.reservationRequested = false;
                });
            }
        },
          callPsychics: function (res, name, extId) {
            var self = this;

            if (OA.cookie.ManageCookieValue("PsychicTalkCookie")) {
                OA.cookie.ManageCookieValue("PsychicTalkCookie", null, { expires: -1 });
            }

            var status = parseInt(res.result);
            var readerLinePhone = res.readerLineNumber;
            if (!readerLinePhone) readerLinePhone = OAApp.appsettings.ReaderLineNumber;

            switch (status) {
                case 1:
                    var readLineNumber = "tel:" + OA.utils.stringHelpers.getOriginalPhoneNumber(readerLinePhone),
                        msg = "You are about to be connected with psychic " + name + " at " + readerLinePhone + ".";

                    var callbackTimer = $.timer(function () {
                        OA.utils.talkButtonHelper.diaplayCallDialog(readLineNumber, this);
                    });
                    callbackTimer.set({ time: 100, autostart: true });
                    break;
                case 2:
                    $.mobile.loading('hide');
                    if (!OAApp.featureConfig.isPurchaseReadingsEnabled)
                        return;

                    if (typeof talk_button_click_result != 'undefined') {
                        if (talk_button_click_result == 'customer-service') {
                            OA.utils.talkButtonHelper.callTalkButtonPhoneNumber();
                        } else {
                            window.location.href = "/purchase-reading?extid=" + extId;
                        }
                    } else {
                        window.location.href = "/purchase-reading?extid=" + extId;
                    }
                    break;
                case 3:
                    OA.utils.ajaxHelpers.closeJQMLoader();
                    var header = 'Queue is Full';
                    var body = 'The waiting list for this psychic is full. Please select another psychic or call Customer Care at <a id="psychic-list-callback-error-mas-number" class="tel ui-link mas-number" href="[[telnumber]]">[[number]]</a> for help.';
                    body = body.replace("[[telnumber]]", $('#navbar-phone-number').attr('href'));
                    body = body.replace("[[number]]", OAApp.appsettings.defaultMasNumber);

                    if (OA.PsychicCircle != undefined) {
                        OA.PsychicCircle.openCallBackErrorPopup(body, header)
                    }
                    if (OA.FreeReading != undefined) {
                        OA.FreeReading.OpenErrorPopup(header, body, "OA.FreeReading.RedirectToReading()");
                    }
                    $('#psychic-list-callback-error-popup').find('span').html(header);
                    $('#psychic-list-callback-error-popup').find('#psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').find('#index-psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').popup("open");
                    break;
                case 4:
                    OA.utils.ajaxHelpers.closeJQMLoader();
                    var header = 'Choose a Discounted Psychic';
                    var body = 'You are eligible for a reduced rate of $1/min on $4.00 and $5.00 psychics! Please choose a discounted psychic or call Customer Care at <a class="tel ui-link mas-number" href="[[telnumber]]">[[number]]</a> for assistance.';
                    body = body.replace("[[telnumber]]", $('#navbar-phone-number').attr('href'));
                    body = body.replace("[[number]]", OAApp.appsettings.defaultMasNumber);

                    if (OA.PsychicCircle != undefined) {
                        OA.PsychicCircle.openCallBackErrorPopup(body, header)
                    }
                    if (OA.FreeReading != undefined) {
                        OA.FreeReading.OpenErrorPopup(header, body, "OA.FreeReading.RedirectToReading()");
                    }
                    $('#psychic-list-callback-error-popup').find('span').html(header);
                    $('#psychic-list-callback-error-popup').find('#psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').find('#index-psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').popup("open");
                    break;
                case 5:
                    OA.utils.ajaxHelpers.closeJQMLoader();
                    var header = ' Already in Queue';
                    var body = 'You already have a pending callback with this psychic. Please go to the Psychic List to view your estimated wait time.';

                    if (OA.PsychicCircle != undefined) {
                        OA.PsychicCircle.openCallBackErrorPopup(body, header)
                    }
                    if (OA.FreeReading != undefined) {
                        OA.FreeReading.OpenErrorPopup(header, body, "OA.FreeReading.RedirectToReading()");
                    }
                    $('#psychic-list-callback-error-popup').find('span').html(header);
                    $('#psychic-list-callback-error-popup').find('#psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').find('#index-psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').popup("open");
                    break;
                case 6:
                    OA.utils.ajaxHelpers.closeJQMLoader();
                    var header = 'Pending Callbacks';
                    var body = 'You already have pending callbacks. If you would like a callback with this psychic, please cancel a pending callback first.';

                    if (OA.PsychicCircle != undefined) {
                        OA.PsychicCircle.openCallBackErrorPopup(body, header)
                    }
                    if (OA.FreeReading != undefined) {
                        OA.FreeReading.OpenErrorPopup(header, body, "OA.FreeReading.RedirectToReading()");
                    }
                    $('#psychic-list-callback-error-popup').find('span').html(header);
                    $('#psychic-list-callback-error-popup').find('#psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').find('#index-psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').popup("open");
                    break;
                default:
                    OA.utils.ajaxHelpers.closeJQMLoader();
                    var header = 'Oops!';
                    var body = 'Something went wrong. Please try again or call Customer Care at <a class="tel ui-link mas-number" href="[[telnumber]]">[[number]]</a>.';
                    body = body.replace("[[telnumber]]", $('#navbar-phone-number').attr('href'));
                    body = body.replace("[[number]]", OAApp.appsettings.defaultMasNumber);

                    if (OA.PsychicCircle != undefined) {
                        OA.PsychicCircle.openCallBackErrorPopup(body, header)
                    }
                    if (OA.FreeReading != undefined) {
                        OA.FreeReading.OpenErrorPopup(header, body, "OA.FreeReading.RedirectToReading()");
                    }
                    $('#psychic-list-callback-error-popup').find('span').html(header);
                    $('#psychic-list-callback-error-popup').find('#psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').find('#index-psychic-list-callback-error-p').html(body);
                    $('#psychic-list-callback-error-popup').popup("open");
                    break;
            }

            self.reservationRequested = false;
        },
        callTalkButtonPhoneNumber: function () {
            var TalkButtonNumber = "tel:" + OA.utils.stringHelpers.getOriginalPhoneNumber(OAAPP.appsettings.TalkButtonNumber);
            window.location = TalkButtonNumber;
        },
        callMasPhoneNumber: function () {
            var MasNumber = "tel:" + OA.utils.stringHelpers.getMasPhone();
            window.location = MasNumber;
        },
        diaplayCallDialog: function (href, timer) {
            $.mobile.loading('hide');
            window.location = href;
            timer.stop();
        },
        checkDuplicates: function (custId, extId) {
            var
                curCustId = custId,
                curPsychicId = extId,
                curTimestamp = 0,
                curDiff = 0,
                dups = false;

            if (!Date.now) {
                Date.now = function () { return new Date().getTime(); }
            }
            curTimestamp = Math.floor(Date.now() / 1000);

            curDiff = curTimestamp - this.clickedTimestamp;
            console.log(curTimestamp);
            //return false;

            ////if same cust and psychic check timestamp and prevent doubl click
            if (curCustId == this.clickedCustId && curPsychicId == this.clickedPsychicId && curDiff < 5) {
                    console.log(curDiff);
                    dups = true;
            }

            OA.utils.talkButtonHelper.clickedCustId = curCustId;
            OA.utils.talkButtonHelper.clickedPsychicId = extId;
            OA.utils.talkButtonHelper.clickedTimestamp = curTimestamp;

            return dups;
        },
        chatWithPsychics: function (e) {
            //self = this;
            //$target = $(e.target),

            var extId = e.target.getAttribute("data-extid"),
                auth = OA.cookie.ManageCookieValue('auth'),
                lineName = e.target.getAttribute("data-name");

            OA.cookie.ManageCookieValue("CTAType", "chat");
            //mvc
            if (auth != "" && auth != undefined) {
                if (OA.utils.talkButtonHelper.checkDuplicates(auth.custId, extId))
                    return false;
            }

                //alert(extId);
                //alert(lineName);

                //var extId = e.target.getAttribute("data-extid"),
                //   name = e.target.getAttribute("data-name"),
                //   auth = OA.cookie.ManageCookieValue('auth'),
                //   talkToPsychic = e.target.getAttribute("data-talk") === 'true',
                //   custId = '',
                //   userInQueue = e.target.getAttribute("data-inqueue"),
                //   prtappenabled = e.target.getAttribute("data-prtappenabled");
                console.log('e.preventDefault');
            e.preventDefault();
            e.stopPropagation();

            console.log('FiveFreeAccountInfo');
                //Remove five free cookie because on talk click always follow the ask flow - TO-4569
                OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");

                //if (!auth && !OA.auth.isECCookied()) {
                //    window.location.href = "../JJ-chat?extid=" +extId;
                //    return;
                //    }

                console.log('ManageCookieValue-jj');
            var info;
            var acctInfo = OA.cookie.ManageCookieValue("auth");
            if (acctInfo == null) {
                info = {
                    firstName: '',
                    lastName: '',
                    email: '',
                    dob: '',
                    password: '',
                    sendFreeHoroAndNewsLetter: true,
                    offerDuration: '',
                    cardHolderName: '',
                    cardNumber: '',
                    expMonth: '',
                    expYear: '',
                    cvv: '',
                    cardType: '',
                    billingCountry: '',
                    billingCountryName: '',
                    zipCode: '',
                    state: '',
                    stateRegion: '',
                    city: '',
                    address1: '',
                    address2: '',
                    phoneCountry: '',
                    phoneNumber: '',
                    masId: '',
                    custId: '',
                    callbackId: '',
                    extId: extId,
                    offerId: '',
                    priceId: '',
                    transactionId: '',
                    transactionAmount: '',
                    statusCode: '',
                    errorMessage: '',
                    subscriptionId: '',
                    package: OA.utils.talkButtonHelper.offersDictionary[1],
                    questionText: '',
                    chat: true
            };
            OA.cookie.ManageCookieValue("askAccountInfo", info);
            } else {
                acctInfo.extId = extId;
                acctInfo.chat = true;
                OA.cookie.ManageCookieValue("askAccountInfo", acctInfo);
            }

            console.log('isECCookied');
            if (!auth && !OA.auth.isECCookied()) {
                window.location.href = "../" + OA.paths.askNcCheckout.createAccount + "?extid=" + extId + "&ischat=1";
                return;
            }

            console.log('extId ' + extId);
            console.log('lineName ' + lineName);
            OA.chatCommon.confirmChat(extId, lineName);
        },
        talkWithPsychicsClickHandler: function (e, extId, name, talkToPsychic, userInQueue, prtappenabled) {

            var auth = OA.cookie.ManageCookieValue('auth'),
                custId = '',
                self = this;

            if (prtappenabled == "1" && $(e.target).hasClass('getCallBack')) {
                $.mobile.loading('show');
                var startDate = moment().format('YYYY-MM-DD');
                var endDate = moment().add('days', 1).format('YYYY-MM-DD');
                var timeZoneId = OA.utils.timeHelpers.getTimezoneName();

                OA.services.getPsychicsAvailableScheduleSlot({
                    ExtId: extId,
                    StartDate: startDate,
                    EndDate: endDate,
                    TimeZoneId: timeZoneId
                }).done(function (response) {
                    OA.utils.talkButtonHelper.getTimeSlots(response, extId, name);
                }).fail(function (error) {
                    console.log("error", error);
                    $.mobile.loading('hide');
                    self.reservationRequested = false;
                });
        }
            else {
                if ($(e.target).html() == 'IN QUEUE' || userInQueue == "true" || userInQueue == true) {
                    window.location.href = '/my-account/readings';
                    return;
                }

                if (auth && !_.isEmpty(auth)) {
                    custId = auth.custId;
                }

                OAApp.featureConfig.isPurchaseReadingsEnabled = true;

                var dataObj = { ExtId: extId, Name: name, TalkToPsychic: talkToPsychic };
                OA.utils.talkButtonHelper.talkWithPsychicsHandler(dataObj, OA.utils.talkButtonHelper.offersDictionary[1]);
            }
        }
    };

    OA.utils.favoriteHelper = {
        toggleFavorite: function (e, cv) {
            e.preventDefault();
            e.stopPropagation();
            OA.utils.tooltips.hideDesktopTooltip($(".set-favorite"));
            OA.utils.tooltips.hideDesktopTooltip($(".psychics-status"));

            var $el = $(e.target),
                auth = OA.cookie.ManageCookieValue('auth'),
                custId = !_.isEmpty(auth) ? auth.custId : undefined,
                ExtId = $el.attr("data-extid"),
                Note = '',
                mpp = '';

            if (auth != null) {
                if ($el.hasClass('fav'))
                    $(".add-to-favorites-" + ExtId).html("add to favorites");
                else
                    $(".add-to-favorites-" + ExtId).html("remove from favorites");

                OA.utils.favoriteHelper.setPsychicsfavorite($el, auth.authToken, custId, ExtId, Note);
            }
            else {
                var currentView = OA.cookie.ManageCookieValue("CurrentView");

                if (cv != undefined) {
                    currentView = cv;
                }

                if (currentView == 0) {
                    OA.utils.tooltips.showTooltip($("#psychics-fav-" + ExtId), "Please login to mark this psychic as favorite", "top");
                    var hideTooltipTimer = $.timer(function () {
                        OA.utils.tooltips.hideDesktopTooltip($("#psychics-fav-" + ExtId));
                        hideTooltipTimer.stop();
                    });
                    hideTooltipTimer.set({ time: 5000, autostart: true });
                }
                else {
                    OA.utils.tooltips.showTooltip($("#psychics-fav-des-" + ExtId), "Please login to mark this psychic as favorite", "top");
                    OA.utils.tooltips.showTooltip($("#psychics-fav-mob-" + ExtId), "Please login to mark this psychic as favorite", "top");
                    var hideTooltipTimer = $.timer(function () {
                        OA.utils.tooltips.hideDesktopTooltip($("#psychics-fav-des-" + ExtId));
                        OA.utils.tooltips.hideDesktopTooltip($("#psychics-fav-mob-" + ExtId));
                        hideTooltipTimer.stop();
                    });
                    hideTooltipTimer.set({ time: 5000, autostart: true });
                }
            }
        },
        toggleFavoritePsychic: function ($el, authToken, custId, extId, note) {
            var self = this;
            if (!(!!note)) {
                note = '';
            }

            if (!$el.hasClass('fav')) {
                return OA.services.addFavoritePsychic(custId, {
                    'Authorization': authToken
                }, {
                        CustId: custId,
                        ExtId: extId,
                        Note: note
                    })
                    .done(function (res) {
                        if (res.isSuccess) {
                            $el.addClass('fav')
                            $el.addClass('oa-icon-favorite-filled oa-icon-favorite-empty')
                        }
                    });
            } else {
                return OA.services.removeFavoritePsychic(custId, {
                    'Authorization': authToken
                }, {
                        CustId: custId,
                        ExtIds: extId
                    })
                    .done(function (res) {
                        if (res.isSuccess) {
                            $el.removeClass('fav').removeClass('oa-icon-favorite-filled oa-icon-favorite-remove').addClass('oa-icon-favorite-empty');
                        }
                    });
            }
        },
        setPsychicsfavorite: function ($el, authToken, custId, extId, note) {
            var self = this;
            var isFavoriteSet = false;

            $.mobile.loading("show");

            if (!(!!note)) {
                note = '';
            }

            if (!$el.hasClass('fav')) {
                return OA.services.addFavoritePsychic(custId, {
                    'Authorization': authToken
                }, {
                        CustId: custId,
                        ExtId: extId,
                        Note: note
                    }).done(function (res) {
                        if (res.isSuccess) {
                            $el.removeClass('oa-icon-favorite-psychics-empty').addClass('fav').addClass('oa-icon-favorite-psychics-filled');
                            OA.utils.tooltips.showDesktopTooltip($("#" + $el.attr("id")), "Added to favorites");
                            var hideTooltipTimer = $.timer(function () {
                                OA.utils.tooltips.hideDesktopTooltip($("#" + $el.attr("id")));
                                hideTooltipTimer.stop();
                            });
                            hideTooltipTimer.set({ time: 5000, autostart: true });
                            isFavoriteSet = true;

                        }
                    }).always(function () {
                        $.mobile.loading("hide");
                    });
            }
            else {
                return OA.services.removeFavoritePsychic(custId, {
                    'Authorization': authToken
                }, {
                        CustId: custId,
                        ExtIds: extId
                    }).done(function (res) {
                        if (res.isSuccess) {
                            $el.removeClass('fav').removeClass('oa-icon-favorite-psychics-filled').addClass('oa-icon-favorite-psychics-empty');
                            OA.utils.tooltips.showDesktopTooltip($("#" + $el.attr("id")), "Removed from favorites");
                            var hideTooltipTimer = $.timer(function () {
                                OA.utils.tooltips.hideDesktopTooltip($("#" + $el.attr("id")));
                                hideTooltipTimer.stop();
                            });
                            hideTooltipTimer.set({ time: 5000, autostart: true });
                        }
                    }).always(function () {
                        $.mobile.loading("hide");
                    });
            }
            return isFavoriteSet;
        }
    };

    OA.utils.windowHelpers = {
        displayType: function () {
            return window.devicePixelRatio > 0 ? 1 : 0;
        },
        deviceType: function () {
            return (window.innerWidth <= OAApp.appsettings.MobileResolution ? "mobile" : "desktop");
        }
    };

    OA.utils.psychicStatusUpdateManager = {
        GetExtIds: function () {
            var extids = new Array();

            $('#psychic-list-ul').find('li').each(function () {
                var extId = $(this).attr("data-extid");
                if (extId != undefined) {
                    if (extids.indexOf(extId) < 0) {
                        extids.push(extId);
                    }
                }
            });

            if (OA.PsychicCircle != undefined) {
                $('#karma-psychic-circle').find('.psychic-box').each(function () {
                    var extId = $(this).attr("data-extid");
                    if (extId != undefined) {
                        if (extids.indexOf(extId) < 0) {
                            extids.push(extId);
                        }
                    }
                });

            }

            return extids.join(',');
        },
        refreshPsychicStatus: function (isPsychicList, cv, callFrom) {
            var self = this,
                custId = null,
                auth = OA.cookie.ManageCookieValue('auth');

            if (auth && auth.custId) {
                custId = auth.custId;
            }

            var psychicOption = OA.cookie.ManageCookieValue("PsychicOptions");
            var sortBy = "";

            if (psychicOption != null) {
                sortBy = psychicOption.SortBy;
            }

            var sortByCookie = OA.cookie.ManageCookieValue('CurrentSort');

            if (sortByCookie != undefined) {
                sortBy = sortByCookie;
            }

            var searchText = "";
            var searchOption = OA.cookie.ManageCookieValue("CurrentCategoty");
            var sortByValue = sortBy;
            var options = {};
            var extIds = OA.utils.psychicStatusUpdateManager.GetExtIds();

            var data = { ExtIds: extIds, CustId: custId, SearchText: searchText, SearchOptions: searchOption, SortBy: sortByValue };

            $.ajax({
                type: "POST",
                url: OAApp.appsettings.apiUrl + OAApp.appsettings.psychicsStatusURL + "?t=" + new Date().getTime(),
                data: JSON.stringify(data),
                contentType: 'application/json',
                success: function (response) {
                    if (response) {
                        $('.totalPsychicsAvailable').html(response.totalPsychicsAvailable);
                        $('.totalPsychicsOnCall').html(response.totalPsychicsOnCall);
                        $('.totalPsychicsOffline').html(response.totalPsychicsOffline);
                        if (response.psychics && response.psychics.length > 0) {
                            for (var i = 0; i < response.psychics.length; i++) {
                                OA.utils.psychicStatusUpdateManager.updateStatus(response.psychics[i], isPsychicList, cv, callFrom);
                            }
                        }
                    }
                }
            });
        },
        updateStatus: function (response, isPsychicList, cv, callFrom) {
            var auth = OA.cookie.ManageCookieValue('auth'),
                extId = response.extId,
                status = response.lineStatus.toLowerCase(),
                peopleInQueue = response.peopleInQueue,
                talkToPsychis = false,
                waitTimeText,
                talkButtonText,
                talkButtonCss,
                talkButtonCssGrande,
                $psychic = $('#psychic-li-' + extId),
                $btn = $psychic.find('.talk-button-div').find('a[data-extid=' + extId + ']'),
                $btnTalkWChatEnabled = $psychic.find('.chat-available-div').find('a[data-extid=' + extId + ']'),
                $btnCondensedChat = $psychic.find('.chat-button-div').find('a[data-extid=' + extId + ']'),
                $btnCondensedChatMobile = $psychic.find('.condense-talk-chat').find('.btnChat'),
                $btnCondensedChatGrande = $psychic.find('.psychicsInfo').find('.btnChat'),                
                isPsychicAvailable = true,
                estWaitTimeCss = 'estWaitTime-available',
                inQueueDisplayCss = "display-none",
                otherDisplayCss = "display-inline-block",
                talk_button_test_result = 1,
                estWaitTimeText,
                estWaitTimeClass = '',
                onCallText = status,
                talkButtonImageCss = '',
                $imgDiv = $psychic.find('.btnTalk-img'),    //Talk with or without chat should have same style
                $talkStatusTextDiv = $psychic.find('.btnTalk-status'),//Talk with or without chat should have same style
                chatStatus = response.chatStatus.toLowerCase(),
                chatView = false,
                isChatShow = OAApp.appsettings.isChatShow,
                displayStatus = '';


            if (isChatShow && (response.isChatEnabled == true && response.chatStatus.toUpperCase() == 'AVAILABLE' && response.lineStatus.toUpperCase() != 'ONCALL')) {
                chatView = true;
            }
            else {
                chatView = false;
            }

            if (typeof response.talk !== 'undefined') {
                talkToPsychis = response.talk;
            }
            if (OA.FreeReading != undefined)
            {
            OA.FreeReading.updatepsychicstatus(response);
            }
            if (OA.PsychicCircle != undefined) {
                OA.PsychicCircle.updatepsychicstatus(response);
            }
            //Both Talk and Chat Status need to be considered going forward
            if (status == "oncall" || chatStatus == "oncall") {
                isPsychicAvailable = false;
                estWaitTimeCss = 'estWaitTime-oncall-text';
                onCallText = "busy";
                displayStatus = "oncall";   //style was missing when busy
            }
            else if (status == 'available' || chatStatus == "available") {
                isPsychicAvailable = false;
                if (status == 'available')
                    isPsychicAvailable = true;

                estWaitTimeCss = 'estWaitTime-available-text';
                onCallText = "available";
                displayStatus = "available";
            }
            else if (status == 'onbreak' || ((status == 'offline' || status == 'busy') && chatStatus == "onbreak")) {  //Not part of this ticket CHAT2-2115 but coding in advance for TO-7294
                isPsychicAvailable = false;
                estWaitTimeCss = 'estWaitTime-offline-text';   
                onCallText = "on a break";
                displayStatus = "onbreak";
            }
            else if (status == "offline" || status == "busy") {
                isPsychicAvailable = false;
                estWaitTimeCss = 'estWaitTime-offline-text';
                onCallText = "offline";
                displayStatus = "offline";
            }

            var currentView = OA.cookie.ManageCookieValue("CurrentView");
            if (currentView == null) {
                currentView = OA.cookie.GetRawCookieValue("CurrentView");
                if (currentView == null || currentView == '') {
                    currentView = 1;
                }
            }

            if (isPsychicList != undefined) {
                currentView = 1;
            }

            if (cv != undefined) {
                currentView = cv;
            }                     

            //console.log('onCallText ' +onCallText);
            //Moving status text assignment down as currentView is wrong value which gets corrected below

            if (!auth && !OA.auth.isECCookied()) {
                if (!isPsychicAvailable) {
                    talkButtonText = 'CALLBACK';
                    talkButtonCss = "getCallBack";
                        talkButtonCssGrande = "getCallBack-list-grande";
                    if (callFrom != undefined && callFrom == 'similarPsychics') {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-detail-on-a-call";
                    }
                    else {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-on-a-call";
                    }
                } else {
                    talkButtonText = 'TALK';
                    talkButtonCss = "talk";
                        talkButtonCssGrande = "talk-grande";
                    if (callFrom != undefined && callFrom == 'similarPsychics') {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-detail-available";
                    }
                    else {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-available";
                    }
                }
            }
            else {
                if (response.customerPlaceInQueue == undefined || !response.customerPlaceInQueue) {
                    talkButtonText = 'TALK';
                    talkButtonCss = "talk";
                    talkButtonCssGrande = "talk-grande";
                    if (callFrom != undefined && callFrom == 'similarPsychics') {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-detail-available";
                    }
                    else {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-available";
                    }
                    peopleInQueue = response.peopleInQueue;
                }
                else {
                    talkButtonText = 'IN QUEUE';
                    talkButtonCss = "inQueue";
                    talkButtonCssGrande = "inQueue-grande";
                    peopleInQueue = response.customerPlaceInQueue;
                    inQueueDisplayCss = "display-inline-block";
                    otherDisplayCss = "display-none";
                }

                if ((response.customerPlaceInQueue == undefined || !response.customerPlaceInQueue) && !isPsychicAvailable) {
                    talkButtonText = 'CALLBACK';
                    talkButtonCss = "getCallBack";
                    talkButtonCssGrande = "getCallBack-list-grande";
                    if (callFrom != undefined && callFrom == 'similarPsychics') {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon-call-psychics-detail-on-a-call";
                    }
                    else {
                        talkButtonImageCss = "btnTalk-img oa-icon oa-icon oa-icon-call-psychics-on-a-call";
                    }
                }
            }

            if (typeof talk_button_test_result != 'undefined') {
                if (talk_button_test_result == 2) {
                    if (talkButtonText == 'TALK') {
                        talkButtonText = 'TALK';
                    }
                    else if (talkButtonText == 'CALLBACK') {
                        talkButtonText = 'TALK';
                    }
                    else if (talkButtonText == 'IN QUEUE') {
                        talkButtonText = 'IN QUEUE';
                    }
                }
            }

            $psychic.find('#psychics-default-bar-' + extId).find('.col-1').removeClass().addClass('col-1 psychics-padding-top arrowDiv ' + otherDisplayCss)
            $psychic.find('#psychics-default-bar-' + extId).find('.col-2').removeClass().addClass('col-2 psychics-padding-top arrowDiv ' + otherDisplayCss)
            $psychic.find('#psychics-default-bar-' + extId).find('.col-5').removeClass().addClass('col-5 arrowDiv ' + inQueueDisplayCss)

            //$btn.html(talkButtonText);
            $talkStatusTextDiv.html(talkButtonText);

            if (window.location.href.indexOf("/psychics/") > -1) {
                var viewtype = OA.cookie.ManageCookieValue("CurrentView");
                if (viewtype != null) {
                    currentView = viewtype;
                }
            }

            var ViewChanging = OA.cookie.ManageCookieValue("ViewChanging");

            if (currentView == 0) {
                $psychic.find(".status-icon").removeClass()
                    .addClass("status-icon status-big-" + displayStatus + " " + displayStatus + " display-inline-block");

                $psychic.find(".status-text").removeClass()
                    .addClass("status-text row-" + displayStatus + "-text");

                $psychic.find(".status-text").html(onCallText.toUpperCase());
            } else {
                $psychic.find('#status-' + extId).find(".psychic-status").removeClass()
                    .addClass("psychic-status " + displayStatus + " psychic-status-main");
                $psychic.find('#status-' + extId).find(".status-big").removeClass()
                    .addClass("status-big " + displayStatus + " psychic-status-align");
                $psychic.find('.status-' + extId).find(".status-big").removeClass()
                    .addClass("status-big " + displayStatus + " psychic-status-align");
            }

            if (!ViewChanging) {
                if (currentView == 0) {
                    $btn.removeClass().addClass("btnTalk ui-btn psychics-talk talk-shadow-text " + talkButtonCss + " box-sizing-initial");
                    $btnTalkWChatEnabled.removeClass().addClass("btnTalk ui-btn psychics-talk talk-shadow-text " + talkButtonCss + " box-sizing-initial");
                    $('#psychics-default-bar-' + extId).find('col-1').removeClass().addClass('col-1 psychics-padding-top arrowDiv ' + otherDisplayCss);
                    $('#psychics-default-bar-' + extId).find('col-2').removeClass().addClass('col-2 psychics-padding-top arrowDiv ' + otherDisplayCss);
                    $('#psychics-default-bar-' + extId).find('col-5').removeClass().addClass('col-5 arrowDiv ' + inQueueDisplayCss);
                    $('#psychics-profile-bar-' + extId).find('.estWaitTimeText').removeClass().addClass('estWaitTimeText ' + otherDisplayCss);
                    $('#psychics-profile-bar-' + extId).find('.estWaitTimeVal').removeClass().addClass('estWaitTimeVal ' + estWaitTimeCss + ' ' + otherDisplayCss);
                    $('#psychics-profile-bar-' + extId).find('.inqueue-status').removeClass().addClass('inqueue-status ' + inQueueDisplayCss);
                    $('#psychics-profile-bar-' + extId).find('.inqueue-price').removeClass().addClass('inqueue-price ' + inQueueDisplayCss);
                    $imgDiv.removeClass().addClass(talkButtonImageCss.replace('-condensed', ''));
                } else {
                    $btn.removeClass().addClass("btnTalk ui-btn " + talkButtonCss + "-list" + " condensed-view-button");
                    $btnTalkWChatEnabled.removeClass().addClass("btnTalk ui-btn " + talkButtonCss + "-list" + " condensed-view-button");
                    $('.condense-view-talk').find('div[data-extid=' + extId + ']').removeClass().addClass('btnTalk ico-' + talkButtonCss);
                    $('.condense-view-talk-grande').find('div[data-extid=' + extId + ']').removeClass().addClass('btnTalk ico-' + talkButtonCssGrande);
                    $imgDiv.removeClass().addClass(talkButtonImageCss + '-list')
                }
            }

            $btn.attr('data-talk', talkToPsychis);
            $btnTalkWChatEnabled.attr('data-talk', talkToPsychis);

            if (response.estimatedWaitTime == 0) {
                waitTimeText = '0m';
            }
            else if (response.estimatedWaitTime < 60) {
                waitTimeText = response.estimatedWaitTime + 'm';
            }
            else {
                waitTimeText = Math.floor(response.estimatedWaitTime / 60) + 'h ' + (response.estimatedWaitTime % 60) + 'm';
            }

            $('#estWaitTime-' + extId).html(waitTimeText);
            $('#estWaitTime-val-' + extId).html(waitTimeText);
            $('#estWaitTime-val-' + extId).text(waitTimeText);

            if (peopleInQueue == 1) {
                $('#peopleInQueue-' + extId).html(peopleInQueue + " person");
            }
            else {
                $('#peopleInQueue-' + extId).html(peopleInQueue + " people");
            }

            var queueDiv = $('#peopleInQueue-desktop-' + extId);
            var i = 1, queueClass = 'empty';
            var queuePosition = response.customerPlaceInQueue;
            var queueMessage, positionTxt = 'st';

            if (queuePosition) {
                if (queuePosition > 3) {
                    positionTxt = 'th';
                }
                else if (queuePosition == 3) {
                    positionTxt = 'rd';
                }
                else if (queuePosition == 2) {
                    positionTxt = 'nd';
                }
            }

            if (queuePosition) {
                queueMessage = queuePosition + '<span>' + positionTxt + '</span>' + ' place';
            } else if (!queuePosition || queuePosition < 6) {
                if (peopleInQueue == 1) {
                    queueMessage = response.peopleInQueue + ' Person'
                }
                else {
                    queueMessage = response.peopleInQueue + ' People'
                }
            }

            for (i = 1; i < OAApp.appsettings.queueSize + 1; i += 1) {
                if (queuePosition === i) {
                    queueClass = 'filled-user';
                } else if (i <= response.peopleInQueue) {
                    queueClass = 'filled';
                } else {
                    queueClass = 'empty';
                }

                queueDiv.find('ul').find('#li-queue-count-' + i).find('span').removeClass().addClass("oa-icon oa-icon-" + queueClass);
            }

            if (queuePosition) {
                queueDiv.find('p').html(queueMessage).removeClass().addClass('filled-para');
            } else {
                queueDiv.find('p').html(queueMessage).removeClass().addClass('empty-para');
            }

            var estWaitTimeText = '';
            if (status == "onbreak" || status == "offline") {
                estWaitTimeClass = 'estWaitTime-uponreturn-text';
                estWaitTimeText = 'est. wait on return';
            } else if (status == "oncall" || status == "busy") {
                estWaitTimeClass = '';
                estWaitTimeText = 'est. wait time';
            } else if (status == 'available') {
                estWaitTimeClass = '';
                estWaitTimeText = 'est. wait time';
            }

            $('#psychics-profile-bar-' + extId).find('.estWaitTimeText').addClass(estWaitTimeClass);
            $('#psychics-profile-' + extId).find('.estWaitTimeText').addClass(estWaitTimeClass);
            $('#psychics-profile-bar-' + extId).find('.estWaitTimeText').html(estWaitTimeText);
            $('#psychics-profile-' + extId).find('.estWaitTimeText').html(estWaitTimeText);
            $('#est-desktop-text-span-' + extId).html(estWaitTimeText);
            $('#psychicsInfo-' + extId).find('.est-mobile-text').html(estWaitTimeText);

            ////same condition as html
            if (currentView == 0) {
                if (chatView) {
                    $psychic.find('#chatViewFalse').hide();
                    $psychic.find('#chatViewTrue').show();
                }
                else {
                    $psychic.find('#chatViewTrue').hide();
                    $psychic.find('#chatViewFalse').show();
                }
            }
            else {
                if (chatView) {
                    $btnCondensedChat.show();   
                    $btnCondensedChatMobile.show();
                    $btnCondensedChatGrande.show();
                }
                else {
                    $btnCondensedChat.hide();
                    $btnCondensedChatMobile.hide();
                    $btnCondensedChatGrande.hide();
                }
            }
        }
    };

    OA.utils.common = {
        redirectToAskQuestion: function (e) {
            e.preventDefault();
            var isEC = OA.auth.isECCookied();

            var info,
                cookieName = 'askAccountInfo';

            if (OA.cookie.ManageCookieValue("FiveFreeAccountInfo") != null && OA.cookie.ManageCookieValue("FiveFreeAccountInfo") != undefined && OA.cookie.ManageCookieValue("FiveFreeAccountInfo") != "") {
                cookieName = 'FiveFreeAccountInfo';
            }
            else if (window.location.href.indexOf("/ask-question-offers") > -1) {
                cookieName = 'askAccountInfo';
            }

            var acctInfo = OA.cookie.ManageCookieValue(cookieName);
            if (acctInfo == null) {
                info = {
                    firstName: '',
                    lastName: '',
                    email: '',
                    dob: '',
                    password: '',
                    sendFreeHoroAndNewsLetter: true,
                    offerDuration: '',
                    cardHolderName: '',
                    cardNumber: '',
                    expMonth: '',
                    expYear: '',
                    cvv: '',
                    cardType: '',
                    billingCountry: '',
                    billingCountryName: '',
                    zipCode: '',
                    state: '',
                    stateRegion: '',
                    city: '',
                    address1: '',
                    address2: '',
                    phoneCountry: '',
                    phoneNumber: '',
                    masId: '',
                    custId: '',
                    callbackId: '',
                    extId: '',
                    offerId: '',
                    priceId: '',
                    transactionId: '',
                    transactionAmount: '',
                    statusCode: '',
                    errorMessage: '',
                    subscriptionId: '',
                    package: OA.utils.purchases.fillOffersDictionary("20"),
                    questionText: ''
                };
            }
            else {
                info = acctInfo;
            }
            OA.cookie.ManageCookieValue(cookieName, info);

            if (isEC) {
                window.location.href = "../" + OA.paths.askNcCheckout.offers;
            }
            else {
                window.location.href = "../" + OA.paths.askNcCheckout.offers + "?nc=1";
            }
        },
        redirectToConfirmation: function (e) {
            $.mobile.loading("show");
            var target = $(e.target);
            var temp = target.attr("id");
            var id = temp.split("-")[1];

            //Remove five free cookie because on talk click always follow the ask flow - TO-4569
            OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");
            var acctInfo = OA.cookie.ManageCookieValue("askAccountInfo");
            var offersDictionary = OA.utils.purchases.fillOffersDictionary('20');

            if (acctInfo == null) {
                var info = {
                    firstName: '',
                    lastName: '',
                    email: '',
                    dob: '',
                    password: '',
                    sendFreeHoroAndNewsLetter: '',
                    offerDuration: '',
                    cardHolderName: '',
                    cardNumber: '',
                    expMonth: '',
                    expYear: '',
                    cvv: '',
                    cardType: '',
                    billingCountry: '',
                    billingCountryName: '',
                    zipCode: '',
                    state: '',
                    stateRegion: '',
                    city: '',
                    address1: '',
                    address2: '',
                    phoneCountry: '',
                    phoneNumber: '',
                    masId: '',
                    custId: '',
                    callbackId: '',
                    extId: '',
                    offerId: '',
                    priceId: '',
                    transactionId: '',
                    transactionAmount: '',
                    statusCode: '',
                    errorMessage: '',
                    subscriptionId: '',
                    package: offersDictionary[id],
                    questionText: ''
                };
            }
            else {
                acctInfo.package = offersDictionary[id];
                info = acctInfo;
            }
            OA.cookie.ManageCookieValue('askAccountInfo', info);
            acctInfo = OA.cookie.ManageCookieValue("askAccountInfo");
            if (acctInfo != null) {
                acctInfo.package = offersDictionary[id];
                var auth = OA.cookie.ManageCookieValue('auth');
                if (auth != null)
                {
                    acctInfo.firstName = auth.firstName;
                    acctInfo.lastName = auth.lastName;
                    acctInfo.email = auth.userEmail;
                    acctInfo.dob = auth.userDob;
                    acctInfo.custId = auth.custId;
                  
                }

             
                OA.cookie.ManageCookieValue('askAccountInfo', acctInfo);
                window.location.href = OA.paths.askNcCheckout.createAccount;
            } else {
                window.location.href = "../" + OA.paths.askNcCheckout.question;
            }
        },
        redirectToPsychicReadings: function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.location.href = OA.paths.psychicReading;
        },
        clickTopicsToolsAndAbilities: function (e) {
            e.stopPropagation();
            if (window.location.href.indexOf("about-psychic-readings") == -1) {
                if ($('.filtercontainer-navbar').is(':visible')) {
                    $("#subnav-topics").css("font-weight", "400");
                    OA.utils.hoverTopicsToolsAndAbilities.TopicsToolsAndAbilitiesbold();
                }
                else {
                    $("#subnav-topics").css("font-weight", "700");
                    OA.utils.hoverTopicsToolsAndAbilities.TopicsToolsAndAbilitiesUnbold();
                }
            }
            $('.filtercontainer-navbar').toggle();
            return false;
        },
        setHomePath: function () {
            if (window.location.href.indexOf('/horoscope') > -1 || window.location.href.indexOf('/psychic-readings') > -1 || window.location.href.indexOf('/ask-free') > -1 || window.location.href.indexOf('/ask-question') > -1) {
                $('.cp-logo').prop('href', OA.paths.home);
                $("#btnhome").prop('href', OA.paths.home);
                $("#btnGotoHome").prop('href', OA.paths.home);
                $('.cp-logo').attr('data-ajax', false);
                $('#btnhome').attr('data-ajax', false);
            } else {
                $('.cp-logo').prop('href', OA.paths.mobileHome);
                $("#btnhome").prop('href', OA.paths.mobileHome);
                $("#btnGotoHome").prop('href', OA.paths.mobileHome);
                $('.cp-logo').attr('data-ajax', false);
                $('#btnhome').attr('data-ajax', false);
            }
        }
    };

    OA.utils.events = {
        addScrollStopHandler: function (handler) {
            var events = $._data(document, 'events');
            if (events && !events.scrollstop)
                $(document).on("scrollstop", handler);
        },
        removeScrollStopHandler: function () {
            var events = $._data(document, 'events');
            if (events && events.scrollstop)
                events.scrollstop = undefined;
        },
        isElementInView: function (element, fullyInView) {
            var pageTop = $(window).scrollTop();
            var pageBottom = pageTop + $(window).height();
            var elementTop = $(element).offset().top;
            var elementBottom = elementTop + $(element).height();

            if (fullyInView === true) {
                return ((pageTop < elementTop) && (pageBottom > elementBottom));
            } else {
                return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
            }
        }
    };

    OA.utils.hoverTopicsToolsAndAbilities = {
        TopicsToolsAndAbilitiesUnbold: function () {

            if (window.location.href.indexOf("/phone-psychic-readings") > 0) {
                $("#subnav-how-it-works").css("font-weight", "400");
            } else if (window.location.href.indexOf("/why-california-psychics") > 0) {
                $("#subnav-why-california-psychics").css("font-weight", "400");
            } else if (window.location.href.indexOf("/how-we-help") > 0) {
                $("#subnav-how-we-help").css("font-weight", "400");
            } else if (window.location.href.indexOf("/most-gifted-psychics") > 0) {
                $("#subnav-most-gifted-psychics").css("font-weight", "400");
            } else if (window.location.href.indexOf("/pricing") > 0) {
                $("#subnav-pricing").css("font-weight", "400");
            } else if (window.location.href.indexOf("/about-california-psychics") > 0) {
                $("#subnav-about-us").css("font-weight", "400");
            } else if (window.location.href.indexOf("/articles") > 0) {
                $("#subnav-articles").css("font-weight", "400");
            } else if (window.location.href.indexOf("topics") > 0) {
                $("#subnav-topics").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("abilities") > 0) {
                $("#subnav-abilities").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("tools") > 0) {
                $("#subnav-tools").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("styles") > 0) {
                $("#subnav-styles").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("hot-deals") > 0) {
                $("#subnav-hotDeals").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("vip-specials") > 0) {
                $("#subnav-vipDeals").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("new-psychics") > 0) {
                $("#subnav-newPsychics").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("premier-psychics") > 0) {
                $("#subnav-Premier").css("font-weight", "400");

            }
            else if (window.location.href.indexOf("staff-favorite-psychics") > 0) {
                $("#subnav-StaffPicks").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("customer-favorite-psychics") > 0) {
                $("#subnav-CustomerFavorites").css("font-weight", "400");
                $("#subnav-MyFavorites").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("rising-stars") > 0) {
                $("#subnav-RisingStars").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("about-psychic-readings") > 0) {
                $("#subnav-topics").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("my-favorite-psychics") > 0) {
                $("#subnav-MyFavorites").css("font-weight", "400");
            }
            else if (window.location.href.indexOf("psychic-readings") > 0) {
                $("#subnav-all").css("font-weight", "400");
            }

        },
        TopicsToolsAndAbilitiesbold: function () {

            if (window.location.href.indexOf("/phone-psychic-readings") > 0) {
                $("#subnav-how-it-works").css("font-weight", "700");
            } else if (window.location.href.indexOf("/why-california-psychics") > 0) {
                $("#subnav-why-california-psychics").css("font-weight", "700");
            } else if (window.location.href.indexOf("/how-we-help") > 0) {
                $("#subnav-how-we-help").css("font-weight", "700");
            } else if (window.location.href.indexOf("/most-gifted-psychics") > 0) {
                $("#subnav-most-gifted-psychics").css("font-weight", "700");
            } else if (window.location.href.indexOf("/pricing") > 0) {
                $("#subnav-pricing").css("font-weight", "700");
            } else if (window.location.href.indexOf("/about-california-psychics") > 0) {
                $("#subnav-about-us").css("font-weight", "700");
            } else if (window.location.href.indexOf("/articles") > 0) {
                $("#subnav-articles").css("font-weight", "700");
            } else if (window.location.href.indexOf("topics") > 0) {
                $("#subnav-topics").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("abilities") > 0) {
                $("#subnav-abilities").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("tools") > 0) {
                $("#subnav-tools").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("styles") > 0) {
                $("#subnav-styles").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("hot-deals") > 0) {
                $("#subnav-hotDeals").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("vip-specials") > 0) {
                $("#subnav-vipDeals").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("new-psychics") > 0) {
                $("#subnav-newPsychics").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("premier-psychics") > 0) {
                $("#subnav-Premier").css("font-weight", "700");

            }
            else if (window.location.href.indexOf("staff-favorite-psychics") > 0) {
                $("#subnav-StaffPicks").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("customer-favorite-psychics") > 0) {
                $("#subnav-CustomerFavorites").css("font-weight", "700");
                $("#subnav-MyFavorites").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("rising-stars") > 0) {
                $("#subnav-RisingStars").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("about-psychic-readings") > 0) {
                $("#subnav-topics").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("my-favorite-psychics") > 0) {
                $("#subnav-MyFavorites").css("font-weight", "700");
            }
            else if (window.location.href.indexOf("psychic-readings") > 0) {
                $("#subnav-all").css("font-weight", "700");
            }
        }
    };

    OA.utils.callback = {
        objPrimaryNumber: new Object(),
        objReadingPrimaryNumber: new Object(),
        initialize: function (options, e) {

            //log.trace("initialize()");
            var self = this, dfr;
            $.extend(self.settings, options);

            OA.auth.setAuth();

            if (!OA.auth.session || _.isEmpty(OA.auth.session))
                return null;

            dfr = self.loadCallbackAdd();
            if (dfr != null) {
                $('#popupAddCallBackNumber .done').off('click').on('click', function (e) {
                    e.preventDefault();
                    OA.utils.callback.addNumber(e, "popupAddCallBackNumber");
                    return false;
                });
                $('#popupAddCallBackNumber .close').off('click').on('click', function (e) {
                    e.preventDefault();
                    OA.utils.callback.closeCallbackPopup(e, "");
                });
                $('#callbackCountry').off('click').on('change', function (e) {
                    e.preventDefault();
                    OA.utils.callback.onCountryChange(e, "popupAddCallBackNumber");
                });
                OA.utils.callback.talkEvent = e;
                OA.utils.callback.callbackPopup(OA.utils.callback.talkEvent, "psychic-reading");
            }
        },
        initializeFromChat: function (options, e) {
            var self = this, dfr;
            $.extend(self.settings, options);

            OA.auth.setAuth();

            if (!OA.auth.session || _.isEmpty(OA.auth.session))
                return null;

            OA.auth.setAuth();

            OA.utils.callback.talkEvent = e;
            OA.utils.callback.callbackPopup(OA.utils.callback.talkEvent, "dc-chat");
            $('#popupAddCallBackNumberPopup .done').off('click').on('click', function (e) {
                e.preventDefault();
                OA.utils.callback.addNumber(e, "popupAddCallBackNumberPopup");
                return false;
            });
            $('#popupAddCallBackNumberPopup .close').off('click').on('click', function (e) {
                e.preventDefault();
                OA.utils.callback.closeCallbackPopup(e, "dc-chat");
            });
            $('#popupAddCallBackNumberPopup #callbackCountry').off('click').on('change', function (e) {
                e.preventDefault();
                OA.utils.callback.onCountryChange(e, "popupAddCallBackNumberPopup");
            });
            $("#popupAddCallBackNumberPopup").find('input#callbackPhoneNumber').css('border', '1px solid #ababab');
        },
        countries: [],
        phoneTypes: [],
        objPsychicData: new Object(),
        callFrom: undefined,
        talkEvent: undefined,
        settings: {
            callbackCont: undefined,
            callbackAddCont: undefined,
            currentReadingId: undefined,
            currentPhoneNumber: undefined,
            currentPhoneCountryCode: undefined,
            currentReadingType: undefined,
            currentReadingCallDirection: undefined
        },
        addCallbackValidator: undefined,
        loadCountries: function (forceRefresh) {
            var self = this;

            if (!self.countries || self.countries && self.countries.length == 0) {
                OA.services.getCountryList().done(function (res) {
                    self.countries = res;
                });
            }
            return;
        },
        loadPhoneTypes: function () {
            var self = this;

            if (!self.phoneTypes || self.phoneTypes && self.phoneTypes.length == 0) {
                OA.services.getPhoneTypeList().done(function (res) {
                    self.phoneTypes = res;
                });
            }
            return;
        },
        getCountryCallingCode: function (countryCode) {
            var self = this, i, l;
            if (!self.countries || !self.countries.length) {
                self.loadCountries(true);
                if (!self.countries)
                    return null;
            }
            for (i = 0, l = self.countries.length; i < l; i++) {
                if (countryCode == self.countries[i].countryCode)
                    return self.countries[i].countryCallingCode;
            }
            return null;
        },
        loadCallbackAdd: function (readingId) {
            OA.auth.setAuth();
            var callbackTemplate = $("#callback-popup-temp").html();
            return $("#addNewCallback").html(_.template(callbackTemplate)).trigger('create');
        },
        onCountryChange: function (e, id) {
            var $form = $('#' + id).find("form"),
                countryCode,
                phoneNumber;

            countryCode = $form.find("select").val();
            phoneNumber = $form.find('input').val().replace(/ /g, "");

            if (phoneNumber != "") {
                if (countryCode == "USA" || countryCode == "CAN") {
                    var phonenovalidation = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
                    if (!phoneNumber.match(phonenovalidation)) {
                        $form.find('input').css('border', '1px solid red');
                        return;
                    }
                }
                else {
                    $form.find('input').css('border', '1px solid #ababab');
                }
            }
            else
                $form.find('input').css('border', '1px solid #ababab');
            OA.utils.callback.setInputMask();
        },
        callbackPopup: function (e, callFrom) {
            var self = this;
            OA.utils.callback.callFrom = callFrom;
            OA.utils.callback.talkEvent = e;

            OA.utils.callback.objPsychicData.extId = e.target.getAttribute("data-extid");
            OA.utils.callback.objPsychicData.name = e.target.getAttribute("data-name");
            OA.utils.callback.objPsychicData.talkToPsychic = e.target.getAttribute("data-talk") === 'true';
            OA.utils.callback.objPsychicData.targetButtonText = $(e.target).html();
            OA.utils.callback.objPsychicData.userInQueue = e.target.getAttribute("data-inqueue");
            OA.utils.callback.objPsychicData.prtappenabled = e.target.getAttribute("data-prtappenabled");
            OA.utils.callback.openAddCallback();
            $('#callbackPhoneNumber').inputmask('999-999-9999');
        },
        openAddCallback: function (e) {
            var self = this;
            var authCookie = OA.cookie.ManageCookieValue('auth');
            if (authCookie == undefined || authCookie == null) {
                OA.auth.redirect();
                return;
            }
            OA.cookie.ManageCookieValue('serverCustIdVerification', authCookie.custId);
            OA.utils.callback.bindCallbackCountries();
            OA.utils.callback.checkSession(e);
            $("#mobilecallbackcheckbox .ui-checkbox .ui-corner-all").removeClass('ui-btn');
            $("#mobilecallbackcheckbox .ui-checkbox .ui-corner-all").removeClass('ui-btn-icon-left');
            $("#popupAddCallBackNumber-screen").click(function () {
                OA.utils.callback.closeCallbackPopup();
            });
        },
        bindCallbackCountries: function () {
            var self = this;
            self.loadCountries();

            if (self.countries && $('#callbackCountry').length > 0) {
                $('#callbackCountry option').remove(); //clear all the options from the drop-down
                for (var i = 0; i < self.countries.length; i++) {
                    $("#callbackCountry").append("<option value=\"" + self.countries[i].countryCode + "\">" + " (+" + self.countries[i].countryCallingCode + ") " + self.countries[i].countryName + "</option>");
                }
            }
        },
        checkSession: function (e) {
            var self = this,
                session = OA.auth.session;
            if (OA.auth.isLoggedIn()) {
                try {
                    OA.services.getCustomerSession(session.custId, session.authToken).done(function (res) {
                        OA.utils.callback.openAdd(e, OA.utils.callback.settings.currentReadingId);
                    }).fail(function () {
                        OA.utils.callback.closeCallbackPopup(e, function () {
                            OA.auth.redirect();
                        });
                    });
                } catch (e) {
                    OA.utils.callback.closeCallbackPopup(e, function () {
                        OA.auth.redirect();
                    });
                }
            }
            else {
                OA.utils.callback.closeCallbackPopup(e, function () {
                    OA.auth.redirect();
                });
            }
        },
        openAdd: function (e) {
            var self = this;
            var $popup, $form;
            if (OA.utils.callback.callFrom == "dc-chat") {
                $popup = $('#popupAddCallBackNumberPopup');
            }
            else {
                $popup = $('#popupAddCallBackNumber');
            }
                $form = $popup.find('form');

            $("#mobilecallbackcheckbox").hide();
            if (OA.utils.callback.callFrom == "dc-chat") {
                $('#addNewCallbackPopup').trigger('openModal').trigger('create');
            }
            else {
            $('#popupAddCallBackNumber-popup').removeClass("popup-resize");
            $popup.show();
            $popup.popup();

            $popup.popup('open', { transition: "slideup" });
            }

            var $sel = $form.find("select#callbackCountry");
            $form.find("input").val('');
            $sel.prop('selectedIndex', 0);
            $sel.parent().find('span').text($sel.find('option:selected').text());
            $form.find('input').css('border', '1px solid #ababab');
            $.mobile.loading("hide");
            $(window).resize(function () {
                if (OA.utils.callback.callFrom != "dc-chat") {
                    if (window.innerWidth > OAApp.appsettings.MobileResolution) {
                        if (OA.utils.callback != undefined) {
                            self.callFrom = undefined;
                            $('#popupAddCallBackNumber').popup('close');
                        }
                    }
                    else {
                        if (!$('#popupAddCallBackNumber-popup').hasClass("popup-resize")) {
                            OA.utils.callback.openAdd();
                        }
                        else {
                            if (OA.utils.callback != undefined) {
                                self.callFrom = undefined;
                                $('#popupAddCallBackNumber').popup('close');
                            }
                        }
                    }
                }
            });
        },
        addNumber: function (e, id) {
            $.mobile.loading("show");
            var self = this;
            if (e != undefined) {
                e.preventDefault();
                e.stopPropagation();
            }
            var $form = $('#' + id).find("form"),
                countryCode,
                phoneNumber,
                phoneType,
                readingId = OA.utils.callback.settings.currentReadingId,
                readingType = OA.utils.callback.settings.currentReadingType,
                isprimary = false;

            countryCode = $form.find("select").first().val();
            phoneNumber = $form.find('input').val().replace(/ /g, "");
            isprimary = $("#mobile-set-callbackprimary").prop("checked");
            phoneType = $form.find("select").last().val();
            if (isprimary) {
                isprimary = 1;
            }
            else {
                isprimary = 0;
            }

            phoneNumber = phoneNumber.replace(/[_-]/g, '').trim();
            //check country code if it's USA or CAN,
            //then only check for 10 digit number validation.
            if (countryCode == "USA" || countryCode == "CAN") {
                var phonenovalidation = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
                if (!phoneNumber.match(phonenovalidation)) {
                    $form.find('input').css('border', '1px solid red');
                    $.mobile.loading("hide");
                    return;
                }
            }
            else {
                if (phoneNumber == "") {
                    $form.find('input').css('border', '1px solid red');
                    $.mobile.loading("hide");
                    return;
                }
                else {
                    phoneNumber = phoneNumber.replace(/\(/g, "").replace(/\)/g, "").replace(/\-/g, "");
                }
            }

            $form.find('input').css('border', '1px solid #ababab');

            $.mobile.loading("show");
            self.updateCallbackNumber(e, phoneNumber, countryCode, phoneType, isprimary);

            OA.settings.outdial = true;
        },
        closeCallbackPopup: function (e, callFrom) {
            var self = this;
            $.mobile.loading("hide");
            self.callFrom = undefined;
            if (callFrom == "dc-chat") {
                $('#addNewCallbackPopup').trigger('closeModal');
            }
            else {
                $('#popupAddCallBackNumber-popup').addClass("popup-resize");
                $('#popupAddCallBackNumber').popup('close');
            }
        },
        updateCallbackNumber: function (e, phoneNumber, countryCode, phoneType, isprimary) {
            var self = this;

            var auth = OA.cookie.ManageCookieValue('auth');
            if (auth == undefined || auth == null) {
                OA.auth.redirect();
                return;
            }
            $.mobile.loading('show');

            OA.utils.callback.makeCallbackPrimaryNumber(e, phoneNumber, countryCode, phoneType, isprimary);
        },
        makeCallbackPrimaryNumber: function (e, cPrimaryNumber, cPrimaryCountryCode, cPrimaryPhoneType, cIsPrimary) {
            var self = this, cPrimaryNumber, cPrimaryCountryCode, auth, cPrimaryPhoneType, cIsPrimary;

            var qs = OA.utils.stringHelpers.getQueryString();
            var extId = qs['extid'];
            auth = OA.cookie.ManageCookieValue('auth');
            if (auth == undefined || auth == null) {
                OA.auth.redirect();
                return;
            }

            cIsPrimary = 1;
            $.mobile.loading('show');
            OA.services.updateCallbackNumber(auth.custId, cPrimaryNumber, cPrimaryCountryCode, auth.authToken, cPrimaryPhoneType, cIsPrimary).done(function (res) {
                if (cIsPrimary == 1) {
                    auth.customerPhoneNumber = cPrimaryNumber;
                    auth.phoneCountryCode = cPrimaryCountryCode;
                    auth.phoneType = cPrimaryPhoneType;

                    var date = new Date();
                    date.setTime(date.getTime() + (3652 * 24 * 60 * 60 * 1000));
                    OA.cookie.ManageCookieValue('auth', auth, date, OAApp.appsettings.OATrackingCookieDomain);
                }
                $.mobile.loading("hide");
                self.getCustomerDetails();
                if (OA.utils.callback.objPsychicData != null) {
                    if (OA.utils.callback.callFrom == "dc-chat") {
                        self.callFrom = undefined;
                        $('#addNewCallbackPopup').trigger('closeModal');
                        $("#callNow").click();
                        $.mobile.loading("hide");
                    }
                    else {
                        OA.utils.talkButtonHelper.talkWithPsychicsClickHandler(OA.utils.callback.talkEvent, OA.utils.callback.objPsychicData.extId, OA.utils.callback.objPsychicData.name, OA.utils.callback.objPsychicData.talkToPsychic, OA.utils.callback.objPsychicData.userInQueue, OA.utils.callback.objPsychicData.prtappenabled);
                        OA.utils.callback.closeCallbackPopup();
                    }
                }
            }).fail(function (xhr) {
                OA.utils.ajaxHelpers.closeJQMLoader();
                $.mobile.loading("hide");
            });
        },
        getCustomerDetails: function () {
            var self = this;
            var auth = OA.auth.setAuth(),
                custId = !auth || !auth.custId ? undefined : auth.custId,
                template = "";
            if (custId != undefined) {
                OA.services.getCustomerDetails(custId).done(function (response) {
                    if (self.countryDictionary != undefined) {
                        self.bindPrimaryNumbers(response);
                        return response;
                    }
                });
            }
        },
        setInputMask: function () {
            if (!OA.utils.device.Android()) {
                if ($("#callbackCountry").val().toLowerCase().indexOf("united states") > -1 || $("#callbackCountry").val().toLowerCase() == "usa".toLowerCase()) {
                    $("#callbackPhoneNumber").inputmask('999-999-9999');
                }
                else {
                    $("#callbackPhoneNumber").inputmask('remove');
                }
            }
        },
        formatCallbackNumber: function (cb, rtnNumberOnly) {
            var callingCode;
            if (!cb)
                return '';
            if (!!cb.callDirection && cb.callDirection == 'CallIn' && !rtnNumberOnly)
                return 'I will call in';
            if (!cb.phoneNumber)
                return '';

            if (!cb.countryCode)
                callingCode = 1;
            else {
                callingCode = cb.countryCallingCode;
                if (!callingCode) {
                    callingCode = OA.utils.callback.getCountryCallingCode(cb.countryCode);
                }
            }
            return OA.utils.stringHelpers.formatPhoneNumber(cb.phoneNumber, callingCode);
        }

    };

}());;
(function () {
    "use strict";
    var Utils = OA.utils.ajaxHelpers;
    var Endpoints = OA.endpoints;
    OA.services = {
        basicAuth: function (token) {
            if (!token)
                return undefined;

            return {
                Authorization: token
            }
        },
        funnels: {
            ncCheckout: 1,
            buyPackage: 2,
            purchaseReading: 6,
            scheduleAppointment: 7,
            oldBuyPackage: 8,
            fiveFreeCheckout: 23,
            callRequest: 24
        },
        getEnvCookieName: function (cookieName) {
            return OAApp.appsettings.envPrefix + cookieName;
        },
        auth: function (provider, headers, clientId, saleLocation) {
            provider = provider || 'basic';
            var url = (!!provider ? Endpoints.Authenticate.authProvider(provider) : Endpoints.Authenticate.auth);
            if ((clientId != undefined || clientId != "") || (saleLocation != undefined || saleLocation != "")) {
                url = url + "?cid=" + clientId + "&sl=" + saleLocation;
            }
            return Utils.ajaxDefault({
                url: url,
                headers: headers,
                type: 'POST',
                sync: true
            });
        },
        getCustomerCreditCard: function (CustID, CCId, headers) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCustomerCreditCard(CustID, CCId),
                headers: headers
            });
        },
        getCustomerCreditCards: function (CustID, headers, authOptional) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCustomerCreditCards(CustID),
                headers: headers,
                authOptional: authOptional
            });
        },
        getCustomerDetails: function (CustID, token, sync) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCustomerDetails(CustID),
                headers: OA.services.basicAuth(token),
                sync: sync && sync === true
            });
        },
        getSiteInfo: function (currentUrl, referrerUrl, windowWidth) {
            return Utils.ajaxDefault({
                url: Endpoints.GetSiteInfo(),
                type: 'POST',
                data: {
                    CurrentUrl: currentUrl,
                    ReferrerUrl: referrerUrl,
                    WindowWidth: windowWidth
                }
            });
        },
        getSubscriptionSetting: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.GetSubscriptionSetting(data.CustId),
                headers: OA.services.basicAuth(token),
                data: data
            });
        },
        getStickyOffer: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.GetStickyOffer(data.CustId),
                headers: OA.services.basicAuth(token),
                data: data
            });
        },
        signOut: function (token) {
            return Utils.ajaxDefault({
                url: Endpoints.SignOut(),
                headers: OA.services.basicAuth(token),
                type: 'POST'
            });
        },
        validateNewCustomer: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.ValidateNewCustomer(),
                type: 'POST',
                data: data
            });
        },
        validateEmail: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.ValidateEmail(),
                type: 'POST',
                data: data,
                sync: true
            });
        },
        addCustomer: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.AddCustomer(),
                type: 'POST',
                data: data
            });
        },
        getCustomerReadingCount: function (data, headers) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCustomerReadingCount(data.CustId, data.LastVisitTime),
                headers: headers,
                data: data
            });
        },
        SearchPsychicsAutoComplete: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.SearchPsychicName(),
                type: 'POST',
                data: data
            });
        },
        GetFiveFreeMasInfo: function (windowWidth) {
            return Utils.ajaxDefault({
                url: Endpoints.GetFiveFreeMas(),
                data: {
                    WindowWidth: windowWidth
                },
                type: 'POST'
            });
        },
        FacebookAuthentication: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.FacebookAuthentication(),
                data: data,
                type: 'POST'
            });
        },
        FacebookAccessLog: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.FacebookAccessLog(),
                data: data,
                type: 'POST'
            });
        },
        GooglereCAPTCHA_Responce: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.GooglereCAPTCHA_Responce(),
                type: 'POST',
                data: data
            });
        },
        CheckSigninAttempt: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.CheckSigninAttempt(),
                type: 'POST',
                data: data
            });
        },
        addSupportLinkXML: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.AddSupportLinkXML(),
                type: 'POST',
                data: data
            });
        },
        getPsychicsAvailableScheduleSlot: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.getPsychicsAvailableScheduleSlot(data.ExtId),
                data: data,
                type: 'POST'
            });
        },
        getPsychicDetails: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.GetPsychicDetails(data.ExtId, data.CustId),
                data: data
            });
        },
        reserveCustomerCallback: function (headers, data) {
            //CHAT2-2231 switching from Endpoints.ReserveCustomerCallback(data.CustID) to reserve endpoint that does auto-reload
            data = { "callbackInfo": data };
            return Utils.ajaxDefault({
                url: Endpoints.ReserveCallback(),
                headers: headers,
                type: 'POST',
                data: data
            }).then(function (res) {
                if (res.result === 7) { res.result = 2; }
                return res;
            });
        },
        addMasToRequest: function (data) {
            return data;

        },
        addFavoritePsychic: function (CustID, headers, data) {
            return Utils.ajaxDefault({
                url: Endpoints.AddFavoritePsychic(CustID),
                headers: headers,
                type: 'POST',
                data: data
            });
        },
        removeFavoritePsychic: function (CustID, headers, data) {
            return Utils.ajaxDefault({
                url: Endpoints.RemoveFavoritePsychic(CustID),
                headers: headers,
                type: 'POST',
                data: data
            });
        },
        getPsychics: function (data, token, skipAppId) {
            if (!skipAppId)
                data.AppId = OAApp.getAppId();

            return Utils.ajaxDefault({
                url: Endpoints.GetPsychics,
                data: data,
                type: 'POST',
                headers: OA.services.basicAuth(token),
            });
        },
        getSignupCountryList: function () {
            return Utils.ajaxDefault({
                url: Endpoints.GetSignupCountryList,
                sync: true
            });
        },
        AddAffiliate: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.AddAffiliate(data),
                type: 'POST',
                data: data
            });
        },
        getStates: function (CountryCode) {
            return Utils.ajaxDefault({
                url: Endpoints.GetStates(CountryCode)
            });
        },
        getCityState: function (CountryCode, PostalCode) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCityState(CountryCode, PostalCode)
            });
        },
        getCountryList: function () {
            return Utils.ajaxDefault({
                url: Endpoints.GetCountryList,
                sync: true
            });
        },
        createCustomerAccount: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.CreateCustomerAccount(),
                type: 'POST',
                data: data
            });
        },
        createHoroscopeSignup: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.CreateHoroscopeSignup,
                data: data,
                type: 'POST'
            });
        },
        GetDiscountedOfferPageContent: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.GetDiscountedOfferPageContent,
                data: data,
                headers: OA.services.basicAuth(token),
                contentType: "application/x-www-form-urlencoded; charset=UTF-8"
            });
        },

        ChatReservationRelease: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.ChatReservationRelease(),
                data: data,
                type: 'POST'
            });
        },
        getChatAllowance: function (data) {
            console.log('GetChatAllowance()');
            return $.ajax({
                url: Endpoints.GetChatAllowance(),
                type: "GET",
                data: data,
                contentType: "application/json"
            });
        },
        ChatReservation: function (data) {
            console.log('ChatReservation()');
            return Utils.ajaxDefault({
                url: Endpoints.ChatReservation(),
                data: data,
                type: 'POST'
            });
        },
        ChatStart: function (data) {
            console.log('ChatStart()');

            return Utils.ajaxDefault({
                url: Endpoints.ChatStart(),
                data: data,
                type: 'POST'
            });
        },
        ChatChargeOnetime: function (data) {
            console.log('ChatChargeOnetime()');

            return Utils.ajaxDefault({
                url: Endpoints.ChatChargeOnetime(),
                data: data,
                type: 'POST'
            });
        },
        GetChatCustomerRecurringPayment: function (custId) {
            console.log('GetChatCustomerRecurringPayment()');

            return Utils.ajaxDefault({
                url: Endpoints.GetChatCustomerRecurringPayment(custId),
                //data: data,
                type: 'GET'
            });
        },
        ChatChargeRecurring: function (data) {
            console.log('ChatChargeRecurring()');

            return Utils.ajaxDefault({
                url: Endpoints.ChatChargeRecurring(),
                data: data,
                type: 'POST'
            });
        },
        getCustomerSession: function (CustID, token) {
            console.log("getCustomerSession()");
            return Utils.ajaxDefault({
                url: Endpoints.CustomerSession(CustID),
                headers: OA.services.basicAuth(token)
            });
        },
        updateCallbackNumber: function (custId, phoneNumber, countryCode, token, phoneType, setprimarynumber) {
            return Utils.ajaxDefault({
                url: Endpoints.UpdateCallbackNumber(custId),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'PhoneNumber': phoneNumber,
                    'PhoneCountry': countryCode,
                    'PhoneType': phoneType,
                    'SetPrimaryNumber': setprimarynumber
                },
                dataType: 'json'
            });
        },
        getIPCountryGeolocationInfo: function () {
            return Utils.ajaxDefault({
                url: Endpoints.GetIPCountryGeolocationInfo(),
                type: 'GET'
            });
        },
        GetGDPRCustomer: function (data) {
            console.log("GetGDPRCustomer()");
            return Utils.ajaxDefault({
                url: Endpoints.GetGDPRCustomer(data.CustId),
                data: data,
                type: 'POST'
            });
        },
        UpdateSubscriptions: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.UpdateSubscriptions(),
                data: data,
                type: 'POST'
            });
        },
        addCustomerCallback: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.AddCustomerCallback(data.CustId),
                data: this.addMasToRequest(data),
                type: 'POST',
                headers: OA.services.basicAuth(token)
            });
        },
        CreateCustomerRequest: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.CreateCustomerRequest(),
                data: data,
                type: 'POST',
                headers: OA.services.basicAuth(token),
            });
        },
        RedeemKRPoints: function (points, CustId, PINActivityId, token) {
            console.log("RedeemKRPoints()");
            return Utils.ajaxDefault({
                url: Endpoints.RedeemKRPoints(CustId),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'points': points
                }
            });
        },
        getPsychicStatus: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.GetPsychicStatus(),
                type: 'POST',
                data: data
            });
        },
        cancelCustomerCallback: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.CancelCustomerCallback(data.CustId, data.CallbackId),
                data: data,
                type: 'DELETE',
                headers: OA.services.basicAuth(token)
            });
        },
        getUpdatedStatus: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.GetUpdatedStatus(),
                type: "POST",
                data: data
            });
        },

        AddPsychicInCircle: function (CustId, ExtId, token) {
            return Utils.ajaxDefault({
                url: Endpoints.AddPsychicInCircle(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'CustId': CustId,
                    'ExtId': ExtId
                }
            });
        },
        GetPsychicInCircle: function (CustId, token) {
            return Utils.ajaxDefault({
                url: Endpoints.GetPsychicInCircle(CustId),
                headers: OA.services.basicAuth(token),
                type: 'GET'
            });
        },
        DeletePsychicInCircle: function (CircleId, CustId, token) {
            return Utils.ajaxDefault({
                url: Endpoints.DeletePsychicInCircle(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'CircleId': CircleId,
                    'CustId': CustId
                }
            });
        },
        CustomerBenefits: function (CustId, token) {
            console.log('CustomerBenefits()');
            return $.ajax({
                url: Endpoints.CustomerBenefits(),
                headers: OA.services.basicAuth(token),
                type: "GET",
                data: {
                    'CustId': CustId
                },
                contentType: "application/json"
            });
        },
        StartExtendCallbackQueueExtension: function (CustId, token) {
            console.log("RedeemKRPoints()");
            return Utils.ajaxDefault({
                url: Endpoints.StartExtendCallbackQueueExtension(CustId),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'CustId': CustId
                }
            });
        },
        RedeemCallbackQueue: function (points, CustId, token) {
            console.log("RedeemCallbackQueue()");
            return Utils.ajaxDefault({
                url: Endpoints.RedeemCallbackQueue(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'points': points,
                    'CustId': CustId
                }
            });
        },
        UpdatePsychicPlaceInCircle: function (CustId, CurrentPsychicCircleId, SwitchedPsychicCircleId, token) {
            return Utils.ajaxDefault({
                url: Endpoints.UpdatePsychicPlaceInCircle(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'CustId': CustId,
                    'CurrentPsychicCircleId': CurrentPsychicCircleId,
                    'SwitchedPsychicCircleId': SwitchedPsychicCircleId,

                }
            });
        },
        GetSimilarPsychic: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.GetSimilarPsychic(),
                type: 'POST',
                data: data
            });
        },
        posttestimonial: function (feedbackSource, custId, readingId, favorite, connect, comment, Subject, reason, token) {
            return Utils.ajaxDefault({
                url: Endpoints.posttestimonial(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'FeedbackSource': feedbackSource,
                    'CustId': custId,
                    'CallRecId': readingId,
                    'Favorite': favorite,
                    'Connect': connect,
                    'Comment': comment,
                    'Subject': Subject,
                    'Reason': reason

                }
            });
        },
        CustomerBirthChart: function (custId, DateOfBirth, Location, Reason, Email, token, Latitude, Longitude, Sent, CustomerTimeZone) {
            return Utils.ajaxDefault({
                url: Endpoints.CustomerBirthChart(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: {
                    'CustId': custId,
                    'DOB': DateOfBirth,
                    'Location': Location,
                    'Reason': Reason,
                    'Email': Email,
                    'Latitude': Latitude,
                    'Longitude': Longitude,
                    'Sent': Sent,
                    'CustomerTimeZone': CustomerTimeZone
                }
            });
        },

        joinKarmaRewards: function (data, token) {
            if (!data.addBonus) { data.addBonus = false; }
            return Utils.ajaxDefault({
                url: Endpoints.JoinKarmaRewards(data.CustID, data.addBonus),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: data
            });
        },
        FreeReadingRedeemKRPoints: function (data, token) {
            return Utils.ajaxDefault({
                url: Endpoints.FreeReadingRedeemKRPoints(),
                headers: OA.services.basicAuth(token),
                type: 'POST',
                data: data
            });
        },
        KarmaHubPointsActivity: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.KarmaHubPointsActivity(data),
                headers: OA.services.basicAuth(data.token),
                type: 'GET'
            });
        },
        GetCustomerGifts: function (CustId, token) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCustomerGifts(CustId),
                headers: OA.services.basicAuth(token),
                type: 'GET'
            });
        },
        GetCustomerBirthChartForecast: function (data) {
            return Utils.ajaxDefault({
                url: Endpoints.GetCustomerBirthChartForecast(data),
                headers: OA.services.basicAuth(data.token),
                type: 'GET',
            });
        },
    };
}());
;
(function () {
    'use strict';
    var selected = "";
    var Attemptsignin = 0;
    var CorrectEmail = 0;
    var recaptchaHeader;
    var recaptchaDesktop;
    var facebookSdkLoadCount = 0;
    OA.cpHeader = {
        isExternalJsEnable: true,
        supportLinkId: undefined,
        isSearchDone: false,
        timeInterval: 3000,
        timeoutReference: undefined,
        mobileResolution: OAApp.appsettings.MobileResolution,
        offersDictionary: {},
        isSearchDisplay: false,
        currentView: undefined,
        toggleSignInPanel: function (e) {
            if (facebookSdkLoadCount == 0) {
                (function (d, s, id) {
                    var js, fjs = d.getElementsByTagName(s)[0];
                    if (d.getElementById(id)) return;
                    js = d.createElement(s); js.id = id;
                    js.src = "//connect.facebook.net/en_US/sdk.js";
                    fjs.parentNode.insertBefore(js, fjs);
                }(document, 'script', 'facebook-jssdk'));
                facebookSdkLoadCount = 1;
                var FBappiid = OAApp.appsettings.Facebookappkey;
                window.fbAsyncInit = function () {
                    FB.init({
                        appId: FBappiid,
                        cookie: true,
                        xfbml: true,
                        version: 'v2.7'
                    });

                };
            }
            //add recaptcha file
            if (window.location.href.indexOf("sign-in") > -1) {
                $('.recapchasigninmobile').hide();
            }

            //var template = $("#signIn-temp").html();
            //$(".sign-in-popup-main").html(_.template(template));

            var emailTemplate = $("#signIn-email-temp").html();
            $("#signIn-email-div").html(_.template(emailTemplate));
            var passTemplate = $("#signIn-password-temp").html();
            $("#signIn-password-div").html(_.template(passTemplate));

            $('.Facebook-sign-in-error').css('display', 'none');
            $('.sign-in-error').css('display', 'none');
            $('.Facebook-sign-in-error').addClass('AccountLockMsg');
            $('.AccountLockMsg').css('display', 'none');
            $('.signInDesktopHeight').css('height', '642px');
            $('.sign-in-error-desktop-display').css('display', 'none');
            $('.sign-in-popup-main').toggle();

            // added code for TO-4586
            if ($("#DesktopHeader-popup").is(":visible")) {
                $('#DesktopHeader-popup #txtEmail').val($('#DesktopHeader #txtEmail').val());
                $('#DesktopHeader-popup #txtPassword').val($('#DesktopHeader #txtPassword').val());
            }
            //
        },
        getSubscription: function () {

            var auth = OA.cookie.ManageCookieValue('auth');
            OA.services.getSubscriptionSetting({
                CustId: auth.custId,
                Email: auth.userEmail
            }, auth.authToken)
                .done(function (res) {
                    var ExpDate = new Date();
                    ExpDate.setDate(ExpDate.getDate() + 365);
                    if (res.subscriptions === 0 || res.subscriptions === 128) {
                        OA.cookie.ManageCookieValue('isSubscribeNewsletter', false, ExpDate, '.californiapsychics.com');
                        OA.cookie.ManageCookieValue('DisplaySubscribeOptIn', true, ExpDate, '.californiapsychics.com');
                    }
                    else {
                        OA.cookie.ManageCookieValue('isSubscribeNewsletter', true, ExpDate, '.californiapsychics.com');
                        var currentDate = new Date();
                        currentDate.setDate(currentDate.getDate() - 1);
                        OA.cookie.ManageCookieValue('DisplaySubscribeOptIn', '', currentDate, '.californiapsychics.com');

                    }
                    if (res.subscriptions == 128 || res.subscriptions == 511) {
                        OA.cookie.ManageCookieValue('isSubscribedCRM', true, ExpDate, '.californiapsychics.com');
                        var currentDate = new Date();
                        currentDate.setDate(currentDate.getDate() - 1);
                        OA.cookie.ManageCookieValue('displayCRMoptin', '', currentDate, '.californiapsychics.com');
                    }
                    else {
                        OA.cookie.ManageCookieValue('isSubscribedCRM', false, ExpDate, '.californiapsychics.com');
                        OA.cookie.ManageCookieValue('displayCRMoptin', true, ExpDate, '.californiapsychics.com');
                    }
                }).fail(function (hrx) {

                });
        },
        toggleMyAccount: function (e) {
            var self = this,
                session = OA.auth.setAuth(),
                auth = OA.auth.setAuth();

            var template = $("#myaccount-temp").html();
            $(".my-account-popup-main").html(_.template(template));

            if (auth != undefined && auth != null) {
                OA.services.getCustomerDetails(session.custId, session.authToken).done(function (res) {
                    session.loggedIn = res.isAuthenticated;
                    session.dollarBalance = res.dollarBalance;
                    session.availableBalance = res.availableDollarBalance;
                    session.karmaPoints = res.karmaPoints;
                    session.isEmployeeAccount = res.isEmployeeAccount;
                    OA.auth.saveAuthCookie(session);
                    self.dollarBalance = OA.utils.stringHelpers.formatDollarAmount(res.availableDollarBalance);
                    self.karmaPoints = OA.cpHeader.formatKarmaPts(res.karmaPoints);
                    $('.psychic-balance').html(self.dollarBalance);
                    $('.karma-balance').html(self.karmaPoints);
                }).fail(function () {
                    window.location.href = OA.paths.psychicReading;
                }).always(function () {
                    OA.utils.ajaxHelpers.closeJQMLoader();
                });
            }
            if (!$('.my-account-popup-main').is(':visible')) {
                OA.utils.UpdateReadingCount();
            }
            $('.my-account-popup-main').toggle();
        },
        authenticate: function (loginPage) {
            OA.cpHeader.logout(false);
            //ga push event for popup
            $('.Facebook-sign-in-error').hide();
            $('p.err').html('');

            var self = this,
                username,
                password;
            var clientID = OA.utils.OAGA.getGAClientID();
            var saleLocation = "Mobile";

            if (window.innerWidth > self.mobileResolution) {
                saleLocation = "Desktop";
            }

            $.mobile.loading('show');

            var url = window.location.href;     // Returns full URL
            url = url.substring(url.indexOf('com') + 3);

            var qs = OA.utils.stringHelpers.getQueryString();
            if (qs['externaljs'] != undefined && qs['externaljs'] == 0) {
                OA.cpHeader.isExternalJsEnable = false;
            }

            if (OA.cpHeader.isExternalJsEnable) {
                dataLayer.push({
                    'event': 'OACPSignInTry',
                    'pageURL': url,
                });
            }
            if (loginPage == "profile") {
                username = $('#psychic-profile').find('#txtEmail').val();
                password = $('#psychic-profile').find('#txtPassword').val();
            }
            else if (loginPage == "sign-in") {
                username = $('.sign-in-desktop').find('#txtEmail').val();
                password = $('.sign-in-desktop').find('#txtPassword').val();
            }
            else {
                username = $('#txtEmail').val();
                password = $('#txtPassword').val();
            }


            if (username == "" || password == "") {
                $('.sign-in').css('max-height', '450px');
                $('.sign-in-error').css('height', '96px');
                if (OA.cpHeader.isExternalJsEnable) {
                    dataLayer.push({
                        'event': 'OACPSignInFailed',
                        'pageURL': url,
                    });
                }
                if (username == "") {
                    $('.sign-in-error').css('display', 'inline-block');
                    $('.sign-in-error-content').html('Please enter a valid email address.');
                    $.mobile.loading('hide');
                    return;
                }
                else {
                    if (!OA.cpHeader.validateEmail(username)) {
                        $('.sign-in-error').css('display', 'inline-block');
                        $('.sign-in-error-content').html('Please enter a valid email address.');
                        $.mobile.loading('hide');
                    }
                    else {
                        $('.sign-in-error').css('display', 'inline-block');
                        $('.sign-in-error-content').html('Please enter a password.');
                        $.mobile.loading('hide');
                    }
                    return;
                }
            }

            var valid = OA.cpHeader.validateEmail(username);


            if (valid) {

                //Create Mobile session and auth cookie

                OA.services.CheckSigninAttempt({
                    Email: $('#txtEmail').val()

                }).done(function (res) {

                    OA.cookie.ManageCookieValue('SignInAttempt', res.signInAttempt);
                    OA.cookie.ManageCookieValue('TrySigninWithCorrectEmail', res.lockAttempt);
                    OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmailDesktop').val());
                    if (res.lockAttempt >= 6) {
                        OA.cpHeader.LockCustomerAccountheader();
                        $.mobile.loading('hide');
                        return;
                    }

                    if (res.signInAttempt >= 3) {
                        OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmail').val());
                        OA.cpHeader.CountSigninAttemptafterfailheader();
                        return;
                    }
                    OA.services.auth(undefined, {
                        Authorization: "Basic " + OA.utils.stringHelpers.base64Encode(username + ':' + password)
                    }, clientID, saleLocation).done(function (res) {
                        OA.services.FacebookAccessLog({
                            ID: 0,
                            CustId: res.custId,
                            PINLogin: 1,
                            ApplicationID: 2,
                            LoginResultID: 1,
                            Email: username, clientID: clientID, saleLocation: saleLocation, password: password
                        }).done(function (res) {
                            console.log("createCustomerAccount Success " + res);
                        });

                        if (OA.cpHeader.isExternalJsEnable) {
                            dataLayer.push({
                                'event': 'OACPSignInSuccess',
                                'pageURL': url,
                                'UserID': res.custId,
                            });
                        }

                        OA.auth.successfulAuth(res).done(function () {
                            if (res != "") {

                                OA.cookie.RemoveCookieValue('sign-out');
                                //Remove five free cookie because on talk click always follow the ask flow - TO-4569
                                OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");
                                // check if customer has group ID = 16
                                if (res.custGroup && res.custGroup == OA.utils.enum.NCCustomerGroupType.NewCustomerLead || res.custGroup < 0) {
                                    OA.utils.leadCustomer.checkCustomerCreditCardData();
                                    //force user to opt in, so once they are logged in they are redirected to Ask question
                                    $.cookie("freeLeadCustomer", 1, { path: '/' });
                                } else {
                                    $.mobile.loading('hide');
                                    window.location.reload();
                                    //OA.cpHeader.redirectAfterLogin();
                                }
                            }
                            OA.cookie.RemoveCookieValue("sign-check");
                        });
                    }).fail(function (ex) {

                        if (OA.cpHeader.isExternalJsEnable) {
                            dataLayer.push({
                                'event': 'OACPSignInFailed',
                                'pageURL': url
                            });
                        }
                        var checksingin = OA.cookie.ManageCookieValue('sign-check');
                        checksingin = true;
                        OA.cookie.ManageCookieValue("sign-check", checksingin);
                        $('.sign-in-error').css('display', 'inline-block');
                        if (ex.responseJSON != null && ex.responseJSON.responseStatus != null && ex.responseJSON.responseStatus.errors[0] != null) {
                            var masPhone = OA.utils.stringHelpers.getMasPhone();
                            if (ex.responseJSON.responseStatus.errors[0].fieldName == "EmailNotFound") {
                                $('.sign-in-error').css('height', '150px');
                                $('.sign-in').css('max-height', '550px');
                                $('.sign-in-error-content').html("Sorry, we couldn't find an account using that email address. If you need help, please call Customer Service " + masPhone + '.');
                            }
                            else if (ex.responseJSON.responseStatus.errors[0].fieldName == "PINLogin") {
                                $('.sign-in-error').css('height', 'auto');
                                $('.sign-in').css('max-height', '550px');
                                $('.sign-in-error-content').html("You have entered your PIN number to log in. We recently made changes that require you to update to a new password. Please click on \"Forgot Password\" to create a new one or call Customer Service 1.800.773.3428 for assistance.");
                            }
                        }
                        else if (ex.responseJSON != null && ex.responseJSON.responseStatus != null && ex.responseJSON.responseStatus.message == 'Failed to retrieve the authenticated session') {
                            OA.cpHeader.logout();
                        }
                        else {
                            $('.sign-in-error').css('height', '125px');
                            $('.sign-in').css('max-height', '550px');
                            var forgotPasswordURL = OAApp.appsettings.desktopSiteUrl + "forgot-password";
                            $('.sign-in-error-content').html("Invalid email or password.");
                            OA.cpHeader.CountSigninAttemptafterfailheader();
                            OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmail').val());
                        }
                    }).always(function () {
                        $.mobile.loading('hide');
                    });
                }).fail(function (ex) {

                });


            }
            else {
                $('.sign-in-error').css('display', 'inline-block');
                $('.sign-in').css('max-height', '450px');
                $('.sign-in-error').css('height', '96px');
                $('.sign-in-error-content').html('Please enter a valid email address.');
                $.mobile.loading('hide');
                if (OA.cpHeader.isExternalJsEnable) {
                    dataLayer.push({
                        'event': 'OACPSignInFailed',
                        'pageURL': url,

                    });
                }
            }
        },
        createAskInfoCookie: function (data) {
            var self = this;
            var info = {
                firstName: data.firstName,
                lastName: data.lastName,
                email: data.email,
                dob: data.birthDate,
                password: '',
                sendFreeHoroAndNewsLetter: '',
                offerDuration: '',
                cardHolderName: '',
                cardNumber: '',
                expMonth: '',
                expYear: '',
                cvv: '',
                cardType: '',
                billingCountry: '',
                billingCountryName: '',
                zipCode: '',
                state: '',
                stateRegion: '',
                city: '',
                address1: '',
                address2: '',
                phoneCountry: '',
                phoneNumber: '',
                masId: '',
                custId: data.custId,
                callbackId: '',
                extId: '',
                offerId: '',
                priceId: '',
                transactionId: '',
                transactionAmount: '',
                statusCode: '',
                errorMessage: '',
                subscriptionId: '',
                package: OA.cpHeader.offersDictionary["1"],
                questionText: ''
            };
            if (data.custGroup == OA.utils.enum.NCCustomerGroupType.FreeLead17) {
                OA.cookie.ManageCookieValue('FiveFreeAccountInfo', info);
            }
            else {
                OA.cookie.ManageCookieValue('askAccountInfo', info);
            }
        },
        LockCustomerAccountheader: function () {
            var SignInAttemptEmail = OA.cookie.ManageCookieValue('SignInAttemptEmail');
            if (SignInAttemptEmail != null) {
                $('#txtEmail').val(SignInAttemptEmail);
            }
            $('.Facebook-sign-in-error-content').html("For security purposes, your account has been locked due to a maximum number of incorrect login attempts. Please call Customer Service at 1.800.773.3428 to unlock your account and reset your password.");
            $('.Facebook-sign-in-error-headerr').hide();
            $('.Facebook-sign-in-error').addClass('AccountLockMsg');
            $('.AccountLockMsg').css('height', '195px');
            $('.Facebook-sign-in-error').show();

            $('#sign-in-header-popup').css('max-height', '427px');
            $('.sign-in-header-popup').css('max-height', '550px');
            $('.DesktopHeader').css('max-height', '550px');

            $('.recapchasignindesktop').hide();
            $('.sign-in-error').css('display', 'none');

            $('#txtPassword').val('');
            $('.FacebookDesktop').hide();

            $('#txtPasswordDesktop').val('');
            OA.cookie.ManageCookieValue('SignInAttempt', 0);

            $('.sign-in-panel-button').css('pointer-events', 'all');
            $('.sign-in-panel-button').removeAttr('disabled');
        },
        reCaptchaResponce: function () {

            grecaptcha.reset();
            $('.recapchasignindesktop').hide();
            $('.remember-me').show();
            $('#txtEmail').removeAttr("disabled");
            $('#txtPassword').removeAttr("disabled");
            $('#txtEmail').css('color', 'rgb(0, 0, 0)');
            $('#txtPassword').css('color', 'rgb(0, 0, 0)');
            $('#txtEmail').css('color', 'rgb(0, 0, 0)');
            $('#txtPassword').css('color', 'rgb(0, 0, 0)');
            $('.RecaptchaError').hide();
            $('.sign-in-error-desktop').hide();
            $('.sign-in-desktop').addClass('signInDesktopHeight');
            $('.signInDesktopHeight').css('height', '650px');
            $('.sign-in-panel-button').css('pointer-events', 'all');
            $(".facebooksigninlogosigninHeader").css("pointer-events", 'all');
            $(".facebooksigninlogo").css("pointer-events", 'all');
            $(".loginwithFacebook").css("pointer-events", 'all');
            var eamil = OA.cookie.ManageCookieValue('SignInAttemptEmail');
            var GoogleRecaptchaResponce = grecaptcha.getResponse();
            OA.services.GooglereCAPTCHA_Responce({
                Responce: GoogleRecaptchaResponce,
                Email: eamil

            }).done(function (res) {

                console.log(" Done", res.result);
                if (res.result == true) {
                    Attemptsignin = 0;
                    OA.cookie.ManageCookieValue('SignInAttempt', Attemptsignin);
                    OA.cpHeader.enableSigninpanelAfterRecaptcha();

                }
                else {
                    $('.RecaptchaError').show();
                    alert(4);
                    return;

                }

            }).fail(function (res) {
                console.log(" Fail", res.result);
                $('.RecaptchaError').show();

            });
        },
        CountSigninAttemptafterfailheader: function () {

            var signinAttempt = OA.cookie.ManageCookieValue('SignInAttempt');
            signinAttempt = signinAttempt + 1;
            var trySigninWithCorrectEmail = OA.cookie.ManageCookieValue('TrySigninWithCorrectEmail');
            trySigninWithCorrectEmail = trySigninWithCorrectEmail + 1;
            if (trySigninWithCorrectEmail >= 6) {
                var SignInAttemptEmail = OA.cookie.ManageCookieValue('SignInAttemptEmail');

                if (SignInAttemptEmail != null) {
                    $('#txtEmail').val(SignInAttemptEmail);
                }
                $('.Facebook-sign-in-error-content').html("For security purposes, your account has been locked due to a maximum number of incorrect login attempts. Please call Customer Service at 1.800.773.3428 to unlock your account and reset your password.");
                $('.Facebook-sign-in-error-headerr').hide();
                $('.Facebook-sign-in-error').addClass('AccountLockMsg');
                $('.AccountLockMsg').css('height', '195px');
                $('.Facebook-sign-in-error').show();

                $('#sign-in-header-popup').css('max-height', '427px');
                $('.sign-in-header-popup').css('max-height', '550px');

                $('.recapchasignindesktop').hide();
                $.mobile.loading('hide');
                $('.sign-in-error').css('display', 'none');
                $('#txtPassword').val('');

                $('.FacebookDesktop').hide();

                $('#txtPasswordDesktop').val('');
                OA.cookie.ManageCookieValue('SignInAttempt', 0);

                $('.sign-in-panel-button').css('pointer-events', 'all');
                $('.sign-in-panel-button').removeAttr('disabled');
                return;
            }
            if (signinAttempt >= 3) {
                var url = 'https://www.google.com/recaptcha/api.js';
                if ($('script[src="' + url + '"]').length < 1) {
                    $('<script />', { src: 'https://www.google.com/recaptcha/api.js' }).appendTo('head');
                }
                $('.RecaptchaError').show();
                $('.recapchasignindesktop').show();
                OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmail').val());
                $('#sign-in-panel-button').attr('disabled', 'disabled');
                $('#txtEmail').attr('disabled', 'disabled');
                $('#txtPassword').attr('disabled', 'disabled');
                $('#txtEmail').css('color', 'rgb(138, 135, 135)');
                $('#txtPassword').css('color', 'rgb(138, 135, 135)');
                $('#txtEmail').css('background-color', '#eee');
                $('#txtPassword').css('background-color', '#eee');
                $('.sign-in-panel-button').css('pointer-events', 'none');
                $('#txtPassword').val('');
                $('#recapchamaimpage').hide();
                $.mobile.loading('hide');
                if (window.location.href.indexOf("sign-in") > -1) {
                    $('.recapchasigninmobile').hide();
                    $('.sign-in-error').hide();
                }
                OA.cpHeader.DisableSigninBox();
                $('.sign-in-main').css('height', '436px');
                $('.signInDesktopHeight').css('height', '786px');
                $(".sign-in-header-popup").css('max-height', '565px');

                $('.sign-in-error').show();
            }


        },
        DisableSigninBox: function () {
            var signinAttempt = OA.cookie.ManageCookieValue('SignInAttempt');
            signinAttempt = signinAttempt + 1;
            OA.cookie.ManageCookieValue('SignInAttempt', signinAttempt);
            if (signinAttempt >= 3) {
                $('.remember-me').hide();

                $('.sign-in-desktop').addClass('signInDesktopHeight');
                $('.sign-in-main').css('height', '590px');
                $('.signInDesktopHeight').css('height', '872px');
                $('.RecaptchaError').show();
                OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmailDesktop').val());
                $('#txtEmailDesktop').attr('disabled', 'disabled');
                $('#txtPasswordDesktop').attr('disabled', 'disabled');
                $('#txtEmailDesktop').css('color', '#8a8787)');
                $('.email-input').css('color', '#8a8787)');
                $('#txtPasswordDesktop').css('color', '#8a8787');
                $('#txtEmailDesktop').css('background-color', '#eee');
                $('#txtPasswordDesktopr').css('background-color', '#eee');
                $('#email').attr('disabled', 'disabled');
                $('#password').attr('disabled', 'disabled');
                $('#email').css('color', 'rgb(138, 135, 135)');
                $('#password').css('color', 'rgb(138, 135, 135)');
                $('#email').css('background-color', '#eee');
                $('#password').css('background-color', '#eee');
                $(".sign-in #submit-6").attr("disabled", "disabled");
                $.mobile.loading('hide');
                $('#password').val('');
                $('#txtPasswordDesktop').val('');
                $("#btnSignindesktop").css("pointer-events", 'none');
                $('.recapchasignindesktop').show();
                //$('.sign-in-header-popup').css('max-height', '570px');
                $('.DesktopHeader').css('max-height', '570px');
                $(".facebooksigninlogosigninHeader").css("pointer-events", 'none');
                $(".facebooksigninlogo").css("pointer-events", 'none');
                $('#submit-6').data('disabled', true);
                $('.facebooksigninlogo').data('disabled', true);
            }

        },
        CountSigninAttemptafterfail: function () {
            var mobileResolution = OAApp.appsettings.MobileResolution;

            var signinAttempt = OA.cookie.ManageCookieValue('SignInAttempt');
            signinAttempt = signinAttempt + 1;
            OA.cookie.ManageCookieValue('SignInAttempt', signinAttempt);

            var trySigninWithCorrectEmail = OA.cookie.ManageCookieValue('TrySigninWithCorrectEmail');
            trySigninWithCorrectEmail = trySigninWithCorrectEmail + 1;
            OA.cookie.ManageCookieValue('TrySigninWithCorrectEmail', trySigninWithCorrectEmail);

            if (trySigninWithCorrectEmail >= 6) {
                $('.sign-in-error-desktop').hide();
                $('.Facebook-sign-in-error').show();
                $('.Facebook-sign-in-error-content').html("For security purposes, your account has been locked due to a maximum number of incorrect login attempts. Please call Customer Service at 1.800.773.3428 to unlock your account and reset your password.");
                $('.RecaptchaError').hide();
                $('.sign-in-error-desktop').css('height', '190px')
                $('.Facebook-sign-in-error').addClass('AccountLockMsg');
                $('.AccountLockMsg').css('height', '195px');
                $('.recapchasignindesktop').hide();
                $('.sign-in-desktop').addClass('signInDesktopHeight');
                $('.sign-in-main').css('height', '630px');
                $('.signInDesktopHeight').css('height', '872px');
                $('.remember-me').show();
                OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmailDesktop').val());
                $('p.err').html("<label for='fields' class='error'>* For security purposes, your account has been locked due to a maximum number of incorrect login attempts. Please call Customer Service at 1.800.773.3428 to unlock your account and reset your password.");
                $('.sign-in-error').hide();
                $('#password').val('');
                $('#txtPasswordDesktop').val('');
                $.mobile.loading('hide');
                $(".sign-in #submit-6").removeAttr("disabled");
                OA.cookie.ManageCookieValue('SignInAttempt', 0);

                $('.sign-in-panel-button').css('pointer-events', 'all');
                $('.sign-in-panel-button').removeAttr('disabled');
                return;
            }
            if (signinAttempt >= 3) {
                $('.remember-me').hide();

                $('.sign-in-desktop').addClass('signInDesktopHeight');
                $('.sign-in-main').css('height', '590px');
                $('.signInDesktopHeight').css('height', '872px');
                $('.RecaptchaError').show();
                OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmailDesktop').val());
                $('#txtEmailDesktop').attr('disabled', 'disabled');
                $('#txtPasswordDesktop').attr('disabled', 'disabled');
                $('#txtEmailDesktop').css('color', '#8a8787)');
                $('.email-input').css('color', '#8a8787)');
                $('#txtPasswordDesktop').css('color', '#8a8787');
                $('#txtEmailDesktop').css('background-color', '#eee');
                $('#txtPasswordDesktopr').css('background-color', '#eee');
                $('#email').attr('disabled', 'disabled');
                $('#password').attr('disabled', 'disabled');
                $('#email').css('color', 'rgb(138, 135, 135)');
                $('#password').css('color', 'rgb(138, 135, 135)');
                $('#email').css('background-color', '#eee');
                $('#password').css('background-color', '#eee');
                $(".sign-in #submit-6").attr("disabled", "disabled");
                $.mobile.loading('hide');
                $('#password').val('');
                $('#txtPasswordDesktop').val('');
                $("#btnSignindesktop").css("pointer-events", 'none')
                $('.recapchasignindesktop').show();
                $('.sign-in-header-popup').css('max-height', '570px');
                $('.DesktopHeader').css('max-height', '570px');
                $(".facebooksigninlogosigninHeader").css("pointer-events", 'none');
                $(".facebooksigninlogo").css("pointer-events", 'none');
                $('#submit-6').data('disabled', true);
                $('.facebooksigninlogo').data('disabled', true);
            }


        },
        enableSigninpanelAfterRecaptcha: function () {
            var GoogleRecaptchaResponce = grecaptcha.getResponse();

            $('#txtEmailDesktop').removeAttr("disabled");
            $('#txtPasswordDesktop').removeAttr("disabled");
            $('#email').removeAttr("disabled");
            $('#password').removeAttr("disabled");
            $('#txtEmail').removeAttr("disabled");
            $('#txtPassword').removeAttr("disabled");
            $('#email').css('background-color', '#fff');
            $('#password').css('background-color', '#fff');
            $('#txtEmailDesktop').css('background-color', '#fff');
            $('#txtPasswordDesktop').css('background-color', '#fff');
            $('#txtEmail').css('background-color', '#fff');
            $('#txtPassword').css('background-color', '#fff');
            $(".facebooksigninlogosigninHeader").css("pointer-events", 'all');
            $(".facebooksigninlogo").css("pointer-events", 'all');
            $(".loginwithFacebook").css("pointer-events", 'all');
            $('#btnSignindesktop').css('pointer-events', 'all');
            $('.sign-in-panel-button').css('pointer-events', 'all');
            $('.recapchasignindesktop').hide();
            $('.remember-me').show();
            $('.RecaptchaError').hide();
            $('.sign-in-error-desktop').hide();
            $('.sign-in-desktop').addClass('signInDesktopHeight');
            $('.signInDesktopHeight').css('height', '650px');
            OA.cookie.ManageCookieValue('SignInAttempt', 0);
            $('#btnSignindesktop').css('pointer-events', 'all');
            $('#submit-6').data('disabled', false);
            $('.recapchasignindesktop').hide();
            $('.remember-me').show();
            $('.RecaptchaError').hide();
            $('.sign-in-error-desktop').hide();
            $('.sign-in-desktop').addClass('signInDesktopHeight');
            $('.signInDesktopHeight').css('height', '650px');
            OA.cookie.ManageCookieValue('SignInAttempt', 0);

        },
        formatCurrency: function (value) {
            if (isNaN(value)) {
                return;
            }
            if (value < 0) {
                return "-$" + Math.abs(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
            } else {
                return "$" + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
            }
        },
        formatKarmaPts: function (value) {
            if (isNaN(value)) {
                return;
            }
            return numeral(value).format('0,0') + ' pts';
        },
        formatKarma: function (value) {
            if (isNaN(value)) {
                return;
            }
            return numeral(value).format('0,0');
        },
        logout: function (e) {

            var refresh = true;
            if (e === false) {
                refresh = false;
            }

            //Mobile Sign-Out
            var authCookie = OA.cookie.ManageCookieValue('auth');
            var cookies = $.cookie();

            if (document.cookie && /ASP.NET_SessionId=\w+/g.test(document.cookie))
                document.cookie = "ASP.NET_SessionId=;path=/;domain=.californiapsychics.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";

            var arrCookies = ["auth", "mas", "MASPhoneNumber", "rememberMeData", "PsychicListOption", "offerpromoCode", "discountedOffer", "redDotURl"];
            for (var cookie in cookies) {
                if ($.inArray(cookie, arrCookies) === -1)
                    OA.cookie.RemoveCookieValue(cookie);
            }

            var date = new Date();
            date.setTime(date.getTime() + (3652 * 24 * 60 * 60 * 1000));
            if (_.isEmpty(authCookie)) {
                OA.cookie.RemoveCookieValue('auth');
            }
            else {
                OA.services.signOut(authCookie.authToken);
                authCookie.loggedIn = false;
                OA.cookie.ManageCookieValue('auth', authCookie, date, OAApp.appsettings.OATrackingCookieDomain);
            }

            if (OA.cookie.ManageCookieValue("impersonate") == 1) {
                OA.cookie.RemoveCookieValue("impersonate");
                OA.cookie.RemoveCookieValue("existingClogin");
                OA.cookie.RemoveCookieValue("rememberMeData");
                OA.cookie.RemoveCookieValue('auth');
            }

            OA.cookie.ManageCookieValue('sign-out', 1, date, OAApp.appsettings.OATrackingCookieDomain);
            if (refresh) window.location.reload();
            $('.my-account-popup-main').toggle();
        },
        goToHeaderLink: function (e) {
            var name = $(e.target).attr("data-name");
            switch (name) {
                case "home":
                    $.cookie("ActiveNavLink", "home", {
                        path: '#'
                    });
                    break;
                case "search":
                    $.cookie("ActiveNavLink", "search", { path: '/' });
                    break;
                case "horoscope":
                    $.cookie("ActiveNavLink", "horoscope", { path: '/' });
                    break;
                case "blog":
                    $.cookie("ActiveNavLink", "blog", { path: '/' });
                    break;
                case "myaccount":
                    $.cookie("ActiveNavLink", "myaccount", { path: '/' });
                    break;
                case "aboutus":
                    $.cookie("ActiveNavLink", "aboutus", { path: '/' });
                    break;
                case "support":
                    $.cookie("ActiveNavLink", "support", { path: '/' });
                    break;
                case "karmarewards":
                    $.cookie("ActiveNavLink", "karmarewards", { path: '/' });
                    break;
            }

            if (window.location.href.split('/')[3] == '' || window.location.href.split('/')[3] == '#' || window.location.href.split('/')[3] == 'mvc-home' || window.location.href.indexOf("dashboard") > 0 || window.location.href.indexOf("dashboard#") > 0) {
                if (window.location.href.indexOf("dashboard#") > 0) {
                    window.location.href = 'dashboard#';
                }
                else {
                    window.location.href = '#';
                }
            }
            else {
                window.location.href = '/';
            }

        },
        goToMainMenuLink: function (e) {
            if (window.location.href.split('/')[3] == '' || window.location.href.split('/')[3] == '#' || window.location.href.split('/')[3] == 'mvc-home' || window.location.href.indexOf("dashboard") > 0 || window.location.href.indexOf("dashboard#") > 0) {
                if (window.location.href.indexOf("dashboard#") > 0) {
                    window.location.href = 'dashboard#';
                }
                else {
                    window.location.href = '#';
                }
            }
            else {
                window.location.href = '/';
            }
        },
        headerSearchKeyUp: function (e) {
            var self = this,
                $e,
                search = $(".header-right #headersearch").val(),
                isSearchClicked = false;
            if ($("#DesktopHeader-popup").is(":visible")) {
                search = $("#psychic-profile #profile-header .header-right #headersearch").val();
            }

            var qs = OA.utils.stringHelpers.getQueryString();
            if (qs['externaljs'] != undefined && qs['externaljs'] == 0) {
                OA.cpHeader.isExternalJsEnable = false;
            }
            OA.cookie.ManageCookieValue('isAutoSearch', false);
            if (e != undefined) {
                $e = $(e.target);
            }
            $('.div-searchList').removeClass('searchData');
            if (search.length > 0) {
                search = search.trim();
            }
            if (search != "") {
                if (OA.cpHeader.isSearchDisplay == false) {
                    OA.cpHeader.showMobileSearchModule();
                }
                $('.div-searchList').show();
                if (e != undefined) {
                    OA.cpHeader.autoCompletePsychicName(e);
                }
                $('.div-searchList').addClass('searchData');
                $("#searchicon").removeClass("search-icon").addClass("search-icon-active");
                $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid #325e89");
                $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid #325e89");
                $(".cpheader #searchClear").removeClass("display-none").css("display", "inline-block");
                if (e != undefined) {
                    if (e.which == 13) {// enter
                        var cookieSearchText = OA.cookie.ManageCookieValue('SearchText');
                        if (cookieSearchText != null) {
                            if (cookieSearchText.toLowerCase() != search.toLowerCase()) {
                                OA.cpHeader.isSearchDone = false;
                            }
                        } else {
                            OA.cpHeader.isSearchDone = false;
                        }
                        isSearchClicked = true;
                    }
                }
                else if (e == undefined) {// search icon clicked
                    isSearchClicked = true;
                    OA.cpHeader.isSearchDone = false;
                }

                if (isSearchClicked) {
                    if (OA.cpHeader.isExternalJsEnable) {
                        OA.utils.tracking.sendSearchToGA(search);
                    }
                    if (!OA.cpHeader.isSearchDone) {
                        OA.cookie.ManageCookieValue('SearchText', search);
                        $('.div-searchList').hide();
                        if (window.location.href.indexOf('/psychic-readings') > 0) {
                            OA.app.psychicsListView.filterPsychicList(search);
                        } else {
                            //window.location.href = window.location.href + OA.paths.searchPsychicByText.format(search);
                            window.location.href = OA.paths.psychicReading + "?search=" + search;
                        }
                    }
                }
            } else {
                if (e != undefined) {
                    if (e.keyCode == 8 || e.keyCode == 46) { // backspace and delete
                        $('.div-searchList').hide();
                        if (search == "") {
                            $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid #325e89");
                            $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid #325e89");
                            $(".cpheader #searchClear").css("display", "none");

                            //Run Psychic Search to reset search and bring the whole psychic list
                            if (window.location.href.indexOf('/psychic-readings') > 0) {
                                OA.app.psychicsListView.filterPsychicList(search);
                            }
                            //  else {
                            //   window.location.href = "/mobile/" + OA.paths.psychic.list + "?search=" + search;
                            if (search == '') {
                                OA.cookie.RemoveCookieValue('SearchText');
                                $('#headersearch').val('');
                                $('#pychisc-filter-input').val('');
                                $('#profile-header').find('#DesktopHeader-popup').find("#headersearch").val('');
                                $("#searchMainDiv").addClass("search-main-div").removeClass("search-text-main-div");
                                $(".search-cancel").addClass("display-none").removeClass("display-inline-block");
                                $("#searchMainDiv a.ui-input-clear").addClass("ui-input-clear-hidden");
                                $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid #325e89");
                                $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid #325e89");
                                $(".cpheader #searchClear").css("display", "none");
                                $("#searchicon").removeClass("search-icon-active").addClass("search-icon");
                            }
                            // }
                        }
                    } else {
                        $('.div-searchList').hide();
                        $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid red");
                        $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid red");
                        $(".cpheader #searchClear").css("display", "none");
                    }
                } else if (e == undefined) {// search icon clicked
                    $('.div-searchList').hide();
                    $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid red");
                    $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid red");
                    $(".cpheader #searchClear").css("display", "none");
                }
            }
        },
        redirectToSearchEnterEvent: function (e) {
            if (e.keyCode == 13) {
                OA.cpHeader.redirectToSearch();
            }

        },
        redirectToSearch: function (e) {
            var self = this,
                $e = $(".header-right #headersearch");
            OA.cpHeader.headerSearchKeyUp();

        },
        loginKeyUp: function (e) {
            if (e.which == 13) {
                OA.cpHeader.logout(false);
                var self = this,
                    username,
                    password;
                var clientID = OA.utils.OAGA.getGAClientID();
                var saleLocation = "Mobile";

                if (window.innerWidth > self.mobileResolution) {
                    saleLocation = "Desktop";
                }
                username = $('#txtEmail').val();
                password = $('#txtPassword').val();
                $.mobile.loading('show');


                OA.services.CheckSigninAttempt({
                    Email: $('#txtEmail').val()

                }).done(function (res) {

                    console.log(" signinAttempe.......", res.lockAttempt);
                    console.log(" LockAccountAttempe................", res.signInAttempt);
                    OA.cookie.ManageCookieValue('SignInAttempt', res.signInAttempt);
                    OA.cookie.ManageCookieValue('TrySigninWithCorrectEmail', res.lockAttempt);
                    OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmailDesktop').val());
                    if (res.lockAttempt >= 6) {
                        OA.cpHeader.LockCustomerAccountheader();
                        $.mobile.loading('hide');
                        return;
                    }

                    if (res.signInAttempt >= 3) {
                        OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmail').val());
                        OA.cpHeader.CountSigninAttemptafterfailheader();
                        return;
                    }
                    OA.services.auth(undefined, {
                        Authorization: "Basic " + OA.utils.stringHelpers.base64Encode(username + ':' + password)
                    }, clientID, saleLocation).done(function (res) {
                        OA.services.FacebookAccessLog({
                            ID: 0,
                            CustId: res.custId,
                            PINLogin: 1,
                            ApplicationID: 2,
                            LoginResultID: 1,
                            Email: username, clientID: clientID, saleLocation: saleLocation, password: password
                        }).done(function (res) {
                            console.log("createCustomerAccount Success" + res);
                        })

                        OA.auth.successfulAuth(res).done(function () {
                            if (res != "") {
                                OA.cookie.RemoveCookieValue('sign-out');
                                // check if customer has group ID = 16
                                if (res.custGroup && res.custGroup == OA.utils.enum.NCCustomerGroupType.NewCustomerLead || res.custGroup < 0) {
                                    OA.utils.leadCustomer.checkCustomerCreditCardData();
                                    //force user to opt in, so once they are logged in they are redirected to Ask question
                                    $.cookie("freeLeadCustomer", 1, { path: '/' });
                                } else {
                                    $.mobile.loading('hide');
                                    OA.cpHeader.redirectAfterLogin();
                                }
                            }
                            OA.cookie.RemoveCookieValue("sign-check");
                        });
                    }).fail(function (ex) {
                        var checksingin = OA.cookie.ManageCookieValue('sign-check');
                        checksingin = true;
                        OA.cookie.ManageCookieValue("sign-check", checksingin);
                        $.mobile.loading('show');
                        $('.sign-in-error').css('display', 'inline-block');
                        if (ex.responseJSON != null && ex.responseJSON.responseStatus != null && ex.responseJSON.responseStatus.errors[0] != null) {
                            var masPhone = OA.utils.stringHelpers.getMasPhone();
                            if (ex.responseJSON.responseStatus.errors[0].fieldName == "EmailNotFound") {
                                $('.sign-in-error').css('height', '150px');
                                $('.sign-in').css('max-height', '550px');
                                $('.sign-in-error-content').html("Sorry, we couldn't find an account using that email address. If you need help, please call Customer Service " + masPhone + '.');
                            }
                            else if (ex.responseJSON.responseStatus.errors[0].fieldName === "PINLogin") {
                                $('.sign-in-error').css('height', 'auto');
                                $('.sign-in').css('max-height', '550px');
                                $('.sign-in-error-content').html("You have entered your PIN number to log in. We recently made changes that require you to update to a new password. Please click on \"Forgot Password\" to create a new one or call Customer Service 1.800.773.3428 for assistance.");
                            }
                        }
                        else {
                            $('.sign-in-error').css('height', '125px');
                            $('.sign-in').css('max-height', '550px');
                            var forgotPasswordURL = OAApp.appsettings.desktopSiteUrl + "forgot-password";
                            $('.sign-in-error-content').html("Invalid email or password.");
                            OA.cpHeader.CountSigninAttemptafterfailheader();
                            OA.cookie.ManageCookieValue('SignInAttemptEmail', $('#txtEmail').val());
                            $.mobile.loading('hide');
                        }
                    }).always(function () {
                        $.mobile.loading('hide');
                    });
                }).fail(function (ex) {

                });

            }
        },
        createaccountClickHandler: function (e) {
            OA.cookie.RemoveCookieValue('serversessionverification');
            OA.cookie.RemoveCookieValue('serverCustIdVerification');

            if (e != undefined) {
                e.preventDefault();
                e.stopPropagation();
            }

            //Remove five free cookie because on talk click always follow the ask flow - TO-4569
            OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");

            var objOffers = new Object();
            objOffers.packageName = "Popular";
            objOffers.packageType = "1";
            objOffers.packageBasePrice = "$100";
            objOffers.packageOfferPrice = "$20";
            objOffers.saveAmount = "$80";

            var acctInfo = OA.cookie.ManageCookieValue("askAccountInfo");

            if (acctInfo == null) {
                var info = {
                    firstName: '',
                    lastName: '',
                    email: '',
                    dob: '',
                    password: '',
                    sendFreeHoroAndNewsLetter: '',
                    offerDuration: '',
                    cardHolderName: '',
                    cardNumber: '',
                    expMonth: '',
                    expYear: '',
                    cvv: '',
                    cardType: '',
                    billingCountry: '',
                    billingCountryName: '',
                    zipCode: '',
                    state: '',
                    stateRegion: '',
                    city: '',
                    address1: '',
                    address2: '',
                    phoneCountry: '',
                    phoneNumber: '',
                    masId: '',
                    custId: '',
                    callbackId: '',
                    extId: '',
                    offerId: '',
                    priceId: '',
                    transactionId: '',
                    transactionAmount: '',
                    statusCode: '',
                    errorMessage: '',
                    subscriptionId: '',
                    package: objOffers,
                    questionText: ''
                };
            }
            else {
                acctInfo.package = objOffers;
                info = acctInfo;
            }
            OA.cookie.ManageCookieValue('askAccountInfo', info);
            window.location.href = "../" + OA.paths.askNcCheckout.createAccount + "?fromaskitself=true";
        },
        introofferClickHandler: function (e) {
            //Remove five free cookie because on talk click always follow the ask flow - TO-4569
            OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");
        },
        desktopClearSearch: function () {
            var search = $(".header-right #headersearch").val();
            $('.div-searchList').hide();
            $('.div-searchList').removeClass('searchData');
            OA.cookie.RemoveCookieValue('SearchText');
            $('#headersearch').val('');
            $('#pychisc-filter-input').val('');
            $('#profile-header').find('#DesktopHeader-popup').find("#headersearch").val('');
            $("#searchMainDiv").addClass("search-main-div").removeClass("search-text-main-div");
            $(".search-cancel").addClass("display-none").removeClass("display-inline-block");
            $("#searchMainDiv a.ui-input-clear").addClass("ui-input-clear-hidden");
            $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid #325e89");
            $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid #325e89");
            $(".cpheader #searchClear").css("display", "none");
            $("#searchicon").removeClass("search-icon-active").addClass("search-icon");

            //Run Psychic Search to reset search and bring the whole psychic list
            if (OA.cpHeader.timeoutReference) {
                clearTimeout(OA.cpHeader.timeoutReference);
            }

            if (window.location.href.indexOf('/psychic-readings') > 0) {
                OA.app.psychicsListView.filterPsychicList("");
            }
        },
        clearPsychicsSearch: function (e) {
            OA.cpHeader.desktopClearSearch();
            $('.seachList').html('');
            $(".search-module #pychisc-filter-input").val("");
            $('.div-searchList').hide();
        },
        redirectAfterLogin: function () {
            var redirect = OA.cookie.ManageCookieValue('redirect');
            if (redirect != null && redirect != undefined && redirect != '') {
                $.mobile.loading('show');
                OA.cookie.RemoveCookieValue('redirect');

                //remove tilde from beginning of redirect URL, if it exists (TO-3087)
                if (redirect.charAt(0) === '~')
                    redirect = redirect.substring(1, redirect.length);

                window.location.href = redirect;
            }
            else {
                window.location.reload();
            }
        },
        autoCompletePsychicName: function (e) {
            var self = this,
                custId,
                auth = OA.cookie.ManageCookieValue('auth'),
                searchText = "";
            if (window.innerWidth >= self.mobileResolution) {
                searchText = $(".header-right #headersearch").val();
                if ($("#DesktopHeader-popup").is(":visible")) {
                    searchText = $("#psychic-profile #profile-header .header-right #headersearch").val();
                }
            }
            else {
                searchText = $(".search-module #pychisc-filter-input").val();
            }
            if (auth) {
                custId = auth.custId;
            }
            var data = { CustId: custId, SearchText: searchText };

            OA.services.SearchPsychicsAutoComplete(data).done(function (response) {
                self.renderAutoCompletelist(response);
            })
        },
        currentUpIndex: 0,
        currentDownIndex: 0,
        renderAutoCompletelist: function (response) {
            var self = this;
            selected = "";
            var itemlength = response.length;
            if (itemlength > 0) {
                $('.seachList').html('');
                var strHTML = '';
                for (var i = 0; i < itemlength; i++) {
                    strHTML += "<li data-item='" + response[i].psychicName + "' data-extid='" + response[i].psychicExtID + "' data-index='" + i + "'>" + response[i].psychicName + "</li>";
                }

                self.currentUpIndex = 0;
                self.currentDownIndex = 0;
                $('.seachList').append(strHTML);
                $('.div-searchList').scrollTop(0);
                $('.seachList li').bind('click', function (event) { self.setSearchText(event); });

                var li;
                var liSelected;
                var searchid = null, divsearchid;
                if (window.innerWidth > self.mobileResolution) {
                    searchid = '#headersearch';
                    selected = "";
                }
                else {
                    searchid = '#pychisc-filter-input';
                    selected = "";
                }

                $(searchid).on('keyup', function (e) {
                    if (window.innerWidth > self.mobileResolution) {
                        li = $('#lstdesktop > li');
                        divsearchid = $('#divdesktop');
                    }
                    else {
                        li = $('#lstmobile > li');
                        divsearchid = $('#divmobilesearch');
                    }
                    if (divsearchid.is(":visible") == false) {
                        return;
                    }
                    if (e.which === 40) {
                        self.currentDownIndex = 0;
                        if (liSelected) {
                            var next = liSelected.next();
                            if (next.length > 0) {
                                liSelected.removeClass('seachListhovered');
                                liSelected = next.addClass('seachListhovered');
                                selected = next.text();
                                next.focus();
                            } else {
                                liSelected.removeClass('seachListhovered');
                                liSelected = li.eq(0).addClass('seachListhovered');
                                selected = li.eq(0).text();
                                li.focus();

                            }
                        } else {
                            liSelected = li.eq(0).addClass('seachListhovered');
                            selected = li.eq(0).text();
                            li.focus();

                        }
                        $(searchid).val(selected);
                        var currentIndex = $("ul.seachList").find("li.seachListhovered").attr("data-index");
                        if (currentIndex != undefined) {

                            if ((currentIndex % 5) != 0) {
                                if (self.currentUpIndex != currentIndex) {
                                    self.currentUpIndex = currentIndex;
                                    if (currentIndex == 1)
                                        $("div.searchData").animate({ scrollTop: 0 }, 50);
                                }
                            }
                            else {
                                if (self.currentUpIndex != currentIndex) {
                                    self.currentUpIndex = currentIndex;

                                    var $container = $("div.searchData");
                                    var $scrollTo = $('ul.seachList li.seachListhovered');
                                    var sTop = $scrollTo.offset().top - $container.offset().top + $container.scrollTop();

                                    var a = currentIndex / 5;
                                    var b = a * 10;
                                    $container.animate({ scrollTop: a * 110 + b }, 30);
                                }
                            }

                        }
                    } else if (e.which === 38) {
                        self.currentUpIndex = 0;
                        if (liSelected) {
                            var next = liSelected.prev();
                            if (next.length > 0) {
                                liSelected.removeClass('seachListhovered');
                                liSelected = next.addClass('seachListhovered');
                                selected = next.text();
                                next.focus();
                            } else {
                                liSelected.removeClass('seachListhovered');
                                liSelected = li.last().addClass('seachListhovered');
                                selected = li.last().text();
                                li.focus();

                            }
                        } else {
                            liSelected = li.last().addClass('seachListhovered');
                            selected = li.last().text();
                            li.focus();
                        }
                        $(searchid).val(selected);

                        var index = $("ul.seachList").find("li.seachListhovered").attr("data-index");
                        if (index != undefined) {
                            if ((index % 5) != 0) {
                                if (self.currentDownIndex != index) {
                                    self.currentDownIndex = index;
                                    if (index == $("#lstdesktop li").length) {
                                        self.currentDownIndex = index;
                                        $("div.searchData").animate({ scrollTop: ($("#lstdesktop li").length) * 30 }, 50);
                                    }
                                }
                            }
                            else {
                                if (self.currentDownIndex != index) {
                                    self.currentDownIndex = index;

                                    var $container = $("div.searchData");
                                    var $scrollTo = $('ul.seachList li.seachListhovered');

                                    if (index == $("#lstdesktop li").length) {
                                        $("div.searchData").animate({ scrollTop: ($("#lstdesktop li").length) * 30 }, 50);
                                    }
                                    else {

                                        var a = (index - 5) * 30;
                                        $container.animate({ scrollTop: a }, 30);
                                    }
                                }
                            }
                        }

                    } else if (e.which === 8 || e.which === 46 || e.which === 65) { // backspace and delete
                        $('.div-searchList').hide();
                        $('.seachList li').removeClass("seachListhovered");
                        selected = "";
                        if (search == "") {
                            $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid #325e89");
                            $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid #325e89");
                            $(".cpheader #searchClear").css("display", "none");

                            //Run Psychic Search to reset search and bring the whole psychic list
                            if (window.location.href.indexOf('/psychic-readings') > 0) {
                                OA.app.psychicsListView.filterPsychicList(search);
                            }
                            //  else {
                            //   window.location.href = "/mobile/" + OA.paths.psychic.list + "?search=" + search;
                            if (search == '') {
                                OA.cookie.RemoveCookieValue('SearchText');
                                $('#headersearch').val('');
                                $('#pychisc-filter-input').val('');
                                $('#profile-header').find('#DesktopHeader-popup').find("#headersearch").val('');
                                $("#searchMainDiv").addClass("search-main-div").removeClass("search-text-main-div");
                                $(".search-cancel").addClass("display-none").removeClass("display-inline-block");
                                $("#searchMainDiv a.ui-input-clear").addClass("ui-input-clear-hidden");
                                $(".cpheader #DesktopHeader #headersearch").css("border", "1px solid #325e89");
                                $(".cpheader #DesktopHeader-popup #headersearch").css("border", "1px solid #325e89");
                                $(".cpheader #searchClear").css("display", "none");
                                $("#searchicon").removeClass("search-icon-active").addClass("search-icon");

                            }
                            // }
                        }
                    }
                    else if (e.which == 13) {//Enter key pressed                      
                        var searchText = $('.seachList li.seachListhovered').attr("data-item");
                        var searchTerm = $('.seachList li.seachListhovered').attr("data-extid");
                        if (searchText != undefined || searchTerm != undefined) {
                            self.setSearchTextByEnter(searchText, searchTerm);
                        }

                    }
                    if (selected != "") {
                        return false;
                    }
                });

                var serachElement = $('.search-module .div-searchList .seachList li').length;
                if (serachElement < 6) {
                    var divHeight = serachElement * 28.5;
                    $('.searchData').css("height", divHeight + 'px');
                }
                else {
                    $('.searchData').css("height", '171px');
                }
            }
        },
        setSearchText: function (e) {
            var self = this,
                $el = $(e.target),
                searchText = $el.attr("data-item"),
                searchTerm = $el.attr("data-extid");
            self.bindSearchData(searchText, searchTerm);
        },
        setSearchTextByEnter: function (searchText, searchTerm) {
            var self = this;
            self.bindSearchData(searchText, searchTerm);
        },
        bindSearchData: function (searchText, searchTerm) {
            var self = this;
            if (window.innerWidth > self.mobileResolution) {
                $(".header-right #headersearch").val(searchText);
                OA.cookie.ManageCookieValue('SearchText', searchText);
            }
            else {
                $(".search-module #pychisc-filter-input").val(searchText);
            }
            OA.cpHeader.isSearchDone = true;
            OA.cookie.ManageCookieValue('isAutoSearch', true);
            var qs = OA.utils.stringHelpers.getQueryString();
            if (qs['externaljs'] != undefined && qs['externaljs'] == 0) {
                OA.cpHeader.isExternalJsEnable = false;
            }
            if (OA.cpHeader.isExternalJsEnable) {
                OA.utils.tracking.sendSearchToGA(searchText);
            }
            if (window.location.href.indexOf('/psychic-readings') > 0) {
                OA.app.psychicsListView.filterPsychicList(searchTerm);
                $("#headersearch").blur();
            } else {
                //window.location.href = window.location.href + OA.paths.searchPsychic.format(searchText, searchTerm);
                window.location.href = OA.paths.psychicReading + "?search=" + searchText + "&extid=" + searchTerm;
            }
        },
        showSupportHelpPopup: function (e) {
            e.preventDefault();
            e.stopPropagation();
            $.mobile.loading('show');
            var self = this;
            $('#DesktopFooter').find('#footer2').find('.get-help').html('');
            $('#DesktopFooter-popup').find('#footer2').find('.get-help').html('');
            if (window.innerWidth > self.mobileResolution) {
                OAApp.appsettings.currentView = "Desktop";
                self.renderDesktopHelpPopup();
                $.mobile.loading('hide');
            } else {
                OAApp.appsettings.currentView = "Mobile";
                self.renderMobileHelpPopup();
                $.mobile.loading('hide');
            }
        },
        showMobileSearchModule: function () {
            $(".mobile-search-module").html('');
            var template = $("#mobile-search-temp").html();
            $(".mobile-search-module").html(_.template(template));
            $('.mobile-search-module').trigger('create');
            //$(".ui-input-search").trigger("create");
            if (window.innerWidth <= OAApp.appsettings.MobileResolution) {
                if (OAApp.appsettings.currentView == "Mobile" || OAApp.appsettings.currentView == "") {
                    $('.search-module').slideDown().show();
                    $('.mobile-search-module').show();
                    $("html, body").animate({ scrollTop: 0 }, 0);
                    $('.div-searchList').hide();
                    $('.ui-content').addClass('ui-content-search-margin');
                    if (window.location.href.indexOf("/my-account") > 0) {
                        $('.leftPanal').addClass('leftPanel-search-margin');
                    }
                }
                if (window.innerWidth < OAApp.appsettings.MobileResolution)
                {
                    var stickyhieght = $("#other-header").height();
                    stickyhieght = 50 + stickyhieght+"px";
                    $(".mobile-search-module").css('margin-top', stickyhieght);
                    $('.mobile-search-module').addClass("ui-header-fixed");
                    if ($("#sticky-offer-bar-mobile").is(":visible")) {
                        $("#kr-banner-inner").css("margin-top", "118px");
                    }
                    else {
                        $("#kr-banner-inner").css("margin-top", "80px");
                    }
                }
               

                
            }
            else {
                $('.mobile-search-module').hide();
                $(".search-module").slideUp(300);
            }
            OA.cpHeader.isSearchDisplay = true;
        },
        renderMobileSearchModule: function (e) {
            $(".ui-input-clear").css("display", "none");
            //$('.header').removeClass$('.mobile-search-module').addClass("ui-header-relative");
            $('.ui-panel-wrapper').css("margin-top", "0px");
            OA.cpHeader.showMobileSearchModule();
        },
        mobileHeaderSearchKeyUp: function (e) {
            var self = this,
                $e = $(".search-module #pychisc-filter-input"),
                searchText = $e.val(),
                isSearchClicked = false;

            var qs = OA.utils.stringHelpers.getQueryString();
            if (qs['externaljs'] != undefined && qs['externaljs'] == 0) {
                OA.cpHeader.isExternalJsEnable = false;
            }
            $('.ui-input-clear').bind('click', function (event) { self.mobileClearSearch(event); });

            $("#searchMainDiv").addClass("search-text-main-div").removeClass("search-main-div");
            $(".search-cancel").addClass("display-inline-block").removeClass("display-none");
            $(".ui-input-clear").css("display", "block");
            OA.cookie.ManageCookieValue('isAutoSearch', false);
            if (searchText.length > 0) {

                searchText = searchText.trim();
            }
            if (searchText != "") {
                //call autocomplete functionality
                $('.div-searchList').show();
                $('.div-searchList').addClass('searchData');
                if (e != undefined) {
                    OA.cpHeader.autoCompletePsychicName(e);
                    if (e.which == 13) {// enter
                        isSearchClicked = true;
                    }
                } else if (e == undefined) {// search icon clicked
                    isSearchClicked = true;
                }

                if (isSearchClicked) {
                    if (OA.cpHeader.isExternalJsEnable) {
                        OA.utils.tracking.sendSearchToGA(searchText);
                    }
                    OA.cookie.ManageCookieValue('SearchText', searchText);
                    //window.location.href = window.location.href + OA.paths.searchPsychicByText.format(searchText, 0);
                    window.location.href = OA.paths.psychicReading + "?search=" + searchText;
                }
            }
            else {
                if (e != undefined) {
                    if (e.keyCode == 8 || e.keyCode == 46) { // backspace and delete
                        $('.div-searchList').hide();
                        if (search == '') {
                            OA.cookie.RemoveCookieValue('SearchText');
                        }
                    }
                    else {
                        $('.div-searchList').hide();
                    }
                } else if (e == undefined) {
                    $('.div-searchList').hide();
                }
            }
        },
        mobileSearchCancel: function (e) {
            if (window.innerWidth < OAApp.appsettings.MobileResolution) {
                $('.mobile-search-module').removeClass("ui-header-fixed");
                $("#kr-banner").css("margin-top", "0px");
                $(".mobile-search-module").css('margin-top', '0px');
            }
            $('.seachList').html('');
            $('.div-searchList').hide();
            $(".search-module #pychisc-filter-input").val("");
            $("#searchMainDiv").addClass("search-main-div").removeClass("search-text-main-div");
            $(".search-cancel").addClass("display-none").removeClass("display-inline-block");
            $(".search-module").slideUp(300);
            $("html, body").animate({ scrollTop:0 }, 0);
            $('.ui-content').removeClass('ui-content-search-margin');
            if (window.location.href.indexOf("/my-account") > 0) {
                $('.leftPanal').removeClass('leftPanel-search-margin');
            }

            if ($("div[data-role=header]").css("position") == "fixed") {
                if ($("#sticky-offer-bar-mobile").is(":visible")) {
                    $(".ui-panel-wrapper").css("margin-top", "85px");
                }
                else {
                    $(".ui-panel-wrapper").css("margin-top", "50px");
                }
            }
          
            OA.cpHeader.isSearchDisplay = false;
          
        },
        mobileClearSearch: function (e) {
            var self = this;
            $(".ui-input-clear").css("display", "none");
            $(".search-module #pychisc-filter-input").val("");
            $('.seachList').html('');
            $('.div-searchList').hide();
            OA.cpHeader.desktopClearSearch();
        },
        searchTextFocus: function () {
           
            $('.ui-content').addClass('ui-content-search-margin');
            if (window.innerWidth <= OAApp.appsettings.MobileResolution) {
                if (OAApp.appsettings.currentView == "Mobile" || OAApp.appsettings.currentView == "") {
                    $("html, body").animate({ scrollTop: 0 }, 0);
                }
            }
            else {
                $('.mobile-search-module').hide();
                $(".search-module").slideUp(300);
            }
        },
        redirectToMobileSearch: function (e) {
            OA.cpHeader.mobileHeaderSearchKeyUp();
        },
        loginwithFacebookImageHeader: function () {
            var whichpage = "signin_Header";
            var saleLocation = "Mobile";

            if (window.innerWidth > OAApp.appsettings.MobileResolution) {
                saleLocation = "Desktop";
            }
            OA.LoginWithFacebookInit.GetfacebookUserDetail(whichpage, saleLocation);
        },
        validateEmail: function (value) {
            var emailtest = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
            return emailtest.test(value);
        },
        renderDesktopHelpPopup: function () {
            var self = this;
            OA.cpHeader.currentView = "Desktop";
            var template = $("#support-help-desktop-temp").html();
            OAApp.appsettings.isSupportLinkOpen = true;

            $('#DesktopFooter').find('#footer2').find('.get-help').html(_.template(template));
            $('#DesktopFooter-popup').find('#footer2').find('.get-help').html(_.template(template));
            $('.get-help-popup').removeClass('display-none').addClass('display-block');
            $('.support-overlay').show();
            $('#DesktopFooter-popup .support-overlay').show();
            $(".cpFooter").css("display", "block");
            $("#help-support-dialog").find(".cpFooter").css("display", "none");
            $.mobile.loading('hide');
            var isSupportClicked = OAApp.appsettings.isSupportSubmitted;
            if (isSupportClicked) {
                OA.cpHeader.updateCompatibilityIssues(function () {
                    $(".support-thank-you").removeClass('display-none').addClass('display-block');
                    $(".support-get-all-button").addClass('display-none');
                    $("#supportLinkID").html(" " + OA.cpHeader.supportLinkId);
                    $("#supportLinkID-mobile").html(" " + OA.cpHeader.supportLinkId);
                });
            }

            var regx = /psychics\/([a-z]+)\-([0-9]+)/;
            var currentURL = window.location.href;

            if (currentURL.match(regx)) {
                var profileheaderheight = $('#DesktopHeader-popup').css('height');
                var psychicprofileheight = $('#psychic-profile').css('height');
                $('#DesktopFooter-popup .support-overlay').css({ "display": "block", "height": psychicprofileheight, "top": profileheaderheight });
            }

            $('#btnSupportSubmit').click(function (e) {
                OA.cpHeader.submitSupportClickHandler(e);
            });
            $('#btnSupportCancel').click(function (e) {
                OA.cpHeader.closeHelpDialog(e);
            });
            $('#btnSupportClose').click(function (e) {
                OA.cpHeader.closeHelpDialog(e);
            });
        },
        renderMobileHelpPopup: function () {
            OA.cpHeader.currentView = "Mobile";
            var self = this;
            var template = $("#voc-support-help-temp").html();
            $('.ui-panel-wrapper').hide();
            $(".cpFooter").css("display", "none");
            $("#help-support-dialog").find(".cpFooter").css("display", "block");
            OAApp.appsettings.isSupportLinkOpen = true;

            $('#help-support-dialog').html('');
            $('#help-support-dialog').html(_.template(template));
            $('#help-support-dialog').trigger('create');

            var isSupportClicked = OAApp.appsettings.isSupportSubmitted;
            if (isSupportClicked) {
                OA.cpHeader.updateCompatibilityIssues(function () {
                    $(".support-thank-you").removeClass('display-none').addClass('display-block');
                    $(".support-get-all-button").addClass('display-none');
                    $("#supportLinkID").html(" " + OA.cpHeader.supportLinkId);
                    $("#supportLinkID-mobile").html(" " + OA.cpHeader.supportLinkId);
                });
            }
            $('.header-mas-number').prop('href', 'tel:' + OA.utils.stringHelpers.getMasPhone());

            $('#btnSupportSubmit').click(function (e) {
                OA.cpHeader.submitSupportClickHandler(e);
            });
            $('#btnSupportCancel').click(function (e) {
                OA.cpHeader.closeHelpDialog(e);
            });
            $('#btnSupportClose').click(function (e) {
                OA.cpHeader.closeHelpDialog(e);
            });
            $('#simpledialog-help-close').click(function (e) {
                OA.cpHeader.closeHelpDialog(e);
            });
        },
        closeHelpDialog: function (e) {
            OAApp.appsettings.isSupportSubmitted = false;
            OAApp.appsettings.isSupportLinkOpen = false;
            var self = this;
            if (window.innerWidth > self.mobileResolution) {
                $('.get-help-popup').removeClass('display-block').addClass('display-none');
                $('.support-overlay').hide();
                $('#DesktopFooter-popup .support-overlay').hide();
            }
            else {
                $('#help-support-dialog').html('');
                $(document).trigger('simpledialog', {
                    'method': 'close'
                });
                $('.ui-panel-wrapper').show();
                $(".cpFooter").css("display", "block");
                $("html,body").animate({ scrollTop: $(document).height() }, 500);
            }
        },
        submitSupportClickHandler: function (e) {
            $.mobile.loading("show");
            OA.cpHeader.supportLinkId = undefined;
            OA.cpHeader.getRequiredDataForSupport(e);
        },
        getRequiredDataForSupport: function (e) {
            var deviceType, ipAddress;
            var auth = OA.cookie.ManageCookieValue('auth');

            if (OA.utils.device.Android()) {
                deviceType = "Android";
            } else if (OA.utils.device.BlackBerry()) {
                deviceType = "BlackBerry";
            } else if (OA.utils.device.iOS()) {
                deviceType = "iOS";
            } else if (OA.utils.device.Opera()) {
                deviceType = "Opera";
            } else if (OA.utils.device.Windows()) {
                deviceType = "Windows";
            } else if (OA.utils.device.iPad()) {
                deviceType = "iPad";
            } else if (OA.utils.device.iPod()) {
                deviceType = "iPod";
            }
            else {
                deviceType = "Desktop";
            }

            var custId = 0, loggedIn = "";

            if (auth) {
                custId = auth.custId;
                if (auth.loggedIn)
                    loggedIn = "Logged In";
                else
                    loggedIn = "Cookied";
            }
            $.getJSON(OAApp.appsettings.getIPAddressURL, function (data) {
                var ipAddress = '';
                if (data) {
                    ipAddress = data.ip;
                }
                var supportObject = new Object();
                supportObject.DeviceType = deviceType;
                supportObject.OSName = window.browserInfo.os.name;
                supportObject.OSVersion = window.browserInfo.os.versionString;
                supportObject.DeviceWidth = window.browserInfo.device.screen.width;
                supportObject.DeviceHeght = window.browserInfo.device.screen.height;
                supportObject.BrowserName = window.browserInfo.browser.name;
                supportObject.BrowserVersion = window.browserInfo.browser.version;
                supportObject.BrowserWidth = window.innerWidth;
                supportObject.BrowserHeight = window.innerHeight;
                supportObject.IPAddress = ipAddress;
                supportObject.CustomerID = custId;
                supportObject.LoggedInState = loggedIn;
                supportObject.IsJSEnable = "Yes";
                supportObject.PageURL = window.location.href;
                if (navigator.cookieEnabled) {
                    supportObject.IsCookieEnable = "Yes";
                } else {
                    supportObject.IsCookieEnable = "No";
                }
                supportObject.Dom = $("html").html();

                OA.cpHeader.createSupportXML(supportObject);
            });
        },
        createSupportXML: function (supportObject) {
            var xml = '<SUPPORT><INFO>';

            xml += '<OS><NAME>' + supportObject.OSName + '</NAME>';
            xml += '<VERSION>' + supportObject.OSVersion + '</VERSION></OS>';
            xml += '<BROSWER>';
            xml += '<VERSION>' + supportObject.BrowserVersion + '</VERSION></BROSWER>';
            xml += '<CUSTID>' + supportObject.CustomerID + '</CUSTID>';
            xml += '<JAVASCRIPT>' + supportObject.IsJSEnable + '</JAVASCRIPT>';
            xml += '<COOKIES>' + supportObject.IsCookieEnable + '</COOKIES>';
            xml += '</INFO></SUPPORT>';

            var width, height;
            if (supportObject.DeviceType == "Desktop") {
                width = supportObject.BrowserWidth;
                height = supportObject.BrowserHeight;
            }
            else {
                width = supportObject.DeviceWidth;
                height = supportObject.DeviceHeght;
            }
            OA.cpHeader.addSupportXML(xml, supportObject.DeviceType, width, height, supportObject.IPAddress, supportObject.LoggedInState, supportObject.BrowserName, supportObject.Dom, supportObject.PageURL);
        },
        addSupportXML: function (supportXML, deviceType, width, height, IPAddress, LoggedInState, browserName, domContent, pageURL) {
            var auth = OA.cookie.ManageCookieValue('auth')

            var custId = '', loggedIn = "";
            var self = this;
            if (auth) {
                custId = auth.custId;
                if (auth.loggedIn)
                    loggedIn = "Logged In";
                else
                    loggedIn = "Cookied";
            }

            var data = { CustId: custId, SupportXML: supportXML, Device: deviceType, Width: width, Height: height, IP: IPAddress, LoggedIn: LoggedInState, BrowserName: browserName, DOM: domContent, PageURL: pageURL };
            OA.services.addSupportLinkXML(data).done(function (response) {
                if (response) {
                    OAApp.appsettings.isSupportSubmitted = true;

                    OA.cpHeader.updateCompatibilityIssues(function () {
                        if (window.innerWidth >= self.mobileResolution) {
                            $('.get-help-popup').removeClass('display-none').addClass('display-block');
                        }
                        $(".support-thank-you").removeClass('display-none').addClass('display-block');
                        $(".support-get-all-button").addClass('display-none');
                        OA.cpHeader.supportLinkId = response;
                        $("#supportLinkID").html(" " + OA.cpHeader.supportLinkId);
                        $("#supportLinkID-mobile").html(" " + OA.cpHeader.supportLinkId);
                        $('#DesktopFooter-popup').find('#footer2').find('#supportLinkID').html(" " + OA.cpHeader.supportLinkId);
                        $.mobile.loading('hide');
                    });
                }
            }).fail(function (error) {
            }).always(function () {
                $.mobile.loading('hide');
            });
        },
        updateCompatibilityIssues: function (callback) {
            var jsString = OA.cpHeader.checkBroswerForJSEnable();
            var cookieString = OA.cpHeader.checkBroswerForCookieEnable();
            var self = this;
            var CompatibilityString = '';

            if (jsString) {
                CompatibilityString = "<div class='help-div'> 1. " + jsString + "</div>";
            }
            if (cookieString) {
                if (jsString) {
                    CompatibilityString += "<div class='help-div'> 2. " + cookieString + "</div>";
                    $('.get-help').css('height', 'auto');
                    $('.get-help').css('top', '-280px');
                } else {
                    CompatibilityString += "<div class='help-div'> 1. " + cookieString + "</div>";
                }
            }
            if (CompatibilityString != '') {
                $('.issue-content').show();
                $('.sub-cont-p1').show();
                $('.compatibility-issues').show();
                $('#alldone-heading').hide();
                $('.compatibility-issues').html(CompatibilityString);
            } else {
                $('.issue-content').hide();
                $('.sub-cont-p1').hide();
                $('#alldone-heading').show();
                $('.compatibility-issues').hide();
                if (window.innerWidth < self.mobileResolution) {
                    $(".thanks-heading").css('margin-top', '0px').css('margin-bottom', '0px').css('padding-bottom', '0px');
                }
            }
            return callback(true);
        },
        checkBroswerForJSEnable: function () {
            var isJSEnable = true;

            var returnString;
            var self = this;

            if (!isJSEnable) {
                var href;
                var browserName = window.browserInfo.browser.name;

                switch (browserName) {
                    case "Opera":
                        href = 'http://activatejavascript.org/en/instructions/opera';
                        break;
                    case "Microsoft Internet Explorer":
                        href = "https://support.microsoft.com/en-us/gp/howtoscript";
                        break;
                    case "Chrome":
                        href = "https://support.google.com/chrome/answer/114662?hl=en";
                        break;
                    case "Safari":
                        href = "http://activatejavascript.org/en/instructions/safari";
                        break;
                    case "Firefox":
                        href = "https://support.mozilla.org/en-US/kb/javascript-settings-for-interactive-web-pages";
                        break;
                }

                if (window.innerWidth >= self.mobileResolution) {
                    returnString = "JavaScript is disabled. Click " + "<a style='color: #000;font-weight: 700;font-size: 14px;text-decoration: underline;' target='_blank' class='support-error-text' href='" + href + "'>here</a> " + "to learn how to enable it."
                } else {
                    returnString = "JavaScript is disabled. Click " + "<a style='color: #000;font-weight: 700;font-size: 25px;text-decoration: underline;' target='_blank' class='support-error-text' href='" + href + "'>here</a> " + "to learn how to enable it."
                }
            }

            return returnString;
        },
        checkBroswerForCookieEnable: function () {
            var isCookieEnable = navigator.cookieEnabled;

            var returnString;
            var self = this;

            if (!isCookieEnable) {
                var href;
                var browserName = window.browserInfo.browser.name;

                switch (browserName) {
                    case "Opera":
                        href = 'http://www.opera.com/help/tutorials/security/privacy/';
                        break;
                    case "Microsoft Internet Explorer":
                        href = "http://windows.microsoft.com/en-us/windows-vista/block-or-allow-cookies";
                        break;
                    case "Chrome":
                        if (OA.utils.device.Android()) {
                            href = "https://www.google.com/chrome/browser/mobile/index.html";
                        } else {
                            href = "https://support.google.com/accounts/answer/61416?hl=en";
                        }
                        break;
                    case "Safari":
                        href = "http://www.macworld.co.uk/how-to/mac/how-enable-cookies-mac-3462635/";
                        break;
                    case "Firefox":
                        href = "https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences";
                        break;
                }
                if (window.innerWidth >= self.mobileResolution) {
                    returnString = "Cookies are disabled. Click " + "<a style='color: #000;font-weight: 700;font-size: 14px;text-decoration: underline;' target='_blank' class='support-error-text' href='" + href + "'>here</a> " + "to learn how to enable them."
                } else {
                    returnString = "Cookies are disabled. Click " + "<a style='color: #000;font-weight: 700;font-size: 25px;text-decoration: underline;' target='_blank' class='support-error-text' href='" + href + "'>here</a> " + "to learn how to enable them."
                }
            }

            return returnString;
        },
        checkBroswerForUptoDate: function () {
            var browserName = window.browserInfo.browser.name;
            var update = true;
            var self = this;
            if (!update) {
                var returnString;
                if (window.innerWidth >= self.mobileResolution) {
                    returnString = browserName + " is out of date. Click <a style='color: #000;font-weight: 700;font-size: 14px;text-decoration: underline;' target='_blank' class='support-error-text' href='#'>here</a> to update now.";
                }
                else {
                    returnString = browserName + " is out of date. Click <a style='color: #000;font-weight: 700;font-size: 25px;text-decoration: underline;' target='_blank' class='support-error-text' href='#'>here</a> to update now.";
                }
                return returnString
            }
        },
      
        redirectToPremire: function (e) {
            e.stopPropagation();
            e.preventDefault();

            var PsychicListOption = OA.cookie.ManageCookieValue('PsychicListOption');
            var auth = OA.cookie.ManageCookieValue('auth');
            var custId = null;

            if (auth != undefined) {
                custId = auth.custId;
            }

            if (!PsychicListOption) {
                PsychicListOption = new Object();
                PsychicListOption.CookieName = "PsychicListOption";
                PsychicListOption.CustId = custId;
                PsychicListOption.PageSize = 5;
                PsychicListOption.PageIndex = 0;
                PsychicListOption.CustFavorite = false;
                PsychicListOption.SearchText = '';
                PsychicListOption.SortBy = 'ElitePsychics';
                PsychicListOption.SortByText = "Premier Psychics";
                PsychicListOption.SearchOptions = null;
                PsychicListOption.CurrentView = 0;
                PsychicListOption.ResultType = 1; // 1 for full result & 2 for count on the fly.,
                PsychicListOption.currentTimeStamp = new Date().getTime();
                PsychicListOption.AppId = OAApp.getAppId();
                PsychicListOption.ExtId = null;
            } else {
                PsychicListOption.SortBy = 'ElitePsychics';
                PsychicListOption.SortByText = "Premier Psychics";
            }

            var date = new Date();
            var m = OAApp.appsettings.psychicsCookieExpiryMin; //12 hrs
            date.setTime(date.getTime() + (m * 60 * 1000));
            OA.cookie.ManageCookieValue("PsychicListOption", JSON.stringify(PsychicListOption), date);

            window.location.href = "/psychic-readings";
        }
    };
})();

$(function () {
    documentReady();
});

function onBodyClick(e) {
    var className = $(e.target).context.className;
    if (className != "signIN" && className != "facebooksigninlogosigninHeader" && className.indexOf('sign-in') < 0 && className.indexOf('signIN') < 0) {
        $('.sign-in-popup-main').hide();
    }

    if (className != "myAccount" && className.indexOf('my-account') < 0 && className.indexOf('myAccount') < 0) {
        $('.my-account-popup-main').hide();
    }
    if (className != "selectValue" && className.indexOf('selectValue') < 0 && $('#selectSortByUL').css('display') == 'block') {
        $("#selectSortByUL").slideToggle();
    }
}

var globelPsychicListTimer;

function documentReady() {

    // if the impersonate cookie is set, but there's no parent window, clear out the session
    // This will happen if the impersonation session was abandoned without returning to cs.net first
    if (OA.cookie.ManageCookieValue("impersonate") == 1) {
        if (!window.opener) {
            $("body").hide();
            OA.cookie.RemoveCookieValue("impersonate");
            OA.cookie.RemoveCookieValue("existingClogin");
            OA.cookie.RemoveCookieValue('auth');
            OA.cookie.RemoveCookieValue('ss-id');
            OA.cookie.RemoveCookieValue('rememberMeData');
            window.location.reload();  // reload the page to refresh the display
        }
        else {
            // Show indicator on the header to make it clear that the current user is being impersonated
            $("#loggedin").prepend("<span class='impersonation-msg'>Impersonating</span>");
        }
    }

	OA.cookie.RemoveCookieValue('SeoLink');
	OA.cookie.RemoveCookieValue('discountedOffer');

	var retina = (window.devicePixelRatio > 1) ? 1 : 0;
	var currentView = OA.cookie.ManageCookieValue("CurrentView");
	var PsychicOptions = OA.cookie.ManageCookieValue("PsychicOptions");
	var auth = OA.cookie.ManageCookieValue('auth');
    var psychicListOption = OA.cookie.ManageCookieValue('PsychicListOption')
	var browser = OA.utils.browser.GetAllBrowser();
	var device = OA.utils.device.getAllDevice();

	OA.cookie.ManageCookieValue("WindowWidth", window.innerWidth);
	OA.cookie.ManageCookieValue("WindowHeight", window.innerHeight);
	OA.cookie.ManageCookieValue("WindowViewportWidth", $(window).width());
	OA.cookie.ManageCookieValue("WindowViewportHeight", $(window).height());
	OA.cookie.ManageCookieValue("DevicePixelRatio", retina);
	OA.cookie.ManageCookieValue("DeviceType", device);
	OA.cookie.ManageCookieValue("BrowserType", browser);

	if (currentView == null) {
		currentView = OA.cookie.GetRawCookieValue("CurrentView");
		if (currentView == "") {
			currentView = null;
		}
	}

	if (currentView == null) {
		OA.cookie.ManageCookieValue("CurrentView", 1);
	}

	if (!PsychicOptions && PsychicOptions != undefined && PsychicOptions != null) {
		PsychicOptions.TotalCount = 0;
		PsychicOptions.IsViewAll = false;
		OA.cookie.ManageCookieValue("PsychicOptions", PsychicOptions);
	}

	if (!psychicListOption && psychicListOption != undefined && psychicListOption != null) {
		psychicListOption.SortBy = "";
		psychicListOption.SortByText = "";
		OA.cookie.ManageCookieValue("PsychicListOption", psychicListOption);
	}

	$('#premir-psychic-item').off('click').on('click', function () {
		OA.cpHeader.redirectToPremire(event);
	});

	if (window.innerWidth >= OAApp.appsettings.MobileResolution) {
		$('a').attr('data-ajax', false);
	} else {
		$('a').removeAttr('data-ajax');
		$('#receipt-done').attr('data-ajax', false); //arkadiy
		$('a[oa-data-ajax="false"]').attr('data-ajax', false);
	}

	// default empty object
	var data = new Object();
	data.CustomerId = 0;
	data.CustomerName = null;
	data.IsCookied = false;
	data.IsExistingCustomer = false;
	data.IsKRMember = false;
	data.IsNewCustomer = false;
	data.IsNewVisiter = false;
	data.IsReturningCustomer = false;
	data.KRPoints = null;
	data.LoggedIn = false;
	data.dollarBalance = 0;
	data.CustomerGroup = 0;
	data.custGroup = 0;

	if (auth != undefined) {
		$("#btnMedicCross").show();
		data.CustomerId = auth.customerId;
		data.CustomerName = auth.displayNameHeader;
		data.IsCookied = true;
		data.IsExistingCustomer = true;
		data.IsKRMember = auth.isKarmaMember;

		if (auth && auth.loggedIn)
			data.IsNewVisiter = auth.loggedIn;
		else
			data.IsNewVisiter = false;

		if (auth && auth.custId != "") {
			data.IsNewCustomer = true;
			data.IsReturningCustomer = true;
		}
		else {
			data.IsNewCustomer = false;
			data.IsReturningCustomer = false;
		}

		data.KRPoints = auth.karmaPoints;
		data.LoggedIn = auth.loggedIn;
		data.dollarBalance = auth.dollarBalance;
		data.CustomerGroup = auth.custGroup;
		data.custGroup = auth.custGroup;
	}
	else {
		$("#btnMedicCross").hide();
	}

	if (OA.auth.isLoggedIn() || OA.auth.isECCustomer()) {
		if (window.innerWidth < OAApp.appsettings.MobileResolution) {
			OA.utils.UpdateReadingCount();
		}
	}

    var template = $("#helpSearch-temp").html();
	$("#helpsearch").html(_.template(template));
	OA.utils.page.getCopyrightText();
      if (OA.auth.dfrMas == undefined) {
        OA.auth.dfrMas = OA.auth.getMasNumber().done(function () {
            if (data.custGroup && data.custGroup == 16) {
                OA.cpHeader.createAskInfoCookie(data);
            }
            else if (data.custGroup && data.custGroup == OA.utils.enum.NCCustomerGroupType.FreeLead17) {
                OA.cpHeader.createAskInfoCookie(data);
            }
            else {
                // do nothing
            }
        });
    }
    else {
        if (data.custGroup && data.custGroup == 16) {
            OA.cpHeader.createAskInfoCookie(data);
        }
        else if (data.custGroup && data.custGroup == OA.utils.enum.NCCustomerGroupType.FreeLead17) {
            OA.cpHeader.createAskInfoCookie(data);
        }
        else {
            // do nothing
        }

    }

    $(".seoItem").css("font-weight", "400");
    var category = $('#hdnCatgoryName').val();
    if (category != null) {
        if (category.toLowerCase().indexOf("topics") > 0) {
            $("#subnav-topics").css("font-weight", "700");
        }
        else if (category.toLowerCase().indexOf("abilities") > 0) {
            $("#subnav-topics").css("font-weight", "700");
        }
        else if (category.toLowerCase().indexOf("tools") > 0) {
            $("#subnav-topics").css("font-weight", "700");
        }
        else if (category.toLowerCase().indexOf("styles") > 0) {
            $("#subnav-topics").css("font-weight", "700");
        }
    }

    if (window.location.href.indexOf("californiapsychics.com/mvc-home") > 0
        || window.location.href.indexOf("californiapsychics.com/ec") > 0
        || window.location.href.indexOf("californiapsychics.com/nc") > 0) {
        $('#home').addClass("active");
        $.cookie("ActiveNavLink", "home", { path: '/' });
    }   
    else if (window.location.href.indexOf("horoscope") > 0) {
        $('#horoscope').addClass("active");
        $.cookie("ActiveNavLink", "horoscope", { path: '/' });
    }
    else if (window.location.href.indexOf("mykarmahub") > 0) {
        $('#karmarewards').addClass("active");
        $.cookie("ActiveNavLink", "karmarewards", { path: '/' });
    }
    else if (window.location.href.indexOf("/phone-psychic-readings") > 0 || window.location.href.indexOf("/why-california-psychics") > 0
        || window.location.href.indexOf("/how-we-help") > 0 || window.location.href.indexOf("/most-gifted-psychics") > 0
        || window.location.href.indexOf("/pricing") > 0 || window.location.href.indexOf("/about-california-psychics") > 0
        || window.location.href.indexOf("/articles") > 0) {
        $('#aboutUs').addClass("active");
        $.cookie("ActiveNavLink", "aboutUs", { path: '/' });
    }
    else if (window.location.href.indexOf("/faq") > 0 || window.location.href.indexOf("/telcash") > 0
        || window.location.href.indexOf("/my-alerts") > 0 || window.location.href.indexOf("/psychic-dictionary") > 0
        || window.location.href.indexOf("/contact_us") > 0 || window.location.href.indexOf("/sitemap") > 0
        || window.location.href.indexOf("/affiliates") > 0) {
        $('#support').addClass("active");
        $.cookie("ActiveNavLink", "support", { path: '/' });
    }
    else if (window.location.href.indexOf("/psychic-readings") > 0 || window.location.href.indexOf("psychic-reading") > 0
        || window.location.href.indexOf("abilities") > 0 || window.location.href.indexOf("tools") > 0 || window.location.href.indexOf("styles") > 0 || window.location.href.indexOf("/psychics/") > 0) {
        $('#search').addClass("active");
        $.cookie("ActiveNavLink", "search", { path: '/' });
    }
    else if ($(".navbar-ul li.active").length <= 0) {
        $('#home').addClass("active");
        $.cookie("ActiveNavLink", "home", { path: '/' });
    }  

    if (window.location.href.indexOf("/phone-psychic-readings") > 0) {
        $("#subnav-how-it-works").css("font-weight", "700");
    } else if (window.location.href.indexOf("/why-california-psychics") > 0) {
        $("#subnav-why-california-psychics").css("font-weight", "700");
    } else if (window.location.href.indexOf("/how-we-help") > 0) {
        $("#subnav-how-we-help").css("font-weight", "700");
    } else if (window.location.href.indexOf("/most-gifted-psychics") > 0) {
        $("#subnav-most-gifted-psychics").css("font-weight", "700");
    } else if (window.location.href.indexOf("/pricing") > 0) {
        $("#subnav-pricing").css("font-weight", "700");
    } else if (window.location.href.indexOf("/about-california-psychics") > 0) {
        $("#subnav-about-us").css("font-weight", "700");
    } else if (window.location.href.indexOf("/articles") > 0) {
        $("#subnav-articles").css("font-weight", "700");
    } else if (window.location.href.indexOf("topics") > 0) {
        $("#subnav-topics").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("abilities") > 0) {
        $("#subnav-abilities").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("tools") > 0) {
        $("#subnav-tools").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("styles") > 0) {
        $("#subnav-styles").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("hot-deals") > 0) {
        $("#subnav-hotDeals").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("vip-specials") > 0) {
        $("#subnav-vipDeals").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("new-psychics") > 0) {
        $("#subnav-newPsychics").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("premium-psychics") > 0) {
        $("#subnav-Premium").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("staff-favorite-psychics") > 0) {
        $("#subnav-StaffPicks").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("customer-favorite-psychics") > 0) {
        $("#subnav-CustomerFavorites").css("font-weight", "700");
        $("#subnav-MyFavorites").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("rising-stars") > 0) {
        $("#subnav-RisingStars").css("font-weight", "700");
    }
    else if (window.location.href.indexOf("about-psychic-readings") > 0) {
        $("#subnav-topics").css("font-weight", "700");
        //if (window.innerWidth > OAApp.appsettings.MobileResolution) {
        //    $('.filtercontainer-navbar').css("display", "inline-block");
        //    $("#filter-arrowup").css("display", "inline-block");
        //    $("#filter-arrowdown").css("display", "none");
        //    slideToggleNavBar = 0;
        //} else {
        //    slideToggleNavBar = 1;
        //}
    }
    else if (window.location.href.indexOf("my-favorite-psychics") > 0) {
        $("#subnav-MyFavorites").css("font-weight", "700");
    }

    // fallback for Firefox - does not support onload event on <link> tags
    $("link[rel='preload']").attr("rel", "stylesheet");
}

$(window).resize(function () {
    OA.cookie.ManageCookieValue("WindowWidth", window.innerWidth);
    OA.cookie.ManageCookieValue("WindowHeight", window.innerHeight);
    OA.cookie.ManageCookieValue("DevicePixelRatio", parseInt(window.devicePixelRatio));
    OA.cookie.ManageCookieValue("WindowViewportWidth", $(window).width());
    OA.cookie.ManageCookieValue("WindowViewportHeight", $(window).height());

    selected = "";
    if (window.innerWidth >= OAApp.appsettings.MobileResolution) { // Desktop
        $('a').attr('data-ajax', false);
    }
    else {
        $('a').removeAttr('data-ajax');
        $('a[oa-data-ajax="false"]').attr('data-ajax', false);
        $('#receipt-done').attr('data-ajax', false);
    }

    var isSupportOpen = OAApp.appsettings.isSupportLinkOpen;
    if (window.innerWidth > OAApp.appsettings.MobileResolution) {
        if (OAApp.appsettings.currentView == "Mobile") {
            if (isSupportOpen) {
                $('#help-support-dialog').html('');
                $(document).trigger('simpledialog', {
                    'method': 'close'
                });
                $('.ui-panel-wrapper').show();
                OA.cpHeader.renderDesktopHelpPopup();
                $("html,body").animate({ scrollTop: $(document).height() }, 500);
            } else {
                $('.get-help-popup').removeClass('display-block').addClass('display-none');
                $('.support-overlay').hide();
                $('#DesktopFooter-popup .support-overlay').hide();
            }
        }
    }
    else {
        if (OAApp.appsettings.currentView == "Desktop") {
            if (isSupportOpen) {
                $('#DesktopFooter').find('#footer2').find('.get-help').html('');
                OA.cpHeader.renderMobileHelpPopup();
            }
        }
    }
    var auth = OA.cookie.ManageCookieValue('auth');
    if (auth != null) {

        if (window.innerWidth <= OAApp.appsettings.MobileResolution) {
            OA.utils.UpdateReadingCount();
        }       
        var ua = window.navigator.userAgent;
        var edge = ua.indexOf('Edge/');
        if (window.innerWidth > 1220) {
            if (window.location.href.indexOf("/psychic-readings") > 0 || window.location.href.indexOf("/psychics") > 0 || window.location.href.indexOf("/psychic") > 0 || window.location.href.indexOf("psychic-readings") > 0 ||
                window.location.href.indexOf("/phone-psychic-readings") > 0 || window.location.href.indexOf("/why-california-psychics") > 0 || window.location.href.indexOf("/how-we-help") > 0 || window.location.href.indexOf("/most-gifted-psychics") > 0 || window.location.href.indexOf("/pricing") > 0 || window.location.href.indexOf("/about-california-psychics") > 0 || window.location.href.indexOf("/articles") > 0 ||
                window.location.href.indexOf("/faq") > 0 || window.location.href.indexOf("/telcash") > 0 || window.location.href.indexOf("/my-alerts") > 0 || window.location.href.indexOf("/psychic-dictionary") > 0 || window.location.href.indexOf("/contact_us") > 0 || window.location.href.indexOf("/sitemap") > 0 || window.location.href.indexOf("/affiliates") > 0 ||
                window.location.href.indexOf("/mvc-home") > 0) {
                //$('.psychics .ui-panel-wrapper').css('margin', '175px auto auto auto');
                $('.psychics .seo-header-main').css('padding-top', '0px');
                //$('#DesktopHeader .header').css('height', '152px');
                $(".psychic-categories-main").css("padding-top", "0px");
            }
            else {
                //$('#DesktopHeader .header').css('height', '168px');
                $('#DesktopHeader .bottom-bar').css('top', '0px');
            }
            //if (window.location.href.indexOf("/mvc-home") > 0) {
            //    $(".ui-content-margin").css("margin-top", "122px");
            //}
        }
        else if (window.innerWidth < 1220 && window.innerWidth > 1100) {
            if (window.location.href.indexOf("/psychic-readings") > 0 || window.location.href.indexOf("/psychics") > 0 || window.location.href.indexOf("/psychic") || window.location.href.indexOf("psychic-readings") > 0 ||
                window.location.href.indexOf("/phone-psychic-readings") > 0 || window.location.href.indexOf("/why-california-psychics") > 0 || window.location.href.indexOf("/how-we-help") > 0 || window.location.href.indexOf("/most-gifted-psychics") > 0 || window.location.href.indexOf("/pricing") > 0 || window.location.href.indexOf("/about-california-psychics") > 0 || window.location.href.indexOf("/articles") > 0 ||
                window.location.href.indexOf("/faq") > 0 || window.location.href.indexOf("/telcash") > 0 || window.location.href.indexOf("/my-alerts") > 0 || window.location.href.indexOf("/psychic-dictionary") > 0 || window.location.href.indexOf("/contact_us") > 0 || window.location.href.indexOf("/sitemap") > 0 || window.location.href.indexOf("/affiliates") > 0 || 
                window.location.href.indexOf("/mvc-home") > 0) {
                //$('#DesktopHeader .header').css('height', '172px');
                $(".psychic-categories-main").css("padding-top", "30px");
                //$('.psychics .ui-panel-wrapper').css('margin', '185px auto auto auto');
                $('.psychics .seo-header-main').css('padding-top', '0px');
            }
            else {
                //$('#DesktopHeader .header').css('height', '208px');
                $('#DesktopHeader .bottom-bar').css('top', '20px').css('position', 'relative');
            }

            //$('#DesktopHeader #navbar').css('top', '20px').css('position', 'relative').css('margin-right', 'auto !important');
            //if (window.location.href.indexOf("/mvc-home") > 0) {
            //    $(".ui-content-margin").css("margin-top", "143px");
            //}
        }
        else if (window.innerWidth < 1100) {
            if (window.location.href.indexOf("/psychic-readings") > 0 || window.location.href.indexOf("/psychics") > 0 || window.location.href.indexOf("/psychic") || window.location.href.indexOf("psychic-readings") > 0 ||
                window.location.href.indexOf("/phone-psychic-readings") > 0 || window.location.href.indexOf("/why-california-psychics") > 0 || window.location.href.indexOf("/how-we-help") > 0 || window.location.href.indexOf("/most-gifted-psychics") > 0 || window.location.href.indexOf("/pricing") > 0 || window.location.href.indexOf("/about-california-psychics") > 0 || window.location.href.indexOf("/articles") > 0 ||
                window.location.href.indexOf("/faq") > 0 || window.location.href.indexOf("/telcash") > 0 || window.location.href.indexOf("/my-alerts") > 0 || window.location.href.indexOf("/psychic-dictionary") > 0 || window.location.href.indexOf("/contact_us") > 0 || window.location.href.indexOf("/sitemap") > 0 || window.location.href.indexOf("/affiliates") > 0) {
                if ($('#DesktopHeader .header').height() == 172)
                    $('.psychics .seo-header-main').css('padding-top', '20px');
                else if ($('#DesktopHeader .header').height() == 152) {
                    $('.psychics .seo-header-main').css('padding-top', '40px');
                }
                else { $('.psychics .seo-header-main').css('padding-top', '20px'); }
                //$('.psychics .ui-panel-wrapper').css('margin', '225px auto auto auto');
            }
            else {
                $('#DesktopHeader .bottom-bar').css('top', '40px');
                $('#DesktopHeader #navbar').css('top', '20px').css('position', 'relative').css('margin-right', 'auto !important');
            }
            //if (window.location.href.indexOf("/mvc-home") > 0) {
            //    $(".ui-content-margin").css("margin-top", "163px");
            //}
        }
        else if (window.innerWidth > 1220) {
            $('#DesktopHeader .bottom-bar').css('top', '0px').css('position', 'relative');
            $('#DesktopHeader #navbar').css('top', '0px');
            if (window.location.href.indexOf("/psychic-readings") > 0 || window.location.href.indexOf("/psychics") > 0 || window.location.href.indexOf("/psychic") || window.location.href.indexOf("psychic-readings") > 0 ||
                window.location.href.indexOf("/phone-psychic-readings") > 0 || window.location.href.indexOf("/why-california-psychics") > 0 || window.location.href.indexOf("/how-we-help") > 0 || window.location.href.indexOf("/most-gifted-psychics") > 0 || window.location.href.indexOf("/pricing") > 0 || window.location.href.indexOf("/about-california-psychics") > 0 || window.location.href.indexOf("/articles") > 0 ||
                window.location.href.indexOf("/faq") > 0 || window.location.href.indexOf("/telcash") > 0 || window.location.href.indexOf("/my-alerts") > 0 || window.location.href.indexOf("/psychic-dictionary") > 0 || window.location.href.indexOf("/contact_us") > 0 || window.location.href.indexOf("/sitemap") > 0 || window.location.href.indexOf("/affiliates") > 0) {
                $('.psychics .seo-header-main').css('padding-top', '0px');
                //$('#DesktopHeader .header').css('height', '152px');
                $(".psychic-categories-main").css("padding-top", "0px");
            }
            else {
                //$('#DesktopHeader .header').css('height', '168px');
            }
            //if (window.location.href.indexOf("/mvc-home") > 0) {
            //    $(".ui-content-margin").css("margin-top", "122px");
            //}
        }
        if (window.innerWidth > 990) {
            $('#DesktopHeader .logoRightContent').css('margin-right', '51px');
            $('#DesktopHeader .logoRightContent').css('width', '790px');
        } else {
            $('#DesktopHeader .logoRightContent').css('margin-right', '0px');
            $('#DesktopHeader .logoRightContent').css('width', '100%');
        }

        //if (window.innerWidth <= 740) {           
        //    if (window.location.href.indexOf("/mvc-home") > 0) {
        //        $(".ui-content-margin").css("margin-top", "49px");
        //    }
        //}
    }
    var SearchText = OA.cookie.ManageCookieValue('SearchText'),
         desktopSearchText = $("#headersearch").val(),
         mobileSearchText = $(".search-module #pychisc-filter-input").val();
    if (desktopSearchText != undefined && desktopSearchText.length > 0) {
        desktopSearchText = desktopSearchText.trim();
    }
    if (mobileSearchText != undefined && mobileSearchText.length > 0) {
        mobileSearchText = mobileSearchText.trim();
    }
    if ((window.location.href.indexOf("/ask") < 0) && (window.location.href.indexOf("/free") < 0) && (window.location.href.indexOf("/callrequest") < 0) && (window.location.href.indexOf("/purchase-reading-receipt2") < 0)) {
        if (window.innerWidth >= OAApp.appsettings.MobileResolution) {
            if (OAApp.appsettings.currentView == "Mobile" || OAApp.appsettings.currentView == "") {
                if (SearchText != "" && SearchText != null) {
                    if (SearchText == mobileSearchText) {
                        $("#headersearch").val(SearchText);
                        $("#searchClear").css("display", "inline-block");
                        $('#profile-header').find('#DesktopHeader-popup').find("#headersearch").val(SearchText);
                        $(".search-module #pychisc-filter-input").val(SearchText);
                    }
                }
                $('.header').removeClass("ui-header-relative").addClass('ui-header-fixed');
                $('.ui-content').removeClass('ui-content-search-margin');
                $('.mobile-search-module').hide();
                $(".search-module").slideUp(300);
                $(".header-right #headersearch").val($(".search-module #pychisc-filter-input").val());
                if (window.location.href.indexOf("/my-account") > 0) {
                    $('.leftPanal').addClass('leftPanel-search-margin');
                }
                if ($('.searchData').is(':visible') && $(".header-right #headersearch").val() != "") {
                    $("#searchMainDiv a.ui-input-clear").removeClass("ui-input-clear-hidden");
                    $(".cpheader #searchClear").css("display", "inline-block");
                    $('#helpsearch .div-searchList').show();
                }
                else {
                    $("#searchMainDiv a.ui-input-clear").addClass("ui-input-clear-hidden");
                    $(".cpheader #searchClear").css("display", "none");
                    $('#helpsearch .div-searchList').hide();
                }
            }
        }
        else {
            if (OAApp.appsettings.currentView == "Desktop" || OAApp.appsettings.currentView == "") {
                if (SearchText != "" && SearchText != null) {
                    if (SearchText == desktopSearchText) {
                        $("#headersearch").val(SearchText);
                        $("#searchClear").css("display", "inline-block");
                        $('#profile-header').find('#DesktopHeader-popup').find("#headersearch").val(SearchText);
                        $(".search-module #pychisc-filter-input").val(SearchText);
                    }
                }
                if (OA.cpHeader.isSearchDisplay == true || $(".header-right #headersearch").val() != "") {
                    if (OA.cpHeader.isSearchDisplay == false) {
                        OA.cpHeader.showMobileSearchModule();
                    }
                    $('.mobile-search-module').show();
                    $('.search-module').slideDown().show();
                    $(".search-module #pychisc-filter-input").val($(".header-right #headersearch").val());
                    if (window.location.href.indexOf("/my-account") > 0) {
                        $('.leftPanal').addClass('leftPanel-search-margin');
                    }
                    if ($('.searchData').is(':visible') && $(".header-right #headersearch").val() != "") {
                        $('.mobile-search-module .div-searchList').show();
                        $("#searchMainDiv").addClass("search-text-main-div").removeClass("search-main-div");
                        $(".search-cancel").addClass("display-inline-block").removeClass("display-none");
                        $("#searchMainDiv a.ui-input-clear").removeClass("ui-input-clear-hidden");
                    }
                    else {
                        $("#searchMainDiv").addClass("search-main-div").removeClass("search-text-main-div");
                        $(".search-cancel").addClass("display-none").removeClass("display-inline-block");
                        $("#searchMainDiv a.ui-input-clear").addClass("ui-input-clear-hidden");
                        $('.mobile-search-module .div-searchList').hide();
                    }
                }
                else {
                    $(".search-module").slideUp(300);
                    $('.mobile-search-module').hide();
                }
            }
        }
    }

    if (window.innerWidth > OAApp.appsettings.MobileResolution) {
        if (OAApp.appsettings.currentView == "Mobile" || OAApp.appsettings.currentView == "") {
            OAApp.appsettings.currentView = "Desktop";
        }
    }
    else {
        if (OAApp.appsettings.currentView == "Desktop" || OAApp.appsettings.currentView == "") {
            OAApp.appsettings.currentView = "Mobile";
        }
    }
});;
(function (window) {
    "use strict";
    // Auth is for purely for checking user authentication
    OA.auth.session = undefined;
    OA.auth.dfrMas = undefined;
    OA.auth.mobileResolution = OAApp.appsettings.MobileResolution;
    OA.auth.IsSiteInfoLoad = false;

    OA.auth.setAuthenticatedUser = function () {
        var self = this,
            isEC = OA.auth.isECCookied(),
            auth = OA.cookie.ManageCookieValue('auth'),
            mainMenu = $('.main-menu'),
            profileContent = $('.profile-content'),
            isLoggedIn = false;

        // display the user information in the header and in the main menu.
        if (auth && !_.isEmpty(auth)) {
            if (typeof auth != 'object') {
                auth = JSON.parse(auth);
            }
            
            if (auth.loggedIn) {
                isLoggedIn = true;
                $('p.username').text('Hi ' + auth.displayNameHeader + '!');
                profileContent.find('.account-name').text('Hi ' + auth.displayNameHeader + '!')
                profileContent.find(".account-balance").text('$' + auth.dollarBalance)

                var kPoints = OA.utils.stringHelpers.formatKarma(auth.karmaPoints);
                profileContent.find(".karma-points").text(kPoints);
            }

            $("#btnMedicCross").show();
        }
        else {
            $('p.username').text("");
            profileContent.addClass("hidden");

            $("#btnMedicCross").hide();
        }

        if (isLoggedIn) {
            mainMenu.find(".nav-add-dollars").removeClass("hidden");
            mainMenu.find(".nav-my-account").removeClass("hidden");
            mainMenu.find(".sidebar-auth-btn").text("Sign Out");
            $("#btnMedicCross").show();

            profileContent.removeClass('hidden');
        }
        else {
            $("#btnMedicCross").hide();
            mainMenu.find(".sidebar-auth-btn").text("Sign In");

            if (isEC) {
                $("#btnMedicCross").show();
            } else {
                $("#btnMedicCross").hide();
            }
        }
            OA.utils.common.setHomePath();

        // Menu update for query strings - append query string to menu href for current page, to prevent page reload
        var currentPage = document.location.pathname.match(/[^\/]+$/);
        if (!!currentPage) {
            currentPage = currentPage[0];
            mainMenu.find("a[href='" + currentPage + "']").each(function () {
                $(this).attr("href", currentPage + window.location.search);
            });
        }

        if (OA.utils.browser.isIOS8()) {  // iOS8 workaround for missing/wrapping header/footer elements
            $(document).one("pagecontainershow", function (e, ui) {
                $(".ui-content").css("height", "1000px");
                window.scrollTo(0, 1);
                $.mobile.silentScroll(0);
                window.setTimeout(function () { $(".ui-content").css("height", "auto"); }, 10);
            });
        }

        $(".view-site").on("click", function () {
            // Click event for "view full site" link
            // Set "sitesource" cookie - consumed by both mobile and desktop
            $.cookie.json = false;
            OA.cookie.SetCookieValue(OAApp.appsettings.sourceCookie, "mobile", moment().add(2, 'hours')._d);
            $.cookie.json = true;

            // If this is a responsive page, reset the width to desktop dimension
            if ($(this).attr("href") === "#") {
                $('meta[name="viewport"]').prop('content', 'width=780');
                $(window).scrollTop(0);
                $.mobile.silentScroll(0);
            }
        });

        $(".view-mobile-site").on("click", function () {
            // Click event for "view mobile site" link
            // Remove "sitesource" cookie
            $.cookie.json = false;
            OA.cookie.RemoveCookieValue(OAApp.appsettings.sourceCookie);
            $.cookie.json = true;

            // If this is a responsive page, reset the width to mobile dimension
            if ($(this).attr("href") === "#") {
                $('meta[name=viewport]').prop('content', 'width=device-width');
                $(window).scrollTop(0);
                $.mobile.silentScroll(0);
            }
        });

        if (window.innerWidth > 780) {
            $("#view-mobile-site").hide();
        }

        $.cookie.json = false;
        var sourceCookie = OA.cookie.GetCookieValue(OAApp.appsettings.sourceCookie);
        $.cookie.json = true;

        if (!!sourceCookie) {
            if ($("a.view-site").attr("href") === "#" || $("a.view-site").attr("href") == undefined) {  // responsive page - resize viewport for desktop layout
                $(function () {
                    $('meta[name="viewport"]').prop('content', 'width=780');
                });
            }
            else if (window.location.href != window.location.origin + '/')  // non responsive page - just go to cp.com homepage
                window.location.href = window.location.origin;
        }
        else {
            if ($("a.view-site").attr("href") === "#" || $("a.view-site").attr("href") == undefined) {  // responsive page - resize viewport for desktop layout
                $(function () {
                    $('meta[name=viewport]').prop('content', 'width=device-width');
                });
            }
        }
    };

    OA.auth.psychicListMenu = function (e) {
        e.preventDefault();
        e.stopPropagation();

        var authCookie = OA.cookie.ManageCookieValue('auth');
        if (!authCookie) {
            $("#sub-nav-psychic-list .hot-deals-psy-list").css("display", "none");
            $("#sub-nav-psychic-list .vip-exclusive-deals-psy-list").css("display", "none");
        }
        else {
            //$(".main-menu").panel("open");
            
            if (authCookie.custGroup == OA.utils.enum.NCCustomerGroupType.DiscountRate) {
                $("#sub-nav-psychic-list .hot-deals-psy-list").css("display", "none");
            }
            else {
                $("#sub-nav-psychic-list .hot-deals-psy-list").css("display", "block");
            }
            if (authCookie.isVIPCustomer == 1) {
                $("#sub-nav-psychic-list .vip-exclusive-deals-psy-list").css("display", "block");
            }
            else {
                $("#sub-nav-psychic-list .vip-exclusive-deals-psy-list").css("display", "none");
            }
        }
        if ($("#collapse-icon").hasClass("oa-icon-plus")) {
            if (window.location.href.indexOf("/psychic-readings") > 0) {
                var dataSubCategory = window.location.href.substring(window.location.href.lastIndexOf('/') + 1, window.location.href.length);
                var parentDiv = $("#sub-nav-psychic-list");
                parentDiv.find(".nav-psychic-list a").css("font-weight", "500");

                if (OA.app.psychicsListView) {
                    OA.app.psychicsListView.clearPsychicInfoOpt();
                }
                switch (dataSubCategory) {
                    case "psychic-readings":
                        parentDiv.find("#all-psychic-list").css("font-weight", "700");
                        break;
                    case "love-relationships":
                        parentDiv.find("#love-relationship-psychic-list").css("font-weight", "700");
                        break;
                    case "tarot-readings":
                        parentDiv.find("#tarot-readings-psychic-list").css("font-weight", "700");
                        break;
                    case "clairvoyants":
                        parentDiv.find("#clairvoyants-psychic-list").css("font-weight", "700");
                        break;
                    case "mediums":
                        parentDiv.find("#mediums-psychic-list").css("font-weight", "700");
                        break;
                    case "empaths":
                        parentDiv.find("#empaths-psychic-list").css("font-weight", "700");
                        break;
                    case "hot-deals":
                        parentDiv.find("#hot-deals-psychic-list").css("font-weight", "700");
                        break;
                    case "vip-exclusive-deals":
                        parentDiv.find("#vip-exclusive-deals-psychic-list").css("font-weight", "700");
                        break;
                }
            }
            $("#collapse-icon").removeClass("oa-icon oa-icon-plus").addClass("oa-icon oa-icon-minus");
        }
        else {
            $("#collapse-icon").removeClass("oa-icon oa-icon-minus").addClass("oa-icon oa-icon-plus");
        }
        $("#sub-nav-psychic-list").stop().slideToggle(1000);
    };

    OA.auth.supportListMenu = function (e) {
        var expDate = new Date();
        expDate.setDate(expDate.getDate() + 365);
        OA.cookie.ManageCookieValue('tabClicked', false, expDate, '.californiapsychics.com');
    };

    OA.auth.aboutUsMenu = function (e) {
        e.preventDefault();
        e.stopPropagation();
        var authCookie = OA.cookie.ManageCookieValue('auth');
        if (authCookie) {
            $("#sub-nav-about-us .li-pricing").css("display", "none");
            //$(".main-menu").panel("open");
        }
        else {
            $("#sub-nav-about-us .li-pricing").css("display", "block");
        }
        var parentDiv = $("#sub-nav-about-us");
        parentDiv.find(".nav-about-us a").css("font-weight", "500");
        //parentDiv.find("li#li-how-to-articles").css("display", "none");

        if (window.location.href.indexOf("/phone-psychic-readings") > 0) {
            parentDiv.find("#a-how-it-works").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/why-california-psychics") > 0) {
            parentDiv.find("#a-why-california-psychics").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/how-we-help") > 0) {
            parentDiv.find("#a-how-we-help").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/most-gifted-psychics") > 0) {
            parentDiv.find("#a-most-gifted-psychics").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/pricing") > 0) {
            parentDiv.find("#a-pricing").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/about-california-psychics") > 0) {
            parentDiv.find("#a-about-california-psychics").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/how-to-articles") > 0) {
            parentDiv.find("#a-how-to-articles").css("font-weight", "700");
        }

        if ($("#aboutus-collapse-icon").hasClass("oa-icon-plus")) {
            $("#aboutus-collapse-icon").removeClass("oa-icon oa-icon-plus").addClass("oa-icon oa-icon-minus");
        }
        else {
            $("#aboutus-collapse-icon").removeClass("oa-icon oa-icon-minus").addClass("oa-icon oa-icon-plus");
        }
        $("#sub-nav-about-us").stop().slideToggle(1000);
    };

    OA.auth.horoscopeMenu = function (e) {
        e.preventDefault();
        e.stopPropagation();

        var authCookie = OA.cookie.ManageCookieValue('auth');
        if (authCookie) {
            //$(".main-menu").panel("open");
        }

        var parentDiv = $("#sub-nav-horoscope-list");
        parentDiv.find(".nav-horoscope-list a").css("font-weight", "500");
      //  parentDiv.find("li.nav-horoscope-list.ui-last-child").hide();
        if (window.location.href.indexOf("/weekend-horoscope") > 0) {
            parentDiv.find("#weekend-horoscope").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/weekly-love-horoscope") > 0) {
            parentDiv.find("#weekly-love-horoscope").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/monthly-horoscope") > 0) {
            parentDiv.find("#monthly-horoscope").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/monthly-money-horoscope") > 0) {
            parentDiv.find("#monthly-money-horoscope").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/yearly-horoscope") > 0) {
            parentDiv.find("#yearly-horoscope").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/birthday-horoscope") > 0) {
            parentDiv.find("#birthday-horoscope").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/horoscope") > 0) {
            parentDiv.find("#daily-horoscope").css("font-weight", "700");
        }
        if ($("#horoscope-collapse-icon").hasClass("oa-icon-plus")) {
            $("#horoscope-collapse-icon").removeClass("oa-icon oa-icon-plus").addClass("oa-icon oa-icon-minus");
        }
        else {
            $("#horoscope-collapse-icon").removeClass("oa-icon oa-icon-minus").addClass("oa-icon oa-icon-plus");
        }
        $("#sub-nav-horoscope-list").stop().slideToggle(1000);
    };
    OA.auth.blogMenu = function (e) {
        e.preventDefault();
        e.stopPropagation();

        var authCookie = OA.cookie.ManageCookieValue('auth');
        if (authCookie) {
           //$(".main-menu").panel("open");
        }

        var parentDiv = $("#sub-nav-blog-list");
        parentDiv.find(".nav-blog-list a").css("font-weight", "500");
        //  parentDiv.find("li.nav-horoscope-list.ui-last-child").hide();
        if (window.location.href.indexOf("/blog/category/psychic-tools-abilities") > 0) {
            parentDiv.find("#menu-item-sub-psychic-tools").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/blog/category/astrology-numerology") > 0) {
            parentDiv.find("#menu-item-sub-astrology-numerology").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/blog/angels-guides") > 0) {
            parentDiv.find("#menu-item-sub-angels-guides").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/blog/category/mind-body-spirit") > 0) {
            parentDiv.find("#menu-item-sub-mind-body").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/blog/love-relationships") > 0) {
            parentDiv.find("#menu-item-sub-love-relationships").css("font-weight", "700");
        }
        else if (window.location.href.indexOf("/blog/category/dreams") > 0) {
            parentDiv.find("#menu-item-sub-dreams").css("font-weight", "700");
        }
        if ($("#blog-collapse-icon").hasClass("oa-icon-plus")) {
            $("#blog-collapse-icon").removeClass("oa-icon oa-icon-plus").addClass("oa-icon oa-icon-minus");
        }
        else {
            $("#blog-collapse-icon").removeClass("oa-icon oa-icon-minus").addClass("oa-icon oa-icon-plus");
        }
        $("#sub-nav-blog-list").stop().slideToggle(1000);
    };
    OA.auth.signInMenu = function (e) {
        e.preventDefault();
        var authCookie = OA.cookie.ManageCookieValue('auth');
        if (!authCookie || !authCookie.loggedIn) {
            window.location.href = '../' + OA.paths.signIn.main;
        }
        else {
            var cookies = $.cookie();

            if (document.cookie && /ASP.NET_SessionId=\w+/g.test(document.cookie))
                document.cookie = "ASP.NET_SessionId=;path=/;domain=.californiapsychics.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";

            var arrCookies = ["auth", "mas", "MASPhoneNumber", "rememberMeData", "PsychicListOption", "offerpromoCode", "discountedOffer", "redDotURl"];
            for (var cookie in cookies) {
                if ($.inArray(cookie, arrCookies) === -1)
                    OA.cookie.RemoveCookieValue(cookie);
            }

            if (_.isEmpty(authCookie)) {
                OA.cookie.RemoveCookieValue('auth');
            }
            else {
                OA.services.signOut(authCookie.authToken);
                authCookie.loggedIn = false;
                OA.cookie.ManageCookieValue('auth', authCookie, undefined, OAApp.appsettings.OATrackingCookieDomain);
            }
            OA.cookie.RemoveCookieValue('redirect');
            var date = new Date();
            date.setTime(date.getTime() + (3652 * 24 * 60 * 60 * 1000));
            OA.cookie.ManageCookieValue('sign-out', 1, date, OAApp.appsettings.OATrackingCookieDomain);
            window.location.href = OA.paths.psychicReading;
        }
    };

    OA.auth.successfulAuth = function (data) {
        var authorized = {
            authToken: 'Token ' + data.sessionId,
            custId: data.custId,
            displayNameHeader: (data.displayName) ? data.displayName : data.firstName,
            displayNameMenu: (data.displayName) ? data.displayName : (data.firstName + " " + data.lastName),
            loggedIn: true,
            firstName: data.firstName,
            lastName: data.lastName,
            country: undefined,
            city: '',
            custGroup: data.custGroup,
            custSegment: data.custSegment,
            isEmployeeAccount: 0,
            isFiveFree: data.fiveFree,
            isVIPCustomer: data.vipCustomer
        }, ecExpires;

        OA.auth.saveAuthCookie(authorized);
        OA.auth.setAuth();
        OA.cpHeader.getSubscription();
        if (data.custSegment) {
            OA.auth.saveCustSegmentCookie(data.custSegment);
        }

        if (data.eCustId) {
            ecExpires = new Date();
            ecExpires.setTime(ecExpires.getTime() + (3652 * 24 * 60 * 60 * 1000));
            document.cookie = 'existingClogin=' + data.eCustId + ';path=/;domain=.californiapsychics.com;expires=' + ecExpires.toGMTString();
        }

        return OA.services.getCustomerDetails(data.custId).done(function (response) {
            authorized.dollarBalance = response.dollarBalance;
            authorized.availableBalance = response.availableDollarBalance;
            authorized.karmaPoints = response.karmaPoints
            authorized.userSign = response.horoSign;
            authorized.userEmail = response.email;
            authorized.userDob = response.birthDate;
            authorized.country = response.country;
            authorized.isLeadCustomer = response.isLeadCustomer;
            authorized.isDollarNewCustomer = response.isDollarNewCustomer;
            authorized.minutesBalance = response.minutesBalance;
            authorized.city = response.city;
            authorized.isKarmaMember = response.isKarmaMember;
            authorized.isNewCreditCardDisabled = response.isNewCreditCardDisabled;
            authorized.customerPhoneNumber = response.customerPhoneNumber;
            authorized.phoneCountryCode = response.phoneCountryCode;
            authorized.isEmployeeAccount = response.isEmployeeAccount;
            authorized.customerId = response.customerId;
            authorized.isFiveFree = response.fiveFree;
            authorized.isMyAlertEnable = response.myAlertOptIn;
            authorized.nonPrimaryNumber = response.nonPrimaryNumber;
            authorized.isAcceptGDPR = response.isAcceptGDPR;
            authorized.isAppInstalled = response.isAppInstalled;
            authorized.countryCallingCode = response.countryCallingCode;
            OA.auth.saveAuthCookie(authorized);
            OA.auth.setAuth();
        });
    };

    OA.auth.getReferrer = function () {
        var referrer = document.referrer;
        if (referrer) {
            if (referrer.indexOf(window.location.protocol + '//' + window.location.hostname) === 0)
                referrer = '';
            else {
                for (var i = 0; i < OAApp.appsettings.MASReferrerExclusionList.length; i++) {
                    if (referrer.indexOf(OAApp.appsettings.MASReferrerExclusionList[i]) > 0) {
                        referrer = '';
                        break;
                    }
                }
            }
        }
        return referrer;
    }

    OA.auth.getMasNumber = function () {
        var ctmPhone = OAApp.appsettings.defaultCTMPhoneNumber;
        var readerLinePhoneNumber = OAApp.appsettings.ReaderLineNumber;

        if (OA.cookie.ManageCookieValue('MASPhoneNumber')) {
            ctmPhone = OA.utils.stringHelpers.parsePhoneNumber(OA.cookie.ManageCookieValue('MASPhoneNumber'));
        }

        OA.auth.setMasNumber(ctmPhone, OA.cookie.ManageCookieValue('MASPhoneNumber'), readerLinePhoneNumber, null);
        return OA.auth.getSiteInfo();
    };

    OA.auth.getMas = function (url, referrer, windowWidth, mId, mName, isFiveFree) {
        console.log("Get Mas called", moment(new Date()).format("MM-DD-YYYY hh:mm:ss.SSS"));

        var ctmPhone = OAApp.appsettings.defaultCTMPhoneNumber;
        var readerLinePhoneNumber = OAApp.appsettings.ReaderLineNumber;

        if (OA.cookie.ManageCookieValue('MASPhoneNumber')) {
            ctmPhone = OA.utils.stringHelpers.parsePhoneNumber(OA.cookie.ManageCookieValue('MASPhoneNumber'));
        }

        if (window.location.href.indexOf('free-psychic-reading') > -1) {
            $('.five-free-question-header .mas-number').prop('href', 'tel:' + ctmPhone);
            $('.five-free-question-header .mas-number').text("Need help? Call " + ctmPhone + "!");
            $(".five-free-question-header #DynamicPhone").text('1.' + ctmPhone);
        }

        OA.auth.setMasNumber(ctmPhone, OA.cookie.ManageCookieValue('MASPhoneNumber'), readerLinePhoneNumber, null);
        return OA.auth.getSiteInfo();
    };

    OA.auth.getSiteInfo = function () {
        if (!OA.auth.IsSiteInfoLoad) {
            return OA.services.getSiteInfo(document.URL, OA.auth.getReferrer(), OA.utils.browser.GetWindowWidth()).done(function (data) {
                OA.auth.IsSiteInfoLoad = true;

                OAApp.featureConfig.isPurchaseReadingsEnabled = data.purchaseReadingEnabled;
                OAApp.featureConfig.isScheduleAppointmentEnabled = data.scheduleAppointmentEnabled;
                OAApp.featureConfig.isNCCheckoutEnabled = data.ncCheckoutEnabled;
                OAApp.featureConfig.isPaypalEnabled = data.paypalEnabled;
            }).fail(function (res) {
            });
        }
        else // return empty promise
            return $.when(null);
    }

    OA.auth.setMasPhoneNumber = function (masPhone) {
        var ExpDate = new Date();
        ExpDate.setDate(ExpDate.getDate() + 365);
        document.cookie = 'MASPhoneNumber=' + masPhone.replace(/\./g, '') + ';path=/;domain=.californiapsychics.com;expires=' + ExpDate;
    };

    OA.auth.setMasNumber = function (phoneNumber, MASPhoneNumber, readerLinePhoneNumber, data) {
        $('.mas-number a').text("1." + phoneNumber);
        $('.mas-number a').prop('href', 'tel:1' + MASPhoneNumber);
        $('.header-mas-number').prop('href', 'tel:1' + MASPhoneNumber);
        $('.dynamic_phone_number').text("1." + phoneNumber)
        $('.mas-tel').prop('href', 'tel:1' + MASPhoneNumber);
        $('#us-psychic-mas-number').text("1." + OA.utils.stringHelpers.parsePhoneNumber(readerLinePhoneNumber));
        $('#us-psychic-mas-number').prop('href', 'tel:1' + readerLinePhoneNumber);
    };

    OA.auth.setAuth = function (suppressRefresh) {
        var auth = OA.cookie.ManageCookieValue('auth');
        this.session = auth;

        if (!auth || _.isEmpty(auth)) {
            OA.cookie.RemoveCookieValue('auth');
            this.session = undefined;
        }

        return this.session;
    };

    OA.auth.isECCookied = function () {
        var auth = OA.cookie.ManageCookieValue('auth');
        var mCustIdCookie = OA.cookie.GetRawCookieValue('mCustId');
        var authCookie = {
            authToken: true,
            custId: mCustIdCookie,
            displayNameHeader: '',
            displayNameMenu: '',
            loggedIn: false,
            firstName: '',
            lastName: '',
            country: '',
            city: ''
        }

        if (!auth || _.isEmpty(auth)) {
            if (mCustIdCookie && !_.isEmpty(mCustIdCookie)) {
                var gcd = OA.services.getCustomerDetails(mCustIdCookie, null, true).done(function (response) {
                    authCookie.displayNameHeader = (response.displayName) ? response.displayName : response.firstName,
                    authCookie.displayNameMenu = (response.displayName) ? response.displayName : (response.firstName + " " + response.lastName),
                    authCookie.firstName = response.firstName;
                    authCookie.lastName = response.lastName;
                    authCookie.karmaPoints = response.karmaPoints;
                    authCookie.userSign = response.horoSign;
                    authCookie.userEmail = response.email;
                    authCookie.userDob = response.birthDate;
                    authCookie.country = response.country;
                    authCookie.dollarBalance = response.dollarBalance;
                    authCookie.minutesBalance = response.minutesBalance;
                    authCookie.city = response.city;
                    authCookie.isKarmaMember = response.isKarmaMember;
                    authCookie.loggedIn = response.isAuthenticated;
                    authCookie.isEmployeeAccount = response.isEmployeeAccount;
                    authCookie.customerId = response.customerId;
                    authCookie.nonPrimaryNumber = response.nonPrimaryNumber;
                    OA.auth.saveAuthCookie(authCookie);
                    OA.auth.setAuth(true);
                });
                return true;
            }
        }

        if (auth && !_.isEmpty(auth))
            // not logged in but EC "Cookied"
            return true;

        return false;
    };

    OA.auth.isLoggedIn = function () {
        return this.session && this.session.loggedIn;
    };

    OA.auth.isECCustomer = function () {
        var auth = OA.cookie.ManageCookieValue('auth');
        if (auth && !_.isEmpty(auth))
            return true;
        return false;
    }

    OA.auth.saveAuthCookie = function (auth) {
        var date = new Date();
        date.setTime(date.getTime() + (3652 * 24 * 60 * 60 * 1000));
        //$.cookie('auth', auth, { expires: date });
        OA.cookie.ManageCookieValue('auth', auth, date, OAApp.appsettings.OATrackingCookieDomain);
    };

    OA.auth.saveCustSegmentCookie = function (custSegment) {
        var date = new Date(),
            cookieName = OA.services.getEnvCookieName('custSegment');

        date.setTime(date.getTime() + (3652 * 24 * 60 * 60 * 1000));
        OA.cookie.ManageCookieValue(cookieName, custSegment, date, OAApp.appsettings.OATrackingCookieDomain);
    };

    OA.auth.stickyBannerClickHandler = function (e) {
        var $el = $(e.target),
            offerID = $el.attr("data-offerid"),
            promoCode = $el.attr("data-promocode"),
            href = $el.attr("href");

        if (href.indexOf("buy-package") > -1) {
            if (promoCode != '')
                OA.cookie.ManageCookieValue("offerpromoCode", promoCode);

            OA.index.setCheckOutCookie(offerID, promoCode);
        }
    };

    OA.auth.getStickyOffer = function () {
        var auth = OA.cookie.ManageCookieValue('auth');
        var custId = (auth && auth.customerId ? auth.customerId : 0);
        var self = this;

        if (custId > 0 && auth.isKarmaMember) {
            $('.oa-icon-karmarewards').hide();
        }
        if (window.innerWidth < OA.auth.mobileResolution) {
            $('.oa-icon-karmarewards').show();
        }
        if (custId > 0 && $("#MobileHeader").length > 0 && $("#DesktopHeader").length > 0) {
            OA.services.getStickyOffer({
                CustId: custId
            }).done(function (res) {
                if (!!res && res.stickyBannerTitle !== '') {
                    if (res.stickyBannerURL === '')
                        res.stickyBannerURL = '/buy-package';

                    $("<div id=\"sticky-offer-bar-mobile\"><a id=\"sticky-offer-bar-text-mobile\" rel=\"external\" data-promocode=\"" + res.promoCode + "\" data-offerid=\"" + res.offerId + "\" data-category=\"Sticky Banner\" data-action=\"EC Offer\" href=\"" + res.stickyBannerURL + "\">" + res.stickyBannerTitle + "</a></div>")
                        .prependTo("#MobileHeader #other-header")
                        .on("click", function (e) {
                            self.stickyBannerClickHandler(e);
                        });

                    $("<div id=\"sticky-offer-bar\"><a id=\"sticky-offer-bar-text\" rel=\"external\" data-promocode=\"" + res.promoCode + "\" data-offerid=\"" + res.offerId + "\" href=\"" + res.stickyBannerURL + "\">" + res.stickyBannerTitle + "</a></div>")
                        .prependTo("#DesktopHeader .header")
                        .on("click", function (e) {
                            self.stickyBannerClickHandler(e);
                        });
                }
                $("#kr-banner-inner").css("margin-top", "20px");
                // if header is set to position: fixed (as on the EC homepage), then push the content area down to match header height
                if ($("#MobileHeader").is(":visible") && $(".cpheader").css("position") === "fixed") {
                    var offset = 50;
                    var originalHeight = $("#sticky-offer-bar-mobile").height();

                    if ($("#sticky-offer-bar-mobile").is(":visible")) {
                        offset = 66 + originalHeight;

                        if (window.location.href.indexOf("mykarmahub") >0) {
                            if ($("#sticky-offer-bar-mobile").is(":visible")) {
                                $(".ui-panel-wrapper").css("margin-top", offset);                               
                            }  
                        }
                       
                        
                        // set up sticky bar to scroll off the page when scrolling down
                        $(window).on("scroll", function () {
                           

                            $(window).css('overflow-y', 'hidden');
                            var ypos = $(window).scrollTop();
                            $(window).css('overflow-y', 'auto');
                            //$("#sticky-offer-bar-mobile").height(originalHeight - ypos);

                            if (originalHeight - ypos <= 0) {
                                $("#sticky-offer-bar-mobile").hide();
                                $(".mobile-search-module").hide();
                            }
                            else {
                                $("#sticky-offer-bar-mobile").show();
                                $(".mobile-search-module").show();
                                
                            }
                            if (window.location.href.indexOf("new-karma-rewards-benefits") == -1) {
                                
                                $(".ui-panel-wrapper").css("margin-top", offset);
                            }
                        });
                    }
                    else {
                        $(".ui-panel-wrapper").css("margin-top", offset);
                    }

                    if ($(".GDPR-Cookie-PopUp-bar").is(":visible")) {
                        offset = offset + $(".GDPR-Cookie-PopUp-bar").height();
                        $(".ui-panel-wrapper").css("margin-top", offset);
                    }
                }
            });
        }
        else {
            // no sticky banner - set header height, and add top margin if header is fixed
            if ($("#MobileHeader").is(":visible")) {
                if ($(".GDPR-Cookie-PopUp-bar").is(":visible")) {
                    if (window.innerWidth < OA.auth.mobileResolution) {
                        var offset = 50;
                        offset = offset + $(".GDPR-Cookie-PopUp-bar").height();
                        $(".ui-panel-wrapper").css("margin-top", offset);
                    }
                }
                else {
                    $(".ui-panel-wrapper").css("margin-top", 50);
                }
            }
        }
    };

    OA.auth.setGDPRCookie = function () {
        var ExpDate = new Date();
        ExpDate.setDate(ExpDate.getDate() + 365);      

        var auth = OA.cookie.ManageCookieValue('auth');
        if (auth && !_.isEmpty(auth)) {
            var custId = auth.custId;

            OA.services.GetGDPRCustomer({
                CustId: custId
            }).done(function (res) {

            });

        }
        OA.cookie.ManageCookieValue('GDPRCookie', true, ExpDate, OAApp.appsettings.OATrackingCookieDomain);
        $("#GDPR-Cookie-PopUp-bar").html('');
        $("#GDPR-Cookie-PopUp-bar").hide();             
        $("#DesktopHeader .header #GDPR-Cookie-PopUp-bar").remove();
        $("#MobileHeader #GDPR-Cookie-PopUp-bar").remove();
        $(".GDPR-Cookie-PopUp-bar").remove();        
        OA.auth.GDPRWindowResize();
    }
    OA.auth.GDPRCookiePopUpHtml = function () {
        var GDPRCookie = OA.cookie.ManageCookieValue('GDPRCookie');
        if (!GDPRCookie) {
            var GDPRHtml = '<div id=\"GDPR-Cookie-PopUp-bar\" class=\"GDPR-Cookie-PopUp-bar\">' +
                '<div id=\"GDPR-Cookie-title\"><div id=\"GDPR-Cookie-bar-text\"><p  id=\"GDPR-experience-text\">Cookies & Privacy</p>' +
                '<p id=\"GDPR-cookies-text\">This site uses cookies to ensure you get the best browsing experience. By using our site you agree to our <span id="btn-GDPR-FindMore"  class="btn-GDPR btn-GDPR-FindMore"><span style="text-decoration: underline;" class="Cookie-Policy">Cookie Policy</span><span style="cursor: text;"> and updated </span><span style="text-decoration: underline;" class="Privacy-Policy">Privacy Policy<span></span></p></div> </div>' +
                '<div id=\"GDPR-Cookie-button\"><div id="btn-GDPR-Agree" class="btn-GDPR btn-GDPR-Agree"><a id="anchor-GDPR-Agree">Accept</a></div>';

            var auth = OA.cookie.ManageCookieValue('auth');
            if (auth && !_.isEmpty(auth)) {
                if (!auth.isAcceptGDPR) {
                    OA.auth.GDPRprependHtml(GDPRHtml);
                }
            }
            else {
                OA.auth.GDPRprependHtml(GDPRHtml);
            }
            $(".Cookie-Policy").on("click", function () {
                window.location.href = '/cookie-policy';
            });
            $(".Privacy-Policy").on("click", function () {
                window.location.href = '/about/privacy-policy';
            });
            $(".btn-GDPR-Agree").on("click", function () {
                OA.auth.setGDPRCookie();
            });
            if (window.location.href.split('/')[3] == '' || window.location.href.split('/')[3] == '#' || window.location.href.split('/')[3] == 'mvc-home' || window.location.href.indexOf("dashboard") > 0 || window.location.href.indexOf("dashboard#") > 0) {
                if ($(".GDPR-Cookie-PopUp-bar").is(":visible")) {
                    if (window.innerWidth < OA.auth.mobileResolution) {
                        var offset = 50;
                        offset = offset + $(".GDPR-Cookie-PopUp-bar").height();
                        $(".ui-panel-wrapper").css("margin-top", offset);
                    }
                }
                else {
                    $(".ui-panel-wrapper").css("margin-top", 50);
                }
            }
            else {
                OA.auth.GDPRWindowResize();
            }
        }
    };

    OA.auth.GDPRCookiePopUp = function () {
        var GDPRCookieHtml = OA.cookie.ManageCookieValue('GDPRCookieHtml');
        var geoIPcookie = OA.cookie.ManageCookieValue("geoip");
        if (!GDPRCookieHtml) {
            if (!geoIPcookie) {
            OA.services.getIPCountryGeolocationInfo().done(function (res) {
                    OA.cookie.ManageCookieValue("geoip", res);
                    OA.auth.GDPRCookieCallback(res);
                });
            }
            else {
                OA.auth.GDPRCookieCallback(geoIPcookie);
                }
        }
        else {
            OA.auth.GDPRCookiePopUpHtml();
        }
    };

    OA.auth.GDPRCookieCallback = function (res) {
        var isEU = (res && res.isInEuropeanUnion);
        if (isEU) {
            OA.auth.GDPRCookiePopUpHtml();
        }
    };

    OA.auth.GDPRprependHtml = function (GDPRHtml) {

        $("#DesktopHeader .header #GDPR-Cookie-PopUp-bar").remove();
        $("#MobileHeader #GDPR-Cookie-PopUp-bar").remove();
        $(".GDPR-Cookie-PopUp-bar").remove();

        $("#DesktopHeader .header").before(GDPRHtml);
        $("#MobileHeader").prepend(GDPRHtml);
        if (window.location.href.indexOf("/cookie-policy") > 0) {
            $(".ui-panel-wrapper").css("margin-top", 0);
        }
        OA.cookie.ManageCookieValue('GDPRCookieHtml', true);
    };

    OA.auth.GDPRWindowResize = function () {
        if (window.innerWidth < OA.auth.mobileResolution) {
            if ($("#MobileHeader").is(":visible")) {
                if ($(".cpheader").css("position") == "fixed") {
                    var offset = 50;
                    if ($("#sticky-offer-bar-mobile").is(":visible")) {
                        offset = offset + $("#other-header").height();
                    }
                    if ($(".GDPR-Cookie-PopUp-bar").is(":visible")) {
                        offset = offset + $(".GDPR-Cookie-PopUp-bar").height();
                    }
                    $(".ui-panel-wrapper").css("margin-top", offset);
                }
            }
        }
        else {
            $(".ui-panel-wrapper").removeAttr("style");
        }
    };

    OA.auth.redirect = function (loc) {
        if (!loc) {
            loc = window.location.href;
        }

        OA.auth.session = undefined;
        OA.cookie.ManageCookieValue('redirect', loc);

        if (OAApp.featureConfig.isOldDesktopSiteLoginEnabled) {
            OA.auth.logoutDesktop();
        }

        window.location.href = OA.paths.signIn.main;
    };

    $('body').on("pagecontainerbeforeshow", function (event, ui) {
        OA.auth.dfrMas = OA.auth.getMasNumber();
        OA.auth.setAuthenticatedUser();
    }).on('pageshow', function (event, ui) {
        //Fire this event when DOM is ready
        $(function () {
            var auth = OA.cookie.ManageCookieValue('auth'),
                isEC = OA.auth.isECCookied(),
                custId = 0;

            if (auth) {
                custId = auth.custId;
            }

            if (custId != 0) {
                $('.support-icon-div').css('opacity', '1');
            } else {
                $('.support-icon-div').css('opacity', '0.5');
            }
        });
    });

    // added to track pageviews properly
    $(document).on('pageshow', '[data-role=page]', function (event, ui) {
        if (window.location.href.indexOf("/psychic-readings") == -1) {
            OA.cookie.RemoveCookieValue('SearchText');
            $('#headersearch').val('');
            OA.cookie.RemoveCookieValue('PsychicListOption');
        }
        var currentLocation = window.location.href;

        if (window.innerWidth < OA.auth.mobileResolution) {
            OA.cookie.ManageCookieValue('ReadingVisitTime', new Date());
            OA.utils.UpdateReadingCount();
        }
    });

    $(window).on('resize', function () {
        OA.auth.GDPRWindowResize();
    });
}(window));

$(document).ready(function () {

    if (OA.auth.dfrMas == undefined) {
        OA.auth.dfrMas = OA.auth.getMasNumber();
    }
    OA.auth.setAuthenticatedUser();
    OA.auth.getStickyOffer();
    OA.auth.GDPRCookiePopUp();
});;
(function () {
    "use strict";
    OA.validator = {
        validator: null,
        setValidation: function (form, $error, rules, messages, customProperties) {
            if (!!customProperties)
                $.validator.setDefaults(customProperties);

            var validator = $(form).validate({
                rules: rules,
                messages: messages,
                errorLabelContainer: $error,
                ignore: ".ignore, :hidden:not(.validate-me)"
            });

            this.validator = validator;
            return validator;
        },
        purchase: {
            init: function (form, $error) {
                var validator = OA.validator.setValidation(form, $error, this.rules, this.messages, this.customProperties);
                OA.validator.methods.initPostalCodeValidation();
                OA.validator.methods.initPhoneNumberValidation();
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        // For the ui-select elements, we need to highlight the <select> element, the <span> with the currently selected value, and the parent ui-select <div>
                        this.findByName(element.name).removeClass(validClass).addClass(errorClass).prev().removeClass(validClass).addClass(errorClass).parent().parent().removeClass(validClass).addClass(errorClass);
                    } else if (element.name === 'exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=expMonth]").prev().removeClass(validClass).addClass(errorClass).parent().parent().removeClass(validClass).addClass(errorClass);
                        $("select[name*=expYear]").prev().removeClass(validClass).addClass(errorClass).parent().parent().removeClass(validClass).addClass(errorClass);
                    } else {
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                    if ($("#country").val() != undefined) {
                        if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "us".toLowerCase() || $("#country").val() == "") {
                            if (element.name == "bill-zip") {
                                if ($('#bill-zip').val().length > 0) {
                                    var reg = /^[0-9]+$/;
                                    var Zip = $('#bill-zip').val();

                                    if (!reg.test(Zip)) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        if ((Zip.length) < 5) {
                                            $("#zip-validation").addClass('error').removeClass('pass');
                                        }
                                        else {
                                            $("#zip-validation").addClass('pass').removeClass('error');
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#bill-zip').val());
                            if (Zip_check.length == 0) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#bill-zip').val();
                                if (!reg1.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                                // $("#zip-validation").addClass('pass').removeClass('error');
                                // $("#zip").removeAttr("pattern");
                            }
                        }
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        this.findByName(element.name).removeClass(errorClass).addClass(validClass).prev().removeClass(errorClass).addClass(validClass).parent().parent().removeClass(errorClass).addClass(validClass);
                    } else if (element.name === 'exp-date-hidden') {
                        $("select[name*=expMonth]").prev().removeClass(errorClass).addClass(validClass).parent().parent().removeClass(errorClass).addClass(validClass);
                        $("select[name*=expYear]").prev().removeClass(errorClass).addClass(validClass).parent().parent().removeClass(errorClass).addClass(validClass);
                    } else {
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                    if ($("#country").val() != undefined) {
                        if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "us".toLowerCase() || $("#country").val() == "") {
                            if (element.name == "bill-zip") {
                                if ($('#bill-zip').val().length > 0) {
                                    var reg = /^[0-9]+$/;
                                    var Zip = $('#bill-zip').val();

                                    if (!reg.test(Zip)) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        if ((Zip.length) < 5) {
                                            $("#zip-validation").addClass('error').removeClass('pass');
                                        }
                                        else {
                                            $("#zip-validation").addClass('pass').removeClass('error');
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#bill-zip').val());
                            if (Zip_check.length == 0) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#bill-zip').val();
                                if (!reg1.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                                // $("#zip-validation").addClass('pass').removeClass('error');
                                // $("#zip").removeAttr("pattern");
                            }
                        }
                    }
                }
            },
            messages: {
                'address1': {
                    required: 'Please verify the street address.',
                    minlength: 'Please verify the street address.'
                },
                'city': {
                    required: 'Please verify the city.'
                },
                'state': {
                    required: 'Please select a state.'
                },
                'zip': {
                    required: 'Please verify the postal code.'
                },
                'country': {
                    required: 'Please select a country.'
                },
                'card-holder-name': {
                    required: 'Please verify the cardholder name.'
                },
                'card-number': {
                    required: 'Invalid card number.',
                    creditcard: 'Invalid card number.'
                },
                'exp-date-hidden': {
                    required: 'Invalid expiration month or year.',
                    validExpirationDate: 'Invalid expiration month or year.'
                },
                'cvv': {
                    required: 'Invalid CVV code.',
                    validCVV: 'Invalid CVV code.'
                },
                'full-cc-number': {
                    required: 'Invalid card number.',
                    creditcard: 'Invalid card number.'
                }
            },
            rules: {
                'card-holder-name': {
                    required: true,
                    minlength: 2
                },
                'card-number': {
                    required: true,
                    creditcard: true
                },
                'full-cc-number': {
                    required: true,
                    creditcard: true
                },
                'cvv': {
                    required: true,
                    validCVV: "#card-number"
                },
                'address1': {
                    required: true
                },
                'exp-date-hidden': {
                    required: true,
                    validExpirationDate: true
                },
                'city': {
                    required: true,
                    minlength: 2
                },
                'state': {
                    required: true
                },
                'zip': {
                    required: true
                },
                'country': {
                    required: true
                }
            }
        },
        newcustomer: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);

                if ($("select[name*=country]").length)
                    OA.validator.methods.initPostalCodeValidation();

                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.name === 'exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=expMonth]").closest(".row").removeClass(validClass).addClass(errorClass);
                    } else if (element.name == "date_[day]" || element.name == "date_[month]" || element.name == "date_[year]") {
                        var d = $('.day').val();
                        var m = $('.month').val();
                        var y = $('.year').val();
                        if (d != "" && m != "" && y != "") {
                            var date = m + "/" + d + "/" + y;
                            var validDate = OA.validator.methods.validateNewCustDate(date);
                            if (!validDate) {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            } else {
                                $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                $(element).removeClass(errorClass).addClass(validClass);
                                $('#dob').removeClass(errorClass).addClass(validClass);
                            }
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                            $('#dob').addClass(errorClass).removeClass(validClass);
                        }
                    }
                    else if (element.name == "dob" && OA.utils.device.Android()) {
                        if ($("#dob").val() != null) {
                            var mystring = $("#dob").val();
                            var dobarray = new Array();
                            dobarray = mystring.split('/');
                            var m = dobarray[0];
                            var d = dobarray[1];
                            var y = dobarray[2];
                        }
                        if (d != "" && m != "" && y != "") {
                            var date = m + "/" + d + "/" + y;
                            var validDate = OA.validator.methods.validateNewCustDate(date);
                            if (!validDate) {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            } else {
                                $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                $(element).removeClass(errorClass).addClass(validClass);
                                $('#dob').removeClass(errorClass).addClass(validClass);
                            }
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                            $('#dob').addClass(errorClass).removeClass(validClass);
                        }
                    }
                    else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                    if (element.name == "billing-state-select") {
                        if ($("#billing-state-select").val() == null || $("#billing-state-select").val() == '-1') {
                            $("#StateDiv").addClass('error').removeClass('pass');
                        }
                    }
                    if (element.name == "address1") {
                        if ($("#billing-address1").val().length <= 0) {
                            $("#billing-address1").addClass('error').removeClass('pass');
                        }
                    }
                    if (element.name == "city") {
                        if ($("#billing-city").val().length <= 0) {
                            $("#billing-city").addClass('error').removeClass('pass');
                        }
                    }
                    if ($("#billing-country").val() != undefined) {
                        if ($("#billing-country").val().toLowerCase() == "united states".toLowerCase() || $("#billing-country").val().toLowerCase() == "us".toLowerCase() || $("#billing-country").val() == "") {
                            if (element.name == "zip") {
                                if ($('#billing-zip').val().length > 0) {
                                    var reg = /^[0-9]+$/;
                                    var Zip = $('#billing-zip').val();

                                    if (!reg.test(Zip)) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        if ((Zip.length) < 5) {
                                            $("#zip-validation").addClass('error').removeClass('pass');
                                        }
                                        else {
                                            $("#zip-validation").addClass('pass').removeClass('error');
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#billing-zip').val());
                            if (Zip_check.length == 0) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#billing-zip').val();
                                if (!reg1.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                                // $("#zip-validation").addClass('pass').removeClass('error');
                                // $("#zip").removeAttr("pattern");
                            }
                        }
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.name === 'exp-date-hidden') {
                        $("select[name*=expMonth]").closest(".row").removeClass(errorClass).addClass(validClass);
                    } else if (element.name == "date_[day]" || element.name == "date_[month]" || element.name == "date_[year]") {
                        var d = $('.day').val();
                        var m = $('.month').val();
                        var y = $('.year').val();

                        if (d != "" && m != "" && y != "") {
                            var date = m + "/" + d + "/" + y;
                            var validDate = OA.validator.methods.validateNewCustDate(date);
                            if (validDate) {
                                $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                $(element).removeClass(errorClass).addClass(validClass);
                                $('#dob').removeClass(errorClass).addClass(validClass);
                            } else {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            }
                        }
                    } else if (element.name == "expYear" || element.name == "expMonth") {
                        var month = $("select[name*=expMonth]").val();
                        var year = $("select[name*=expYear]").val();
                        var $expDate = $("input[name*=exp-date-hidden]");
                        var expDate;

                        if (month === '' || year === '')
                            $expDate.val("");
                        else {
                            expDate = moment(new Date(month + "/1/" + year));
                            expDate.add(1, 'months');

                            $expDate.val(expDate.format("M/D/YYYY"));
                        }
                        if (window.innerWidth >= OAApp.appsettings.MobileResolution) {
                            if (year === "" || year === "0") {
                                $("#expYear-button").css("width", "77px");
                            }
                            else {
                                $("#expYear-button").css("width", "50px");
                            }
                        }
                        $expDate.valid();
                    }
                    else if (element.name == "dob" && OA.utils.device.Android()) {
                        if ($("#dob").val() != null) {
                            var mystring = $("#dob").val();
                            var dobarray = new Array();
                            dobarray = mystring.split('/');
                            var m = dobarray[0];
                            var d = dobarray[1];
                            var y = dobarray[2];
                        }
                        if (d != "" && m != "" && y != "") {
                            var date = m + "/" + d + "/" + y;
                            var validDate = OA.validator.methods.validateNewCustDate(date);
                            if (!validDate) {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            } else {
                                $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                $(element).removeClass(errorClass).addClass(validClass);
                                $('#dob').removeClass(errorClass).addClass(validClass);
                            }
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                            $('#dob').addClass(errorClass).removeClass(validClass);
                        }
                    }
                    else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                    if ($("#billing-state-select").val() == null || $("#billing-state-select").val() == '-1') {
                        $("#StateDiv").removeClass("pass");
                    }
                    if (element.name == "billing-state-select") {
                        if ($("#billing-state-select").val() == null || $("#billing-state-select").val() == '-1') {
                            $("#StateDiv").addClass('error').removeClass('pass');
                        }
                    }
                    if (element.name == "address1") {
                        if ($("#billing-address1").val().length <= 0) {
                            $("#billing-address1").addClass('error').removeClass('pass');
                        }
                    }
                    if (element.name == "city") {
                        if ($("#billing-city").val().length <= 0) {
                            $("#billing-city").addClass('error').removeClass('pass');
                        }
                    }
                    if ($("#billing-country").val() != undefined) {
                        if ($("#billing-country").val().toLowerCase() == "united states".toLowerCase() || $("#billing-country").val().toLowerCase() == "us".toLowerCase() || $("#billing-country").val() == "") {
                            if (element.name == "zip") {
                                if ($('#billing-zip').val().length > 0) {
                                    var reg = /^[0-9]+$/;
                                    var Zip = $('#billing-zip').val();

                                    if (!reg.test(Zip)) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        if ((Zip.length) < 5) {
                                            $("#zip-validation").addClass('error').removeClass('pass');
                                        }
                                        else {
                                            $("#zip-validation").addClass('pass').removeClass('error');
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#billing-zip').val());
                            if (Zip_check.length == 0) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#billing-zip').val();
                                if (!reg1.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                                // $("#zip-validation").addClass('pass').removeClass('error');
                                // $("#zip").removeAttr("pattern");
                            }
                        }
                    }
                    if (parseInt($('#desktop-callback-phonetype').val()) == 2) {
                        if ($("#callback-mobile-phone").val() == null || $("#callback-mobile-phone").val() == "") {
                            $("#callback-mobile-phone-validation").removeClass("pass");
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].type !== 'checkbox') {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                    else {
                        error.insertAfter($(element));
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'first-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'last-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'email': {
                    required: true,
                    email: true
                },
                'password': {
                    required: true,
                    validPassword: '#cpassword'
                },
                'cpassword': {
                    required: true,
                    validCPassword: '#password'
                },
                'dob': {
                    required: true,
                    validNcDOB: "#dob"
                },
                'card-holder-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'card-number': {
                    required: true,
                    creditcard: true
                },
                'cvv': {
                    required: true,
                    validCVV: '#card-number'
                },
                'exp-date-hidden': {
                    required: true,
                    validExpirationDate: true
                },
                'zip': {
                    required: true
                },
                'billing-state-select': {
                    required: true
                },
                'billing-region': {
                    required: true
                },
                'city': {
                    required: true
                },
                'address1': {
                    required: true
                },
                'callback-phone': {
                    required: true,
                    validCallbackNumber: '#callback-country'
                },
                'agree': {
                    required: true
                },
                'callback-mobile-phone': {
                    validNonPrimaryMobileNumber: '#desktop-callback-phonetype'
                }
            },
            messages: {
                'first-name': {
                    required: 'Please enter your first name.',
                    letterswithbasicpunc: 'Invalid first name. Please use only alpha characters.'
                },
                'last-name': {
                    required: 'Please enter your last name.',
                    letterswithbasicpunc: 'Invalid last name. Please use only alpha characters.'
                },
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                },
                'password': {
                    required: 'Please enter your password.',
                    validPassword: 'Use at least 6 characters for your password.'
                },
                'cpassword': {
                    required: 'Confirm your password.',
                    validCPassword: 'Passwords do not match. Please enter again.'
                },
                'dob': {
                    required: 'Please enter your date of birth.',
                    validNcDOB: 'Must be at least 18 years or older.'
                },
                'card-holder-name': {
                    required: 'Please enter a name.',
                    letterwithbasicpunc: 'Invalid name. Please use only alphanumeric characters.'
                },
                'card-number': {
                    required: 'Please enter a credit card number.',
                    creditcard: 'Invalid card number.'
                },
                'cvv': {
                    required: 'Please enter the CVV code.',
                    validCVV: 'Invalid CVV.'
                },
                'exp-date-hidden': {
                    required: 'Invalid expiration date.',
                    validExpirationDate: 'Invalid expiration date.'
                },
                'billing-state-select': {
                    required: 'Please select a state.'
                },
                'billing-region': {
                    required: 'Please enter a region.'
                },
                'zip': {
                    required: 'Please enter a postal code.'
                },
                'city': {
                    required: 'Please enter a city.'
                },
                'address1': {
                    required: 'Please enter an address.'
                },
                'callback-phone': {
                    required: 'Invalid callback phone number.',
                    validCallbackNumber: 'Invalid callback phone number.'
                },
                'agree': {
                    required: 'Please accept the Terms and Conditions in order to use our service.'
                },
                'callback-mobile-phone': {
                    validNonPrimaryMobileNumber: 'Invalid callback phone number.'
                }
            }
        },
        buyPackage: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);

                if ($("select[name*=country]").length)
                    OA.validator.methods.initPostalCodeValidation();

                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        // For the ui-select elements, we need to highlight the <select> element, the <span> with the currently selected value, and the parent ui-select <div>
                        this.findByName(element.name).closest('.row').removeClass(validClass).addClass(errorClass);
                    } else if (element.name === 'exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=expMonth]").closest('.row').removeClass(validClass).addClass(errorClass);
                        $("select[name*=expYear]").closest('.row').removeClass(validClass).addClass(errorClass);
                    } else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        this.findByName(element.name).closest('.row').removeClass(errorClass).addClass(validClass);
                    } else if (element.name === 'exp-date-hidden') {
                        $("select[name*=expMonth]").closest('.row').removeClass(errorClass).addClass(validClass);
                        $("select[name*=expYear]").closest('.row').removeClass(errorClass).addClass(validClass);
                    } else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }

                    if ($("#country").val() != undefined) {
                        if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "us".toLowerCase() || $("#country").val() == "") {
                            if (element.name == "zip") {
                                if ($('#zip').val().length > 0) {
                                    var Zip_check = $.trim($('#zip').val());
                                    if (Zip_check.length == 0) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else if ($('#zip').val().length < 5) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        $("#zip-validation").addClass('pass').removeClass('error');
                                        $("#zip").removeAttr("pattern");
                                    }
                                    $("#zip").attr("pattern", "[0-9]*");
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#zip').val());
                            if (Zip_check.length == 0) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#zip').val();
                                if (!reg1.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                                // $("#zip-validation").addClass('pass').removeClass('error');
                                // $("#zip").removeAttr("pattern");
                            }
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'card-holder-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'card-number': {
                    required: true,
                    creditcard: true
                },
                'cvv': {
                    required: true,
                    validCVV: '#card-number'
                },
                'exp-date-hidden': {
                    required: true,
                    validExpirationDate: true
                },
                'zip': {
                    required: true
                },
                'buy-state-select': {
                    required: true
                },
                'billing-region': {
                    required: true
                },
                'city': {
                    required: true
                },
                'address1': {
                    required: true
                }
            },
            messages: {
                'card-holder-name': {
                    required: 'Please enter a name.',
                    letterwithbasicpunc: 'Invalid name. Please use only alphanumeric characters.'
                },
                'card-number': {
                    required: 'Invalid card number.',
                    creditcard: 'Invalid card number.'
                },
                'cvv': {
                    required: 'Invalid CVV.',
                    validCVV: 'Invalid CVV.'
                },
                'exp-date-hidden': {
                    required: 'Invalid expiration month or year.',
                    validExpirationDate: 'Invalid expiration month or year.'
                },
                'buy-state-select': {
                    required: 'Please enter state.'
                },
                'billing-region': {
                    required: 'Please enter region.'
                },
                'zip': {
                    required: 'Please enter a postal code.'
                },
                'city': {
                    required: 'Please enter city.'
                },
                'address1': {
                    required: 'Please enter address.'
                }
            }
        },
        myaccountcreditcard: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);

                //if ($("input[name*=credit-country]").val().length)
                //    OA.validator.methods.initPostalCodeValidation();

                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        // For the ui-select elements, we need to highlight the <select> element, the <span> with the currently selected value, and the parent ui-select <div>
                        this.findByName(element.name).closest('.row').removeClass(validClass).addClass(errorClass);
                    } else if (element.name === 'exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=expMonth]").closest('.row').removeClass(validClass).addClass(errorClass);
                        $("select[name*=expYear]").closest('.row').removeClass(validClass).addClass(errorClass);
                    } else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                    //if (element.name == "zip") {
                    //    if ($("#country").val().toLowerCase() != "United States".toLowerCase() || $("#country").val().toLowerCase() != "us".toLowerCase()) {
                    //
                    //        var zipVal = $('#zip').val();
                    //        var zipCode = zipVal.split(' ');
                    //
                    //        if ($('#zip').val().length > 0) {
                    //            if (zipCode[1] == null) {
                    //
                    //                $('#zip-validation').removeClass(errorClass).addClass(validClass).addClass('ignore');
                    //                $('#zip').removeClass(errorClass).addClass(validClass).addClass('ignore');
                    //            }
                    //        }
                    //    }
                    //}
                    var formId = element.form.id;
                    var isValid = true;

                    if (formId == "frm-creditcard") {
                        $("#" + formId + " input").each(function () {
                            var $el = $(this);

                            if ($el.context.type != "submit" && $el.context.type != "checkbox" && $el.context.type != "hidden" && !$el.hasClass("ignore") && $el.closest(".row").css("display") != "none") {
                                if (!$el.hasClass(validClass)) {
                                    isValid = false;
                                }
                            }
                        });

                        if (isValid) {
                            // $("#save-card-button").removeClass('disabled');
                            // $("#save-card-button").removeClass('disableBtn').addClass('enableBtn');
                        } else {
                            //  $("#save-card-button").addClass('disabled');
                            // $("#save-card-button").removeClass('enableBtn').addClass('disableBtn');
                        }
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        this.findByName(element.name).closest('.row').removeClass(errorClass).addClass(validClass);
                    } else if (element.name === 'exp-date-hidden') {
                        $("select[name*=expMonth]").closest('.row').removeClass(errorClass).addClass(validClass);
                        $("select[name*=expYear]").closest('.row').removeClass(errorClass).addClass(validClass);
                    } else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                    if ($("#credit-country").val().toLowerCase() == "united states".toLowerCase() || $("#credit-country").val().toLowerCase() == "us".toLowerCase() || $("#credit-country").val() == "") {
                        if (element.name == "zip") {
                            if ($('#zip').val().length > 0) {
                                var Zip_check = $.trim($('#zip').val());
                                if (Zip_check.length == 0) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else if ($('#zip').val().length < 5) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                    $("#zip").removeAttr("pattern");
                                }
                                $("#zip").attr("pattern", "[0-9]*");
                            }
                        }
                    }
                    else {
                        var Zip_check = $.trim($('#zip').val());
                        if (Zip_check.length == 0) {
                            $("#zip-validation").addClass('error').removeClass('pass');
                        }
                        else {
                            var reg1 = /^[a-zA-Z0-9\s]+$/;
                            var Zip = $('#zip').val();
                            if (!reg1.test(Zip)) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                $("#zip-validation").addClass('pass').removeClass('error');
                            }
                            // $("#zip-validation").addClass('pass').removeClass('error');
                            // $("#zip").removeAttr("pattern");
                        }
                    }
                    var formId = element.form.id;
                    var isValid = true;

                    if (formId == "frm-creditcard") {
                        $("#" + formId + " input").each(function () {
                            var $el = $(this);

                            if ($el.context.type != "submit" && $el.context.type != "checkbox" && $el.context.type != "hidden" && !$el.hasClass("ignore") && $el.closest(".row").css("display") != "none") {
                                if (!$el.hasClass(validClass)) {
                                    isValid = false;
                                }
                            }
                        });

                        if (isValid) {
                            // $("#save-card-button").removeClass('disabled');
                            // $("#save-card-button").removeClass('disableBtn').addClass('enableBtn');
                        } else {
                            // $("#save-card-button").addClass('disabled');
                            // $("#save-card-button").removeClass('enableBtn').addClass('disableBtn');
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'card-holder-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'card-number': {
                    required: true,
                    creditcard: true
                },
                'cvv': {
                    required: true,
                    validCVV: '#card-number'
                },
                'exp-date-hidden': {
                    required: true,
                    validExpirationDate: true
                },
                'zip': {
                    required: true
                },
                'buy-state-select': {
                    required: true
                },
                'billing-region': {
                    required: true
                },
                'city': {
                    required: true
                },
                'address1': {
                    required: true
                }
            },
            messages: {
                'card-holder-name': {
                    required: 'Please enter a name.',
                    letterwithbasicpunc: 'Invalid name. Please use only alphanumeric characters.'
                },
                'card-number': {
                    required: 'Invalid card number.',
                    creditcard: 'Invalid card number.'
                },
                'cvv': {
                    required: 'Invalid CVV.',
                    validCVV: 'Invalid CVV.'
                },
                'exp-date-hidden': {
                    required: 'Invalid expiration month or year.',
                    validExpirationDate: 'Invalid expiration month or year.'
                },
                'buy-state-select': {
                    required: 'Please enter state.'
                },
                'billing-region': {
                    required: 'Please enter region.'
                },
                'zip': {
                    required: 'Please enter a postal code.'
                },
                'city': {
                    required: 'Please enter city.'
                },
                'address1': {
                    required: 'Please enter address.'
                }
            }
        },
        horoscope: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    //$(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    //$(element).addClass(errorClass).removeClass(validClass);
                    if (window.innerWidth <= 740 && element.name == "dob" && OA.utils.browser.isIE()) {
                        if (element.name == "dob") {
                            if ($("#dob").val() != null) {
                                var mystring = $("#dob").val();
                                var dobarray = new Array();
                                dobarray = mystring.split('/');
                                var m = dobarray[0];
                                var d = dobarray[1];
                                var y = dobarray[2];
                            }
                            if (d != "" && m != "" && y != "") {
                                var date = m + "/" + d + "/" + y;
                                var validDate = OA.validator.methods.validmobileHoroDOB(date);
                                if (!validDate) {
                                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                    $(element).addClass(errorClass).removeClass(validClass);
                                    $('#dob').addClass(errorClass).removeClass(validClass);
                                } else {
                                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                    $(element).removeClass(errorClass).addClass(validClass);
                                    $('#dob').removeClass(errorClass).addClass(validClass);
                                }
                            } else {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            }
                        }
                        else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                        }
                    }
                    else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    //$(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    //$(element).removeClass(errorClass).addClass(validClass);
                    if (window.innerWidth <= 740 && element.name == "dob" && OA.utils.browser.isIE()) {
                        if (element.name == "dob") {
                            if ($("#dob").val() != null) {
                                var mystring = $("#dob").val();
                                var dobarray = new Array();
                                dobarray = mystring.split('/');
                                var m = dobarray[0];
                                var d = dobarray[1];
                                var y = dobarray[2];
                            }
                            if (d != "" && m != "" && y != "") {
                                var date = m + "/" + d + "/" + y;
                                var validDate = OA.validator.methods.validmobileHoroDOB(date);
                                if (!validDate) {
                                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                    $(element).addClass(errorClass).removeClass(validClass);
                                    $('#dob').addClass(errorClass).removeClass(validClass);
                                } else {
                                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                    $(element).removeClass(errorClass).addClass(validClass);
                                    $('#dob').removeClass(errorClass).addClass(validClass);
                                }
                            } else {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            }
                        }
                        else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                        }
                    }
                    else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'signUpName': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'signUpNameMobile': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'signUpEmail': {
                    required: true,
                    email: true
                },
                'signUpEmailMobile': {
                    required: true,
                    email: true
                },
                'dob': {
                    required: true,
                    validHoroDOB: true
                }
            },
            messages: {
                'signUpName': {
                    required: 'Please enter your name.',
                    letterswithbasicpunc: 'Please use only alphanumeric characters.'
                },
                'signUpEmail': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                },
                'signUpNameMobile': {
                    required: 'Please enter your name.',
                    letterswithbasicpunc: 'Please use only alphanumeric characters.'
                },
                'signUpEmailMobile': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                },
                'dob': {
                    required: 'Please enter your date of birth using MM/DD/YYYY format.',
                    validHoroDOB: 'Must be at least 16 years or older.'
                }
            }
        },
        purchaseDesktop: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                OA.validator.methods.initPostalCodeValidation();
                OA.validator.methods.initPhoneNumberValidation();
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        // For the ui-select elements, we need to highlight the <select> element, the <span> with the currently selected value, and the parent ui-select <div>
                        this.findByName(element.name).closest('.row').removeClass(validClass).addClass(errorClass);
                    } else if (element.name === 'bill-exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=bill-expMonth]").closest('.row').removeClass(validClass).addClass(errorClass);
                        $("select[name*=bill-expYear]").closest('.row').removeClass(validClass).addClass(errorClass);
                    } else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }

                    if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "us".toLowerCase() || $("#country").val() == "") {
                        if (element.name == "bill-zip") {
                            var reg = /^[0-9]+$/;
                            var Zip = $('#bill-zip').val();
                            if (!reg.test(Zip)) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                if ((Zip.length) < 5) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                            }
                        }
                    }
                    else {
                        var Zip_check = $.trim($('#bill-zip').val());
                        if (Zip_check.length == 0) {
                            $("#zip-validation").addClass('error').removeClass('pass');
                        }
                        else {
                            var reg1 = /^[a-zA-Z0-9\s]+$/;
                            var Zip = $('#bill-zip').val();
                            if (!reg1.test(Zip)) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                $("#zip-validation").addClass('pass').removeClass('error');
                            }
                            // $("#zip-validation").addClass('pass').removeClass('error');
                            // $("#bill-zip").removeAttr("pattern");
                        }
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.type === "select-one") {
                        this.findByName(element.name).closest('.row').removeClass(errorClass).addClass(validClass);
                    } else if (element.name === 'bill-exp-date-hidden') {
                        $("select[name*=bill-expMonth]").closest('.row').removeClass(errorClass).addClass(validClass);
                        $("select[name*=bill-expYear]").closest('.row').removeClass(errorClass).addClass(validClass);
                    } else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }

                    if ($("#country").val() != undefined) {
                        if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "us".toLowerCase() || $("#country").val() == "") {
                            if (element.name == "bill-zip") {
                                var reg = /^[0-9]+$/;
                                var Zip = $('#bill-zip').val();
                                if (!reg.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    if ((Zip.length) < 5) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        $("#zip-validation").addClass('pass').removeClass('error');
                                    }
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#bill-zip').val());
                            if (Zip_check.length == 0) {
                                $("#zip-validation").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#bill-zip').val();
                                if (!reg1.test(Zip)) {
                                    $("#zip-validation").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#zip-validation").addClass('pass').removeClass('error');
                                }
                                // $("#zip-validation").addClass('pass').removeClass('error');
                                // $("#bill-zip").removeAttr("pattern");
                            }
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'desktop-callback-phonenumber': {
                    required: true,
                    validCallbackNumber: '#desktop-callback-country'
                },
                'bill-card-holder-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'bill-card-number': {
                    required: true,
                    creditcard: true
                },
                'bill-exp-date-hidden': {
                    required: function () { return ($(".cc-module").is(":visible")); },
                    validExpirationDate: function () { return ($(".cc-module").is(":visible")); }
                },
                'bill-cvv': {
                    required: true,
                    validCVV: '#bill-card-number'
                },
                'bill-zip': {
                    required: true
                },
                'bill-state-select': {
                    required: true,
                    ValidBillingState: '#bill-state-select'
                },
                'bill-region': {
                    required: true
                },
                'bill-city': {
                    required: true
                },
                'bill-address1': {
                    required: true
                },
                'full-cc-number-desktop': {
                    required: true,
                    creditcard: true
                }
            },
            messages: {
                'desktop-callback-phonenumber': {
                    required: 'Please enter callback phone.',
                    validCallbackNumber: 'Invalid callback phone number. Please try again.'
                },
                'bill-card-holder-name': {
                    required: 'Please enter a name.',
                    letterswithbasicpunc: 'Invalid name. Please use only alphanumeric characters.'
                },
                'bill-card-number': {
                    required: 'Please enter a card number.',
                    creditcard: 'Invalid card number. Please try again.'
                },
                'bill-exp-date-hidden': {
                    required: 'Invalid expiration month or year.',
                    validExpirationDate: 'Invalid expiration month or year.'
                },
                'bill-cvv': {
                    required: 'Please enter CVV.',
                    validCVV: 'Invalid CVV. Please try again.'
                },
                'bil-zip': {
                    required: 'Please enter zip code.'
                },
                'bill-state-select': {
                    required: 'Please enter state.',
                    ValidBillingState: 'Please select bill state.'
                },
                'bill-region': {
                    required: 'Please enter region.'
                },
                'bill-city': {
                    required: 'Please enter city.'
                },
                'bill-address1': {
                    required: 'Please enter address.'
                },
                'callback-phone': {
                    required: 'Please enter callback phone',
                    validCallbackNumber: 'Invalid callback phone number. Please try again.'
                },
                'full-cc-number-desktop': {
                    required: 'Invalid card number.',
                    creditcard: 'Invalid card number.'
                }
            }
        },
        myprofilePassword: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass('removeBorder');
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);
					/*var formId = element.form.id;
		            var isValid = true;
		            if (formId == "myProfileAccountPass") {
		                $("#" + formId + " input").each(function () {
		                    var $el = $(this);
		                    if ($el.context.type != "submit" && $el.context.type != "checkbox") {
		                        if (!$el.hasClass(validClass)) {
		                            isValid = false;
		                        }
		                    }
		                });

		                if (isValid) {
		                    $("#btnSavePwd").removeClass("disableBtn").addClass("enableBtn");
		                } else {
		                    $("#btnSavePwd").removeClass("enableBtn").addClass("disableBtn");
		                }
		            }*/
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    $(element).removeClass(errorClass).addClass(validClass);
                    if (element.id == "cpassword2") {
                        $(element).closest(".row").addClass('removeBorder');
                    }
					/*var formId = element.form.id;
		            var isValid = true;
		            if (formId == "myProfileAccountPass") {
		                $("#" + formId + " input").each(function () {
		                    var $el = $(this);
		                    if ($el.context.type != "submit" && $el.context.type != "checkbox") {
		                        if (!$el.hasClass(validClass)) {
		                            isValid = false;
		                        }
		                    }
		                });

		                if (isValid) {
		                    $("#btnSavePwd").removeClass("disableBtn").addClass("enableBtn");
		                } else {
		                    $("#btnSavePwd").removeClass("enableBtn").addClass("disableBtn");
		                }
		            }*/
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $(".pass .tooltip").css('display', 'none');
                    $(".pass .tooltip-arrow").css('display', 'none');
                    $(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'oldpassword': {
                    required: true,
                    validPassword: '#oldpassword'
                },
                'cpassword1': {
                    required: true,
                    validPassword: '#cpassword2'
                },
                'cpassword2': {
                    required: true,
                    validCPassword: '#cpassword1'
                }
            },
            messages: {
                'oldpassword': {
                    required: 'Please enter your password.',
                    validPassword: 'Use at least 6 characters for your password.'
                },
                'cpassword1': {
                    required: 'Please enter your password.',
                    validPassword: 'Use at least 6 characters for your password.'
                },
                'cpassword2': {
                    required: 'Confirm your password.',
                    validCPassword: 'Passwords do not match. Please enter again.'
                }
            }
        },
        myprofileEmail: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass('removeBorder');
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);

                    if (element.name == "email") {
                        var valid = OA.validator.methods.validateEmail(element.value);
                        if (valid) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).removeClass(validClass).addClass(errorClass);
                        }
                    }
					/*var formId = element.form.id;
		            var isValid = true;
		            if (formId == "myProfileAccountEmail") {
		                $("#" + formId + " input").each(function () {
		                    var $el = $(this);
		                    if ($el.context.type != "submit" && $el.context.type != "checkbox") {
		                        if (!$el.hasClass(validClass)) {
		                            isValid = false;
		                        }
		                    }
		                });

		                if (isValid) {
		                    $("#btnEditEmail").removeClass("disableBtn").addClass("enableBtn");
		                    $(element).closest(".row").addClass('removeBorder');
		                } else {
		                    $("#btnEditEmail").removeClass("enableBtn").addClass("disableBtn");
		                    $(element).closest(".row").removeClass('removeBorder');
		                }
		            }*/
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    $(element).removeClass(errorClass).addClass(validClass);
                    if (element.name == "email") {
                        var valid = OA.validator.methods.validateEmail(element.value);
                        if (valid) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).removeClass(validClass).addClass(errorClass);
                        }
                    }
					/*var formId = element.form.id;
		            var isValid = true;
		            if (formId == "myProfileAccountEmail") {
		                $("#" + formId + " input").each(function () {
		                    var $el = $(this);
		                    if ($el.context.type != "submit" && $el.context.type != "checkbox") {
		                        if (!$el.hasClass(validClass)) {
		                            isValid = false;
		                        }
		                    }
		                });

		                if (isValid) {
		                    $("#btnEditEmail").removeClass("disableBtn").addClass("enableBtn");
		                    $(element).closest(".row").addClass('removeBorder');
		                } else {
		                    $("#btnEditEmail").removeClass("enableBtn").addClass("disableBtn");
		                    $(element).closest(".row").removeClass('removeBorder');
		                }
		            }*/
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $(".pass .tooltip").css('display', 'none');
                    $(".pass .tooltip-arrow").css('display', 'none');
                    $(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'email': {
                    required: true,
                    email: true
                }
            },
            messages: {
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                }
            }
        },
        AccountSubscription: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);

                if ($("select[name*=country]").length)
                    OA.validator.methods.initPostalCodeValidation();
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);

                    if (element.name == "zip") {
                        //if ($("#edit-billing-country_sub").val().toLowerCase() == "canada".toLowerCase() || $("#edit-billing-country_sub").val().toLowerCase() == "ca".toLowerCase()) {
                        //    if ($('#billing-zip_sub').val().length > 0) {
                        //        $('#rowZip').removeClass(errorClass).addClass(validClass).addClass('ignore');
                        //        $('#billing-zip_sub').removeClass(errorClass).addClass(validClass).addClass('ignore');
                        //    }
                        //}

                        if ($("#lbl_billing-country_sub").val().toLowerCase() == 'US'.toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == 'united states'.toLowerCase()) {
                            var reg = /^[0-9]+$/;
                            var Zip = $('#billing-zip_sub').val();

                            if (!reg.test(Zip)) {
                                $("#rowZip").addClass('error').removeClass('pass');
                            }
                            else {
                                if ((Zip.length) < 5) {
                                    $("#rowZip").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#rowZip").addClass('pass').removeClass('error');
                                    $('#billing-zip_sub').removeClass(errorClass).addClass(validClass).addClass('ignore');
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#billing-zip_sub').val());
                            if (Zip_check.length == 0) {
                                $("#rowZip").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#billing-zip_sub').val();
                                if (!reg1.test(Zip)) {
                                    $("#rowZip").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#rowZip").addClass('pass').removeClass('error');
                                    $('#billing-zip_sub').removeClass(errorClass).addClass(validClass).addClass('ignore');
                                }
                                //$("#rowZip").addClass('pass').removeClass('error');
                                // $("#billing-zip_sub").removeAttr("pattern");
                            }
                        }
                    }
                    var formId = element.form.id;
                    var isValid = true;
                    if (formId == "myAccountSubscription") {
                        $("#" + formId + " input").each(function () {
                            var $el = $(this);
                            if ($el[0].id != "billing-address2_sub" && $el[0].id != "hdn_billing-state") {
                                if ($el[0].id != "billing-region_sub") {
                                    $("#billing-region_sub").addClass('pass');
                                }
                                if ($el.context.type != "submit" && $el.context.type != "checkbox" && $el.context.type != "hidden") {
                                    if (!$el.hasClass(validClass)) {
                                        isValid = false;
                                    }
                                }
                            }
                        });

                        if ($("#lbl_billing-country_sub").val().toLowerCase() == "united states".toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == "canada".toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == "us".toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == "ca".toLowerCase() || $("#lbl_billing-country_sub").val() == "") {
                            if ($('#regiondiv').css('display') == 'block' || $('#regiondiv').css('display') == undefined) {
                                if ($("#billing-region_sub").val() == "") {
                                    isValid = false;
                                }
                                else if ($("#edit-billing-country_sub").val().toLowerCase() == "canada".toLowerCase() || $("#edit-billing-country_sub").val().toLowerCase() == "ca".toLowerCase()) {
                                    isValid = true;
                                }
                            }
                            if ($('#statediv').css('display') == 'block') {
                                if ($("#billing-state-select_sub").val() != "-1") {
                                    isValid = true;
                                }
                            }
                        }
                        else {
                            if ($('#regiondiv').css('display') == 'block' || $('#regiondiv').css('display') == undefined) {
                                if ($("#billing-region_sub").val() != "") {
                                    isValid = true;
                                }
                            }
                            if ($('#statediv').css('display') == 'none') {
                                if ($("#billing-state-select_sub").val() == "-1") {
                                    isValid = false;
                                }
                            }
                        }
                        if (isValid) {
                            $("#btnEmailAddress").removeClass("disableBtn").addClass("enableBtn");
                        } else {
                            $("#btnEmailAddress").removeClass("enableBtn").addClass("disableBtn");
                            $(".pass").tooltip('destroy');
                        }

                        //if (isValid) {
                        //    $("#btnEmailAddress").removeClass("disableBtn").addClass("enableBtn");
                        //} else {
                        //    $("#btnEmailAddress").removeClass("enableBtn").addClass("disableBtn");
                        //}
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.name == "billing-state-select" && $(element).val() == "-1") {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                    else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                        $(".pass").tooltip('destroy');
                        $(".tooltip").css('display', 'none');
                    }
                    if (element.name == "zip") {
                        //if ($("#edit-billing-country_sub").val().toLowerCase() == "canada".toLowerCase() || $("#edit-billing-country_sub").val().toLowerCase() == "ca".toLowerCase()) {
                        //    if ($('#billing-zip_sub').val().length > 0) {
                        //        $('#rowZip').removeClass(errorClass).addClass(validClass).addClass('ignore');
                        //        $('#billing-zip_sub').removeClass(errorClass).addClass(validClass).addClass('ignore');
                        //    }
                        //}
                        if ($("#lbl_billing-country_sub").val().toLowerCase() == 'US'.toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == 'united states'.toLowerCase()) {
                            var reg = /^[0-9]+$/;
                            var Zip = $('#billing-zip_sub').val();

                            if (!reg.test(Zip)) {
                                $("#rowZip").addClass('error').removeClass('pass');
                            }
                            else {
                                if ((Zip.length) < 5) {
                                    $("#rowZip").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#rowZip").addClass('pass').removeClass('error');
                                    $('#billing-zip_sub').removeClass(errorClass).addClass(validClass).addClass('ignore');
                                }
                            }
                        }
                        else {
                            var Zip_check = $.trim($('#billing-zip_sub').val());
                            if (Zip_check.length == 0) {
                                $("#rowZip").addClass('error').removeClass('pass');
                            }
                            else {
                                var reg1 = /^[a-zA-Z0-9\s]+$/;
                                var Zip = $('#billing-zip_sub').val();
                                if (!reg1.test(Zip)) {
                                    $("#rowZip").addClass('error').removeClass('pass');
                                }
                                else {
                                    $("#rowZip").addClass('pass').removeClass('error');
                                    $('#billing-zip_sub').removeClass(errorClass).addClass(validClass).addClass('ignore');
                                }
                                //$("#rowZip").addClass('pass').removeClass('error');
                                // $("#billing-zip_sub").removeAttr("pattern");
                            }
                        }
                    }
                    // debugger;
                    var formId = element.form.id;
                    var isValid = true;
                    if (formId == "myAccountSubscription") {
                        $("#" + formId + " input").each(function () {
                            var $el = $(this);
                            if ($el[0].id != "billing-address2_sub" && $el[0].id != "hdn_billing-state") {
                                if ($el[0].id != "billing-region_sub") {
                                    $("#billing-region_sub").addClass('pass');
                                }
                                if ($el.context.type != "submit" && $el.context.type != "checkbox" && $el.context.type != "hidden") {
                                    if (!$el.hasClass(validClass)) {
                                        isValid = false;
                                    }
                                }
                            }
                        });
                        //if ($('#RegionDiv').css('display') == 'block') {
                        //    if ($("#billing-region_sub").val() == "") {
                        //        isValid = false;
                        //    }
                        //}
                        //if ($('#StateDiv').css('display') == 'block') {
                        //    if ($("#billing-state-select_sub").val() == "-1") {
                        //        isValid = false;
                        //    }
                        //}
                        if ($("#lbl_billing-country_sub").val().toLowerCase() == "united states".toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == "canada".toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == "us".toLowerCase() || $("#lbl_billing-country_sub").val().toLowerCase() == "ca".toLowerCase() || $("lbl_billing-country_sub").val() == "") {
                            if ($('#regiondiv').css('display') == 'block' || $('#regiondiv').css('display') == undefined) {
                                if ($("#billing-region_sub").val() == "") {
                                    isValid = false;
                                }
                                else if ($("#edit-billing-country_sub").val().toLowerCase() == "canada".toLowerCase() || $("#edit-billing-country_sub").val().toLowerCase() == "ca".toLowerCase()) {
                                    isValid = true;
                                }
                            }
                            if ($('#statediv').css('display') == 'block') {
                                if ($("#billing-state-select_sub").val() != "-1") {
                                    isValid = true;
                                }
                            }
                        }
                        else {
                            if ($('#regiondiv').css('display') == 'block' || $('#regiondiv').css('display') == undefined) {
                                if ($("#billing-region_sub").val() != "") {
                                    isValid = true;
                                }
                            }
                            if ($('#statediv').css('display') == 'none') {
                                if ($("#billing-state-select_sub").val() == "-1") {
                                    isValid = false;
                                }
                            }
                        }
                        if (isValid) {
                            $("#btnEmailAddress").removeClass("disableBtn").addClass("enableBtn");
                        } else {
                            $("#btnEmailAddress").removeClass("enableBtn").addClass("disableBtn");
                            $(".pass").tooltip('destroy');
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].type !== 'checkbox') {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                    else {
                        error.insertAfter($(element));
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'zip': {
                    required: true
                },
                'billing-state-select': {
                    required: true
                },
                'billing-region': {
                    required: true
                },
                'city': {
                    required: true
                },
                'address1': {
                    required: true
                }
            },
            messages: {
                'billing-state-select': {
                    required: 'Please enter state.'
                },
                'billing-region': {
                    required: 'Please enter region.'
                },
                'zip': {
                    required: 'Please enter a postal code.'
                },
                'city': {
                    required: 'Please enter city.'
                },
                'address1': {
                    required: 'Please enter address.'
                }
            }
        },
        ForgetPasswordEmail: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);

                    if (element.name == "email") {
                        var valid = OA.validator.methods.validateEmail(element.value);
                        if (valid) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).removeClass(validClass).addClass(errorClass);
                        }
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    //$(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    //$(element).removeClass(errorClass).addClass(validClass);
                    if (element.name == "email") {
                        var valid = OA.validator.methods.validateEmail(element.value);
                        if (valid) {
                            //$(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            //$(element).removeClass(errorClass).addClass(validClass);
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).removeClass(validClass).addClass(errorClass);
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    var email = $("#form-forget-panel").find('#email').val();
                    var valid = OA.validator.methods.validateEmail(email);
                    if (!valid) {
                        $(".error-description").html(error.text());
                        $(".email-error").show();
                        var $err = $('#form-forget-panel-mobile').find('#request-error');
                        $err.html(error.text());
                        $err.removeClass('hidden');
                        $('input').addClass('error');
                        $('input').removeClass('pass');
                        $(".page-wrap").addClass('page-wrap-error');
                        $(".forgot-password-panel").css('height', '310px');
                        $(".email-error").css('height', '72px');
                    }
                },
                success: function (label, element) {
                    var email = $("#form-forget-panel").find('#email').val();
                    var valid = OA.validator.methods.validateEmail(email);
                    if (valid) {
                        $('input').removeClass('error');
                        $('input').removeClass('pass');
                        $(".pass").tooltip('destroy');
                        $(".email-error").hide();
                        var inputname = $('#form-forget-panel-mobile').find('#email');
                        // $err.html(error.text());
                        inputname.removeClass('error');
                        //$("#email").closest(".row").removeClass('error');
                        //$("#email").removeClass('error');
                        $(".page-wrap").removeClass('page-wrap-error');
                        $(".forgot-password-panel").css('height', '210px');
                    }
                    else {
                        $(".error-description").html('Please enter a valid email address.');
                    }
                }
            },
            rules: {
                'email': {
                    required: true,
                    email: true
                }
            },
            messages: {
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                }
            }
        },
        ResetPasswordValidator: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    //$(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    //$(element).removeClass(errorClass).addClass(validClass);
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    //element.attr('title', error.text());
                    //element.attr('data-original-title', error.text());
                    //$(".error").tooltip();

                    //  $(".error-description").html(error.text());

                    $("#" + element[0].id).addClass('error');
                    $(".page-wrap").addClass('page-wrap-resetpass-error');
                    $('.error-description').html(error.text());
                    $("#reset-error").html(error.text());

                    $("#reset-error").removeClass('hidden');
                    $('.email-error-reset-pass').show();
                    $(".forgot-password-panel").css('height', '420px !important');
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $("#reset-password-form #" + element.id).removeClass('error');
                    $(".page-wrap").removeClass('page-wrap-resetpass-error');
                    $('.email-error-reset-pass').hide();
                    $("#reset-error").html("");
                    $(".forgot-password-panel").css('height', '307px !important');
                    //$(".pass .tooltip").css('display', 'none');
                    //$(".pass .tooltip-arrow").css('display', 'none');
                    //$(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'resetPassword': {
                    required: true,
                    validPassword: '#resetCPassword'
                },
                'resetCPassword': {
                    required: true,
                    validateConfirmPassword: '#resetPassword'
                }
            },
            messages: {
                'resetPassword': {
                    required: 'Please enter your password.',
                    validPassword: 'Use at least 6 characters for your password.'
                },
                'resetCPassword': {
                    required: 'Confirm your password.',
                    validateConfirmPassword: 'Passwords do not match. Please enter again.'
                }
            }
        },
        MyAccountCallBackNumbervalid: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass('border-bottom-none');
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    var callbackNumber = $(element).val().replace(/[_-]/g, '').trim();
                    if (callbackNumber.length == 10) {
                        if (!isNaN(callbackNumber)) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].id == "primary_number_input") {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $(".pass .tooltip").css('display', 'none');
                    $(".pass .tooltip-arrow").css('display', 'none');
                    $(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'primary_number_input': {
                    required: true,
                    validCallbackNumber: '#primary-callback-number-country'
                }
            },
            messages: {
                'primary_number_input': {
                    required: 'Please enter callback phone',
                    validCallbackNumber: 'Invalid callback phone number. Please try again.'
                }
            }
        },
        MyAccountReadingCallbackNumber: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.name != 'callback-country') {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                    var formId = element.form.id;
                    var isValid = true;

                    $("#" + formId + " input").each(function () {
                        var $el = $(this);

                        // if ($el.context.type != "submit") {
                        if ($el.context.type != "submit" && $el.context.type != "checkbox") {
                            if (!$el.hasClass(validClass)) {
                                isValid = false;
                            }
                        }
                    });

                    if (!isValid) {
                        $('#' + formId).find("#save-callback").addClass('disabled-save-number');
                    } else {
                        $('#' + formId).find("#save-callback").removeClass('disabled-save-number');
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.name != 'callback-country') {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                    var formId = element.form.id;
                    var isValid = true;

                    $("#" + formId + " input").each(function () {
                        var $el = $(this);

                        if ($el.context.type != "submit" && $el.context.type != "checkbox") {
                            if (!$el.hasClass(validClass)) {
                                isValid = false;
                            }
                        }
                    });

                    if (isValid) {
                        $('#' + formId).find("#save-callback").removeClass('disabled-save-number');
                    } else {
                        $('#' + formId).find("#save-callback").addClass('disabled-save-number');
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    element.attr('title', error.text());
                    element.attr('data-original-title', error.text());
                    $(".error").tooltip();
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $(".pass .tooltip").css('display', 'none');
                    $(".pass .tooltip-arrow").css('display', 'none');
                    $(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'callback-phone': {
                    required: true,
                    validCallbackNumber: '#callback-country'
                }
            },
            messages: {
                'callback-phone': {
                    required: 'Please enter callback phone',
                    validCallbackNumber: 'Invalid callback phone number. Please try again.'
                }
            }
        },
        methods: {
            updateExpDate: function () {
                // Set the hidden field with the selected expiration date (i.e. the last day of the selected month/year)
                // Set date to empty if either the month or year isn't selected
                // Trigger validation on the hidden field, which will cause highlighting on the month and year if the date is invalid
                var month = $("select[name*=expMonth]").val();
                var year = $("select[name*=expYear]").val();
                var $expDate = $("input[name*=exp-date-hidden]");
                var expDate;

                if (month === '' || year === '')
                    $expDate.val("");
                else {
                    expDate = moment(new Date(month + "/1/" + year));
                    expDate.add(1, 'months');

                    $expDate.val(expDate.format("M/D/YYYY"));
                }
                if (window.innerWidth >= OAApp.appsettings.MobileResolution) {
                    if (year === "" || year === "0") {
                        $("#expYear-button").css("width", "77px");
                    }
                    else {
                        $("#expYear-button").css("width", "50px");
                    }
                }
                $expDate.valid();
            },
            updateExpDateDesktop: function () {
                // Set the hidden field with the selected expiration date (i.e. the last day of the selected month/year)
                // Set date to empty if either the month or year isn't selected
                // Trigger validation on the hidden field, which will cause highlighting on the month and year if the date is invalid
                var month = $("select[name*=bill-expMonth]").val();
                var year = $("select[name*=bill-expYear]").val();
                var $expDate = $("input[name*=bill-exp-date-hidden]");
                var expDate;

                if (month === '' || year === '')
                    $expDate.val("");
                else {
                    expDate = moment(new Date(month + "/1/" + year));
                    expDate.add(1, 'months');

                    $expDate.val(expDate.format("M/D/YYYY"));
                }

                $expDate.valid();
            },
            initPostalCodeValidation: function () {
                // detect country and set postal code validation accordingly
                // Rule application is dynamic, based on the country

                $("input[name*=zip]").rules("add", {
                    zipcodeUS: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'US' || $("select[name*=callback-country] option:selected").val() === 'PR' || $("#country").text().toLowerCase() === 'united states';
                        }
                    },
                    messages: {
                        zipcodeUS: "Please verify the ZIP code."
                    }
                });

                $("input[name*=zip]").rules("add", {
                    postalCodeCA: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'CA' || $("#country").text().toLowerCase() === 'canada';
                        }
                    },
                    messages: {
                        postalCodeCA: "Please verify the postal code."
                    }
                });

                $("input[name*=zip]").rules("add", {
                    postcodeUK: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'GB' || $("#country").text().toLowerCase() === 'united kingdom';
                        }
                    },
                    messages: {
                        postcodeUK: "Please verify the postal code."
                    }
                });

                $("input[name*=zip]").rules("add", {
                    postalcodeBR: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'BRA' || $("#country").text().toLowerCase() === 'brazil';
                        }
                    },
                    messages: {
                        postalcodeBR: "Please verify the postal code."
                    }
                });

                $("input[name*=zip]").rules("add", {
                    postalcodeIT: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'ITA' || $("#country").text().toLowerCase() === 'italy';
                        }
                    },
                    messages: {
                        postalcodeIT: "Please verify the postal code."
                    }
                });

                $("input[name*=zip]").rules("add", {
                    postalcodeNL: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'NLD' || $("#country").text().toLowerCase() === 'netherlands';
                        }
                    },
                    messages: {
                        postalcodeNL: "Please verify the postal code."
                    }
                });
            },
            initPhoneNumberValidation: function () {
                $("input[name*=callback-phone]").rules("add", {
                    phoneUS: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'US' || $("select[name*=callback-country] option:selected").val() === 'PR' || $("select[name*=callback-country] option:selected").val() === 'CA' || $("#country").text().toLowerCase() === 'united states';
                        }
                    },
                    messages: {
                        phoneUS: "Invalid phone number."
                    }
                });

                $("input[name*=callback-phone]").rules("add", {
                    phoneNL: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'NLD' || $("#country").text().toLowerCase() === 'netherlands';
                        }
                    },
                    messages: {
                        phoneNL: "Invalid phone number."
                    }
                });

                $("input[name*=callback-phone]").rules("add", {
                    phoneUK: {
                        depends: function (element) {
                            return $("select[name*=callback-country] option:selected").val() === 'GB' || $("#country").text().toLowerCase() === 'united kingdom';
                        }
                    },
                    messages: {
                        phoneUK: "Invalid phone number."
                    }
                });
            },
            validateDate: function (date) {
                var m = moment(date);
                return m.isValid();
            },
            validateNewCustDate: function (value) {
                var isDOBValid = false,
                    minAge = 18,
                    dobDay = moment(value).date(),
                    dobMonth = moment(value).month() + 1, //Months are zero indexed, so January is month 0
                    dobYear = moment(value).year();

                var myDate = new Date();
                myDate.setFullYear(dobYear, dobMonth - 1, dobDay);

                var setDate = new Date();
                setDate.setFullYear(setDate.getFullYear() - minAge);

                if (OA.validator.methods.validateDate(value) && dobYear > 1900 && (setDate - myDate) >= 0) {
                    isDOBValid = true;
                }
                else {
                    isDOBValid = false;
                }

                return isDOBValid;
            },
            validDesktopHoroDOB: function (value) {
                var isDOBValid = false;
                //1988-5-22 // Year-Month-Day
                if (value != 0) {
                    var minAge = 16,
                        dobYear = value.split('-')[0],
                        dobMonth = value.split('-')[1],
                        dobDay = value.split('-')[2];
                    //dobDay = moment(value).date(),
                    //dobMonth = moment(value).month(),// + 1, //Months are zero indexed, so January is month 0
                    //dobYear = moment(value).year();

                    var myDate = new Date();
                    myDate.setFullYear(dobYear, dobMonth - 1, dobDay);

                    var setDate = new Date();
                    setDate.setFullYear(setDate.getFullYear() - minAge);

                    if (OA.validator.methods.isValidDate(value) && dobYear > 1900 && (setDate - myDate) >= 0) {
                        isDOBValid = true;
                    }
                    else {
                        isDOBValid = false;
                    }
                }
                return isDOBValid;
            },
            validmobileHoroDOB: function (value) {
                var isDOBValid = false;
                //1988-5-22 // Year-Month-Day
                if (value != 0) {
                    var minAge = 16,

                        dobDay = moment(value).date(),
                        dobMonth = moment(value).month(),// + 1, //Months are zero indexed, so January is month 0
                        dobYear = moment(value).year();

                    var myDate = new Date();
                    myDate.setFullYear(dobYear, dobMonth - 1, dobDay);

                    var setDate = new Date();
                    setDate.setFullYear(setDate.getFullYear() - minAge);

                    if (OA.validator.methods.isValidmobileDate(value) && dobYear > 1900 && (setDate - myDate) >= 0) {
                        isDOBValid = true;
                    }
                    else {
                        isDOBValid = false;
                    }
                }
                return isDOBValid;
            },
            isValidmobileDate: function (text) {
                var isValid = false;
                var comp = text.split('/');
                var y = parseInt(comp[2], 10);
                var m = parseInt(comp[0], 10);
                var d = parseInt(comp[1], 10);
                var date = new Date(y, m - 1, d);
                if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
                    isValid = true;
                } else {
                    isValid = false;
                }
                return isValid;
            },
            isValidDate: function (text) {
                var isValid = false;
                var comp = text.split('-');
                var y = parseInt(comp[0], 10);
                var m = parseInt(comp[1], 10);
                var d = parseInt(comp[2], 10);
                var date = new Date(y, m - 1, d);
                if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
                    isValid = true;
                } else {
                    isValid = false;
                }
                return isValid;
            },
            showSelFieldError: function (validator, $target) {
                var $fld = validator.$selField, $lbl, err;
                if ($target && $target.length) {
                    validator.$selField = $target;
                    $fld = $target;
                }
                if (!$fld)
                    return;

                $lbl = $("#lbl_" + $fld.attr("id"));
                err = $fld.next('label.error').text();
                if (!err)
                    OA.utils.tooltips.hideTooltip($lbl);
                else
                    OA.utils.tooltips.showTooltip($lbl, err);
            },
            showValidatorErrors: function (validator, errorList) {
                var el, elHasErrors, $el, $row, i, j,
                    curElLen = validator.currentElements.length,
                    errLstLen = errorList.length;

                for (i = 0; i < curElLen; i++) {
                    el = validator.currentElements[i];
                    $el = $(el);
                    if ($el.hasClass('combofld'))
                        continue;

                    $row = $el.closest('.row');
                    elHasErrors = false;
                    for (j = 0; j < errLstLen; j++) {
                        if (el === errorList[j].element) {
                            elHasErrors = true;
                            break;
                        }
                    }

                    if (elHasErrors) {
                        $el.removeClass('pass').addClass('error');
                        $row.removeClass('pass').addClass('error');
                    }
                    else {
                        $el.removeClass('error').addClass('pass');
                        $row.removeClass('error').addClass('pass');
                        $el.next('label.error').empty();
                    }
                }

                validator.defaultShowErrors();
                this.showSelFieldError(validator);
            },
            validateEmail: function (value) {
                var emailtest = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
                return emailtest.test(value);
            }
        },
        SignInEmailPassword: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass('removeBorder');
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);

                    if (element.name == "email") {
                        var valid = OA.validator.methods.validateEmail(element.value);
                        if (valid) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                            $('.sign-in-error-desktop-top').addClass('hidden');
                            $('.sign-in-error-desktop').removeClass('sign-in-error-desktop-display');
                            $(".sign-in-desktop").removeClass('signInDesktopHeight');
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $('.sign-in-main').find(($('.sign-in-panel-inner'))).find(($('.reset-Password-Success'))).hide();
                            $(element).removeClass(validClass).addClass(errorClass);
                            $('.sign-in-error-desktop-top').addClass('hidden');
                            //  $('.sign-in-error-desktop').addClass('sign-in-error-desktop-display');
                            $('.sign-in-desktop').addClass('signInDesktopHeight');
                        }
                    }
                    var formId = element.form.id;
                    var isValid = true;
                    if (formId == "SignInForm") {
                        $("#" + formId + " input").each(function () {
                            var $el = $(this);
                            if ($el.context.type != "submit" && $el.context.type != "checkbox") {
                                if (!$el.hasClass(validClass)) {
                                    isValid = false;
                                }
                            }
                        });

                        //if (isValid) {
                        //    $("#btnSignindesktop").removeClass("disableBtn").addClass("enableBtn");
                        //    $(element).closest(".row").addClass('removeBorder');
                        //} else {
                        //    $("#btnSignindesktop").removeClass("enableBtn").addClass("disableBtn");
                        //    $(element).closest(".row").removeClass('removeBorder');
                        //}
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    $(element).removeClass(errorClass).addClass(validClass);
                    if (element.name == "email") {
                        var valid = OA.validator.methods.validateEmail(element.value);
                        if (valid) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                            $('.sign-in-error-desktop-top').addClass('hidden');
                            $('.sign-in-error-desktop').removeClass('sign-in-error-desktop-display');
                            $(".sign-in-desktop").removeClass('signInDesktopHeight');
                            if ($('#txtPasswordDesktop').hasClass('error')) {
                                $('.sign-in-error-desktop-top').addClass('hidden');
                                // $('.sign-in-error-desktop').addClass('sign-in-error-desktop-display');
                                $('.sign-in-desktop').addClass('signInDesktopHeight');
                            }
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).removeClass(validClass).addClass(errorClass);
                            $('.sign-in-main').find(($('.sign-in-panel-inner'))).find(($('.reset-Password-Success'))).hide();
                            $('.sign-in-error-desktop-top').addClass('hidden');
                            //  $('.sign-in-error-desktop').addClass('sign-in-error-desktop-display');
                            $('.sign-in-desktop').addClass('signInDesktopHeight');
                        }
                    }
                    var formId = element.form.id;
                    var isValid = true;
                    if (formId == "SignInForm") {
                        $("#" + formId + " input").each(function () {
                            var $el = $(this);
                            if ($el.context.type != "submit" && $el.context.type != "checkbox") {
                                if (!$el.hasClass(validClass)) {
                                    isValid = false;
                                }
                            }
                        });

                        //if (isValid) {
                        //    $("#btnSignindesktop").removeClass("disableBtn").addClass("enableBtn");
                        //    $(element).closest(".row").addClass('removeBorder');
                        //} else {
                        //    $("#btnSignindesktop").removeClass("enableBtn").addClass("disableBtn");
                        //    $(element).closest(".row").removeClass('removeBorder');
                        //}
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    //element.attr('title', error.text());
                    //$(".error").tooltip();
                    $('.sign-in-desktop').addClass('signInDesktopHeight');
                    $('.sign-in-error-desktop-top').addClass('hidden');
                    // $('.sign-in-error-desktop').addClass('sign-in-error-desktop-display');
                },
                success: function (label, element) {
                    $('.sign-in-error-desktop-top').addClass('hidden');

                    $(".sign-in-desktop").removeClass('signInDesktopHeight');
                    //$(".pass").tooltip('destroy');
                    //$(".pass .tooltip").css('display', 'none');
                    //$(".pass .tooltip-arrow").css('display', 'none');
                    //$(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'email': {
                    required: true,
                    email: true
                },
                'password': {
                    required: true
                    /*  validPassword: 'txtPassword'*/
                },
            },
            messages: {
                'email': {
                    required: "Please check your email address or PIN/password and try again.",
                    email: "Please check your email address or PIN/password and try again."
                },
                'password': {
                    required: "Please check your email address or PIN/password and try again."
                    /* validPassword: "* Invalid Email Address/PIN. Please Try Again."*/
                },
            }
        },
        SupportAffiliate: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);

                    if ($("#country").val() != undefined) {
                        if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "usa".toLowerCase() || $("#country").val() == "") {
                            if (element.name == "zip") {
                                if ($('#zip').val().length > 0) {
                                    var reg = /^[0-9]+$/;
                                    var Zip = $('#zip').val();

                                    if (!reg.test(Zip)) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        if ((Zip.length) < 5) {
                                            $("#zip-validation").addClass('error').removeClass('pass');
                                        }
                                        else {
                                            $("#zip-validation").addClass('pass').removeClass('error');
                                        }
                                    }
                                }
                            }
                        }
                        //else {
                        //	var Zip_check = $.trim($('#zip').val());
                        //	if (Zip_check.length == 0) {
                        //		$("#zip-validation").addClass('error').removeClass('pass');
                        //	}
                        //	else {
                        //		var reg1 = /^[a-zA-Z0-9\s]+$/;
                        //		var Zip = $('#zip').val();
                        //		if (!reg1.test(Zip)) {
                        //			$("#zip-validation").addClass('error').removeClass('pass');
                        //		}
                        //		else {
                        //			$("#zip-validation").addClass('pass').removeClass('error');
                        //		}
                        //	}
                        //}
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    $(element).removeClass(errorClass).addClass(validClass);

                    if ($("#country").val() != undefined) {
                        if ($("#country").val().toLowerCase() == "united states".toLowerCase() || $("#country").val().toLowerCase() == "usa".toLowerCase() || $("#country").val() == "") {
                            if (element.name == "zip") {
                                if ($('#zip').val().length > 0) {
                                    var reg = /^[0-9]+$/;
                                    var Zip = $('#zip').val();

                                    if (!reg.test(Zip)) {
                                        $("#zip-validation").addClass('error').removeClass('pass');
                                    }
                                    else {
                                        if ((Zip.length) < 5) {
                                            $("#zip-validation").addClass('error').removeClass('pass');
                                        }
                                        else {
                                            $("#zip-validation").addClass('pass').removeClass('error');
                                        }
                                    }
                                }
                            }
                        }
                        //else {
                        //	var Zip_check = $.trim($('#zip').val());
                        //	if (Zip_check.length == 0) {
                        //		$("#zip-validation").addClass('error').removeClass('pass');
                        //	}
                        //	else {
                        //		var reg1 = /^[a-zA-Z0-9\s]+$/;
                        //		var Zip = $('#zip').val();
                        //		if (!reg1.test(Zip)) {
                        //			$("#zip-validation").addClass('error').removeClass('pass');
                        //		}
                        //		else {
                        //			$("#zip-validation").addClass('pass').removeClass('error');
                        //		}
                        //	}
                        //}
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].type !== 'checkbox') {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                    else {
                        error.insertAfter($(element));
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'first-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'last-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'organization-name': {
                    required: true
                },
                'organization-function': {
                    required: true
                },
                'phone': {
                    required: true,
                    validCallbackNumber: '#country'
                },
                'email': {
                    required: true,
                    email: true
                },
                'zip': {
                    required: true
                },
                'state-select': {
                    required: true
                },
                'region': {
                    required: true
                },
                'city': {
                    required: true
                },
                'address1': {
                    required: true
                },
                'news-letter': {
                    required: true
                },
                'website-url': {
                    required: true
                },
                'unique-visitor': {
                    required: true
                },
                'affiliate-description': {
                    required: true
                }
            },
            messages: {
                'first-name': {
                    required: 'Please enter your first name.',
                    letterswithbasicpunc: 'Invalid first name. Please use only alpha characters.'
                },
                'last-name': {
                    required: 'Please enter your last name.',
                    letterswithbasicpunc: 'Invalid last name. Please use only alpha characters.'
                },
                'organization-name': {
                    required: 'Please enter your organizaion name.',
                },
                'organization-function': {
                    required: 'Please enter your title/function in organization.',
                },
                'phone': {
                    required: 'Please enter your phone.',
                    validCallbackNumber: 'Invalid phone number. Please try again.'
                },
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                },
                'zip': {
                    required: 'Please enter a postal code.'
                },
                'state-select': {
                    required: 'Please enter state.'
                },
                'region': {
                    required: 'Please enter region.'
                },
                'city': {
                    required: 'Please enter city.'
                },
                'address1': {
                    required: 'Please enter address.'
                },
                'news-letter': {
                    required: 'Please enter news letter details.'
                },
                'website-url': {
                    required: 'Please enter website url.'
                },
                'unique-visitor': {
                    required: 'Please enter monthly unique visitor number.'
                },
                'affiliate-description': {
                    required: 'Please enter description.'
                }
            }
        },
        contactUs: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.name === 'exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=expMonth]").closest(".row").removeClass(validClass).addClass(errorClass);
                    } else if (element.name == "date_[day]" || element.name == "date_[month]" || element.name == "date_[year]") {
                        var d = $('.day').val();
                        var m = $('.month').val();
                        var y = $('.year').val();
                        if (d != "" && m != "" && y != "") {
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                            $('#dob').addClass(errorClass).removeClass(validClass);
                        }
                    } else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.name === 'exp-date-hidden') {
                        $("select[name*=expMonth]").closest(".row").removeClass(errorClass).addClass(validClass);
                    } else if (element.name == "date_[day]" || element.name == "date_[month]" || element.name == "date_[year]") {
                        var d = $('.day').val();
                        var m = $('.month').val();
                        var y = $('.year').val();
                        if (d != "" && m != "" && y != "") {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                            $('#dob').removeClass(errorClass).addClass(validClass);
                        }
                    } else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].type !== 'checkbox') {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                    else {
                        error.insertAfter($(element));
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'first-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'email': {
                    required: true,
                    email: true
                },
                'contact-us-phone': {
                    required: true,
                    validCallbackNumber: '#contact-us-phone'
                },
                'dob': {
                    required: true,
                    validNcDOB: "#dob"
                },
                'txtYourQuestion': {
                    required: true
                }
            },
            messages: {
                'first-name': {
                    required: 'Please enter your first name.',
                    letterswithbasicpunc: 'Invalid first name. Please use only alpha characters.'
                },
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                },
                'contact-us-phone': {
                    required: 'Invalid phone number.',
                    validCallbackNumber: 'Invalid callback phone number.'
                },
                'dob': {
                    required: 'Please enter your date of birth using MM/DD/YYYY format.',
                    validNcDOB: 'Must be at least 18 years or older.'
                },
                'txtYourQuestion': {
                    required: 'Please enter your comment.'
                }
            }
        },
        unsubscribe: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                    $(element).removeClass(errorClass).addClass(validClass);
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].type !== 'checkbox') {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                    else {
                        error.insertAfter($(element));
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                }
            },
            rules: {
                'email': {
                    required: true,
                    email: true
                }
            },
            messages: {
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                }
            }
        },
        fiveFreeNewCustomer: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    if (element.name === 'exp-date-hidden') {
                        // For expiration dates, the hidden field is validated - need to highlight the associated month/year dropdowns
                        $("select[name*=expMonth]").closest(".row").removeClass(validClass).addClass(errorClass);
                    } else if (element.name == "date_[day]" || element.name == "date_[month]" || element.name == "date_[year]") {
                        var d = $('.day').val();
                        var m = $('.month').val();
                        var y = $('.year').val();
                        if (d != "" && m != "" && y != "") {
                            var date = m + "/" + d + "/" + y;
                            var validDate = OA.validator.methods.validateNewCustDate(date);
                            if (!validDate) {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            } else {
                                $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                $(element).removeClass(errorClass).addClass(validClass);
                                $('#dob').removeClass(errorClass).addClass(validClass);
                            }
                        } else {
                            $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                            $(element).addClass(errorClass).removeClass(validClass);
                            $('#dob').addClass(errorClass).removeClass(validClass);
                        }
                    } else {
                        $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                        $(element).addClass(errorClass).removeClass(validClass);
                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.name === 'exp-date-hidden') {
                        $("select[name*=expMonth]").closest(".row").removeClass(errorClass).addClass(validClass);
                    } else if (element.name == "date_[day]" || element.name == "date_[month]" || element.name == "date_[year]") {
                        var d = $('.day').val();
                        var m = $('.month').val();
                        var y = $('.year').val();

                        if (d != "" && m != "" && y != "") {
                            var date = m + "/" + d + "/" + y;
                            var validDate = OA.validator.methods.validateNewCustDate(date);
                            if (validDate) {
                                $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                                $(element).removeClass(errorClass).addClass(validClass);
                                $('#dob').removeClass(errorClass).addClass(validClass);
                            } else {
                                $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                                $(element).addClass(errorClass).removeClass(validClass);
                                $('#dob').addClass(errorClass).removeClass(validClass);
                            }
                        }
                    } else if (element.name == "expYear" || element.name == "expMonth") {
                        var month = $("select[name*=expMonth]").val();
                        var year = $("select[name*=expYear]").val();
                        var $expDate = $("input[name*=exp-date-hidden]");
                        var expDate;

                        if (month === '' || year === '')
                            $expDate.val("");
                        else {
                            expDate = moment(new Date(month + "/1/" + year));
                            expDate.add(1, 'months');

                            $expDate.val(expDate.format("M/D/YYYY"));
                        }
                        if (window.innerWidth >= OAApp.appsettings.MobileResolution) {
                            if (year === "" || year === "0") {
                                $("#expYear-button").css("width", "77px");
                            }
                            else {
                                $("#expYear-button").css("width", "50px");
                            }
                        }
                        $expDate.valid();
                    } else {
                        $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                        $(element).removeClass(errorClass).addClass(validClass);
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].type !== 'checkbox') {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                    else {
                        error.insertAfter($(element));
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $(".pass .tooltip").css('display', 'none');
                    $(".pass .tooltip-arrow").css('display', 'none');
                    $(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'first-name': {
                    required: true,
                    letterswithbasicpunc: true
                },
                'email': {
                    required: true,
                    email: true
                },
                'dob': {
                    required: true,
                    validNcDOB: "#dob"
                },
                'agree': {
                    required: true
                }
            },
            messages: {
                'first-name': {
                    required: 'Please enter your first name.',
                    letterswithbasicpunc: 'Invalid first name. Please use only alpha characters.'
                },
                'email': {
                    required: 'Please enter your email address.',
                    email: 'Please enter a valid email address.'
                },
                'dob': {
                    required: 'Please enter your date of birth using MM/DD/YYYY format.',
                    validNcDOB: 'Must be at least 18 years or older.'
                },
                'agree': {
                    required: 'Please accept the Terms and Conditions in order to use our service.'
                }
            }
        },
        MyAlertCallBackNumber: {
            init: function (formSelector, errorContainerSelector) {
                var validator = OA.validator.setValidation(formSelector, errorContainerSelector, this.rules, this.messages, this.customProperties);
                return validator;
            },
            customProperties: {
                highlight: function (element, errorClass, validClass) {
                    $(element).closest(".row").removeClass('border-bottom-none');
                    $(element).closest(".row").removeClass(validClass).addClass(errorClass);
                    $(element).addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    if ($(element).val().length == 10) {
                        if (!isNaN($(element).val())) {
                            $(element).closest(".row").removeClass(errorClass).addClass(validClass);
                            $(element).removeClass(errorClass).addClass(validClass);
                        }
                    }
                },
                errorClass: 'error',
                validClass: 'pass',
                errorPlacement: function (error, element) {
                    if (element[0].id == "alert_primary_number_input") {
                        element.attr('title', error.text());
                        $(".error").tooltip();
                    }
                },
                success: function (label, element) {
                    $(".pass").tooltip('destroy');
                    $(".pass .tooltip").css('display', 'none');
                    $(".pass .tooltip-arrow").css('display', 'none');
                    $(".pass .tooltip-inner").css('display', 'none');
                }
            },
            rules: {
                'alert_primary_number_input': {
                    required: true,
                    validCallbackNumber: '#alert_primary_number_input'
                }
            },
            messages: {
                'alert_primary_number_input': {
                    required: 'Please enter callback phone',
                    validCallbackNumber: 'Invalid callback phone number. Please try again.'
                }
            }
        }
    }
})();;
(function () {
    "use strict";

    // All custom validation methods - begin
    $.validator.addMethod("validEmailServerValidation", function (value) {
        var isEmailValid = false;

        OA.services.validateEmail({
            Email: value
        }).done(function (res) {
            isEmailValid = true;
        }).fail(function (xhr) {
            var err = OA.utils.ajaxHelpers.getError(xhr);
        }).always(function () {
        });

        return isEmailValid;
    });

    $.validator.addMethod("validPassword", function (value, element, CPasswordSelector) {
        var minPasswordLength = 6;
        var passwordIsValid = false;
        if (value.length >= minPasswordLength) {
            setTimeout(function () {
                if ($(CPasswordSelector).length && $(CPasswordSelector).val().length > 0)
                    $(CPasswordSelector).valid();
            }, 50);
            passwordIsValid = true;
        }
        return passwordIsValid;
    });

    $.validator.addMethod("validCPassword", function (value, element, CPasswordSelector) {
        var Confirm = $(CPasswordSelector).val();
        if (!Confirm)
            return false;
        return (Confirm == value);
    });

    $.validator.addMethod("validateConfirmPassword", function (value, element, CPasswordSelector) {
        var Confirm = $(CPasswordSelector).val();

        if (window.innerWidth > OAApp.appsettings.MobileResolution) {
            Confirm = $('#desktop-reset-password').find('#reset-password-form').find(CPasswordSelector).val();
        }

        if (!Confirm)
            return false;

        if (Confirm == value) {
            return true;
        } else {
            return false;
        }
    });

    $.validator.addMethod("validDOB", function (value) {
        return OA.validator.methods.validateDate(value);
    });

    $.validator.addMethod("validNcDOB", function (value) {
        var isDOBValid = false,
            minAge = 18,
            dobDay = moment(value).date(),
            dobMonth = moment(value).month() + 1, //Months are zero indexed, so January is month 0
            dobYear = moment(value).year();       

        var myDate = new Date();
        myDate.setFullYear(dobYear, dobMonth - 1, dobDay);

        var setDate = new Date();
        setDate.setFullYear(setDate.getFullYear() - minAge);

        if (OA.validator.methods.validateDate(value) && dobYear > 1900 && (setDate - myDate) >= 0) {
            isDOBValid = true;
        }
        else {
            isDOBValid = false;
        }

        return isDOBValid;
    });

    $.validator.addMethod("validHoroDOB", function (value) {
        var minAge = 16,
            dobDay = moment(value).date(),
            dobMonth = moment(value).month() + 1, //Months are zero indexed, so January is month 0
            dobYear = moment(value).year();

        if (OA.utils.device.Android()) {
            var dobarray = new Array();
            dobarray = value.split('/');
            dobMonth  = dobarray[0];
            dobDay = dobarray[1];
            dobYear = dobarray[2];
            value = dobYear + '/' + dobMonth + '/' + dobDay;
        }
        var myDate = new Date();
        myDate.setFullYear(dobYear, dobMonth - 1, dobDay);

        var setDate = new Date();
        setDate.setFullYear(setDate.getFullYear() - minAge);

        return (OA.validator.methods.validateDate(value) && dobYear > 1900 && (setDate - myDate) >= 0);
    });

    $.validator.addMethod("validExpirationDate", function (value, element, params) {
        if (!params)
            return true;

        if (value === '')
            return false;

        var expDate = new Date(value);
        var now = new Date();
        return (expDate > now);
    });

    $.validator.addMethod("validCVV", function (value, element, cardNumberSelector) {
        var cardNumber = $(cardNumberSelector).val();
        if (!cardNumber)
            return false;

        var cvv = value;
        if (!$.isNumeric(cvv))
            return false;
        var firstDigit = cardNumber.charAt(0);
        // visa master, card, and discover
        if ((firstDigit == '4' || firstDigit == '5' || cardNumber.substring(0, 4) == '6011') && cvv.length != 3) {
            return false;
        }
        // am exp
        if (firstDigit == '3' && cvv.length != 4)
            return false;
        return true;
    });

    $.validator.addMethod("validCallbackNumber", function (value, element, CountrySelector) {
        var countryCode = $(CountrySelector).val();
        var isValid = true;
        if (countryCode == "USA" || countryCode == "CAN") {
            var phonenovalidation = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
            if (!value.match(phonenovalidation)) {
                isValid = false;
            }
        }
        return isValid;
    });

    OA.validator = OA.validator || {};
    OA.validator.initialize = function (formSelector, errorContainerSelector, rules, messages) {
        var $frm = $(formSelector),
            validator = $frm.validate({
                rules: rules,
                messages: messages,
                showErrors: function (errorMap, errorList) {
                    OA.validator.methods.showValidatorErrors(this, errorList);
                }
            });

        validator.$errorContainerSelector = errorContainerSelector;
        $frm.find('input, select').on('focus', function (e) {
            OA.validator.methods.showSelFieldError(validator, $(e.target));
        }).on('blur', function (e) {
            var $fld = validator.$selField, $lbl;
            if ($fld && $fld.length)
                OA.utils.tooltips.hideTooltip(findFieldLabel($fld));
        });

        return validator;
    }

    function findFieldLabel($fld) {
        var $lbl, fid = $fld.attr("id");
        $lbl = $("#lbl_" + fid);
        if (!$lbl.length)
            $lbl = $('label[for=' + fid + ']:not(.error)');
        return $lbl;
    }

    function showValidatorErrors(validator, errorList) {
        var el, elHasErrors, $el, $row, i, j,
            curElLen = validator.currentElements.length,
            errLstLen = errorList.length;

        for (i = 0; i < curElLen; i++) {
            el = validator.currentElements[i];
            $el = $(el);
            if ($el.hasClass('combofld'))
                continue;

            $row = $el.closest('.row');
            elHasErrors = false;
            for (j = 0; j < errLstLen; j++) {
                if (el === errorList[j].element) {
                    elHasErrors = true;
                    break;
                }
            }

            if (elHasErrors) {
                $el.removeClass('pass').addClass('error');
                $row.removeClass('pass').addClass('error');
            }
            else {
                $el.removeClass('error').addClass('pass');
                $row.removeClass('error').addClass('pass');
                $el.next('label.error').empty();
            }
        }

        validator.defaultShowErrors();
        showSelFieldError(validator);
    }
    $.validator.addMethod("letterswithbasicpunc", function (value, element) {
        return this.optional(element) || /^[a-z\-.,()'"\s]+$/i.test(value);
    }, "Letters or punctuation only please");

    $.validator.addMethod("validNonPrimaryMobileNumber", function (value, element, phoneTypeSelector) {
        var isValid = true;
        var phoneType = $(phoneTypeSelector).val();
        if (phoneType == "2") {
            if (value != null && value != "") {
                var phonenovalidation = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
                if (!value.match(phonenovalidation)) {
                    isValid = false;
                }
            }
        }
        return isValid;
    });

/**
* Return true if the field value matches the given format RegExp
*
* @example $.validator.methods.pattern("AR1004",element,/^AR\d{4}$/)
* @result true
*
* @example $.validator.methods.pattern("BR1004",element,/^AR\d{4}$/)
* @result false
*
* @name $.validator.methods.pattern
* @type Boolean
* @cat Plugins/Validate/Methods
*/
    $.validator.addMethod("pattern", function (value, element, param) {
        if (this.optional(element)) {
            return true;
        }
        if (typeof param === "string") {
            param = new RegExp("^(?:" + param + ")$");
        }
        return param.test(value);
    }, "Invalid format.");

})();;
/**
 * bxSlider v4.2.12
 * Copyright 2013-2015 Steven Wanderski
 * Written while drinking Belgian ales and listening to jazz
 * Licensed under MIT (http://opensource.org/licenses/MIT)
 */
!function(t){var e={mode:"horizontal",slideSelector:"",infiniteLoop:!0,hideControlOnEnd:!1,speed:500,easing:null,slideMargin:0,startSlide:0,randomStart:!1,captions:!1,ticker:!1,tickerHover:!1,adaptiveHeight:!1,adaptiveHeightSpeed:500,video:!1,useCSS:!0,preloadImages:"visible",responsive:!0,slideZIndex:50,wrapperClass:"bx-wrapper",touchEnabled:!0,swipeThreshold:50,oneToOneTouch:!0,preventDefaultSwipeX:!0,preventDefaultSwipeY:!1,ariaLive:!0,ariaHidden:!0,keyboardEnabled:!1,pager:!0,pagerType:"full",pagerShortSeparator:" / ",pagerSelector:null,buildPager:null,pagerCustom:null,controls:!0,nextText:"Next",prevText:"Prev",nextSelector:null,prevSelector:null,autoControls:!1,startText:"Start",stopText:"Stop",autoControlsCombine:!1,autoControlsSelector:null,auto:!1,pause:4e3,autoStart:!0,autoDirection:"next",stopAutoOnClick:!1,autoHover:!1,autoDelay:0,autoSlideForOnePage:!1,minSlides:1,maxSlides:1,moveSlides:0,slideWidth:0,shrinkItems:!1,onSliderLoad:function(){return!0},onSlideBefore:function(){return!0},onSlideAfter:function(){return!0},onSlideNext:function(){return!0},onSlidePrev:function(){return!0},onSliderResize:function(){return!0}};t.fn.bxSlider=function(n){if(0===this.length)return this;if(this.length>1)return this.each(function(){t(this).bxSlider(n)}),this;var s={},o=this,r=t(window).width(),a=t(window).height();if(!t(o).data("bxSlider")){var l=function(){t(o).data("bxSlider")||(s.settings=t.extend({},e,n),s.settings.slideWidth=parseInt(s.settings.slideWidth),s.children=o.children(s.settings.slideSelector),s.children.length<s.settings.minSlides&&(s.settings.minSlides=s.children.length),s.children.length<s.settings.maxSlides&&(s.settings.maxSlides=s.children.length),s.settings.randomStart&&(s.settings.startSlide=Math.floor(Math.random()*s.children.length)),s.active={index:s.settings.startSlide},s.carousel=s.settings.minSlides>1||s.settings.maxSlides>1,s.carousel&&(s.settings.preloadImages="all"),s.minThreshold=s.settings.minSlides*s.settings.slideWidth+(s.settings.minSlides-1)*s.settings.slideMargin,s.maxThreshold=s.settings.maxSlides*s.settings.slideWidth+(s.settings.maxSlides-1)*s.settings.slideMargin,s.working=!1,s.controls={},s.interval=null,s.animProp="vertical"===s.settings.mode?"top":"left",s.usingCSS=s.settings.useCSS&&"fade"!==s.settings.mode&&function(){for(var t=document.createElement("div"),e=["WebkitPerspective","MozPerspective","OPerspective","msPerspective"],i=0;i<e.length;i++)if(void 0!==t.style[e[i]])return s.cssPrefix=e[i].replace("Perspective","").toLowerCase(),s.animProp="-"+s.cssPrefix+"-transform",!0;return!1}(),"vertical"===s.settings.mode&&(s.settings.maxSlides=s.settings.minSlides),o.data("origStyle",o.attr("style")),o.children(s.settings.slideSelector).each(function(){t(this).data("origStyle",t(this).attr("style"))}),d())},d=function(){var e=s.children.eq(s.settings.startSlide);o.wrap('<div class="'+s.settings.wrapperClass+'"><div class="bx-viewport"></div></div>'),s.viewport=o.parent(),s.settings.ariaLive&&!s.settings.ticker&&s.viewport.attr("aria-live","polite"),s.loader=t('<div class="bx-loading" />'),s.viewport.prepend(s.loader),o.css({width:"horizontal"===s.settings.mode?1e3*s.children.length+215+"%":"auto",position:"relative"}),s.usingCSS&&s.settings.easing?o.css("-"+s.cssPrefix+"-transition-timing-function",s.settings.easing):s.settings.easing||(s.settings.easing="swing"),s.viewport.css({width:"100%",overflow:"hidden",position:"relative"}),s.viewport.parent().css({maxWidth:u()}),s.children.css({float:"horizontal"===s.settings.mode?"left":"none",listStyle:"none",position:"relative"}),s.children.css("width",h()),"horizontal"===s.settings.mode&&s.settings.slideMargin>0&&s.children.css("marginRight",s.settings.slideMargin),"vertical"===s.settings.mode&&s.settings.slideMargin>0&&s.children.css("marginBottom",s.settings.slideMargin),"fade"===s.settings.mode&&(s.children.css({position:"absolute",zIndex:0,display:"none"}),s.children.eq(s.settings.startSlide).css({zIndex:s.settings.slideZIndex,display:"block"})),s.controls.el=t('<div class="bx-controls" />'),s.settings.captions&&P(),s.active.last=s.settings.startSlide===f()-1,s.settings.video&&o.fitVids(),("all"===s.settings.preloadImages||s.settings.ticker)&&(e=s.children),s.settings.ticker?s.settings.pager=!1:(s.settings.controls&&C(),s.settings.auto&&s.settings.autoControls&&T(),s.settings.pager&&w(),(s.settings.controls||s.settings.autoControls||s.settings.pager)&&s.viewport.after(s.controls.el)),c(e,g)},c=function(e,i){var n=e.find('img:not([src=""]), iframe').length,s=0;return 0===n?void i():void e.find('img:not([src=""]), iframe').each(function(){t(this).one("load error",function(){++s===n&&i()}).each(function(){this.complete&&t(this).trigger("load")})})},g=function(){if(s.settings.infiniteLoop&&"fade"!==s.settings.mode&&!s.settings.ticker){var e="vertical"===s.settings.mode?s.settings.minSlides:s.settings.maxSlides,i=s.children.slice(0,e).clone(!0).addClass("bx-clone"),n=s.children.slice(-e).clone(!0).addClass("bx-clone");s.settings.ariaHidden&&(i.attr("aria-hidden",!0),n.attr("aria-hidden",!0)),o.append(i).prepend(n)}s.loader.remove(),m(),"vertical"===s.settings.mode&&(s.settings.adaptiveHeight=!0),s.viewport.height(p()),o.redrawSlider(),s.settings.onSliderLoad.call(o,s.active.index),s.initialized=!0,s.settings.responsive&&t(window).bind("resize",Z),s.settings.auto&&s.settings.autoStart&&(f()>1||s.settings.autoSlideForOnePage)&&H(),s.settings.ticker&&W(),s.settings.pager&&I(s.settings.startSlide),s.settings.controls&&D(),s.settings.touchEnabled&&!s.settings.ticker&&N(),s.settings.keyboardEnabled&&!s.settings.ticker&&t(document).keydown(F)},p=function(){var e=0,n=t();if("vertical"===s.settings.mode||s.settings.adaptiveHeight)if(s.carousel){var o=1===s.settings.moveSlides?s.active.index:s.active.index*x();for(n=s.children.eq(o),i=1;i<=s.settings.maxSlides-1;i++)n=o+i>=s.children.length?n.add(s.children.eq(i-1)):n.add(s.children.eq(o+i))}else n=s.children.eq(s.active.index);else n=s.children;return"vertical"===s.settings.mode?(n.each(function(i){e+=t(this).outerHeight()}),s.settings.slideMargin>0&&(e+=s.settings.slideMargin*(s.settings.minSlides-1))):e=Math.max.apply(Math,n.map(function(){return t(this).outerHeight(!1)}).get()),"border-box"===s.viewport.css("box-sizing")?e+=parseFloat(s.viewport.css("padding-top"))+parseFloat(s.viewport.css("padding-bottom"))+parseFloat(s.viewport.css("border-top-width"))+parseFloat(s.viewport.css("border-bottom-width")):"padding-box"===s.viewport.css("box-sizing")&&(e+=parseFloat(s.viewport.css("padding-top"))+parseFloat(s.viewport.css("padding-bottom"))),e},u=function(){var t="100%";return s.settings.slideWidth>0&&(t="horizontal"===s.settings.mode?s.settings.maxSlides*s.settings.slideWidth+(s.settings.maxSlides-1)*s.settings.slideMargin:s.settings.slideWidth),t},h=function(){var t=s.settings.slideWidth,e=s.viewport.width();if(0===s.settings.slideWidth||s.settings.slideWidth>e&&!s.carousel||"vertical"===s.settings.mode)t=e;else if(s.settings.maxSlides>1&&"horizontal"===s.settings.mode){if(e>s.maxThreshold)return t;e<s.minThreshold?t=(e-s.settings.slideMargin*(s.settings.minSlides-1))/s.settings.minSlides:s.settings.shrinkItems&&(t=Math.floor((e+s.settings.slideMargin)/Math.ceil((e+s.settings.slideMargin)/(t+s.settings.slideMargin))-s.settings.slideMargin))}return t},v=function(){var t=1,e=null;return"horizontal"===s.settings.mode&&s.settings.slideWidth>0?s.viewport.width()<s.minThreshold?t=s.settings.minSlides:s.viewport.width()>s.maxThreshold?t=s.settings.maxSlides:(e=s.children.first().width()+s.settings.slideMargin,t=Math.floor((s.viewport.width()+s.settings.slideMargin)/e)):"vertical"===s.settings.mode&&(t=s.settings.minSlides),t},f=function(){var t=0,e=0,i=0;if(s.settings.moveSlides>0)if(s.settings.infiniteLoop)t=Math.ceil(s.children.length/x());else for(;e<s.children.length;)++t,e=i+v(),i+=s.settings.moveSlides<=v()?s.settings.moveSlides:v();else t=Math.ceil(s.children.length/v());return t},x=function(){return s.settings.moveSlides>0&&s.settings.moveSlides<=v()?s.settings.moveSlides:v()},m=function(){var t,e,i;s.children.length>s.settings.maxSlides&&s.active.last&&!s.settings.infiniteLoop?"horizontal"===s.settings.mode?(e=s.children.last(),t=e.position(),S(-(t.left-(s.viewport.width()-e.outerWidth())),"reset",0)):"vertical"===s.settings.mode&&(i=s.children.length-s.settings.minSlides,t=s.children.eq(i).position(),S(-t.top,"reset",0)):(t=s.children.eq(s.active.index*x()).position(),s.active.index===f()-1&&(s.active.last=!0),void 0!==t&&("horizontal"===s.settings.mode?S(-t.left,"reset",0):"vertical"===s.settings.mode&&S(-t.top,"reset",0)))},S=function(e,i,n,r){var a,l;s.usingCSS?(l="vertical"===s.settings.mode?"translate3d(0, "+e+"px, 0)":"translate3d("+e+"px, 0, 0)",o.css("-"+s.cssPrefix+"-transition-duration",n/1e3+"s"),"slide"===i?(o.css(s.animProp,l),0!==n?o.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(e){t(e.target).is(o)&&(o.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),q())}):q()):"reset"===i?o.css(s.animProp,l):"ticker"===i&&(o.css("-"+s.cssPrefix+"-transition-timing-function","linear"),o.css(s.animProp,l),0!==n?o.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(e){t(e.target).is(o)&&(o.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),S(r.resetValue,"reset",0),L())}):(S(r.resetValue,"reset",0),L()))):(a={},a[s.animProp]=e,"slide"===i?o.animate(a,n,s.settings.easing,function(){q()}):"reset"===i?o.css(s.animProp,e):"ticker"===i&&o.animate(a,n,"linear",function(){S(r.resetValue,"reset",0),L()}))},b=function(){for(var e="",i="",n=f(),o=0;o<n;o++)i="",s.settings.buildPager&&t.isFunction(s.settings.buildPager)||s.settings.pagerCustom?(i=s.settings.buildPager(o),s.pagerEl.addClass("bx-custom-pager")):(i=o+1,s.pagerEl.addClass("bx-default-pager")),e+='<div class="bx-pager-item"><a href="" data-slide-index="'+o+'" class="bx-pager-link">'+i+"</a></div>";s.pagerEl.html(e)},w=function(){s.settings.pagerCustom?s.pagerEl=t(s.settings.pagerCustom):(s.pagerEl=t('<div class="bx-pager" />'),s.settings.pagerSelector?t(s.settings.pagerSelector).html(s.pagerEl):s.controls.el.addClass("bx-has-pager").append(s.pagerEl),b()),s.pagerEl.on("click touchend","a",z)},C=function(){s.controls.next=t('<a class="bx-next" href="">'+s.settings.nextText+"</a>"),s.controls.prev=t('<a class="bx-prev" href="">'+s.settings.prevText+"</a>"),s.controls.next.bind("click touchend",E),s.controls.prev.bind("click touchend",k),s.settings.nextSelector&&t(s.settings.nextSelector).append(s.controls.next),s.settings.prevSelector&&t(s.settings.prevSelector).append(s.controls.prev),s.settings.nextSelector||s.settings.prevSelector||(s.controls.directionEl=t('<div class="bx-controls-direction" />'),s.controls.directionEl.append(s.controls.prev).append(s.controls.next),s.controls.el.addClass("bx-has-controls-direction").append(s.controls.directionEl))},T=function(){s.controls.start=t('<div class="bx-controls-auto-item"><a class="bx-start" href="">'+s.settings.startText+"</a></div>"),s.controls.stop=t('<div class="bx-controls-auto-item"><a class="bx-stop" href="">'+s.settings.stopText+"</a></div>"),s.controls.autoEl=t('<div class="bx-controls-auto" />'),s.controls.autoEl.on("click",".bx-start",M),s.controls.autoEl.on("click",".bx-stop",y),s.settings.autoControlsCombine?s.controls.autoEl.append(s.controls.start):s.controls.autoEl.append(s.controls.start).append(s.controls.stop),s.settings.autoControlsSelector?t(s.settings.autoControlsSelector).html(s.controls.autoEl):s.controls.el.addClass("bx-has-controls-auto").append(s.controls.autoEl),A(s.settings.autoStart?"stop":"start")},P=function(){s.children.each(function(e){var i=t(this).find("img:first").attr("title");void 0!==i&&(""+i).length&&t(this).append('<div class="bx-caption"><span>'+i+"</span></div>")})},E=function(t){t.preventDefault(),s.controls.el.hasClass("disabled")||(s.settings.auto&&s.settings.stopAutoOnClick&&o.stopAuto(),o.goToNextSlide())},k=function(t){t.preventDefault(),s.controls.el.hasClass("disabled")||(s.settings.auto&&s.settings.stopAutoOnClick&&o.stopAuto(),o.goToPrevSlide())},M=function(t){o.startAuto(),t.preventDefault()},y=function(t){o.stopAuto(),t.preventDefault()},z=function(e){var i,n;e.preventDefault(),s.controls.el.hasClass("disabled")||(s.settings.auto&&s.settings.stopAutoOnClick&&o.stopAuto(),i=t(e.currentTarget),void 0!==i.attr("data-slide-index")&&(n=parseInt(i.attr("data-slide-index")),n!==s.active.index&&o.goToSlide(n)))},I=function(e){var i=s.children.length;return"short"===s.settings.pagerType?(s.settings.maxSlides>1&&(i=Math.ceil(s.children.length/s.settings.maxSlides)),void s.pagerEl.html(e+1+s.settings.pagerShortSeparator+i)):(s.pagerEl.find("a").removeClass("active"),void s.pagerEl.each(function(i,n){t(n).find("a").eq(e).addClass("active")}))},q=function(){if(s.settings.infiniteLoop){var t="";0===s.active.index?t=s.children.eq(0).position():s.active.index===f()-1&&s.carousel?t=s.children.eq((f()-1)*x()).position():s.active.index===s.children.length-1&&(t=s.children.eq(s.children.length-1).position()),t&&("horizontal"===s.settings.mode?S(-t.left,"reset",0):"vertical"===s.settings.mode&&S(-t.top,"reset",0))}s.working=!1,s.settings.onSlideAfter.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index)},A=function(t){s.settings.autoControlsCombine?s.controls.autoEl.html(s.controls[t]):(s.controls.autoEl.find("a").removeClass("active"),s.controls.autoEl.find("a:not(.bx-"+t+")").addClass("active"))},D=function(){1===f()?(s.controls.prev.addClass("disabled"),s.controls.next.addClass("disabled")):!s.settings.infiniteLoop&&s.settings.hideControlOnEnd&&(0===s.active.index?(s.controls.prev.addClass("disabled"),s.controls.next.removeClass("disabled")):s.active.index===f()-1?(s.controls.next.addClass("disabled"),s.controls.prev.removeClass("disabled")):(s.controls.prev.removeClass("disabled"),s.controls.next.removeClass("disabled")))},H=function(){if(s.settings.autoDelay>0){setTimeout(o.startAuto,s.settings.autoDelay)}else o.startAuto(),t(window).focus(function(){o.startAuto()}).blur(function(){o.stopAuto()});s.settings.autoHover&&o.hover(function(){s.interval&&(o.stopAuto(!0),s.autoPaused=!0)},function(){s.autoPaused&&(o.startAuto(!0),s.autoPaused=null)})},W=function(){var e,i,n,r,a,l,d,c,g=0;"next"===s.settings.autoDirection?o.append(s.children.clone().addClass("bx-clone")):(o.prepend(s.children.clone().addClass("bx-clone")),e=s.children.first().position(),g="horizontal"===s.settings.mode?-e.left:-e.top),S(g,"reset",0),s.settings.pager=!1,s.settings.controls=!1,s.settings.autoControls=!1,s.settings.tickerHover&&(s.usingCSS?(r="horizontal"===s.settings.mode?4:5,s.viewport.hover(function(){i=o.css("-"+s.cssPrefix+"-transform"),n=parseFloat(i.split(",")[r]),S(n,"reset",0)},function(){c=0,s.children.each(function(e){c+="horizontal"===s.settings.mode?t(this).outerWidth(!0):t(this).outerHeight(!0)}),a=s.settings.speed/c,l="horizontal"===s.settings.mode?"left":"top",d=a*(c-Math.abs(parseInt(n))),L(d)})):s.viewport.hover(function(){o.stop()},function(){c=0,s.children.each(function(e){c+="horizontal"===s.settings.mode?t(this).outerWidth(!0):t(this).outerHeight(!0)}),a=s.settings.speed/c,l="horizontal"===s.settings.mode?"left":"top",d=a*(c-Math.abs(parseInt(o.css(l)))),L(d)})),L()},L=function(t){var e,i,n,r=t?t:s.settings.speed,a={left:0,top:0},l={left:0,top:0};"next"===s.settings.autoDirection?a=o.find(".bx-clone").first().position():l=s.children.first().position(),e="horizontal"===s.settings.mode?-a.left:-a.top,i="horizontal"===s.settings.mode?-l.left:-l.top,n={resetValue:i},S(e,"ticker",r,n)},O=function(e){var i=t(window),n={top:i.scrollTop(),left:i.scrollLeft()},s=e.offset();return n.right=n.left+i.width(),n.bottom=n.top+i.height(),s.right=s.left+e.outerWidth(),s.bottom=s.top+e.outerHeight(),!(n.right<s.left||n.left>s.right||n.bottom<s.top||n.top>s.bottom)},F=function(t){var e=document.activeElement.tagName.toLowerCase(),i="input|textarea",n=new RegExp(e,["i"]),s=n.exec(i);if(null==s&&O(o)){if(39===t.keyCode)return E(t),!1;if(37===t.keyCode)return k(t),!1}},N=function(){s.touch={start:{x:0,y:0},end:{x:0,y:0}},s.viewport.bind("touchstart MSPointerDown pointerdown",X),s.viewport.on("click",".bxslider a",function(t){s.viewport.hasClass("click-disabled")&&(t.preventDefault(),s.viewport.removeClass("click-disabled"))})},X=function(t){if(s.controls.el.addClass("disabled"),s.working)t.preventDefault(),s.controls.el.removeClass("disabled");else{s.touch.originalPos=o.position();var e=t.originalEvent,i="undefined"!=typeof e.changedTouches?e.changedTouches:[e];s.touch.start.x=i[0].pageX,s.touch.start.y=i[0].pageY,s.viewport.get(0).setPointerCapture&&(s.pointerId=e.pointerId,s.viewport.get(0).setPointerCapture(s.pointerId)),s.viewport.bind("touchmove MSPointerMove pointermove",V),s.viewport.bind("touchend MSPointerUp pointerup",R),s.viewport.bind("MSPointerCancel pointercancel",Y)}},Y=function(t){S(s.touch.originalPos.left,"reset",0),s.controls.el.removeClass("disabled"),s.viewport.unbind("MSPointerCancel pointercancel",Y),s.viewport.unbind("touchmove MSPointerMove pointermove",V),s.viewport.unbind("touchend MSPointerUp pointerup",R),s.viewport.get(0).releasePointerCapture&&s.viewport.get(0).releasePointerCapture(s.pointerId)},V=function(t){var e=t.originalEvent,i="undefined"!=typeof e.changedTouches?e.changedTouches:[e],n=Math.abs(i[0].pageX-s.touch.start.x),o=Math.abs(i[0].pageY-s.touch.start.y),r=0,a=0;3*n>o&&s.settings.preventDefaultSwipeX?t.preventDefault():3*o>n&&s.settings.preventDefaultSwipeY&&t.preventDefault(),"fade"!==s.settings.mode&&s.settings.oneToOneTouch&&("horizontal"===s.settings.mode?(a=i[0].pageX-s.touch.start.x,r=s.touch.originalPos.left+a):(a=i[0].pageY-s.touch.start.y,r=s.touch.originalPos.top+a),S(r,"reset",0))},R=function(t){s.viewport.unbind("touchmove MSPointerMove pointermove",V),s.controls.el.removeClass("disabled");var e=t.originalEvent,i="undefined"!=typeof e.changedTouches?e.changedTouches:[e],n=0,r=0;s.touch.end.x=i[0].pageX,s.touch.end.y=i[0].pageY,"fade"===s.settings.mode?(r=Math.abs(s.touch.start.x-s.touch.end.x),r>=s.settings.swipeThreshold&&(s.touch.start.x>s.touch.end.x?o.goToNextSlide():o.goToPrevSlide(),o.stopAuto())):("horizontal"===s.settings.mode?(r=s.touch.end.x-s.touch.start.x,n=s.touch.originalPos.left):(r=s.touch.end.y-s.touch.start.y,n=s.touch.originalPos.top),!s.settings.infiniteLoop&&(0===s.active.index&&r>0||s.active.last&&r<0)?S(n,"reset",200):Math.abs(r)>=s.settings.swipeThreshold?(r<0?o.goToNextSlide():o.goToPrevSlide(),o.stopAuto()):S(n,"reset",200)),s.viewport.unbind("touchend MSPointerUp pointerup",R),s.viewport.get(0).releasePointerCapture&&s.viewport.get(0).releasePointerCapture(s.pointerId)},Z=function(e){if(s.initialized)if(s.working)window.setTimeout(Z,10);else{var i=t(window).width(),n=t(window).height();r===i&&a===n||(r=i,a=n,o.redrawSlider(),s.settings.onSliderResize.call(o,s.active.index))}},B=function(t){var e=v();s.settings.ariaHidden&&!s.settings.ticker&&(s.children.attr("aria-hidden","true"),s.children.slice(t,t+e).attr("aria-hidden","false"))},U=function(t){return t<0?s.settings.infiniteLoop?f()-1:s.active.index:t>=f()?s.settings.infiniteLoop?0:s.active.index:t};return o.goToSlide=function(e,i){var n,r,a,l,d=!0,c=0,g={left:0,top:0},u=null;if(s.oldIndex=s.active.index,s.active.index=U(e),!s.working&&s.active.index!==s.oldIndex){if(s.working=!0,d=s.settings.onSlideBefore.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index),"undefined"!=typeof d&&!d)return s.active.index=s.oldIndex,void(s.working=!1);"next"===i?s.settings.onSlideNext.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index)||(d=!1):"prev"===i&&(s.settings.onSlidePrev.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index)||(d=!1)),s.active.last=s.active.index>=f()-1,(s.settings.pager||s.settings.pagerCustom)&&I(s.active.index),s.settings.controls&&D(),"fade"===s.settings.mode?(s.settings.adaptiveHeight&&s.viewport.height()!==p()&&s.viewport.animate({height:p()},s.settings.adaptiveHeightSpeed),s.children.filter(":visible").fadeOut(s.settings.speed).css({zIndex:0}),s.children.eq(s.active.index).css("zIndex",s.settings.slideZIndex+1).fadeIn(s.settings.speed,function(){t(this).css("zIndex",s.settings.slideZIndex),q()})):(s.settings.adaptiveHeight&&s.viewport.height()!==p()&&s.viewport.animate({height:p()},s.settings.adaptiveHeightSpeed),!s.settings.infiniteLoop&&s.carousel&&s.active.last?"horizontal"===s.settings.mode?(u=s.children.eq(s.children.length-1),g=u.position(),c=s.viewport.width()-u.outerWidth()):(n=s.children.length-s.settings.minSlides,g=s.children.eq(n).position()):s.carousel&&s.active.last&&"prev"===i?(r=1===s.settings.moveSlides?s.settings.maxSlides-x():(f()-1)*x()-(s.children.length-s.settings.maxSlides),u=o.children(".bx-clone").eq(r),g=u.position()):"next"===i&&0===s.active.index?(g=o.find("> .bx-clone").eq(s.settings.maxSlides).position(),s.active.last=!1):e>=0&&(l=e*parseInt(x()),g=s.children.eq(l).position()),"undefined"!=typeof g?(a="horizontal"===s.settings.mode?-(g.left-c):-g.top,S(a,"slide",s.settings.speed)):s.working=!1),s.settings.ariaHidden&&B(s.active.index*x())}},o.goToNextSlide=function(){if(s.settings.infiniteLoop||!s.active.last){var t=parseInt(s.active.index)+1;o.goToSlide(t,"next")}},o.goToPrevSlide=function(){if(s.settings.infiniteLoop||0!==s.active.index){var t=parseInt(s.active.index)-1;o.goToSlide(t,"prev")}},o.startAuto=function(t){s.interval||(s.interval=setInterval(function(){"next"===s.settings.autoDirection?o.goToNextSlide():o.goToPrevSlide()},s.settings.pause),s.settings.autoControls&&t!==!0&&A("stop"))},o.stopAuto=function(t){s.interval&&(clearInterval(s.interval),s.interval=null,s.settings.autoControls&&t!==!0&&A("start"))},o.getCurrentSlide=function(){return s.active.index},o.getCurrentSlideElement=function(){return s.children.eq(s.active.index)},o.getSlideElement=function(t){return s.children.eq(t)},o.getSlideCount=function(){return s.children.length},o.isWorking=function(){return s.working},o.redrawSlider=function(){s.children.add(o.find(".bx-clone")).outerWidth(h()),s.viewport.css("height",p()),s.settings.ticker||m(),s.active.last&&(s.active.index=f()-1),s.active.index>=f()&&(s.active.last=!0),s.settings.pager&&!s.settings.pagerCustom&&(b(),I(s.active.index)),s.settings.ariaHidden&&B(s.active.index*x())},o.destroySlider=function(){s.initialized&&(s.initialized=!1,t(".bx-clone",this).remove(),s.children.each(function(){void 0!==t(this).data("origStyle")?t(this).attr("style",t(this).data("origStyle")):t(this).removeAttr("style")}),void 0!==t(this).data("origStyle")?this.attr("style",t(this).data("origStyle")):t(this).removeAttr("style"),t(this).unwrap().unwrap(),s.controls.el&&s.controls.el.remove(),s.controls.next&&s.controls.next.remove(),s.controls.prev&&s.controls.prev.remove(),s.pagerEl&&s.settings.controls&&!s.settings.pagerCustom&&s.pagerEl.remove(),t(".bx-caption",this).remove(),s.controls.autoEl&&s.controls.autoEl.remove(),clearInterval(s.interval),s.settings.responsive&&t(window).unbind("resize",Z),s.settings.keyboardEnabled&&t(document).unbind("keydown",F),t(this).removeData("bxSlider"))},o.reloadSlider=function(e){void 0!==e&&(n=e),o.destroySlider(),l(),t(o).data("bxSlider",this)},l(),t(o).data("bxSlider",this),this}}}(jQuery);;
(function () {
    'use strict';
    OA.index = {
        visitorType: "NC",
        removedPsychicsQueue: [],
        lastSizeJump: "",
        mobileResolution: OAApp.appsettings.MobileResolution,
        ecBannerSlider: null,
        bLazy: null,
        initialize: function () {
            OA.index.visitorType = $("#VisitorType").val();

            OA.index.resizeWindow("PageLoad");
            OA.index.wireBannerSlider();

            $(".view-all-package-offer").click(function () {
                window.location.href = "/buy-package";
                return;
            });
            $(".redeem-promo").click(function () {
                window.location.href = "/buy-package";
                return;
            });

            $(".horoscope-readmore").click(function () {               
                window.location.href = "horoscope/" + $(this).attr("data-sign").toLowerCase() + "-daily-horoscope/";
            });

            $("#btnQuestion").click(function () {
                OA.index.askQuestion();
            });

            $(".ec-offer").click(function (event) {
                OA.index.ecOfferClickHandler(event);
            });

            //window.setTimeout(function () {
            //    //optimove event
            //    if (typeof (optimoveSDK) != 'undefined') {
            //        var params = {};
            //        params['event_type'] = 'page_load';
            //        params['device'] = OA.utils.windowHelpers.deviceType();
            //        optimoveSDK.API.reportEvent('homepage_popup', params);
            //    }
            //}, 2000);

            $(function () {
                var RecaptchaSitekey = OAApp.appsettings.RecaptchaSitekey;
                $('#myRecaptchaSitekey').attr('data-sitekey', RecaptchaSitekey);
                $('.recapchasigninmobile').css('-webkit-transform', 'scale(0.77)');

                // Initialize
                self.bLazy = new Blazy({
                    selector: 'img, .b-lazy' // all images
                });

                $("a[target='_blank']").attr("rel", "noopener");
            });

            OA.index.setGAData();
        },
        setGAData: function () {
            $('#navbar-menu').attr('data-category', 'Header').attr('data-action', 'Menu');
            $('#horoscope-header-logo').attr('data-category', 'Header').attr('data-action', 'Logo');
            $('#horoscope-header-search').attr('data-category', 'Header').attr('data-action', 'Search Icon');
            $('#navbar-phone-number').attr('data-category', 'Header').attr('data-action', 'Call Icon');
            $('#btnhome a').attr('data-category', 'Navigation').attr('data-action', 'Home');
            $('#menu-psychic-list, #menu-psychic-list span').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics');
            $('#all-psychic-list').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics - All Psychics');
            $('#love-relationship-psychic-list').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics - Love Relationship');
            $('#tarot-readings-psychic-list').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics - Tarot Readings');
            $('#clairvoyants-psychic-list').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics - Clairvoyants');
            $('#mediums-psychic-list').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics - Mediums');
            $('#empaths-psychic-list').attr('data-category', 'Navigation').attr('data-action', 'Our Psychics - Empaths');
            $('#menu-horoscope-list, #menu-horoscope-list span').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes');
            $('#daily-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Daily');
            $('#weekend-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Weekend');
            $('#weekly-love-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Weekly');
            $('#monthly-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Monthly');
            $('#monthly-money-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Money');
            $('#yearly-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Yearly');
            $('#birthday-horoscope').attr('data-category', 'Navigation').attr('data-action', 'Horoscopes - Birthday');
            $('#menu-blog').attr('data-category', 'Navigation').attr('data-action', 'Blog');
            $('#menu-about-us, #menu-about-us span').attr('data-category', 'Navigation').attr('data-action', 'How It Works');
            $('#a-how-it-works').attr('data-category', 'Navigation').attr('data-action', 'How It Works - Psychic Phone Readings');
            $('#a-why-california-psychics').attr('data-category', 'Navigation').attr('data-action', 'How It Works - Why California Psychics');
            $('#a-how-we-help').attr('data-category', 'Navigation').attr('data-action', 'How It Works - How We Help');
            $('#a-most-gifted-psychics').attr('data-category', 'Navigation').attr('data-action', 'How It Works - Most Gifted Psychics');
            $('#a-pricing').attr('data-category', 'Navigation').attr('data-action', 'How It Works - Pricing');
            $('#a-about-california-psychics').attr('data-category', 'Navigation').attr('data-action', 'How It Works - About Us');
            $('#a-how-to-articles').attr('data-category', 'Navigation').attr('data-action', 'How It Works - Tips How - To Articles');
            $('#menu-support').attr('data-category', 'Navigation').attr('data-action', 'Support');
            $('#sidebar-auth-btn').attr('data-category', 'Navigation').attr('data-action', 'Sign In');
        },
        resizeWindow: function (callFrom) {
            if (window.innerWidth > OA.index.mobileResolution) {
                if (OA.index.lastSizeJump == "mobile" || OA.index.lastSizeJump == "") {
                    OA.index.lastSizeJump = "desktop";
                    OA.index.setDesktop(callFrom);
                }
            }
            else {
                if (OA.index.lastSizeJump == "desktop" || OA.index.lastSizeJump == "") {
                    OA.index.lastSizeJump = "mobile";
                    OA.index.setMobile(callFrom);
                }
            }
        },
        setDesktop: function (callFrom) {
            var auth = OA.cookie.ManageCookieValue('auth');

            $(".main-banner").each(function () {
                $(this).css("background-image", "url(" + $(this).attr("data-banner-desktop") + ")");
                $(this).click(function () {
                    window.location.href = $(this).attr("data-bannerurl-desktop");
                });
            });

            if (OA.index.visitorType == "NC") {
                $(".meet-psychic-text").html("MEET OUR TRUSTED PSYCHICS");
                $(".why-california-heading").html("WHY CALIFORNIA PSYCHICS?");
                $(".daily-horoscope-heading").html("YOUR DAILY HOROSCOPE");
                $(".our-packages-main .popular-package-heading .row-1").html("OUR MOST POPULAR PACKAGES");
            } else if (OA.index.visitorType == "EC") {
                $(".meet-psychic-text").html("YOUR PSYCHICS");
                $(".why-california-heading").html("WHY CALIFORNIA PSYCHICS?");
                $(".daily-horoscope-heading").html("YOUR DAILY HOROSCOPE");
                $(".our-packages-main .popular-package-heading .row-1").html("YOUR SPECIALS");
            }

            //Psychic List
            $('.condenseView').find('.row').css('height', 'auto');
            $('.condenseView').css('height', 'auto');
            $('.sortByRightSection').show();
            $('.selectValue').show();
            $('.selectValueArrow').show();
            $(".right-panel").css("display", "none");

            if (OA.index.removedPsychicsQueue.length > 0) {
                while (OA.index.removedPsychicsQueue.length > 0) {
                    var li = OA.index.removedPsychicsQueue.shift();
                    $("#psychic-list-ul").append(li);
                }
            }
            if (callFrom != "PageLoad") {
                if (auth != "" && auth != undefined) {
                    if ($("#ECBannerCount").val() == 0) {
                        OA.index.bindECDefaultBanner(callFrom);
                    }
                    else if ($("#ECBannerCount").val() > 0) {
                        OA.index.bindECDynamicBanner(callFrom);
                    }
                }
                else {
                    if ($("#NCBannerCount").val() == 0) {
                        OA.index.bindNCDefaultBanner(callFrom);
                    }
                    else if ($("#NCBannerCount").val() > 0) {
                        OA.index.bindNCBanners(callFrom);
                    }
                }
            }
        },
        setMobile: function (callFrom) {
            var auth = OA.cookie.ManageCookieValue('auth');

            $(".main-banner").each(function () {
                $(this).css("background-image", "url(" + $(this).attr("data-banner-mobile") + ")");
                $(this).click(function () {
                    window.location.href = $(this).attr("data-bannerurl-mobile");
                });
            });

            if (OA.index.visitorType == "NC") {
                $(".meet-psychic-text").html("MEET OUR PSYCHICS");
                $(".why-california-heading").html("WHY CHOOSE US?");
                $(".daily-horoscope-heading").html("DAILY HOROSCOPE");
                $(".our-packages-main .popular-package-heading .row-1").html("POPULAR PACKAGES");
            } else if (OA.index.visitorType == "EC") {
                $(".meet-psychic-text").html("YOUR PSYCHICS");
                $(".why-california-heading").html("WHY CHOOSE US?");
                $(".daily-horoscope-heading").html("DAILY HOROSCOPE");
                $(".our-packages-main .popular-package-heading .row-1").html("YOUR SPECIALS");
            }

            //Psychic List
            $('.selectValueArrow').hide();
            $('.selectValue').hide();
            if (OA.index.removedPsychicsQueue.length == 0) {
                $(".psychics-li").each(function (idx, li) {
                    if (idx > 2) {
                        if (li != null) {
                            $("#" + $(li).attr("id")).remove();
                            OA.index.removedPsychicsQueue.push(li);
                        }
                    }
                });
            }
            if (callFrom != "PageLoad") {
                if (auth != "" && auth != undefined) {
                    if ($("#ECBannerCount").val() == 0) {
                        OA.index.bindECDefaultBanner(callFrom);
                    } else if ($("#ECBannerCount").val() > 0) {
                        OA.index.bindECDynamicBanner(callFrom);
                    }
                }
                else {
                    if ($("#NCBannerCount").val() == 0) {
                        OA.index.bindNCDefaultBanner(callFrom);
                    }
                    else if ($("#NCBannerCount").val() > 0) {
                        OA.index.bindNCBanners(callFrom);
                    }
                }
            }
        },
        wireBannerSlider: function () {
            var auth = OA.cookie.ManageCookieValue('auth');
            if (!auth && !OA.auth.isECCookied()) {
                $(".ui-content-margin").addClass("nc-homepage-content-margin");
                if ($("#NCBannerCount").val() == 0) {
                    OA.index.bindNCDefaultBanner("PageLoad");
                }
                else if ($("#NCBannerCount").val() > 0) {
                    OA.index.bindNCBanners("PageLoad");
                }
            }
            else {
                $(".ui-content-margin").removeClass("nc-homepage-content-margin");
                if ($("#ECBannerCount").val() == 0) {
                    OA.index.bindECDefaultBanner("PageLoad");
                }
                else if ($("#ECBannerCount").val() > 0) {
                    OA.index.bindECDynamicBanner("PageLoad");
                }
            }
        },
        askQuestion: function () {
            $.mobile.loading("show");

            //Remove five free cookie because on talk click always follow the ask flow - TO-4569
            OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");

            var qt = $(".ask-a-text #txtQuestion").val();
            var acctInfo = OA.cookie.ManageCookieValue("askAccountInfo");

            var info;
            if (acctInfo == null) {
                info = {
                    firstName: '',
                    lastName: '',
                    email: '',
                    dob: '',
                    password: '',
                    sendFreeHoroAndNewsLetter: true,
                    offerDuration: '',
                    cardHolderName: '',
                    cardNumber: '',
                    expMonth: '',
                    expYear: '',
                    cvv: '',
                    cardType: '',
                    billingCountry: '',
                    billingCountryName: '',
                    zipCode: '',
                    state: '',
                    stateRegion: '',
                    city: '',
                    address1: '',
                    address2: '',
                    phoneCountry: '',
                    phoneNumber: '',
                    masId: '',
                    custId: '',
                    callbackId: '',
                    extId: '',
                    offerId: '',
                    priceId: '',
                    transactionId: '',
                    transactionAmount: '',
                    statusCode: '',
                    errorMessage: '',
                    subscriptionId: '',
                    package: '',
                    questionText: qt
                };
            }
            else {
                acctInfo.questionText = qt;
                info = acctInfo;
            }
            OA.cookie.ManageCookieValue('askAccountInfo', info);
            $.mobile.loading("hide");

            window.location.href = "../" + OA.paths.askNcCheckout.question;
        },
        bindECSliderEvents: function () {
            if ($("#ECBannerCount").val() > 1) {
                $(".bx-pager").css("display", "block");
            } else {
                $(".bx-pager").css("display", "none");
            }
            $(".bx-wrapper").on("mouseover", function () {
                if ($("#ECBannerCount").val() > 1 && window.innerWidth > OA.index.mobileResolution) {
                    $(".bx-prev").show();
                    $(".bx-next").show();
                }
            });

            $(".bx-wrapper").on("mouseout", function () {
                $(".bx-prev").hide();
                $(".bx-next").hide();
            });

            $(".bx-next").on("click", function () {
                if (window.innerWidth > OA.index.mobileResolution) {
                    OA.index.ecBannerSlider.stopAuto();
                    OA.index.ecBannerSlider.goToNextSlide();
                    OA.index.ecBannerSlider.startAuto();
                }
            });

            $(".bx-prev").on("click", function () {
                if (window.innerWidth > OA.index.mobileResolution) {
                    OA.index.ecBannerSlider.stopAuto();
                    OA.index.ecBannerSlider.goToPrevSlide();
                    OA.index.ecBannerSlider.startAuto();
                }
            });

            $("ul.bxSilderEC li").click(function (event) {
                OA.index.ecBannerClickHandler(event);
            });
        },
        bindNCSliderEvents: function () {
            if ($("#NCBannerCount").val() > 1) {
                $(".bx-pager").css("display", "block");
            } else {
                $(".bx-pager").css("display", "none");
            }
            $(".bx-wrapper").on("mouseover", function () {
                if ($("#NCBannerCount").val() > 1 && window.innerWidth > OA.index.mobileResolution) {
                    $(".bx-prev").show();
                    $(".bx-next").show();
                }
            });

            $(".bx-wrapper").on("mouseout", function () {
                $(".bx-prev").hide();
                $(".bx-next").hide();
            });

            $(".bx-next").on("click", function () {
                if (window.innerWidth > OA.index.mobileResolution) {
                    OA.index.ncBannerSlider.stopAuto();
                    OA.index.ncBannerSlider.goToNextSlide();
                    OA.index.ncBannerSlider.startAuto();
                }
            });

            $(".bx-prev").on("click", function () {
                if (window.innerWidth > OA.index.mobileResolution) {
                    OA.index.ncBannerSlider.stopAuto();
                    OA.index.ncBannerSlider.goToPrevSlide();
                    OA.index.ncBannerSlider.startAuto();
                }
            });

            $("ul.bxSilderNC li").click(function (event) {
                OA.index.ncBannerClickHandler(event);
            });
        },
        bindECDefaultBanner: function (callFrom) {
            var pauseDuration = OAApp.appsettings.pauseDurationDesktop;
            console.log("", OAApp.appsettings.pauseDurationDesktop);
            if (callFrom == "Resize") {
                $(".ec-slider-container").empty().append('<ul class="bxslider bxSilderEC"></ul>').trigger("create");
            }
            $('ul.bxSilderEC li').remove();
            if (window.innerWidth > OA.index.mobileResolution) {
                pauseDuration = OAApp.appsettings.pauseDurationDesktop;
                $('.bxSilderEC').append('<li > <div class="ec-banner-default-desktop-image" ></div></li>');
            }
            else {
                pauseDuration = OAApp.appsettings.pauseDurationMobile;
                $('.bxSilderEC').append('<li data-from="default" ><div class="ec-banner-default-mobile-image" ></div></li>');
            }
            if (OA.index.ecBannerSlider) {
                OA.index.ecBannerSlider.destroySlider();
            }
            OA.index.ecBannerSlider = $('.bxSilderEC').bxSlider({
                auto: true,
                autoControls: true,
                pause: OAApp.appsettings.pauseDurationMobile,
                slideWidth: 1920,
                touchEnabled: false
            });
            $("ul.bxSilderEC li").click(function (event) {
                OA.index.ecBannerClickHandler(event);
            });
            $(".bx-pager").css("display", "none");
        },
        bindECDynamicBanner: function (callFrom) {
            var pauseDuration = OAApp.appsettings.pauseDurationDesktop;
            console.log("", OAApp.appsettings.pauseDurationDesktop);
            if (callFrom == "Resize") {
                $(".ec-slider-container").empty().append('<ul class="bxslider bxSilderEC"></ul>').trigger("create");
            }
            $('ul.bxSilderEC li').remove();

            var offerArray = JSON.parse($("#ECBannerArray").text());
            var bannerCollection = JSON.parse($("#ECBannerCollection").text());

            if (offerArray != null) {
                var offerWithPromoArray = _.filter(offerArray, function (offers) {
                    return offers.PromoCode != "";
                });

                if (offerWithPromoArray.length > 0) {
                    var offerWithOutPromoArray = _.filter(offerArray, function (offers) {
                        return offers.PromoCode == "";
                    });
                    //offerArray = new Array();
                    //offerArray = offerWithPromoArray.concat(offerWithOutPromoArray);
                }

                for (var i = 0; i < offerArray.length; i++) {
                    var offer = offerArray[i];
                    var dictObj = bannerCollection[offer.OfferId];
                    var promoCode = "Nothing", bannerURL = "Nothing";
                    if (offer.PromoCode != "") {
                        promoCode = offer.PromoCode;
                    }
                    if (dictObj.LinkURL !== "" && dictObj.LinkURL != '' && dictObj.LinkURL != null && dictObj.LinkURL != undefined) {
                        bannerURL = dictObj.LinkURL;
                    }
                    if (window.innerWidth > OA.index.mobileResolution) {
                        pauseDuration = OAApp.appsettings.pauseDurationDesktop;
                        if (dictObj.BannerType == 0 || dictObj.BannerType == 1) {
                            $('.bxSilderEC').append('<li data-from="offers" data-offerID=' + offer.OfferId + ' data-promoCode=' + promoCode + ' data-bannerURL=' + bannerURL + '><div data-from="offers" data-offerID=' + offer.OfferId + ' data-promoCode=' + promoCode + '  data-bannerURL=' + bannerURL + ' class="banner-image-desktop" style="background-image:url(' + dictObj.DesktopBannerImage + ')" data-bannerURL=""></div></li>');
                        }
                        if (offerArray.length == 1 && dictObj.DesktopBannerImage == "") {
                            $('.bxSilderEC').append('<li ><div class="ec-banner-default-desktop-image"  data-bannerURL=""></div></li>');
                        }
                    } else {
                        pauseDuration = OAApp.appsettings.pauseDurationMobile;
                        if (dictObj.BannerType == 0 || dictObj.BannerType == 2) {
                            $('.bxSilderEC').append('<li data-from="offers" data-offerID=' + offer.OfferId + ' data-promoCode=' + promoCode + '  data-bannerURL=' + bannerURL + '><img data-from="offers" data-offerID=' + offer.OfferId + ' data-promoCode=' + promoCode + '  data-bannerURL=' + bannerURL + ' src=' + dictObj.MobileBannerImage + '></li>');
                        }
                        if (offerArray.length == 1 && dictObj.MobileBannerImage == "") {
                            $('.bxSilderEC').append('<li data-from="default"><img data-from="default" src="/mobile/images/homepage/banners/EC_Home_Banner_Default_mobile.jpg"  data-bannerURL=""/></li>');
                        }
                    }
                }

                if (OA.index.ecBannerSlider != null) {
                    OA.index.ecBannerSlider.destroySlider();
                }

                OA.index.ecBannerSlider = $('.bxSilderEC').bxSlider({
                    auto: true,
                    autoControls: true,
                    pause: pauseDuration,
                    slideWidth: 1920,
                    touchEnabled: false
                });

                OA.index.bindECSliderEvents();
            }
        },
        bindNCBanners: function (callFrom) {
            var pauseDuration = OAApp.appsettings.pauseDurationDesktop;
            console.log("", OAApp.appsettings.pauseDurationDesktop);
            var isDefultBanner = false;
            if (callFrom == "Resize") {
                $(".nc-slider-container").empty().append('<ul class="bxslider bxSilderNC"></ul>').trigger("create");
            }
            $('ul.bxSilderNC li').remove();

            var offerArray = JSON.parse($("#NCBannerArray").text());
            var bannerCollection = JSON.parse($("#NCBannerCollection").text());

            // This code is for filtering the offer according to the promo code
            var offerWithPromoArray = _.filter(offerArray, function (offers) {
                return offers.PromoCode != "";
            });

            if (offerWithPromoArray.length > 0) {
                var offerWithOutPromoArray = _.filter(offerArray, function (offers) {
                    return offers.PromoCode == "";
                });
                offerArray = new Array();
                offerArray = offerWithPromoArray.concat(offerWithOutPromoArray);
            }

            for (var i = 0; i < offerArray.length; i++) {
                var offer = offerArray[i];
                var dictObj = bannerCollection[offer.OfferId];

                if (window.innerWidth > OA.index.mobileResolution) {
                    pauseDuration = OAApp.appsettings.pauseDurationDesktop;
                    if (dictObj.BannerType == 0 || dictObj.BannerType == 1) {
                        $('.bxSilderNC').append('<li><div class="banner-image-desktop" style="background-image:url(' + dictObj.DesktopBannerImage + ');height: 300px;" data-bannerURL=' + dictObj.LinkURL + '></div></li>');
                    }
                    if (offerArray.length == 1 && dictObj.DesktopBannerImage == "") {
                        $('.bxSilderNC').append('<li ><div class="nc-banner-default-desktop-image"></div></li>');
                    }
                } else {
                    pauseDuration = OAApp.appsettings.pauseDurationMobile;
                    if (dictObj.BannerType == 0 || dictObj.BannerType == 2) {
                        $('.bxSilderNC').append('<li ><div class="banner-image-mobile" style="background-image:url(' + dictObj.MobileBannerImage + ');" data-bannerURL=' + dictObj.LinkURL + '></div></li>');
                    }
                    if (offerArray.length == 1 && dictObj.MobileBannerImage == "") {
                        isDefultBanner = true;
                        $('.bxSilderNC').append('<li ><div class="nc-banner-default-mobile-image"></div></li>');
                    }
                }
            }


            if (OA.index.ncBannerSlider) {
                OA.index.ncBannerSlider.destroySlider();
            }
            if (isDefultBanner == true) {
                OA.index.ncBannerSlider = $('.bxSilderNC').bxSlider({
                    auto: true,
                    autoControls: true,
                    pause: pauseDuration,
                    slideWidth: 1920,
                    autoStart: true,
                    touchEnabled: false
                });
            }
            else {
                OA.index.ncBannerSlider = $('.bxSilderNC').bxSlider({
                    auto: true,
                    autoControls: true,
                    pause: pauseDuration,
                    slideWidth: 1920,
                    autoStart: true
                });
            }

            OA.index.bindNCSliderEvents();

            if (offerArray.length == 1) {
                $(".bx-pager").css("display", "none");
            }
            else {
                $(".bx-pager").css("display", "block");
            }
        },
        bindNCDefaultBanner: function (callFrom) {
            var pauseDuration = OAApp.appsettings.pauseDurationDesktop;
            console.log("", OAApp.appsettings.pauseDurationDesktop);
            if (callFrom == "Resize") {
                $(".nc-slider-container").empty().append('<ul class="bxslider bxSilderNC"></ul>').trigger("create");
            }
            $('ul.bxSilderNC li').remove();

            if ($("#NCDefaultBannerCount").val() == 0) {

                if (window.innerWidth > OA.index.mobileResolution) {
                    pauseDuration = OAApp.appsettings.pauseDurationDesktop;
                    $('.bxSilderNC').append('<li><div class="nc-banner-default-desktop-image" ></div></li>');
                } else {
                    pauseDuration = OAApp.appsettings.pauseDurationMobile;
                    $('.bxSilderNC').append('<li><div class="nc-banner-default-mobile-image" ></div></li>');
                }
            }
            else {
                var offerArray = JSON.parse($("#NCDefaultBannerArray").text());
                var bannerCollection = JSON.parse($("#NCDefaultBannerCollection").text());

                for (var i = 0; i < offerArray.length; i++) {
                    var offer = offerArray[i];
                    var dictObj = bannerCollection[offer.ID];

                    if (window.innerWidth > OA.index.mobileResolution) {
                        pauseDuration = OAApp.appsettings.pauseDurationDesktop;
                        if (dictObj.BannerType == 0 || dictObj.BannerType == 1) {
                            $('.bxSilderNC').append('<li><div class="banner-image-desktop" style="background-image:url(' + dictObj.DesktopBannerImage + ');height: 300px;" data-bannerURL=' + dictObj.LinkURL + '></div></li>');
                        }
                        if (offerArray.length == 1 && dictObj.DesktopBannerImage == "") {
                            $('.bxSilderNC').append('<li ><div class="nc-banner-default-desktop-image" ></div></li>');
                        }
                    } else {
                        pauseDuration = OAApp.appsettings.pauseDurationMobile;
                        if (dictObj.BannerType == 0 || dictObj.BannerType == 2) {
                            $('.bxSilderNC').append('<li ><div class="banner-image-mobile" style="background-image:url(' + dictObj.MobileBannerImage + ');" data-bannerURL=' + dictObj.LinkURL + '></div></li>');
                        }
                        if (offerArray.length == 1 && dictObj.MobileBannerImage == "") {

                            $('.bxSilderNC').append('<li ><div class="nc-banner-default-mobile-image" ></div></li>');
                        }
                    }
                }
            }

            if (OA.index.ncBannerSlider) {
                OA.index.ncBannerSlider.destroySlider();
            }

            OA.index.ncBannerSlider = $('.bxSilderNC').bxSlider({
                auto: true,
                autoControls: true,
                pause: pauseDuration,
                slideWidth: 1920,
                autoStart: true,
                touchEnabled: false
            });

            $(".bx-clone").remove();
            $(".bxSilderNC").removeAttr("style");
            $(".bxSilderNC li").removeAttr("style");


            $("ul.bxSilderNC li").click(function (event) {
                OA.index.ncBannerClickHandler(event);
            });
            $(".bx-pager").css("display", "none");
        },
        ncBannerClickHandler: function (e) {
            //OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");
            //OA.cookie.RemoveCookieValue("askAccountInfo");
            //window.location.href = OA.paths.psychicReading;

            var $el = $(e.target),
                bannerURL = $(e.target).attr("data-bannerURL");

            OA.cookie.RemoveCookieValue("FiveFreeAccountInfo");
            OA.cookie.RemoveCookieValue("askAccountInfo");
            if (bannerURL != undefined && bannerURL != '' && bannerURL != "" && bannerURL != null && bannerURL != "Nothing") {
                window.location.href = bannerURL;
            }
            else {
                window.location.href = OA.paths.psychicReading;
            }

        },
        ecBannerClickHandler: function (e) {
            var $el = $(e.target),
                dataFrom = $(e.target).attr("data-from"),
                offerID = $(e.target).attr("data-offerID"),
                promoCode = $(e.target).attr("data-promoCode"),
                bannerURL = $(e.target).attr("data-bannerURL");

            if (bannerURL != undefined && bannerURL != '' && bannerURL != "" && bannerURL != null && bannerURL != "Nothing") {
                window.location.href = bannerURL;
            }
            else if (offerID == undefined) {
                window.location.href = "/buy-package";
                return;
            }
            else if (promoCode == "" || promoCode == "Nothing") {
                OA.index.setCheckOutCookie(offerID, "");
                window.location.href = "/buy-package/?offer_id=" + offerID;
                return;
            }
            else {
                OA.index.setCheckOutCookie(offerID, promoCode);
                OA.cookie.ManageCookieValue("offerpromoCode", promoCode);
                window.location.href = "/buy-package/?offer_id=" + offerID + "&promocode=" + promoCode;
                return;
            }
        },
        setCheckOutCookie: function (offerID, promoCode) {
            var checkoutInfo = {
                offerId: offerID,
                priceId: '',
                promoCode: promoCode,
                amountToCharge: '',
                amountToCredit: '',
                karmaRewardPoints: '',
                currentBalance: "",
                offerIndex: 0,
                packageIndex: undefined,
                benefitType: "",
                description: "",
                offerName: "",
                isDefaultOffer: undefined
            }
            OA.cookie.ManageCookieValue("offerCheckout", checkoutInfo);
        },
        ecOfferClickHandler: function (event) {
            event.preventDefault();
            var offerId = $(event.target).attr("data-offerid").trim(),
                priceId = $(event.target).attr("data-priceid").trim(),
                amountToCharge = $(event.target).attr("data-amounttocharge").trim(),
                amountToCredit = $(event.target).attr("data-amounttocredit").trim(),
                karmaRewardPoints = $(event.target).attr("data-karmapoints").trim(),
                packageIndex = $(event.target).attr("data-packageindex").trim(),
                promoCode = $(event.target).attr("data-promocode").trim();

            OA.cookie.ManageCookieValue('serversessionverification', "");
            OA.cookie.ManageCookieValue('serverCustIdVerification', "");
            OA.cookie.ManageCookieValue('card', "");

            if (promoCode == "" || promoCode == "Nothing") {
                promoCode = "";
            }
            var checkoutInfo = {
                offerId: offerId,
                priceId: parseInt(priceId),
                promoCode: promoCode,
                amountToCharge: amountToCharge,
                amountToCredit: amountToCredit,
                karmaRewardPoints: karmaRewardPoints,
                currentBalance: "",
                offerIndex: undefined,
                packageIndex: undefined,
                benefitType: "",
                description: "",
                offerName: "",
                isDefaultOffer: undefined
            }
            OA.cookie.ManageCookieValue("offerCheckout", checkoutInfo);
            window.location.href = OA.paths.buyOfferPackage.main + "?&price_id=" + priceId + "&offer_id=" + offerId + "&kr=" + karmaRewardPoints + "&rate=" + amountToCharge;
        }
    }
})();

$(document).ready(function () {
    OA.index.initialize();
});

$(window).resize(function () {
    OA.index.resizeWindow("Resize");
});;
$(window).on("load", function () {
    if (!$.mobile) {
        $("div[data-role=header]").attr("class", "cpheader header ui-header-fixed ui-header ui-bar-inherit");
        $("div[data-role=footer]").attr("class", "cpFooter ui-footer ui-bar-inherit");
        $("div[data-role=footer] a").each(function () {
            var $class = this.className;
            $(this).attr("class", $class + " ui-link");
        });

        $("div[data-role=content]").wrap("<div class='ui-panel-wrapper'></div>");
        if ($("div[data-role=header]").css("position") == "fixed") {
            $(".ui-panel-wrapper").attr("style", "margin-top:50px");
        }

        $("ul[data-role=listview]").addClass("ui-listview");
        $("ul[data-role=listview] a[data-rel=close]").attr("class", "ui-btn ui-btn-icon-right ui-icon-carat-r");

        $("#main-menu").attr("class", "main-menu ui-panel-closed ui-panel ui-panel-position-left ui-panel-display-push ui-body-inherit ui-panel-animate").wrapInner("<div class='ui-panel-inner'></div>");
        $("#navbar-menu").attr("class", "menu-icon ui-link ui-btn ui-shadow ui-corner-all");
        $("#horoscope-header-search").removeAttr("href").attr("class", "search ui-link");
        $("#sidebar-auth-btn").attr("class", "mt-2 sidebar-auth-btn btn-sign-in ui-btn ui-shadow ui-corner-all");

        $(".nav-psychic-list").attr("class", "nav-psychic-list ui-li-static ui-body-inherit");
        $(".nav-horoscopes").attr("class", "nav-horoscopes ui-li-static ui-body-inherit");
        $(".nav-about-us").attr("class", "nav-about-us ui-li-static ui-body-inherit");
        $(".nav-support").attr("class", "nav-support ui-last-child");

        $("#navbar-menu").removeAttr("href").on("click", function (e) {
            e.stopPropagation();
            window.scrollTo(0, 0);

            $("div[data-role=header]").attr("class", "cpheader header ui-header ui-bar-inherit ui-header-fixed ui-panel-fixed-toolbar ui-panel-animate ui-panel-page-content-position-left ui-panel-page-content-display-push ui-panel-page-content-open");
            $("body").attr("class", "async-hide ui-mobile-viewport ui-overlay-a ui-panel-page-container");
            $("#main-menu").attr("class", "main-menu ui-panel ui-panel-position-left ui-panel-display-push ui-body-inherit ui-panel-animate ui-panel-open");
            if (!$(".ui-panel-dismiss").length) {
                $("body").append("<div class='ui-panel-dismiss'></div>");
            }

            $(".ui-panel-dismiss")
                .attr("class", "ui-panel-dismiss ui-panel-dismiss-position-left ui-panel-dismiss-display-push ui-panel-dismiss-open")
                .attr("style", "height:" + $("div[data-role=page]").height() + "px")
                .one("click", function (e) {
                    e.stopPropagation();
                    $("div[data-role=header]").attr("class", "cpheader header ui-header-fixed ui-header ui-bar-inherit ui-panel-fixed-toolbar ui-panel-animate");
                    $("body").attr("class", "async-hide ui-mobile-viewport ui-overlay-a");
                    $("#main-menu").attr("class", "main-menu ui-panel ui-panel-position-left ui-panel-display-push ui-body-inherit ui-panel-animate ui-panel-closed");
                    $(".ui-panel-dismiss").toggleClass("ui-panel-dismiss");
                    $(".ui-panel-wrapper").attr("class", "ui-panel-wrapper ui-panel-animate");
                    $(".ui-panel-dismiss-open").remove();
                });

            $(".ui-panel-wrapper").attr("class", "ui-panel-wrapper ui-panel-animate ui-panel-page-content-position-left ui-panel-page-content-display-push ui-panel-page-content-open");
        });

        $("#horoscope-header-search").on("click", function (e) {
            e.stopPropagation();
            $("#searchMainDiv").wrapInner("<div class='ui-input-search ui-body-inherit ui-corner-all ui-shadow-inset ui-input-has-clear'></div>");
            $("div[data-role=content]").attr("class", "ui-content-margin ui-content ui-content-search-margin");
        });

        $("div[data-role=popup]").each(function (e) {
            var $target = this;
            var $class = $(this).attr("class");
            if (!$class) {
                $class = '';
            }

            $(this).attr("class", $class + " ui-popup ui-body-b ui-overlay-shadow ui-corner-all");
            $(this).wrap("<div class=\"ui-popup-container ui-popup-hidden ui-popup-truncate\" id=\"" + $target.id + "-popup\">");
        });

        // patch a/g homepages, after Optimize fixes for main homepage
        if (window.location.href.indexOf("homepage") > 0) {
            OA.index.initialize();
            $(".async-hide").removeClass("async-hide");
            $(".menu-icon").css("border", "none");
        }
    }

    $.mobile = {
        loading: function (s) {
            if (s === "show") {
                if ($("#overlay-new").length > 0) {
                    $("body").append("<div id='overlay-new'></div>");
                }
            }
            else {
                $("#overlay-new").remove();
            }
        }
    };
});;
(function () {
    'use strict';
    OA.HoroscopeRegistrationForm = {
        data: {},
            initialize: function () {
            this.data.frequency = 511;
            this.data.country = "US";
            this.resizeHoroscopeRegistrationForm();
            this.wireHoroscopeRegFormEvents();
        },
        resizeHoroscopeRegistrationForm: function () {
            if (window.innerWidth > OA.index.mobileResolution) {
                $("#dob").hide();
                $("#dobDropdown").show();
            } else {
                if (OA.utils.browser.isSafari()) {
                    $("#dob").show();
                    $("#dobDropdown").hide();
                } else {
                    $("#dob").hide();
                    $("#dobDropdown").show();
                }
            }
        },
        wireHoroscopeRegFormEvents: function () {
            $("#first-name").on("blur", function () {
                OA.HoroscopeRegistrationForm.validateFirstName();
            });

            $("#email").on("blur", function () {
                OA.HoroscopeRegistrationForm.validateEmail();
            });

            $("#dob").on("blur", function () {
                OA.HoroscopeRegistrationForm.validateDob();
            });
            $("#dobMonth").on("change", function () {
                if ($("#dobDay").val() != null && $("#dobDay").val() != "" && $("#dobYear").val() != null && $("#dobYear").val() != "") {
                    OA.HoroscopeRegistrationForm.validateDob();
                }
            });
            $("#dobDay").on("change", function () {
                if ($("#dobMonth").val() != null && $("#dobMonth").val() != "" && $("#dobYear").val() != null && $("#dobYear").val() != "") {
                    OA.HoroscopeRegistrationForm.validateDob();
                }
            });
            $("#dobYear").on("change", function () {
                if ($("#dobMonth").val() != null && $("#dobMonth").val() != "" && $("#dobDay").val() != null && $("#dobDay").val() != "") {
                    OA.HoroscopeRegistrationForm.validateDob();
                }
            });

            $(".input-row").on("mouseleave", function () {
                OA.utils.tooltips.hideTooltip($(this));
            });

            $(".input-row").on("mouseenter", function () {
                if ($(this).hasClass("input-error")) {
                    OA.utils.tooltips.showTooltip($(this), $(this).attr("data-err-message"), "top");
                }
            });

            $("#horoscopeSignUp").on("click", function () {
                OA.HoroscopeRegistrationForm.validateAndHoroscopeRegister();
            });
        },
        validateFirstName: function () {
            var firstName = $("#first-name").val();
            var isFirstNameValid = false;

            if (firstName != null && $.trim(firstName).length > 0) {
                isFirstNameValid = true;
            }

            if (isFirstNameValid == true) {
                $("#first-name-row").removeClass("input-error");
                $("#first-name-row").addClass("input-pass");
            } else {
                $("#first-name-row").removeClass("input-pass");
                $("#first-name-row").addClass("input-error");
            }

            return isFirstNameValid;
        },
        validateEmail: function () {
            var email = $("#email").val();
            var userEmail = $("#hEmail").val();
            
            var isEmailValid = false;

            if (email != null && $.trim(email).length > 0) {
                var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
                if (pattern.test(email) == true) {
                    isEmailValid = true;
                }
            }

            if (isEmailValid == false || userEmail == email) {
                isEmailValid = false;
                $("#email-row").removeClass("input-pass");
                $("#email-row").addClass("input-error");
            } else {
                $("#email-row").removeClass("input-error");
                $("#email-row").addClass("input-pass");
            }

            return isEmailValid;
        },
        validateDob: function () {
            var dobVal = $("#dob").val();
            if (dobVal == null || dobVal == "") {
                if ($("#dobMonth").val() != null && $("#dobMonth").val() != "" && $("#dobDay").val() != null && $("#dobDay").val() != "" && $("#dobYear").val() != null && $("#dobYear").val() != "") {
                    dobVal = $("#dobMonth").val() + "/" + $("#dobDay").val() + "/" + $("#dobYear").val();
                }
            }

            var isDOBValid = false;
            var minAge = 16;
            var maxAge = 117;

            if (dobVal != null && $.trim(dobVal).length > 0) {
                var dob = new Date(dobVal);
                var age = this.calculateAge(dob);

                if (age < minAge) {
                    var minAgeMsg = "Must be at least " + minAge + ".";
                    if (window.innerWidth > OA.index.mobileResolution) {
                        minAgeMsg = "Must be at least " + minAge + " years or older.";
                    }
                    $("#dob-row").attr("data-err-message", minAgeMsg);
                } else if (age > maxAge) {
                    $("#dob-row").attr("data-err-message", "Maximum age is " + maxAge + ".");
                } else {
                    isDOBValid = true;
                    $("#dobValue").val(dob);
                }
            } else {
                $("#dob-row").attr("data-err-message", "Please enter your DOB.");
            }

            if (isDOBValid == false) {
                $("#dob-row").removeClass("input-pass");
                $("#dob-row").addClass("input-error");
            } else {
                $("#dob-row").removeClass("input-error");
                $("#dob-row").addClass("input-pass");
            }

            return isDOBValid;
        },
        calculateAge: function (birthDate) {
            var birthYear = birthDate.getFullYear();
            var birthMonth = birthDate.getMonth();
            var birthDay = birthDate.getDate();

            var todayDate = new Date();
            var todayYear = todayDate.getFullYear();
            var todayMonth = todayDate.getMonth();
            var todayDay = todayDate.getDate();
            var age = todayYear - birthYear;

            if (todayMonth < birthMonth - 1) {
                age--;
            }

            if (birthMonth - 1 == todayMonth && todayDay < birthDay) {
                age--;
            }

            return age;
        },
        validateHoroscopeRegForm: function () {
            var isFirstNameValid = this.validateFirstName();
            var isEmailValid = this.validateEmail();
            var isDOBValid = this.validateDob();

            if (isFirstNameValid == true && isEmailValid == true && isDOBValid == true) {
                return true;
            } else {
                return false;
            }
        },
        validateAndHoroscopeRegister: function () {
            if (this.validateHoroscopeRegForm() == false) {
                //$('.tooltip').removeClass("in");
                return;
            }

            //var data = {};
            this.data.Name = $("#horoscopeForm #first-name").val();
            this.data.Email = $("#horoscopeForm #email").val();
            this.data.DOB = moment($("#horoscopeForm #dobValue").val()).format("M/D/YYYY");
            //data.frequency = 511;
            //data.country = "US";
            var postData = JSON.stringify(this.data);

            $.mobile.loading("show");

            $('#horoscopeSignUp').addClass('ui-btn-disabled');
            $('#horoscopeSignUp').prop('disabled', true);
            $('#horoscopeSignUp').html('Processing...');

            var url = OAApp.appsettings.apiUrl + "/mhoroscope/signup?ts=ts_" + new Date().getTime();

            $.ajax({
                url: url,
                data: postData,
                method: "POST",
                dataType: "json",
                contentType: 'application/json',
                success: function (res) {
                    if (typeof (optimoveSDK) != 'undefined') optimoveSDK.API.setUserEmail(JSON.parse(this.data).Email);
                    OA.HoroscopeRegistrationForm.processResults(res);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var err = OA.utils.ajaxHelpers.getError(XMLHttpRequest);                                      
                    $('.errorPlaceholder').html('<span for="fields" class="error">* ' + err + '</span>');
                    if (err == "Please enter a valid email address.") {
                        $("#hEmail").val($("#horoscopeForm #email").val())
                        $("#email-row").removeClass("input-pass");
                        $("#email-row").addClass("input-error");
                        $('#horoscopeSignUp').html('SIGN UP FOR YOUR FREE HOROSCOPE');
                    } 
                }
            });

            $.mobile.loading("hide");

            $('.tooltip').removeClass("in");
        },
        processResults: function (res) {
            $("#horo-sign-up").hide();

            if (res != null && res.isSuccess == true) {
                $(".success-header").html("SUCCESS!");
                $(".success-description").html("You have been subscribed for your FREE daily horoscope email.");
            } else {
                $(".success-header").html("ERROR!");
                $(".success-description").html("An unexpected error has ocurred. Please refresh the page and try again.");
            }

            $("#horo-sign-up-message").removeClass("hidden");
        }
    }
})();

$(document).ready(function () {
    OA.HoroscopeRegistrationForm.initialize();
});

$(window).resize(function () {
    OA.HoroscopeRegistrationForm.resizeHoroscopeRegistrationForm();
});
;
$(document).ready(function () {
    $(".elite-package-box").on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();

        var srcElement = e.target;
        if (srcElement != null && $(srcElement).attr("data-info") == "true") {
            closePackInfoTooltips();

            var targetId = $(srcElement).attr("data-id");
            var title = $("#" + targetId).attr("data-title");

            OA.utils.tooltips.showTooltip($("#" + targetId), title, "top");

            var packTooltipTimer = $.timer(function () {
                OA.utils.tooltips.hideDesktopTooltip($("#" + targetId));
                packTooltipTimer.stop();
            });
            packTooltipTimer.set({ time: 5000, autostart: true });
        } else {
            OA.utils.common.redirectToConfirmation(e);
        }
    });

    $(window).click(function (e) {
        closePackInfoTooltips();
    });
});

function closePackInfoTooltips() {
    $(".icon-img").each(function () {
        var targetId = $(this).attr("id");
        OA.utils.tooltips.hideDesktopTooltip($("#" + targetId));
    });
};
var isFullProfileVisible = false;
var psychicListTimer;

$(document).ready(function () {

    bindEvents();
    loadCardImage();
    autoPsychicRefreshStatus();    
});

function bindEvents() {
    $('.arrowDiv').off('click').on('click', function (e) { displayFullProfile(e); });
    $('.psychicsArrow').off('click').on('click', function (e) { displayFullProfile(e); });
    $('.btnTalk').off('click').on('click', function (e) {
        OA.utils.talkButtonHelper.talkWithPsychics(e);
    });
    $('.btnChat').off('click').on('click', function (e) { OA.utils.talkButtonHelper.chatWithPsychics(e); });
    $('.set-favorite').off('click').on('click', function (e) { OA.utils.favoriteHelper.toggleFavorite(e, 0); });
}

function loadCardImage() {
    setTimeout(function () {
        $('.card-img-load').each(function () {
            var src = $(this).attr("data-imgsrc");
            if (src != undefined) {
                $(this).attr('src', src);
            }
            else {
                if (window.innerWidth > OAApp.appsettings.MobileResolution) {
                    $(this).attr("src", "/mvcimages/psychics/0000_360x208.jpg");
                } else {
                    $(this).attr("src", "/mvcimages/psychics/0000_720x416.jpg");
                }
            }
            $(this).removeClass('card-img-load');
            $(this).filter('.psychics-img').on("error", function () {
                if (window.innerWidth > OAApp.appsettings.MobileResolution) {
                    $(this).attr("src", "/mvcimages/psychics/0000_360x208.jpg");
                } else {
                    $(this).attr("src", "/mvcimages/psychics/0000_720x416.jpg");
                }
            });


        });
    }, 100);
}

function displayFullProfile(e) {
    if ($(e.target).hasClass("profileTalkbtn") || $(e.target).hasClass("psychics-icon") || $(e.target).hasClass('psychics-status') || $(e.target).hasClass("psychicsChoice")) {
        return;
    }
    e.stopPropagation();
    e.preventDefault();
    var extId = $(e.target).attr("data-extid");
    showFullProfile(extId);
}

function showFullProfile(extId) {
    var animationSpeed = 300;
    var currentClass = $('.card').find("#psychics-arrow-menu-" + extId).attr('class');
    if (currentClass.indexOf('right-arrow') >= 0) {
        isFullProfileVisible = false;
    }
    else {
        isFullProfileVisible = true;
    }

    if (!isFullProfileVisible) {
        isFullProfileVisible = true;
        $('.card').find("#psychics-arrow-menu-" + extId).removeClass("right-arrow").addClass("left-arrow");
        if (window.innerWidth >= OAApp.appsettings.MobileResolution) {
            $('.card').find("#psychic-li-" + extId).find('.psychicsListLI').find('.psychicsMainDiv').css("border", "1px solid #bdbcbc").css("border-bottom", "0");
            $('.card').find("#psychic-li-" + extId).find('.psychicsListLI').find('.psychics-status-main-div').css("border-right", "0px");
        }
        $('#psychics-list-div-' + extId).animate({
            "margin-left": "-60%"
        }, animationSpeed, function () {
        });
        $('#psychics-default-bar-' + extId).animate({
            "margin-left": "-60%"
        }, animationSpeed, function () {
            $('#psychics-right-menu-' + extId).css("display", "inline-block");
            $('#psychics-profile-bar-' + extId).css("display", "inline-block");
        });
    }
    else {
        $('.card').find("#psychic-li-" + extId).find('.psychicsListLI').find('.psychicsMainDiv').css("border", "0");
        $('.card').find("#psychic-li-" + extId).find('.psychicsListLI').find('.psychics-status-main-div').css("border-right", "1px solid #bdbcbc");
        isFullProfileVisible = false;
        $("#psychics-arrow-menu-" + extId).removeClass("left-arrow").addClass("right-arrow");
        $('#psychics-right-menu-' + extId).css("display", "none");
        $('#psychics-profile-bar-' + extId).css("display", "none");
        $('#psychics-list-div-' + extId).animate({
            "margin-left": "0%"
        }, animationSpeed, function () {
        });
        $('#psychics-default-bar-' + extId).animate({
            "margin-left": "0%"
        }, animationSpeed, function () {
            $('#psychics-right-menu-' + extId).css("display", "none");
            $('#psychics-profile-bar-' + extId).css("display", "none");
        });
    }
}

function FullProfileClick(e) {
    e.stopPropagation();
    e.preventDefault();
    var extId = e.target.getAttribute("data-extid");
    var name = e.target.getAttribute("data-name");
    var liId = "psychic-li-" + extId;
    OA.cookie.ManageCookieValue("BioLink", liId);
    name = name.toLowerCase();
    name = name.replace(" ", "");
    window.location.href = "../psychics/" + name + "-" + extId;
}

function autoPsychicRefreshStatus() {
    if (!psychicListTimer) {
        psychicListTimer = $.timer(function () {
            OA.utils.psychicStatusUpdateManager.refreshPsychicStatus(undefined, 0);
        });
        psychicListTimer.set({ time: OAApp.appsettings.refreshPsychicStatusInterval, autostart: true });
    }
}

function scrollOnCardView(extid, scrollDivId) {
    $('html,body').animate({
        scrollTop: $("#" + scrollDivId).offset().top
    }, 'slow');
    showFullProfile(extid);
}

function showScrollPotion() {
    var BioLinkCookie = OA.cookie.ManageCookieValue("BioLink");
    if (BioLinkCookie != null) {
        var extid = BioLinkCookie.replace("psychic-li-", '');

        if (window.innerWidth > OAApp.appsettings.MobileResolution) {
            scrollOnCardView(extid, BioLinkCookie);
        } else {
            scrollOnCardView(extid, BioLinkCookie);
        }
        OA.cookie.RemoveCookieValue("BioLink");
    }
}

$(window).resize(function () {
    loadCardImage();
});

window.onunload = function () {
    if (psychicListTimer) {
        psychicListTimer.stop();
        psychicListTimer = undefined;
    }

}


function psychicsStatusClick(e) {
    e.preventDefault();
    e.stopPropagation();
    OA.utils.tooltips.hideDesktopTooltip($(".set-favorite"));
    OA.utils.tooltips.hideDesktopTooltip($(".psychics-status"));
    var self = this,
        $el = $(e.target),
        ExtId = $el.attr("data-extid"),
        title = $el.attr("data-title"),
        type = $el.attr("data-listtype");

    if (type == "profile") {
        OA.utils.tooltips.showTooltip($("#psychics-status-" + ExtId), title, "left");
    }
    else {
        OA.utils.tooltips.showTooltip($("#psychics-status-" + ExtId), title, "right");
        OA.utils.tooltips.showTooltip($("#psychics-status-desktop-" + ExtId), title, "right");
    }

    var hideTooltipTimer = $.timer(function () {
        OA.utils.tooltips.hideDesktopTooltip($("#psychics-status-" + ExtId));
        OA.utils.tooltips.hideDesktopTooltip($("#psychics-status-desktop-" + ExtId));
        hideTooltipTimer.stop();
    });
    hideTooltipTimer.set({ time: 5000, autostart: true });
};
