var isIE = document.all;
var isOP = window.opera;
var dragObject = null;
var offsetx = 0;
var offsety = 0;
var nowx = 0;
var nowy = 0;
var dragEnabled = false;
var zlist = [];
var objID = 0;
var dragframe = null;
var oldmousedown = null;
var oldmousemove = null;
var oldmouseup = null;
var oldwidth = 0;
var oldheight = 0;
var pageWidth = 0;
var pageHeight = 0;
var menu = null;
var contacts = null;
var mwindow = null;

// for FireBug logging
function printfire() {
    console.log(arguments);
}

function $(element) {
	var e;
	if (typeof(element) == "string") {
		e = document.getElementById(element);
	}
	e.remove = function() {
		this.parentNode.removeChild(this);
	};
	return e;
}

function $v(element) {
	var e = $(element);
	return e.value;
}	

function execute() {
	var obj = $(arguments[0]).windowRef;
	eval('obj.' + arguments[1] + '(arguments)');
}

function ex(e) {
	return isIE ? event.clientX : e.clientX;
}

function ey(e) {
	return isIE ? event.clientY : e.clientY;
}

function getPageSize() {
	if (typeof(window.innerWidth) == 'number' ) {
		//Non-IE
		pageWidth = window.innerWidth;
		pageHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		pageWidth = document.documentElement.clientWidth;
		pageHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientWidth ) ) {
		//IE 4 compatible
		pageWidth = document.body.clientWidth;
		pageHeight = document.body.clientHeight;
	}

	//if (menu) menu.resize(pageWidth, pageHeight);
}

function getBoundingBox(obj) {
	var oWidth = obj.offsetWidth;
	var oHeight = obj.offsetHeight;
	for (var lx = 0, ly = 0; (obj != null) && (obj.offsetLeft!=undefined); lx += obj.offsetLeft - obj.scrollLeft, ly += obj.offsetTop - obj.scrollTop, obj = obj.parentNode);
	return { bx:lx, by:ly, bw:oWidth, bh:oHeight };
};
function nextObjID() {
	return objID++;
}

function copyStyle(src, dest, list) {
	for (var n=0; n<list.length; n++)
		dest.style[list[n]] = src.style[list[n]];
}

function initDrag(e) {
	if (dragObject != null) {
		copyStyle(dragObject, dragframe, ["left", "top", "width", "height"]);
		dragframe.style.display = '';

		bringtofront(dragframe);
		offsetx = ex(e);
		offsety = ey(e);
		nowx = parseInt(dragObject.style.left);
		nowy = parseInt(dragObject.style.top);
		dragEnabled = true;
	}
}

function doDrag(e) {
	if (!dragEnabled) return;
	dragframe.style.left = (nowx + ex(e) - offsetx);
	dragframe.style.top  = (nowy + ey(e) - offsety);
	return false;
}

function stopDrag() {
	if (dragEnabled) {
		dragEnabled = false;
		copyStyle(dragframe, dragObject, ["left", "top"]);
		dragframe.style.display = 'none';
		bringtofront(dragObject);
	}
}

function setWindowDragEvents() {
	document.onmousedown = initDrag;
	document.onmousemove = doDrag;
	document.onmouseup = stopDrag;
}

function restoreDocumentEvents() {
	document.onmousedown = oldmousedown;
	document.onmousemove = oldmousemove;
	document.onmouseup = oldmouseup;
}

function addToZlist(obj) {
	zlist[zlist.length] = obj;
	bringtofront(obj);
}

function removeFromZlist(obj) {
	var tempzlist = [];
	for (var n=0; n<zlist.length; n++) {
		if (zlist[n] != obj) tempzlist[tempzlist.length] = zlist[n];
	}
	zlist = tempzlist;
}

function showPopup(args) {
	httpcallback = function(response) {
		//alert(response);
		eval(response);
	};
		
	var req = new http('text', args, null);
	req.execute();
}

function bringtofront(obj) {
	var tempzlist = [];
	var n;

	for (n=0; n<zlist.length; n++) {
		if (zlist[n] == obj) break;
	}

	tempzlist[0] = zlist[n];

	for (n=0; n<zlist.length; n++) {
		if (zlist[n] != obj) {
			tempzlist[tempzlist.length] = zlist[n];
		}
	}
	zlist = tempzlist;
	for (n=0; n<zlist.length; n++) {
		zlist[n].style.zIndex = zlist.length - n;
	}
	tempzlist = null;
}

