var obj = null;
var topIndex = 1000;
var swatchSize = 70;
var topSwatch = null;			//highest z-Index assigned to active swatch
var count_new = 1001;			//starting ID index of newly added swatches

var origX, origY;
var currX, currY;

// *** get browser version ***

var agt        = navigator.userAgent.toLowerCase();
//alert(agt) // display for testing
//alert(navigator.appVersion) // display for testing

// Note: On IE5, ver_major returns 4 (due to mozilla/4.0), so use br_ie5up to detect IE5 or higher.
var ver_major   = parseInt(navigator.appVersion);
var ver_minor   = parseFloat(navigator.appVersion);

var br_netsc     = (agt.indexOf("mozilla") != -1 && agt.indexOf("msie") == -1);
var br_netsc4up  = (br_netsc && (ver_major >= 4));
var br_netsc6up  = (br_netsc && (ver_major >= 5));

var br_ie      = ((agt.indexOf("msie") != -1));
var br_ie4     = (br_ie && (ver_major == 4) && (agt.indexOf("msie 4") != -1) );
var br_ie4up   = (br_ie && (ver_major >= 4));
var br_ie5up   = (br_ie && (ver_major >= 4) && ((agt.indexOf("msie 5")!= -1) || (agt.indexOf("msie 6")!= -1)) );

var br_mac     = (agt.indexOf("mac") != -1);
var br_win     = ((agt.indexOf("win") != -1) || (agt.indexOf("16bit") != -1));
var br_linux   = (agt.indexOf("linux") != -1);

//alert(br_netsc4up) // display version - test

// *******


function quitapp(){
	if(br_ie4up) window.event.cancelBubble = true;
	return false;
}

function check(evt){

	if(br_ie4up){
		obj = window.event.srcElement;
		if(obj.parentElement == null) return quitapp();
		if(obj.parentElement.id.toLowerCase().indexOf("swatch") == -1) return quitapp();

		obj = obj.parentElement;
		obj.style.zIndex = ++topIndex;
		topSwatch = obj;
		origX = obj.style.pixelLeft
		origY = obj.style.pixelTop

		currX = window.event.clientX + ((br_mac) ? 0 : document.body.scrollLeft);
		currY = window.event.clientY + ((br_mac) ? 0 : document.body.scrollTop);

	}
	else if(br_netsc6up){

		obj = evt.target;
		//if(what.parentNode) obj = document.getElementById(what.parentNode);
		if(obj.parentNode == null) return quitapp();
		if(obj.parentNode.id.toLowerCase().indexOf("swatch") == -1) return quitapp();

		obj = obj.parentNode;
		origX = parseInt(obj.style.left)
		origY = parseInt(obj.style.top)

		obj.style.zIndex = ++topIndex;
		topSwatch = obj;

		currX = parseInt(evt.clientX) + parseInt(window.scrollX);
		currY = parseInt(evt.clientY) + parseInt(window.scrollY);

	}
	else if(br_netsc4up){

		var currLay = findCorrectNN4Layer(evt);
		if( currLay != null ){

			var zId = currLay.id.toLowerCase();
			/*Netscape 4.0 work-around*/
			if(zId.indexOf("swatch") == -1 && zId.indexOf("_js_layer") == -1) return false;

			obj = currLay;
			obj.zIndex = ++topIndex;
			topSwatch = obj;
			origX = obj.left
			origY = obj.top

			currX = evt.pageX;
			currY = evt.pageY;
		}

		if(evt.which == 0x03){
			makeNew(evt);
			return false;
		}
	}

	if(br_netsc4up){
		document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove = drag;
		return false;
	}
}

function drag(evt){

	var newX, newY, deltaX, deltaY;

	if (obj == null) return quitapp();
	if(br_ie4up){
		newX = window.event.clientX + ((br_mac) ? 0 : document.body.scrollLeft);
		newY = window.event.clientY + ((br_mac) ? 0 : document.body.scrollTop);
	}
	else if(br_netsc6up){
		newX = parseInt(evt.clientX) + parseInt(window.scrollX);
		newY = parseInt(evt.clientY) + parseInt(window.scrollY);
	}
	else if(br_netsc4up){
		newX = evt.pageX;
		newY = evt.pageY;
	}

	deltaX = newX - currX;
	deltaY = newY - currY;
	currX = newX;
	currY = newY;

	if(br_ie4up){
		if(br_ie4 && window.event.button==0) return restore(evt);
		obj.style.pixelLeft += deltaX;
		obj.style.pixelTop += deltaY;
		event.returnValue = false;
	}
	else if(br_netsc6up){
		obj.style.left = (parseInt(obj.style.left) + deltaX + "px");
		obj.style.top  = (parseInt(obj.style.top) + deltaY + "px");
	}
	else if(br_netsc4up){
		obj.left += deltaX;
		obj.top  += deltaY;
	}
	return false;
}

