var obj = null;
var topIndex = 1000;
var highestPat = null;			//highest z-Index means active pattern
var indices = 1001;			//starting ID index of newly added pattern images

var beginX, beginY;
var currX, currY;

// *** BROWSER VERSION ***

var agt        = navigator.userAgent.toLowerCase();

// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
var is_major   = parseInt(navigator.appVersion);
var is_minor   = parseFloat(navigator.appVersion);

var is_nav     = (agt.indexOf("mozilla") != -1 && agt.indexOf("msie") == -1);
var is_nav4up  = (is_nav && (is_major >= 4));
var is_nav6up  = (is_nav && (is_major >= 5));
var is_gecko   = (agt.indexOf("gecko") != -1);

var is_ie      = ((agt.indexOf("msie") != -1));
var is_ie4     = (is_ie && (is_major == 4) && (agt.indexOf("msie 4") != -1) );
var is_ie4up   = (is_ie && (is_major >= 4));
var is_ie5up   = (is_ie && (is_major >= 4) && (agt.indexOf("msie 5.0")!= -1) );

var is_mac     = (agt.indexOf("mac") != -1);
var is_win     = ((agt.indexOf("win") != -1) || (agt.indexOf("16bit") != -1));
var is_linux   = (agt.indexOf("linux") != -1);
// *******


function bail(){
	if(is_ie4up) window.event.cancelBubble = true;
	return false;
}

function check(evt){

//alert(is_nav4up) // **********TESTING**********

	if(is_ie4up){
		obj = window.event.srcElement;
		if(obj.parentElement == null) return bail();
		if(obj.parentElement.id.toLowerCase().indexOf("drag") == -1) return bail();

		obj = obj.parentElement;
		obj.style.zIndex = ++topIndex;
		highestPat = obj;

		currX = window.event.clientX + ((is_mac) ? 0 : document.body.scrollLeft);
		currY = window.event.clientY + ((is_mac) ? 0 : document.body.scrollTop);

	}
	else if(is_nav6up){

		obj = evt.target;
		
		//if(what.parentNode) obj = document.getElementById(what.parentNode);
		//these were stopping us from using text boxes on the page
		//if(obj.parentNode == null) return bail();
		//if(obj.parentNode.id.toLowerCase().indexOf("drag") == -1) return bail();
		
		if(obj.parentNode == null) return true;
		if(obj.parentNode.id.toLowerCase().indexOf("drag") == -1) return true;
		

		obj = obj.parentNode;

		obj.style.zIndex = ++topIndex;
		highestPat = obj;

		currX = parseInt(evt.clientX) + parseInt(window.scrollX);
		currY = parseInt(evt.clientY) + parseInt(window.scrollY);

	}
	else if(is_nav4up){

		var currLay = findCorrectNN4Layer(evt);
		if( currLay != null ){

			var zId = currLay.id.toLowerCase();
			/*Horrid NN4 work-around*/
			if(zId.indexOf("drag") == -1 && zId.indexOf("_js_layer") == -1) return false;

			obj = currLay;
			obj.zIndex = ++topIndex;
			highestPat = obj;

			currX = evt.pageX;
			currY = evt.pageY;
		}

		if(evt.which == 0x03){
			makeNew(evt);
			return false;
		}
	}

	if(is_nav4up){
		document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove = drag;
		return false;
	}
}


function drag(evt){

	var newX, newY, deltaX, deltaY;

	if (obj == null) return bail();
	if(is_ie4up){
		newX = window.event.clientX + ((is_mac) ? 0 : document.body.scrollLeft);
		newY = window.event.clientY + ((is_mac) ? 0 : document.body.scrollTop);
	}
	else if(is_nav6up){
		newX = parseInt(evt.clientX) + parseInt(window.scrollX);
		newY = parseInt(evt.clientY) + parseInt(window.scrollY);
	}
	else if(is_nav4up){
		newX = evt.pageX;
		newY = evt.pageY;
	}

	deltaX = newX - currX;
	deltaY = newY - currY;
	currX = newX;
	currY = newY;

	if(is_ie4up){
		if(is_ie4 && window.event.button==0) return restore(evt);
		obj.style.pixelLeft += deltaX;
		obj.style.pixelTop += deltaY;
		event.returnValue = false;
	}
	else if(is_nav6up){
		obj.style.left = (parseInt(obj.style.left) + deltaX + "px");
		obj.style.top  = (parseInt(obj.style.top) + deltaY + "px");
	}
	else if(is_nav4up){
		obj.left += deltaX;
		obj.top  += deltaY;
	}
	return false;
}


function restore(evt){ 

	/*Don't let image accidentally roll off the screen*/
	if(is_ie4up){
		if(highestPat.style.pixelLeft < 0) highestPat.style.pixelLeft = 0;
		if(highestPat.style.pixelTop < 0) highestPat.style.pixelTop = 0;
	}else if(is_nav6up){
		if(parseInt(obj.style.left) < 0) obj.style.left = 0+"px";
		if(parseInt(obj.style.top) < 0) obj.style.top = 0+"px";
	}else if(is_nav4up){

		if(obj==null) return false;

		if(obj.pageX < 0) obj.left = 0;
		if(obj.pageY < 110) obj.top = 110;
	}

	if(is_nav4up){ 
		document.releaseEvents(Event.MOUSEMOVE);
		document.onmousemove = null;  
	}
	obj = null;
	return false;
}