function bringUpPopup(name) {
	console.log('searching for: ' + name);
	var re = new RegExp(name.replace(/\|/g, '\\|') + '$');
	console.log(re.toString());
	
	var found = false;
	
	for (var x=0; x<zlist.length; x++) {
		if (zlist[x].id.match(re)) {
			console.log('found popup: ' + zlist[x].id);
			found = true;
			bringtofront(zlist[x]);
			break;
		}
	}
	if (!found) {
		var parts = name.split('|');
		var args = [];
		for (var x=0; x<parts.length; x++) {
			pair = parts[x].split(':');
			args[x] = { n: pair[0], v: pair[1] };
		}
		showPopup(args);
	}
}


function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}

function getDiv(props) {
	var div = document.createElement('div');
	div.id = props.id;
	div.className = props.className;
	div.style.left = props.left;
	div.style.top = props.top;
	div.style.width = props.width;
	div.style.height = props.height;
	return div;
}

function MWindow(name,aleft, atop, awidth, aheight) {
	var obj = this;
	var wid = 'window' + nextObjID();
	var win = document.createElement('div');
	
	win.id = wid + '|' + name;

	win.style.position = 'absolute';
	win.style.left = aleft;
	win.style.top = atop;
	win.style.width = awidth;
	win.style.height = aheight;
	win.style.display = 'none';

	win.windowRef = this;
	this.element = win;

	this.captionDrag = function() {
		if (!dragEnabled) {
			setWindowDragEvents();
			dragObject = obj.element;
		}
	};

	this.frameOut = function() {
		if (!dragEnabled) {
			restoreDocumentEvents();
			dragObject = null;
		}
	};

	var topleft		= getDiv({id:wid+'topleft',className:'topleft',left:0,top:0,width:327,height:30});
	topleft.style.cursor = 'move';
	topleft.onmouseover = this.captionDrag;
	topleft.onmouseout = this.frameOut;

	var top			= getDiv({id:wid+'top',className:'top',left:327,top:0,width:(awidth-327-18),height:30});
	top.style.cursor = 'move';
	top.onmouseover = this.captionDrag;
	top.onmouseout = this.frameOut;

	var topright	= getDiv({id:wid+'topright',className:'topright',left:(awidth-18),top:0,width:18,height:30});
	topright.style.cursor = 'move';
	topright.onmouseover = this.captionDrag;
	topright.onmouseout = this.frameOut;

	var left1		= getDiv({id:wid+'left1',className:'left1',left:0,top:30,width:8,height:128});
	var left2		= getDiv({id:wid+'left2',className:'left2',left:0,top:158,width:8,height:(aheight-158-18)});
	var right		= getDiv({id:wid+'right',className:'right',left:(awidth-8),top:30,width:8,height:(aheight-30-18)});
	var bottomleft  = getDiv({id:wid+'bottomleft',className:'bottomleft',left:0,top:(aheight-18),width:18,height:19});
	var bottom		= getDiv({id:wid+'bottom',className:'bottom',left:18,top:(aheight-18),width:(awidth-18-18),height:19});
	var bottomright = getDiv({id:wid+'bottomright',className:'bottomright',left:(awidth-18),top:(aheight-18),width:18,height:19});
    var bg 			= getDiv({id:wid+'bg',className:'bg',left:8,top:30,width:(awidth-16),height:(aheight-30-18)});
    var inner1      = getDiv({id:wid+'inner1',className:'inner1',left:8,top:30,width:188,height:128});
    var inner2		= getDiv({id:wid+'inner2',className:'inner2',left:(awidth-214-8),top:(aheight-230-18),width:214,height:230});
	var html		= getDiv({id:wid+'html',className:'html',left:16,top:26,width:(awidth-32),height:(aheight-26-18)});

	win.appendChild(topleft);
	win.appendChild(top);
	win.appendChild(topright);
	win.appendChild(left1);
	win.appendChild(left2);
	win.appendChild(right);
	win.appendChild(bottomleft);
	win.appendChild(bottom);
	win.appendChild(bottomright);
	win.appendChild(bg);
	win.appendChild(inner1);
	win.appendChild(inner2);
	win.appendChild(html);

	document.body.appendChild(win);
	addToZlist(this.element);

	this.show = function() {
		win.style.display = '';
	};

	this.hide = function() {
		win.style.display = 'none';
	};

	this.setContent = function(c) {
		html.innerHTML = c;
	};
	
	this.getHtml = function() {
		return html;
	};
}

