if (!(typeof YUI === 'undefined' || !YUI)) {
  YUI.log("Warning: Quorus will override existing YUI!");
}

(function() {
  //Wrapper-safe way to initialize the QUORUS variable
  if (typeof QUORUS === 'undefined' || !QUORUS) {
    QUORUS = { 
      _bootstrapVersion: "d7d01b4",
      _callbacks: [],
      _siteKey: "shoebuy"
    };
  }
  var Q = QUORUS,
      doc = document,
      win = window,
      head = doc.getElementsByTagName('head')[0],
      events = Q._eventRecord = {boot: new Date()},
      tmp;

  if (doc.addEventListener) {
    doc.addEventListener('DOMContentLoaded', function () {
      events.domLoaded = new Date();
    }, false);
    win.addEventListener('load', function () {
      events.windowLoaded = new Date();
    }, false);
  } else if (win.attachEvent) {
    win.attachEvent('onload', function () {
      events.domLoaded = events.domLoaded || new Date();
      events.windowLoaded = new Date();
    }, false);
  }

  // Pre-bootstrap functions
  function readCookie (name) {
    var nameEQ = name + "=";
    var ca = doc.cookie.split(';');
    for (var i=0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
  }
  function getCfg(name) {
    return (win.sessionStorage && sessionStorage[name]) ||
           (win.localStorage   && localStorage[name]) ||
           readCookie(name);
  }
  function dropScript (url) {
    var script = doc.createElement('script');
    script.src = url;
    script.async = 'async'; // only FF since 3.6
    script.defer = 'defer';
    setTimeout(function () {
      head.appendChild(script);
    }, 0);
  }

  // Overridden by stage2
  Q.use = function (fn) {
    var a = Array.prototype.slice.call(arguments, 0);
    Q._callbacks.push(a);
  };

  var rootUrl = "http://app.quorus.com/bootstrap/";
  if (tmp = getCfg('q_envOverride')) {
    Q._envOverride = tmp;
    Q._dropScript  = dropScript;

    //This script will callback with the apppropriate URLs
    tmp = rootUrl + 'override/' + tmp + '/' + Q._siteKey + '.js';
  } else {
    tmp = rootUrl + Q._siteKey + '/stage2.js';
  }
  dropScript(tmp);
})();

var required_fields = ['id_type','id_value','description','price'];
var quorus_site_url;
var quorus_ref_url;
function updateQuorusProductData(options) {
  for(var i in required_fields) {
    if(typeof options[required_fields[i]] == "undefined") {
	return;
    }
  }
  $('.quorus-product-attributes').empty();

  $('<div/>').addClass('quorus-product-identifier').appendTo('.quorus-product-attributes');

  $('<span/>').addClass('quorus-product-identifier-type').text(options['id_type']).appendTo('.quorus-product-identifier');

  $('<span/>').addClass('quorus-product-identifier-value').text(options['id_value']).appendTo('.quorus-product-identifier');

  $('<span/>').addClass('quorus-product-description').text(options['description']).appendTo('.quorus-product-attributes');

  $('<span/>').addClass('quorus-product-price').text(options['price']).appendTo('.quorus-product-attributes');

  if(typeof options['name'] != "undefined") {
    $('<h2/>').addClass('quorus-product-name').text(options['name']).appendTo('.quorus-product-attributes');
  }

  if(typeof options['images'] != "undefined") {
    if(typeof options['images'] != "object")
      options['images'] = [options['images']];
    for(var i=0; i< options['images'].length; i++) {
        $('<img/>').addClass('quorus-product-photo').attr('src', options['images'][i]).appendTo('.quorus-product-attributes');
    }
  }

  if(typeof options['url'] != "undefined") {
      var url = options['url'];
      if(url && url.indexOf('/cgi-bin/sbref.cgi') == -1) {
	if(url.indexOf(quorus_site_url) != -1) {
	    url = url.replace(quorus_site_url, quorus_ref_url);
	} else if(url.charAt(0) == '/') {
	    url = quorus_ref_url + url;
	}
	url = url.replace('path=/', 'path=');
      }
      $('<a/>').addClass('quorus-product-url').text('permalink').attr('href', url).appendTo('.quorus-product-attributes');
  }

  QUORUS.use(function(Q) {
    Q.newItem(); // Tell Quorus that the product metadata markup changed
  });
}

function loadQuorusUser() {
  var lin = readCookie('lin');
  if (lin) {
    lin = base64_decode(url_decode(lin)).split('\t');
    if (lin.length > 1 && lin[0] && lin[1]){
      QUORUS.use(function(Q) {
      Q.setIdentity({
	  name: lin[0], 
	  email: lin[1]
      });
      });
    }
  }
}

