//===================================================================
//  AUTHORS: app9g29
//  DESCRIPTION: JSObject to perform the iframe resize and
//				 the cross-domain messaging.
//				 trpResize automatically loads to your window at include.
//===================================================================

// assure the singleton run once.  need it because the page could include the .js multiple times.
if (typeof trpResize == "undefined")
{

trpResize = function () {

	var inited = false;
	var height = null;
	var parentDomain = null;
	var parentIFrameID = null;
	var parentChildOnSameDomain = false;
	var disable = false;
	var pollRunning = false;
	var pollCount = 0;
	var resizeListeners = new Array();
	var ie = false;
	
	var _onloadHandler = function() {
		_addBodyDiv();
		_pollSize();
	};
	var _onmouseHandler = function() {
		if (pollRunning==false)
		{
			_pollSize();
		}
	};

	/*
	 * parent side - no action
	 * child side - attach the resize event
	 */
	var _init = function() {
		if (inited)
			return;

		inited = true;
		ie = (typeof document.all != "undefined");

		// parse the meta data
		try
		{
			var loc;
			var parent = null;
			var child = null;

			loc = window.parent.location;
			parent = loc.protocol + "//" + loc.host;
			loc = window.location;
			child = loc.protocol + "//" + loc.host;
			parentChildOnSameDomain = (parent==child);
		}
		catch (error) {}

		if (window.name!=null)
		{
			var fields = window.name.split("&");
			for (var i=0; i <  fields.length; i++)
			{
				var n = "vDomain";
				if (fields[i].indexOf(n)==0)
				{
					parentDomain = fields[i].substring(n.length+1);
					if (parentDomain.indexOf("www3")>0)
					{
						//parentDomain += "/vc2";
						parentDomain += "";
					}
				}
				n = "vIFrameID";
				if (fields[i].indexOf(n)==0)
				{
					parentIFrameID = fields[i].substring(n.length+1);
				}
				n = "vDisable";
				if (fields[i].indexOf(n)==0)
				{
					disable = (fields[i].substring(n.length+1)=="true");
				}
			}
		}
				
		// Parent side.
		if (parentDomain==null)
		{
			return;
		}

		// Child side.
		if (disable)
		{
			return;
		}

		// Create iframe for tunneling the message to parent.
		var eltIFrame = document.createElement("iframe");
	    eltIFrame.setAttribute("id", "vrtTunnelIFrame");
	    eltIFrame.setAttribute("name", "vrtTunnelIFrame");
	    eltIFrame.setAttribute("src", parentDomain+"/529common/images/spacer.gif");
	    eltIFrame.setAttribute("height", "0");
	    eltIFrame.setAttribute("width", "0");
	    eltIFrame.setAttribute("scrolling", "no");
	    eltIFrame.setAttribute("frameborder", "0");
	    // IE does not have the late binding for the onload event.  can't set it on the fly.
		// eltIFrame.setAttribute("onload", "_fireResizeEvent()");
		document.getElementsByTagName('head')[0].appendChild(eltIFrame);

		// Attach onload event to send the first resize
		if (window.addEventListener)
		{
			window.addEventListener("load", _onloadHandler, false);
			document.addEventListener("mouseup", _onmouseHandler, false);
		}
		if (window.attachEvent)
		{
			window.attachEvent("onload", _onloadHandler);
			document.attachEvent("onmouseup", _onmouseHandler);
		}
	};

	var _getHeight = function() {
		return _getBodyDiv().scrollHeight;
	};

	/*
	 * Use by the parent to set the child iframe size
	 */
	var _receiveMessage = function(m) {
		var iframeID;
		var h;
		// skips the leading "?".
		if (m.indexOf("?")==0)
			m = m.substring(1);
		
		var params = m.split( '&' );
		for( var i = 0, l = params.length; i < l; ++i )
		{
			var parts = params[i].split( '=' );
			switch( parts[0] ) {
			 case 'h':
			  h = parseInt( parts[1] );
			  break;
			 case 'id':
			  iframeID = parts[1];
			  break;
			}
		}
		if( typeof( h ) == 'number' )
		{
			var fr = document.getElementById(iframeID);
			if (fr!=null && parseInt(h) >= 0)
			{
				fr.height = h;
				_fireResizeEvent(m, iframeID, h);
			}
		}
	};

	var _sendMessage = function(m) {
		// same domain uses the direct call.
		if (parentChildOnSameDomain)
		{
			try {
				window.parent.trpResize.receiveMessage(m);
			} catch (error) {}
		}
		else
		{
			var tunnel = document.getElementById('vrtTunnelIFrame');
			if (tunnel)
			{
				tunnel.src = parentDomain + "/529common/html/trpTunnelResize.html?" + m;
			}
		}
		_fireResizeEvent(m, parentIFrameID, height);
	};

	var _pollSize = function() {
		var maxpoll = 4;
		var pollTime = 100;

		// initial poll. the else is used for skipping the first polling loop because of the firefox onload event restriction -- outgoing connection suppressed.
		if (pollRunning==false)
		{
			pollCount = 0;
			pollRunning = true;
		}
		else
		{
			if (height != null)
			{
				if (height != _getHeight())
				{
					height = null;
				}
			}
			if (height==null)
			{
				height = _getHeight();
				_sendMessage("h=" + height + "&id=" + parentIFrameID);
			}
		}

		if (pollCount >= maxpoll)
		{
			pollRunning = false;
		}
		else
		{
			setTimeout(_pollSize, pollTime);
		}
		++pollCount;
	};
	
	var _getBodyDiv = function() {
		return ie? document.body:document.getElementById("body_div");
	};
	
	/* insert a body_div to measure the body height.  in non-ie browser, body.scrollHeight does not accurately return the content height */
	var _addBodyDiv = function() {
		if (ie)	return;
		
		var newtag = "body_div";
		var b = document.getElementsByTagName("body")[0];
		var childnodes = b.childNodes;
		var arr = new Array();
		var elt = document.createElement("div");
		elt.setAttribute("id", newtag);

		// insert the tag
		for (var i=0; i < childnodes.length; i++) arr.push(childnodes[i]);
		b.appendChild(elt);
		for (var i=0; i < arr.length; i++) elt.appendChild(arr[i]);

		// validate only the new tag is inserted.
		childnodes = b.childNodes;
		arr = new Array();
		for (var i=0; i < childnodes.length; i++) arr.push(childnodes[i]);
		for (var i=0; i < arr.length; i++) {
			if (arr[i].id != newtag) {
				b.removeChild(arr[i]);
			}
		}
	};

	var _addResizeListener = function(func) {
		if (func!=null)	resizeListeners.push(func);
	};

	var _fireResizeEvent = function(m, iframeID, h) {
		var e = { data: m, appIFrameID: iframeID, appIFrameHeight: h };

		for (var i=0; i < resizeListeners.length; i++)
		{
			var f = resizeListeners[i];
			setTimeout(function(){f(e)}, 400);
		}
	};
	
    return {
        init : function(){
			_init();
        },
        receiveMessage : function(msg){
        	_receiveMessage(msg);
        },
		addResizeListener : function(func){
			_addResizeListener(func);
		},
		// Use by the flash object that can't fire the mouse event on the dom.
		firePollEvent : function(){
			_onmouseHandler();
		}
	}; // public
}();

trpResize.init();
} // singleton if
