if (window.jQuery) {
  (function(jQuery) {
    var $ = jQuery;
    var Realius = window.Realius;
  
    // Allow access to jQuery through our namespace.
    Realius.jQuery = jQuery;
    
    // Attributes that need to be present on a launch_realius element
    Realius.LISTING_ATTRIBUTES = ['listing_id', 'street_address', 'lat', 'lng', 'market', 'category', 'price'];

    Realius.NEW_MOVE_PATH = "/web_service/predictions/new";

    // Realius.config is a hash of settings
    // Realius.config
    //   host: the host name to which the realius client will connect. Does not end in a slash
    //   script_src: The full url (as much as available, may not include host) to the realius script.
    //   script_path: The path where the realius script resides. Does not include the .js file at the end. Ends in a slash.
    //   return_to: The url that the separate window should redirect to after sign in/up.
  
  
    ///////////////////////////////////////////////////////////////////////////////////
    // Browser detection – Assume compatible unless we know it's not
    jQuery.supported = function() {
      if (typeof jQuery.supported.result != "undefined") {
        return jQuery.supported.result;
      }

      jQuery.supported.browsers = [
        ["safari", "412"],
        ["opera", "9.0"],
        ["msie", "6.0"],
        ["mozilla", "1.8.1"]
      ];

      jQuery.supported.result = true;

      var b = jQuery.supported.browsers;
      for (var i=0; i<b.length; i++){
        if (typeof jQuery.browser[b[i][0]] != "undefined" && jQuery.browser[b[i][0]]) {
          var a1 = b[i][1].split(".");  var a2 =
          jQuery.browser.version.split(".");
          var d1 = a1.shift();
          var d2 = a2.shift();
          if ( parseFloat(d2 + "." + a2.join("")) < parseFloat(d1 + "." + a1.join("")) ){
            jQuery.supported.result = false;
          }
        }
      }
      return jQuery.supported.result;
    };
  
    if (!jQuery.supported()) {
      Realius.enabled = false;
      return;
    }
  
    ///////////////////////////////////////////////////////////////////////////////////
    // Utilities
    
    // Parse a recursive <dl> structure into a hash of hashes (and strings). Strip leading and trailing
    // whitespace and html comments since IE doesn't seem to understand the meaning of the word "inner".
    function parseDL(element) {
      var dl = (element[0].tagName.toUpperCase() == "DL") ? element : element.find("dl");
      if (dl.length == 0) {
        return element.html().replace(/^\s+|\s+$|<!--(?:.|\n)*?-->/g, "");

      } else {
        var currentKey, obj = {};
        $(dl).children().each(function() {
          if (this.tagName.toUpperCase() == "DT") {
            currentKey = parseDL($(this));
            
          } else if (currentKey && this.tagName == "DD") {
            var current = obj[currentKey];
            var value = parseDL($(this));
            
            if (current instanceof Array) {
              current.push(value)
            } else {
              obj[currentKey] = obj.hasOwnProperty(currentKey) ? [current, value] : value;
            }
          }
        })
        
        return obj;
      }
    };
    
    // Convert a JSON data structure into a Rails compatible params string..
    var toQueryString = function(obj, namespace) {
      if (typeof(obj) == "object" && !(obj instanceof Array)) {
        var result = [];
        $.each(obj, function(prop, value) {
          prop = prop.replace(/\W+/g,"_").toLowerCase();
          result.push(toQueryString(value, namespace ? namespace+"["+prop+"]" : prop));
        });
        return result.join("&");
        
      } else if (obj instanceof Array ){
        var key = encodeURIComponent(namespace + "[]");
        return $.map(obj, function(val, idx) { return key + "=" + encodeURIComponent(val);}).join("&");
        
      } else {
        return encodeURIComponent(namespace) + "=" + encodeURIComponent(obj);
      }
    };
    
    function clientUrl(args) {
      var params = toQueryString(args) + "&" + toQueryString({return_to: Realius.config.return_to});
      var url = Realius.config.host + Realius.NEW_MOVE_PATH + "?" + params;
      return url;
    }
  
function contentSize(element) {
  var el = $(element);
  
  var css_sum = function() {
    var sum = 0;
    $.each(arguments, function(idx, val) { sum += parseInt(el.css(val)) || 0 });
    return sum;
  };
  
  return {
    width: el[0].offsetWidth - css_sum("padding-left", 'padding-right', "border-left-width", "border-right-width"),
    height: el[0].offsetHeight - css_sum("padding-top", 'padding-bottom', "border-top-width", "border-bottom-width")
  };
}

var rootPath = "/web_service/predictions/new";

$(document).ready(function() {
  $("dl.realius").each(function() {
    var parent = this.parentNode;
    
    var el = $(this);
    var data = parseDL(el);
    
    if (data && data.listing) {
      delete data.listing.description;
    }

    parent.innerHTML = ""
    var replacement = $('<iframe class="realius-client" allowtransparency="true" frameborder="0" src="'+ clientUrl(data) + '"></iframe>');

    $(parent).html(replacement);

    var parentSize = contentSize($(parent));
    replacement.
      data('parameters', data).
      addClass("realius").
      css({
        border: "0px",
        width: parentSize.width + "px",
        height: parentSize.height + "px"});
  });

});

    Realius.enabled = true;

    // Remove jQuery from the global namespace if it was loaded by realius.
  })(window.Realius.jQueryFromRealius ? window.jQuery.noConflict(true) : window.jQuery);
}
