/**
 * Encapsulate XMLHTTPRequest, handle request queueing
 * Loads the given url into the div with the given id
 */
function CFW_HTTPRequest(url, div_id, params) {
	this.url = url;
	this.div_id = div_id;
	this.params = typeof(params) != 'undefined' ? params : null;

	/*
	 * Callback function after completion
	 */
	this.notify = null;

	if (!CFW_HTTPRequest.req) {
		if (window.ActiveXObject) {
			// branch for IE/Windows ActiveX version
			CFW_HTTPRequest.req = new ActiveXObject("Microsoft.XMLHTTP");
			CFW_HTTPRequest.ie = 1;
		} else if  (window.XMLHttpRequest) {
                       // branch for native XMLHttpRequest object
			CFW_HTTPRequest.req = new XMLHttpRequest();
			CFW_HTTPRequest.ie = 0;
		}
	}
	
	if (!CFW_HTTPRequest.waiting) {
		CFW_HTTPRequest.waiting = new Array(10);
		window.setInterval("cfw_scheduledretry();", 400);
	}

	/*
	 * 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, this.params ? this.params.async : 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 = "";
							var 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 encodeURI(str);
	// return escape(str).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}


function cms_session_keepalive() {
	url = home_url + '?page=index'; 
	req = new CFW_HTTPRequest(url, null);
	req.run();
}

/**
 * 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 && obj != null) {
        if (obj) {
            if (dojo.style.isPositionAbsolute(obj) || dojo.style.getComputedStyle(obj,"position") == 'relative') {
                return dojo.style.getAbsolutePosition(obj,true);
            }
            obj = obj.offsetParent;
        }
    }
    return false;
}

function onDivEvent(event,name) {
    var div = dojo.byId(name);
    var target = event.target?event.target:event.srcElement;
    while (target != document.body && target != null) {
        if (target) {
            if (target == div) {
                return true;
            }
            target = target.offsetParent;
        }
    }
    return false;
}

/**
 * Display div named "name" just after obj
 */
function cfw_showdiv(obj, name, z) {

	if (typeof(z) == 'undefined') z = 1;

	//pos = cfw_calculatePosition(obj);
	pos = dojo.style.getAbsolutePosition(obj, true);

	pos[1] += 15;

	div = document.getElementById(name);

	if ((pos1 = cfw_hasAbsoluteParent(div))) {
		pos[0] -= pos1[0];
		pos[1] -= pos1[1];
	}
        
	var margin_x = 5;
	var margin_y = 5;

	var div_width = dojo.style.getMarginBoxWidth(div);	
	var div_height = dojo.style.getMarginBoxHeight(div);	

	var win_top = dojo.html.getScrollTop();
	var win_bottom = win_top + dojo.html.getViewportHeight();
	var win_left = dojo.html.getScrollLeft();
	var win_right = win_left + dojo.html.getViewportWidth();

	var bottom = pos[1] + div_height;
	if (bottom > win_bottom - margin_y) {
		var correction_y = bottom - ( win_bottom - margin_y );
		pos[1] -= correction_y;
		if (pos[1] < win_top + margin_y){
			pos[1] = win_top + margin_y;
		}
	}

	var right = pos[0] + div_width;
	if (right > win_right - margin_x) {
		var correction_x = right - ( win_right - margin_x );
		pos[0] -= correction_x;
		if (pos[0] < win_left + margin_x){
			pos[0] = win_left + margin_x;
		}
	}

	div.style.left = String(pos[0]) + 'px';
	div.style.top = String(pos[1]) + 'px';
	div.style.zIndex = z;
	div.style.visibility = "visible";
}


/**
 * Loads a div
 */

function cfw_loaddiv(obj, name, page, params) 
{
	dojo.io.bind( {
        url: home_url + '?page=' + 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";
}

/**
 * Magazine form auto fill postcode
 */
function checkEventRegionName(event) {
	onDivEvent(event,'region_name-div');
}

function checkEventTown(event) {
	onDivEvent(event,'town-div');
}

function checkEventCity(event) {
	onDivEvent(event,'city-div');
}

function checkEventDistrict(event) {
	onDivEvent(event,'district-div');
}

function checkEventStreet(event) {
	onDivEvent(event,'street-div');
}

function checkEventStreet2(event) {
	onDivEvent(event,'street2-div');
}

function checkEventPcode(event) {
	onDivEvent(event,'pcode-div');
}
function onDivEvent(event,name) {
    var div = dojo.byId(name);
    var target = event.target?event.target:event.srcElement;
    while (target != document.body && target != null) {
        if (target) {
            if (target == div) {
                return true;
            }
            target = target.offsetParent;     
        }
    }
	cfw_hidediv(name);
    return false;
}
/**
 * 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) {
        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 cfw_addlistener(element, type, func, bubbling) {
	bubbling = bubbling || false;
	if (window.addEventListener) {
		element.addEventListener(type, func, bubbling);
		return true;
	}
	else if (window.attachEvent) {
		element.attachEvent('on' + type, function() { func(window.event); } );
		return true;
	}
	else return false;
}

function getElementInNode(node_id, id) {
	context = document.getElementById(node_id);
	x = context.getElementsByTagName('*');
	for (i = 0; i < x.length; i++) {
		if (x[i].id == id) {
			return x[i];
		}
	}
	return null;
}
