var _st = _st || [];

// json2 if not found
"object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(t){return 10>t?"0"+t:t}function this_value(){return this.valueOf()}function quote(t){return rx_escapable.lastIndex=0,rx_escapable.test(t)?'"'+t.replace(rx_escapable,function(t){var e=meta[t];return"string"==typeof e?e:"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+t+'"'}function str(t,e){var r,n,o,u,f,a=gap,i=e[t];switch(i&&"object"==typeof i&&"function"==typeof i.toJSON&&(i=i.toJSON(t)),"function"==typeof rep&&(i=rep.call(e,t,i)),typeof i){case"string":return quote(i);case"number":return isFinite(i)?i+"":"null";case"boolean":case"null":return i+"";case"object":if(!i)return"null";if(gap+=indent,f=[],"[object Array]"===Object.prototype.toString.apply(i)){for(u=i.length,r=0;u>r;r+=1)f[r]=str(r,i)||"null";return o=0===f.length?"[]":gap?"[\n"+gap+f.join(",\n"+gap)+"\n"+a+"]":"["+f.join(",")+"]",gap=a,o}if(rep&&"object"==typeof rep)for(u=rep.length,r=0;u>r;r+=1)"string"==typeof rep[r]&&(n=rep[r],o=str(n,i),o&&f.push(quote(n)+(gap?": ":":")+o));else for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(o=str(n,i),o&&f.push(quote(n)+(gap?": ":":")+o));return o=0===f.length?"{}":gap?"{\n"+gap+f.join(",\n"+gap)+"\n"+a+"}":"{"+f.join(",")+"}",gap=a,o}}var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/g,rx_escapable=/[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value);var gap,indent,meta,rep;"function"!=typeof JSON.stringify&&(meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(t,e,r){var n;if(gap="",indent="","number"==typeof r)for(n=0;r>n;n+=1)indent+=" ";else"string"==typeof r&&(indent=r);if(rep=e,e&&"function"!=typeof e&&("object"!=typeof e||"number"!=typeof e.length))throw Error("JSON.stringify");return str("",{"":t})}),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(t,e){var r,n,o=t[e];if(o&&"object"==typeof o)for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(n=walk(o,r),void 0!==n?o[r]=n:delete o[r]);return reviver.call(t,e,o)}var j;if(text+="",rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(t){return"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})),rx_one.test(text.replace(rx_two,"@").replace(rx_three,"]").replace(rx_four,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}();

!function(win){
  /*!
    * contentloaded.js
    *
    * Author: Diego Perini (diego.perini at gmail.com)
    * Summary: cross-browser wrapper for DOMContentLoaded
    * Updated: 20101020
    * License: MIT
    * Version: 1.2
    *
    * URL:
    * http://javascript.nwbox.com/ContentLoaded/
    * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
    *
    */

  // @fn function reference
  function contentLoaded(fn) {

    var done = false, top = true,

    doc = win.document,
    root = doc.documentElement,
    modern = doc.addEventListener,

    add = modern ? 'addEventListener' : 'attachEvent',
    rem = modern ? 'removeEventListener' : 'detachEvent',
    pre = modern ? '' : 'on',

    init = function(e) {
      if (e.type == 'readystatechange' && doc.readyState != 'complete') return;
      (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
      if (!done && (done = true)) fn.call(win, e.type || e);
    },

    poll = function() {
      try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; }
      init('poll');
    };

    if (doc.readyState == 'complete') fn.call(win, 'lazy');
    else {
      if (!modern && root.doScroll) {
        try { top = !win.frameElement; } catch(e) { }
        if (top) poll();
      }
      doc[add](pre + 'DOMContentLoaded', init, false);
      doc[add](pre + 'readystatechange', init, false);
      win[add](pre + 'load', init, false);
    }
  }

  win.STWidget = {
    _config: {
      sid: 97,
      expiration: 2592000000,
      tags: [],
    },
    _error: "",
    jqVer: function() {
      if (typeof jQuery !== 'undefined') {
        var va = jQuery.fn.jquery.split('.');
        if (va[0] == 1 && va[1] >= 6) {
          return true;
        }
      }
      return false;
    },
    decodeEntities: function(value) {
      var hiddenPre=document.createElement("pre");

      if (!value) { return ''; }
      hiddenPre.innerHTML = value.replace(/</g,"&lt;");
      // innerText depends on styling as it doesn't display hidden elements.
      // Therefore, it's better to use textContent not to cause unnecessary
      // reflows.
      return hiddenPre.textContent;
    },
    getParam: function(pname) {
      var qd = {};
      location.search.substr(1).split("&").forEach(function(item) {
        var s = item.split("="),
            k = s[0],
            v = s[1] && decodeURIComponent(s[1]);
        (k in qd) ? qd[k].push(v) : qd[k] = [v]
      });
      if (qd.hasOwnProperty(pname)) {
        return qd[pname];
      }
      return [];
    },
    getCookie: function(cname) {
      var name = cname + "=";
      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) == 0) return c.substring(name.length,c.length);
      }
      return "";
    },
    setCookie: function(cname, cvalue, expiration) {
      var d = new Date();
      d.setTime(d.getTime() + expiration);
      document.cookie = cname + '=' + cvalue + '; expires=' + d.toUTCString() + '; path=/';
    },
    insertScript: function(url) {
      var _this = this;
      var s=document.createElement('script');
      s.type='text/javascript';
      s.async=true;
      s.src=url;
      var q = document.getElementsByTagName('script')[0];
      var x = q.parentNode.insertBefore(s, q);
    },
    pixel: function() {
      var _this = this;
      var o = _st[0][1];
      var url = 'https://ergobaby.sagetrack.com/pixel/?cid=97&clid=' + _this.getCookie('_st') + "&vid=" + (o.vid || "") + "&value=" + (o.value || "") + "&coupon=" + (o.coupon || "");
      _this.insertScript(url);
    },
    renderTags: function() {
      var _this = this;
      for (i = 0; i < _this._config.tags.length; i++) {
        jQuery('body').append(_this.decodeEntities(_this._config.tags[i]));
      }
    },
    getPostObject: function() {
      var _this = this;
      var o = window.opener || {};
      var t = (window.location === window.top.location) ? "" : window.top.location;
      var p = {
        c: _this._config.sid,
        w: {
          wl: window.location,
          wtl: t,
          wn: window.name,
          wo: "", //o.location || "",
          dim: {
            ih: window.innerHeight,
            iw: window.innerWidth,
            oh: window.outerHeight,
            ow: window.outerWidth,
          },
          n: window.navigator,
          os: {
            x: window.pageXOffset,
            y: window.pageYOffset
          }
        },
        b: jQuery.browser,
        r: document.referrer,
        sc: screen.colorDepth,
        o: [],
        ck: _this.getCookie("_st"),
        ckv: _this.getCookie("_stv")
      };

      return p;
    },
    isOrder: function() {
      if (_st.length > 0 && "object" == typeof _st[0]) {
        for(i = 0; i < _st.length; i++) {
          if (_st[i][0] === "order") {
            return true;
          }
        }
      }
      return false;
    },
    sendOrder: function() {
      var _this = this;
      var ob = _this.getPostObject();
      ob.o = _st;
      jQuery.ajax({
        crossDomain: true,
        global: false,
        xhrFields: {
          withCredentials: true
        },
        type: "POST",
        url: "https://ergobaby.sagetrack.com/site/",
        data: {
          id: 97,
          order: JSON.stringify(ob)
        },
        success: function(d, ts, xhr) {
          'use strict';
          //if (typeof d !== "object" || d.success === "false") {
            STWidget.pixel();
          //}
        },
        error: function() {
          STWidget.pixel();
        },
        dataType: "json"
      });
    },
    sendEvent: function() {
      var _this = this;
      jQuery.ajax({
        crossDomain: true,
        global: false,
        xhrFields: {
          withCredentials: true
        },
        type: "POST",
        url: "https://ergobaby.sagetrack.com/site/",
        data: {
          id: 97,
          event: JSON.stringify(_this.getPostObject())
        },
        success: function(d) {
          return;
        }
      });
    },
    init: function() {
      var _this = this;
      if (_this._error !== '') {
        return;
      }
      if (!_this.jqVer()) {
        var done = false;
        var q = document.getElementsByTagName('script')[0];
        var s=document.createElement('script');
        s.type='text/javascript';
        s.async=true;
        s.src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js';
        s.onload = s.onreadystatechange = function() {
          if (!done && (!_this.readyState || _this.readyState == 'loaded' || _this.readyState == 'complete')) {
            done = true;
            contentLoaded(function(){
              jQuery.noConflict();
              STWidget.run();
            });
            s.onload = s.onreadystatechange = null;
          };
        };
        q.parentNode.insertBefore(s, q);
      } else {
        contentLoaded(function(){ STWidget.run(); });
      }
    },
    run: function() {
      var _this = this,
      lfid = _this.getParam("lfid"),
      lid = '';
      lfid = (lfid.length === 0) ? -1 : lfid[0];
      var cv = (lfid === -1) ? lid : lfid;
      var _sclid = cv + ':fcd4c245c385b8b0b7a164354b442b61:utmcsr=' +
        _this.getParam("utm_source")  + '|utmccn=' +
        _this.getParam("utm_campaign") + '|utmcmd=' +
        _this.getParam("utm_media");
      var c = _this.getCookie('_st');
      var v = _this.getCookie('_stv');
      if (c === "" || (c !== _sclid && cv !== '')) {
        _this.setCookie('_st', _sclid, _this._config.expiration);
      }
      if (v === "") {
        _this.setCookie('_stv', '986ac4260e76ee02ef4e040288a44d70', 31536000000);
      }
      if (_this.isOrder()) {
        _this.sendOrder();
      } else {
        _this.sendEvent();
      }
      _this.renderTags();
    }
  };

  contentLoaded(function(){ STWidget.init(); });
}(window);