function restore(evt){ 

	/*Don't let image accidentally roll off the screen*/
	if(br_ie4up){
		if(topSwatch.style.pixelLeft < 0) topSwatch.style.pixelLeft = 0;
		if(topSwatch.style.pixelTop < 0) topSwatch.style.pixelTop = 0;
	}else if(br_netsc6up){
		if(parseInt(obj.style.left) < 0) obj.style.left = 0+"px";
		if(parseInt(obj.style.top) < 0) obj.style.top = 0+"px";
	}else if(br_netsc4up){

		if(obj==null) return false;

		if(obj.pageX < 0) obj.left = 0;
		if(obj.pageY < 0) obj.top = 0;
	}

	/* mod math checks to see if user moved a swatch within the original zone (not perfect, but helps) */
	if (origX >= 20 && origX <= 180 && origX % 20 == 0) makeCopy(evt)

	if(br_netsc4up){ 
		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(br_netsc4up){

		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 */
function createLayerSyntax(oObj, tTag, iId, eEvents, sStyles, lLeft, tTop){

	var imgSrc = "";
	if(br_ie4up || br_netsc6up) imgSrc = oObj.innerHTML;

	return	"<" + tTag + " ID=\"" + iId + count_new++ + "\" "
			+ eEvents + " STYLE=\"" + sStyles 
			+ "; left:" + lLeft + "px; top:" + tTop + "px;"
			+ "z-Index: " + ++topIndex + "\">"
			+ createImgSyntax(imgSrc)
			+ "<\/" + tTag + ">";
}

/*oSrc is an img src*/
function createImgSyntax(oSrc){

	return "<IMG SRC=\"" + getImgAttr(oSrc,"SRC")
		+ "\" border=0 height=" + swatchSize + " width=" + swatchSize + ">";
}

function getImgAttr(oSrc, att){

	var i, delim1, delim2;
	att = att.toUpperCase();

	//IE takes quotes away from ALT	
	if(br_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 makeCopy(evt){

	tmp = topSwatch;
	if(tmp == null) return false;

	if(br_ie4up){
		var oSrc;
		tmp.outerHTML += createLayerSyntax(topSwatch, "DIV", "swatch", "onDblClick='quitapp();'", "position:absolute", origX, origY);

		eval("topSwatch = document.all[\"swatch" + (count_new-1) + "\"]");
		return true;
	}
	else if(br_netsc6up){

		x = parseInt(topSwatch.style.left) + 20;
		y = parseInt(topSwatch.style.top) + 20;
		var newHTML = createLayerSyntax(topSwatch, "DIV", "swatch", "onDblClick='quitapp()'", "position:absolute", origX, origY);

		var ran = document.body.ownerDocument.createRange();
		ran.setStartBefore(document.body);
		var parsedHTML = ran.createContextualFragment(newHTML);
		document.documentElement.insertBefore(parsedHTML,document.body);

		eval("obj = topSwatch = document.getElementById(\"swatch" + (count_new-1) + "\")");
		return true;
	}
	else if(br_netsc4up){ 

		var newLay = null;
		if(!inBoundsOf(topSwatch,evt)) return quitapp();

		newLay = new Layer(0);
		with(newLay){ 

			document.open();
			//Netscape 4.0 workaround, can't get embedded layer src
			var phonyImg = "IMG SRC=\"" + topSwatch.document.images[0].src + "\"";
			var code = createImgSyntax(phonyImg);

			if(br_mac) code += '\n';

			document.write(code);
			document.close();

			moveTo(origX, origY);
			visibility="show";
			obj = topSwatch = newLay;
			zIndex = ++topIndex;
		}
		giveLayerEvent(newLay);
		return true;
	}
}

function findCorrectNet4layer(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;
}

//Netscape4.0 only
function giveLayerEvent(oObj){

	oObj.document.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
	oObj.document.onMouseDown = check;
	oObj.document.onMouseUp = restore;
}

function invokeHandlers(){

	if(br_netsc6up) document.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP); 
	if(br_ie4up) document.onmousemove = drag; 

	if(br_netsc6up || br_ie4up){
		document.onmousedown = check;
		document.onmouseup   = restore;
	}
	topSwatch = document.images[0];

	if(!br_netsc6up && br_netsc4up){
		for(var i=0; i < document.layers.length; i++) {
			if(document.layers[i].id.toLowerCase().indexOf("swatch") != -1){
				giveLayerEvent(document.layers[i]);
			}
		}
	}
}