/**
 * Encapsulate XMLHTTPRequest, handle request queueing
 * Loads the given url into the div with the given id
 */
function CFW_HTTPRequest(url, div_id) {
	this.url = url;
	this.div_id = div_id;

	/*
	 * Callback function after completion
	 */
	this.notify = null;

	if (!CFW_HTTPRequest.req) {
		if (window.XMLHttpRequest) {
			// branch for native XMLHttpRequest object
			CFW_HTTPRequest.req = new XMLHttpRequest();
			CFW_HTTPRequest.ie = 0;
		} else if (window.ActiveXObject) {
			// branch for IE/Windows ActiveX version
			CFW_HTTPRequest.req = new ActiveXObject("Microsoft.XMLHTTP");
			CFW_HTTPRequest.ie = 1;
		}
	}

	if (!CFW_HTTPRequest.waiting) {
		CFW_HTTPRequest.waiting = new Array(10);
		window.setInterval("cfw_scheduledretry();", 1000);
	}

	/*
	 * Run the request or queue it if another is running
	 */
	this.run = function() {

		with (CFW_HTTPRequest) {

			if (req.readyState != 4 && req.readyState != 0) {
				CFW_HTTPRequest.waiting.push(this);
				return false;
			}

			if (ie) {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}

			var cfwreqThis = this;
			req.onreadystatechange = function() { cfwreqThis.handle() };

			req.open("GET", this.url, true);
			if (ie) {
				req.send();
			} else {
				req.send(null);
			}

			return true;
		}

	}

	/*
	 * XMLHTTPRequest callback function for onreadystatechange
	 */
	this.handle = function() {

		with (CFW_HTTPRequest) {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
					if (this.div_id) {
						div_node = document.getElementById(this.div_id);
						if (div_node) {
							div_node.innerHTML = "";
							content = req.responseText;
							div_node.innerHTML = content;
						}
					}
					if (this.notify) {
						this.notify();
					}
				} else {
					// alert("There was a problem retrieving the XML data:\n" +
					//    req.statusText);
				}

			} else {
				// alert("Status: " + req.readyState);
			}
		}
	}
}

/*
 * Look for unhandled requests in CFW_HTTPRequest queue
 */
function cfw_scheduledretry() {
	while (CFW_HTTPRequest.waiting.length > 0 && (CFW_HTTPRequest.req.readyState == 0 || CFW_HTTPRequest.req.readyState == 4)) {
		newobj = CFW_HTTPRequest.waiting.shift();
		if (newobj) {
			newobj.run();
			return;
		}
	}
}

/**
 * URL-encode a string
 */
function cfw_urlencode(str) {
	return escape(str).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}


/**
 * Calculate the absolute position of an element
 */
function cfw_calculatePosition(obj) {
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (obj.x || obj.y) {
		curleft += obj.x;
		curtop += obj.y;
	}

	ret = new Array(2);
	ret[0] = curleft;
	ret[1] = curtop;

	return ret;
}

function cfw_hasAbsoluteParent(obj) {
    if (obj.offsetParent) {
        obj = obj.offsetParent;
    }
    while (obj != document.body) {
        if (obj) {
            if (dojo.style.isPositionAbsolute(obj) || dojo.style.getComputedStyle(obj,"position") == 'relative') {
                return dojo.style.getAbsolutePosition(obj,true);
            }
            obj = obj.offsetParent;
        }
    }
    return false;
}



/**
 * Display div named "name" just after obj
 */
function cfw_showdiv(obj, name) {
	return cfw_showdiv(obj, name, 1);
}

function cfw_showdiv(obj, name, z) {
        if (!z) z = 1;
        
        //pos = cfw_calculatePosition(obj);  
        pos = dojo.style.getAbsolutePosition(obj, true);
        
        div = document.getElementById(name);
        /*if (!div) {
        	div = document.createElement('div');
                div.setAttribute('id',name);
                dojo.html.addClass(div, 'popup');
                var body_lst = document.getElementsByTagName('body');
                body_lst.item(0).appendChild(div);
        }
        dojo.html.disableSelection(div);
        // new dojo.dnd.HtmlDragMoveSource(div);
        */
        if ((pos1 = cfw_hasAbsoluteParent(div))) {
            pos[0] -= pos1[0];
            pos[1] -= pos1[1];
        }
        
        div.style.left = String(pos[0] - 20) + 'px';
        div.style.top = String(pos[1] + 17) + 'px';
        div.style.zIndex = z;

        dojo.style.setOpacity(div, 0);
        div.style.visibility = "visible";
        
        dojo.lfx.fadeIn(div, 100, dojo.easeInOut).play();
}


function cfw_loaddiv(obj, name, page, params) {
    dojo.io.bind( {
        url: page + '?' + params,
        mimetype: "text/plain",
        preventCache: true,
        load: function (type, data, event) {
            var div = dojo.byId(name);
            if (!div) {
                div = document.createElement('div');
                div.setAttribute('id',name);
                dojo.html.addClass(div, 'popup');
                var body_lst = document.getElementsByTagName('body');
                body_lst.item(0).appendChild(div);
            }
            
            div.innerHTML = data;
            
            cfw_evalscripts(div);
            if (obj) cfw_showdiv(obj, name);
        }
    });
}



/**
 * Hide div named "name"
 */
function cfw_hidediv(name) {
	div = document.getElementById(name);
	div.style.visibility = "hidden";
}
function cfw_sendform(form_id, func) {
	var form = dojo.byId(form_id);
    	if (!form) return;
    	var bindArgs = {
    		formNode: form,
    		mimetype: "text/html",
    		transport: "IframeTransport",
    		handler: function (type, data, evt) {
    			func(data);
    		}
    	};
    	var req = dojo.io.bind(bindArgs);
}

/**
 * Collect a list of selected checkboxes
 */
function cfw_collectselection(name) {
        node_lst = document.getElementsByTagName("input");
        to_del = Array(1);
        for (i = 0; i < node_lst.length; i++) {
                node = node_lst.item(i);
                if (node.getAttribute("type") == "checkbox" && node.getAttribute("name") == name && node.checked) {
                        to_del.unshift(node.getAttribute("value"));
                }
        }

        buf = '';
        for (i = 0; i < to_del.length; i++) {
                if (to_del[i]) {
                        buf += ":" + to_del[i];
                }
        }
        return buf;
}


function cfw_evalscripts(obj, recursive) {
        var scripts = obj.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++) {
                var scrip = scripts[i];
                var txt = '';
                if (scrip.text) {
                        txt = scrip.text;
                } else {
                        if (scrip.childNodes) {
                                txt = dojo.dom.textContent(scrip);
                        }
                }
                eval(txt);
        }
}


function hideShowCovered() {
	
}