function Menu(aleft, atop, aheight) {
	var obj = this;
	var menu = document.createElement('div');

	menu.style.position = 'absolute';
	menu.style.left = aleft;
	menu.style.top = atop;
	menu.style.width = 198;
	menu.style.height = aheight;
	menu.style.display = 'none';

	menu.windowRef = this;
	this.element = menu;

	var top			= getDiv({id:'menutop',className:'menutop',left:0,top:0,width:168,height:81});
	var middle		= getDiv({id:'menumiddle',className:'menumiddle',left:0,top:81,width:168,height:(aheight-81-23)});
	var bottom		= getDiv({id:'menubottom',className:'menubottom',left:0,top:(aheight-23),width:168,height:23});
	var html		= getDiv({id:'html',className:'html',left:12,top:10,width:138,height:(aheight-10-16)});
	html.style.padding = 0;
	html.style.margin = 0;

	menu.appendChild(top);
	menu.appendChild(middle);
	menu.appendChild(bottom);
	menu.appendChild(html);

	document.body.appendChild(menu);
	addToZlist(this.element);

	this.show = function() {
		menu.style.display = '';
	};

	this.hide = function() {
		menu.style.display = 'none';
	};

	this.setContent = function(c) {
		html.innerHTML = c;
	};
}

function closePopup(id) {
	var el = $(id);
	removeFromZlist(el);
	el.remove();
}

function checkOver(el) {
	if (el.getAttribute("selected") == "true") {
		el.className = 'checkOnOver';
	} else {
		el.className = 'checkOver';
	}
}

function checkOut(el) {
	if (el.getAttribute("selected") == "true") {
		el.className = 'checkOn';
	} else {
		el.className = 'check';
	}
}

function checkClick(el) {
	el.setAttribute("selected", el.getAttribute("selected") == "true" ? "false" : "true");
	checkOver(el);
}

function buttonOver(el) {
	el.className = 'buttonOver';
}

function buttonOut(el) {
	el.className = 'button';
}

function buttonDown(el) {
	el.className = 'buttonClick';
}

function buttonUp(el) {
	el.className = 'buttonOver';
}

function editButton(args, el) {
	var argstr = "[";
	for (var x=0; x<args.length; x++) {
		argstr += "{n:\'" + args[x].n + "\',v:\'" + args[x].v + "\'}";
		if (x < args.length-1) argstr += ",";
	}
	argstr += "]";
	return '<td class="editbutton" onmouseover="editOver(this)" onmouseout="editOut(this)" onmousedown="editDown(this)" onmouseup="editUp(this)" onclick="editPopup(' + argstr + ',this)">&nbsp;</td>';
}

function editPopup(args, el) {
	var bbox = getBoundingBox(el);	
	args[args.length] = {n:'cx',v:bbox.bx};
	args[args.length] = {n:'cy',v:bbox.by};
	showPopup(args);
}

function editOver(el) {
	el.className = 'editbuttonOver';
}

function editOut(el) {
	el.className = 'editbutton';
}

function editDown(el) {
	el.className = 'editbuttonClick';
}

function editUp(el) {
	el.className = 'editbuttonOver';
}

function menuOver(el) {
	el.className = 'menuitemOver';
}

function menuOut(el) {
	el.className = 'menuitem';
}

function menuClick(el) {
	eval(el.getAttribute("handler"));
}

function submitPopup(id, action) {
	printfire("submitPopup: " + id + ", " + action);
	var popup = $(id).windowRef;
	
	if (popup.submit) {
		popup.submit(action);
	}
}

function init() {
	oldmousedown = document.onmousedown;
	oldmousemove = document.onmousemove;
	oldmouseup = document.onmouseup;
	
	window.onresize = function() { getPageSize(); };

	dragframe = document.createElement('div');
	dragframe.className = 'dragframe';
	dragframe.style.display = 'none';
	document.body.appendChild(dragframe);
	addToZlist(dragframe);

	showPopup([{n:'action',v:'vfpuPopup'}]);
	getPageSize();
}