/*Is mouse cursor in the bounds of what object IE only for now*/
function inBoundsOf(what, evt){

	var B = what.style;
	var x, y, bRight, bBottom;

	if(is_nav4up){
		return( (evt.pageX > what.pageX) &&
			(evt.pageX < what.pageX + what.clip.width) &&
			(evt.pageY > what.pageY) &&
			(evt.pageY < what.pageY + what.clip.height) );
	}
	return false;
}

/* sStyles must NOT end with a semi-colon */
/* global vars: highestPat, indices and topIndex are incremented automatically */
function createLayerSyntax(oObj, tTag, iId, eEvents, sStyles, lLeft, tTop){

	var imgSrc = "";
	if(is_ie4up || is_nav6up) imgSrc = oObj.innerHTML;
	
	//alert(imgSrc);

	return	"<" + tTag + " ID=\"" + iId + indices++ + "\" "
			+ eEvents + " STYLE=\"" + sStyles 
			+ "; left:" + lLeft + "px; top:" + tTop + "px;"
			+ "z-Index: " + ++topIndex + "\">"
			+ imgSrc
			//+ createImgSyntax(imgSrc)
			+ "<\/" + tTag + ">";
}

/*oSrc is an img src*/
function createImgSyntax(oSrc){

	return "<IMG SRC=\"" + getImgAttr(oSrc,"SRC")
		+ "\" ALT=\"" + getImgAttr(oSrc,"ALT") + "\">";
}

/*get an img attribute*/
function getImgAttr(oSrc, att){

	var i, delim1, delim2;
	att = att.toUpperCase();

	//IE takes quotes away from ALT	
	if(is_ie4up && att=="ALT"){ delim1 = "="; delim2 = " "; }
	else{ delim1=delim2= "\""; }

	/*make sure we have an IMG tag*/
	if(oSrc.toUpperCase().indexOf("IMG") == -1) return "";
	if((i=oSrc.toUpperCase().indexOf(att)) == -1) return "";

	oSrc = oSrc.substring(i);
	oSrc = oSrc.substring(oSrc.indexOf(delim1)+1);
	oSrc = oSrc.substring(0, oSrc.indexOf(delim2));

	return oSrc;

}

function makeNew(evt){

	var x=0, y=0, tmp = highestPat;
	if(tmp == null) return false; 
	if(is_ie4up){
		var oSrc;
		x = highestPat.style.pixelLeft + 15;
		y = highestPat.style.pixelTop + 15;
		//alert(x);
		//alert(y);

		tmp.outerHTML += createLayerSyntax(highestPat, "DIV", "DRAG", "onDblClick='javascript:makeNew();'", "position:fixed", x, y);

		eval("highestPat = document.all[\"DRAG" + (indices-1) + "\"]");
	}
	else if(is_nav6up){

		x = parseInt(highestPat.style.left) + 15;
		y = parseInt(highestPat.style.top) + 15;
		var newHTML = createLayerSyntax(highestPat, "DIV", "DRAG", "onDblClick='javascript:makeNew()'", "position:fixed", x, y);

		var ran = document.body.ownerDocument.createRange();
		ran.setStartBefore(document.body);
		var parsedHTML = ran.createContextualFragment(newHTML);
		document.documentElement.insertBefore(parsedHTML,document.body);

		eval("obj = highestPat = document.getElementById(\"DRAG" + (indices-1) + "\")");
	}
	else if(is_nav4up){ 

		var newLay = null;
		if(!inBoundsOf(highestPat,evt)) return bail();

		newLay = new Layer(0);
		with(newLay){ 

			document.open();
			//NN4 workaround, can't get embedded layer src
			var phonyImg = "IMG SRC=\"" + highestPat.document.images[0].src + "\"";
			var code = createImgSyntax(phonyImg);

			if(is_mac) code += '\n';

			document.write(code);
			document.close();

			moveTo(highestPat.pageX+15, highestPat.pageY+15);
			visibility="show";
			obj = highestPat = newLay;
			zIndex = ++topIndex;
		}
		giveLayerEvent(newLay);
	}
}

function findCorrectNN4Layer(evt){

	var currLay = null;
	/*Cycle through all layers on page in reverse*/
	for(var i=document.layers.length-1; i>=0; i--){

		currLay = document.layers[i];
		if(inBoundsOf(currLay,evt) && currLay.document.images[0])
			return currLay;
	}
	return null;
}

//NN4 only
function giveLayerEvent(oObj){

	oObj.document.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
	oObj.document.onMouseDown = check;
	oObj.document.onMouseUp = restore;
}

function invokeHandlers(){

	if(is_nav6up) document.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP); 
	if(is_ie4up) document.onmousemove = drag; 

	if(is_nav6up || is_ie4up){
		document.onmousedown = check;
		document.onmouseup   = restore;
	}
	highestPat = document.images[0];

	if(!is_nav6up && is_nav4up)
		for(var i=0; i < document.layers.length; i++) {
			if(document.layers[i].id.toLowerCase().indexOf("drag") != -1){
				giveLayerEvent(document.layers[i]);
			}
		}
}
