(function() {
  
	//window.onload = function() {
	  
	// Global vars to control various aspects of the iframe.
	DEQQ_FIT_TO_WINDOW = isDefined(window.DEQQ_FIT_TO_WINDOW) && DEQQ_FIT_TO_WINDOW ? true : false;
	DEQQ_ELEMENT_ID = isDefined(window.DEQQ_ELEMENT_ID) ? DEQQ_ELEMENT_ID : 'deqq';
    DEQQ_COMMUNITY_HANDLE = isDefined(window.DEQQ_COMMUNITY_HANDLE) ? DEQQ_COMMUNITY_HANDLE : 'deqq';
    DEQQ_CLIENT_HOST = isDefined(window.DEQQ_CLIENT_HOST) ? DEQQ_CLIENT_HOST : 'client.deqq.com';
    DEQQ_DEFAULT_FILTER = isDefined(window.DEQQ_DEFAULT_FILTER) ? DEQQ_DEFAULT_FILTER : '';
    DEQQ_AUTO_LOGIN = isDefined(window.DEQQ_AUTO_LOGIN) && DEQQ_AUTO_LOGIN ? true : false;
	DEQQ_USER_HANDLE = isDefined(window.DEQQ_USER_HANDLE) && DEQQ_USER_HANDLE ? DEQQ_USER_HANDLE : '';
	DEQQ_USER_ACCESS_TOKEN = isDefined(window.DEQQ_USER_ACCESS_TOKEN) && DEQQ_USER_ACCESS_TOKEN ? DEQQ_USER_ACCESS_TOKEN : '';
	DEQQ_USER_ACCESS_TIMESTAMP = isDefined(window.DEQQ_USER_ACCESS_TIMESTAMP) && DEQQ_USER_ACCESS_TIMESTAMP ? DEQQ_USER_ACCESS_TIMESTAMP : '';
	DEQQ_EMBED_TYPE = isDefined(window.DEQQ_EMBED_TYPE) && DEQQ_EMBED_TYPE ? DEQQ_EMBED_TYPE : 'vanilla';
	
	  // console.log for IE.
	  if (!console) var console = {log: function(){}};
	  
	  var containEl = null;
	  var frameEl = null;
	  
	  var init = function() {
	    
		var replaceNode = null;
		var styleObj = null;
  	  containEl = xdom.get(DEQQ_ELEMENT_ID);
  	  if (!containEl || containEl.nodeName !== 'DIV') {
  	    // If we found the element but it's not the right type, store the node-to-replace in replaceNode.
  	    replaceNode = containEl;
  	    containEl = xdom.create('div', {'id': DEQQ_ELEMENT_ID});
  	    xdom.insertInto(document.body, containEl);
  	    if (replaceNode) {
  	      replaceNode.parentNode.replaceChild(containEl, replaceNode);
  	      styleObj = {
  	        'height': xdom.style(replaceNode, 'height') || 700,
  	        'width': xdom.style(replaceNode, 'width') || 808
  	      }
  	    }
  	    else {
  	      styleObj = {
  	        'height': 700,
  	        'width': 808
  	      }
  	    }
  	    xdom.style(containEl, styleObj);
  	  }
	  
	  // build query string for auto login
	  if (DEQQ_AUTO_LOGIN) {
		auto_login_params = '&username=' + DEQQ_USER_HANDLE + '&access_token=' + DEQQ_USER_ACCESS_TOKEN + '&timestamp=' + DEQQ_USER_ACCESS_TIMESTAMP;
	  } else {
		auto_login_params ='';
	  }
	  
	  // build query string for default filter
	  DEQQ_DEFAULT_FILTER = DEQQ_DEFAULT_FILTER.toLowerCase();
	  if (DEQQ_DEFAULT_FILTER != '' &&
		  (DEQQ_DEFAULT_FILTER == 'host' ||
		   DEQQ_DEFAULT_FILTER == 'all' ||
		   DEQQ_DEFAULT_FILTER == 'media')) {
		default_filter_params = '&filter=' + DEQQ_DEFAULT_FILTER;		
	  } else {
		default_filter_params = '';		
	  }
	  
	  // get embed location
	  embed_location = '&embedloc=' + encodeURIComponent(location.href);
	  	  
	  // trying to get conversation handle
	  conversation_handle = getQueryVariable('deqq_conversation');
	  if (!conversation_handle || conversation_handle == '') {
		url = 'http://' + DEQQ_CLIENT_HOST + '/community/' + DEQQ_COMMUNITY_HANDLE + '/?embed=' + DEQQ_EMBED_TYPE + auto_login_params + default_filter_params + embed_location;
	  } else {
		url = 'http://' + DEQQ_CLIENT_HOST + '/community/' + DEQQ_COMMUNITY_HANDLE + '/conversation/' + conversation_handle + '/?embed=' + DEQQ_EMBED_TYPE + auto_login_params + default_filter_params + embed_location;
	  }
	  
  	  //var url = 'http://www.google.ca/';
  	  frameEl = xdom.create('iframe', {'src': url, 'width': '100%', 'height': '100%'});
  	  xdom.insertInto(containEl, frameEl);
  	  xdom.style(frameEl, {
  	    'padding': '0px',
  	    'margin': '0px',
  	    'border': '0px'
  	  });
  	  if (DEQQ_FIT_TO_WINDOW) enableFitToWindow();
	  }
	  
    /**
     * Finds the iframe's position in the page and hooks up the onresize handler.
     */
    function enableFitToWindow() {
      // Get the bottom dimensions for the frame.
      var bodyProps = ['marginBottom', 'marginTop', 'paddingBottom', 'paddingTop', 'borderBottom', 'borderTop'];
      
      var calcOffsetTop = function() {
        var y = xdom.position(containEl).y;
		
		var i;
		for (i in bodyProps) {
          y += forceNum(xdom.style(document.body, bodyProps[i]));
		}

		/*		
        // Add body properties.
        bodyProps.each(function(prop) {
          y += forceNum(xdom.style(document.body, prop));
        });
		*/
        return y;
      }
      
      // Set the handler.
      var onresizehandler = function() {
        console.log(xdom.windowHeight());
  	    var newHeight = (xdom.windowHeight() - calcOffsetTop()) + 'px';
  	    window.status = newHeight;
        xdom.style(containEl, 'height', newHeight);
      }
      xdom.addEvent(window, 'resize', onresizehandler);
      
      // Fire once for the initial display.
      onresizehandler();
    }
    
    /**
     * Ensures we get 0 from parseInt.
     */
    function forceNum(val) {
      var n = parseInt(val);
      return n ? n : 0;
    }
    
    
  	var xdom = (function() {
  	  
  	  /**
  	   * Utility function to loop through objects more concisely and without looping 
  	   * through the prototype chain.
  	   * NOTE: overriding Object.prototype will conflict with jQuery. 
  	   */
	  /*
  	  Object.prototype.each = function(fn) {
  	    var i;
  	    for (i in this) {
  	      if (this.hasOwnProperty(i)) fn(this[i], i);
  	    }};
	  */
  	    	  
  	  /**
  	   * Returns a hyphenated string as camelCase, eg. 'font-size' -> 'fontSize'.
  	   */
  	  String.prototype.camelCase = function() {
  	    var s = '',
  	        i = -1,
  	        c;
  	    while ((c = this.charAt(++i)) !== '') {
  	      s += (c === '-') ? this.charAt(++i).toUpperCase() : c;
  	    }
  	    return s;
  	  };
  	  
  	  /**
  	   * Returns a camelCase string as hyphenated, eg. 'fontSize' -> 'font-size'.
  	   */
  	  String.prototype.hyphenate = function() {
  	    var s = '',
  	        i = -1,
  	        code,
  	        c;
  	    while ((c = this.charAt(++i)) !== '') {
  	      code = c.charCodeAt(0);
  	      s += (code > 64 && code < 91) ? '-' + c.toLowerCase() : c;
  	    }
  	    return s;
  	  };
  	  
  	  /**
  	   * Mootools-1.2.3 - Gets a computed style.
  	   */
      function getComputedStyle(targ, property) {
        try {
          if (targ.currentStyle) return targ.currentStyle[property.camelCase()];
        	var computed = getDocument().defaultView.getComputedStyle(targ, null);
      		return (computed) ? computed.getPropertyValue([property.hyphenate()]) : null;
      	}
      	catch (er) {
      	  return null;
      	}
    	};
    	
    	/**
    	 * Mootools-1.2.3 - Returns the document.
    	 */
    	function getDocument() {
    	  return document;
    	};
    	
    	/**
    	 * Get the dimensions of the window.
    	 */
  	  function windowDims() {
    		if(window.innerHeight && window.innerWidth)
    		  return {x: window.innerWidth, y: window.innerHeight};
    		if (document.documentElement.clientWidth && document.documentElement.clientHeight)
    			return {x: document.documentElement.clientWidth, y: document.documentElement.clientHeight};
    		if (document.body.clientWidth && document.body.clientHeight)
    			return {x: document.body.clientWidth, y: document.body.clientHeight};
  	  };
  	  
  	  /**
  	   * The public portion of this object.
  	   */
  	  var exposed = {
  	    /**
  	     * Create a DOM element.
  	     */
    	  create: function(type, attrs) {
    	    var e = document.createElement(type);

            var i;
            for (i in attrs) {
                e.setAttribute(i, attrs[i]);  
            }
			
    	    return e;
    	  },
  	    
  	    /**
  	     * Retrieve a DOM element.
  	     */
    	  get: function(id) {
    	    return document.getElementById(id);
    	  },
    	  
    	  /**
    	   * Appends a DOM element into another DOM element
    	   */
    	  insertInto: function(parent, child) {
    	    var i = 0;
    	    while (++i < arguments.length) {
            parent.appendChild(arguments[i]);
    	    };
    	  },
    	  
    	  /**
    	   * Returns the position of a DOM element as {x:n, y:n}
    	   */
      	position: function(targ) {
      		var curleft = curtop = 0;
      		if (targ.offsetParent) {
      			do {
      				curleft += targ.offsetLeft;
      				curtop += targ.offsetTop;
      			} while (targ = targ.offsetParent);
      			
      			return {x:curleft, y:curtop};
      		}
      		return {x:0, y:0}
      	},
    	  
    	  /**
    	   * Returns the parent of the DOM element.
    	   */
    	  parent: function(targ) {
    	    return targ.parentNode;
    	  },
    	  
    	  /**
    	   * Gets and optionally sets a style attribute for a DOM element.  If k is an object, it
    	   * uses the object to set multiple attributes.
    	   */
    	  style: function(targ, k, v) {
    	    if (typeof(k) == 'object') {
    	      var i;
    	      for (i in k) {
    	        console.log('setting ', i, ' to ', k[i]);
    	        this.style(targ, i, k[i]);
    	      }
    	    }
    	    else {
     	      if (v !== undefined) targ.style[k] = v;
      	    return getComputedStyle(targ, k);
      	  }
    	  },
    	  
    	  /**
    	   * Mootools-1.2.3 - Adds an event listener to an object.
    	   */
      	addEvent: function(targ, type, fn) {
      		if(targ.addEventListener) {
      			targ.addEventListener(type, fn, false);
      		}
      		else if(targ.addEvent) {
      			//targ.addEvent('on' + type, fn);
				targ.addEvent(type, fn);
      		}
      		else {
      			var current_fn = targ['on' + type];
      			targ['on' + type] = function() {
      				if(current_fn) current_fn();
      				fn();
      			}
      		}
      	},
      	
      	/**
      	 * Returns the height of the window.
      	 */
      	windowHeight: function() {
      	  return windowDims().y;
      	}
    	};
    	
  	
   	return exposed;
  	})();
  	// end xdom;
  	
  	function isDefined(v) {
  		return typeof(v) !== 'undefined';
  	}
  	
	function getQueryVariable(variable) {
		try {
			var query = window.location.search.substring(1);
			var vars = query.split("&");
			for (var i=0;i<vars.length;i++) {
				var pair = vars[i].split("=");
				if (pair[0] == variable) {
				  return pair[1];
				}
			}
		} catch (e) {
			return '';
		}
	} 

	/**
	 * Concatenates the values of a variable into an easily readable string
	 * @param {Object} x The variable to debug
	 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
	 * @param {String} sep The separator to use between [default: a single space ' ']
	 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
	 */
	function var_dump(x, max, sep, l) {
	
		l = l || 0;
		max = max || 10;
		sep = sep || ' ';
	
		if (l > max) {
			return "[WARNING: Too much recursion]\n";
		}
	
		var
			i,
			r = '',
			t = typeof x,
			tab = '';
	
		if (x === null) {
			r += "(null)\n";
		} else if (t == 'object') {
	
			l++;
	
			for (i = 0; i < l; i++) {
				tab += sep;
			}
	
			if (x && x.length) {
				t = 'array';
			}
	
			r += '(' + t + ") :\n";
	
			for (i in x) {
				try {
					r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
				} catch(e) {
					return "[ERROR: " + e + "]\n";
				}
			}
	
		} else {
	
			if (t == 'string') {
				if (x == '') {
					x = '(empty)';
				}
			}
	
			r += '(' + t + ') ' + x + "\n";
	
		}
	
		return r;
	
	};
	
    // Debug function
    function traceObj(o,d) {
      var i, s='', m='',t;
      
      d = d || 0;
      while (m.length < d) m += '  ';
      
      t = typeof(o);
      s += t + ':';
      switch (t) {
        case 'function':
          s += '[function]';
          break;
          
        case 'object':
          if (o !== null) {
            s += '{\n';
            for (i in o) {
              if (o.hasOwnProperty(i)) {
                s += m + '  ' + i + ': ';
                try {
                  s += traceObj(o[i], d+1);
                }
                catch (er) {
                  s += '[no access]';
                }
              }
            }
            s += m + '}';
            break;
          }
          // else fall through
          
        default:
          s += o;
          break;
      }
      s += '\n';
      return s;
    }    	

	  	
	//init();
	//}
	
	xdom.addEvent(window, 'load', init);
	
})();
