// *** SETTINGS ***
var iconCount = 1;
var iconLocMultiplier = 10;
var defaultZIndex = 1000;
var selectedIcon = "";
var lastSelIcon = "";

var startX;
var startY;


// *** FUNCTIONS ***
// icon functions
/*function insertIcon(iconType, iconW, iconH) {
	var sketchCanvas = document.getElementById("sketch_canvas");
	
	// manufacture new icon
	var newIconDiv = document.createElement("div");
	newIconDiv.setAttribute("id", "icon_"+iconCount);
	if(document.all && document.getElementById) newIconDiv.className = iconType; // ie
	else newIconDiv.setAttribute("class", iconType);

	// set position of new icon -- be sure to run through manageBounds() function
	var iconStartLoc = iconCount*iconLocMultiplier;
	newIconDiv.style.top = manageBounds("y", iconStartLoc)+"px";
	newIconDiv.style.left = manageBounds("x", iconStartLoc)+"px";
	
	if(iconW && iconH) {
		newIconDiv.style.width = iconW + "px";
		newIconDiv.style.height = iconH + "px";
	}

	// setup icon event listeners
	if(newIconDiv.addEventListener) { newIconDiv.addEventListener("mousedown", selectIcon, true); newIconDiv.addEventListener("mousedown", iconDragStart, true); }
	else { newIconDiv.attachEvent("onmousedown", selectIcon); newIconDiv.attachEvent("onmousedown", iconDragStart); } // ie
	
	// insert new icon into canvas
	sketchCanvas.appendChild(newIconDiv);
	
	createTracker(iconType, iconStartLoc, iconStartLoc, null, iconW, iconH);
	
	// select new icon
	// selectedIcon = "icon_"+iconCount;
	
	iconCount++; // increment counter
	
	// displayInfo("01", "iconCount: ", iconCount);
}*/

function insertIcon(iconType, classN, posX, posY, iconW, iconH) {
	var sketchCanvas = document.getElementById("sketch_canvas");
	
	// manufacture new icon
	var newIconDiv = document.createElement("div");
	newIconDiv.setAttribute("id", "icon_"+iconCount);
	newIconDiv.style.backgroundImage = "url(images/patches/"+iconType+"_t.gif)";
	if(document.all && document.getElementById) newIconDiv.className = classN; // ie
	else newIconDiv.setAttribute("class", classN);
	
	// set position of new icon -- be sure to run through manageBounds() function
	var iconStartLoc = iconCount*iconLocMultiplier;
	newIconDiv.style.position = "absolute";
	newIconDiv.style.top = posY+"px";
	newIconDiv.style.left = posX+"px";
	
	if(iconW && iconH) {
		newIconDiv.style.width = iconW + "px";
		newIconDiv.style.height = iconH + "px";
	}
	
	// setup icon event listeners
	if(newIconDiv.addEventListener) { newIconDiv.addEventListener("mousedown", selectIcon, true); newIconDiv.addEventListener("mousedown", iconDragStart, true); }
	else { newIconDiv.attachEvent("onmousedown", selectIcon); newIconDiv.attachEvent("onmousedown", iconDragStart); } // ie
	
	// insert new icon into canvas
	sketchCanvas.appendChild(newIconDiv);
	
	patchImage = document.getElementById('icon_'+iconCount);
	patchImage.innerHTML = '<span class="info">'+iconCount+'</span>' + patchImage.innerHTML;
	
	createTracker(iconType, iconStartLoc, iconStartLoc, null, iconW, iconH);
	
	// select new icon
	// selectedIcon = "icon_"+iconCount;
	
	addDragPatch(iconType,iconCount,posX,posY);

	iconCount++; // increment counter
	
	// displayInfo("01", "iconCount: ", iconCount);
}

function insertSelText() {
	
}


function manufactureIcon() {
}

function selectIcon(e) {
	lastSelIcon = selectedIcon;
	
	// var thisIcon = (window.event) ? e.srcElement : e.target;
	var thisIcon = (document.all && document.getElementById) ? e.srcElement : this;
	if(document.all && document.getElementById) var thisIconId = thisIcon.id; // ie
	else var thisIconId = thisIcon.getAttribute("id");
	
	// make sure to keep track of selected icon in global var or hidden field
	selectedIcon = thisIconId;
	
	// once clicked, highlight icon in some way -- add 'icon_selected' css class?
	if(lastSelIcon != "") {
		var lastIcon = document.getElementById(lastSelIcon);
		/*if(lastIcon.className == "road1" || lastIcon.className == "road2")
			lastIcon.style.backgroundColor = "#fff";
		else
			lastIcon.style.backgroundColor = "transparent";*/
		//lastIcon.style.backgroundColor = "green"/*"#fff"*/;
	}
	//thisIcon.style.backgroundColor = "green";/*"#ffc"*/

	// check for child text node -- allow for editing text
	/*
	var textEditArea = document.getElementById("sketch_labels");
	if(thisIcon.hasChildNodes()) // treat as text box for labels
	{
		var iconText = thisIcon.childNodes[0].data;
		var editedLabelText = document.getElementById("label_text_edit");
		editedLabelText.value = iconText;
		textEditArea.style.visibility = "visible"; // enable text editing
	} else {
		textEditArea.style.visibility = "hidden"; // disable text editing (if previously enabled)
	}
	*/
	
	// displayInfo("02", "selectedIcon: ", selectedIcon);
}

function iconDragStart(e) {
	// set initial point coordinates
	var tempX1 = (document.all && document.getElementById) ? e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft : e.clientX;
	var tempY1 = (document.all && document.getElementById) ? e.clientY + document.documentElement.scrollTop + document.body.scrollTop : e.clientY;
	
	startX = tempX1;
	startY = tempY1;

	var selectedIconDiv = document.getElementById(selectedIcon);

	if(document.all) {
		document.attachEvent("onmousemove", moveIcon);
		document.attachEvent("onmouseup", iconDragStop);
	} else {
		document.addEventListener("mousemove", moveIcon, true);
		document.addEventListener("mouseup", iconDragStop, true);
	}
}

function iconDragStop(e) {
	var selectedIconDiv = document.getElementById(selectedIcon);

	if(selectedIconDiv.removeEventListener) {
		document.removeEventListener("mousemove", moveIcon, true);
		document.removeEventListener("mouseup", iconDragStop, true);
	} else {
		document.detachEvent("onmousemove", moveIcon);
		document.detachEvent("onmouseup", iconDragStop);
	}
	
	var iconX = parseInt(selectedIconDiv.style.left);
	var iconY = parseInt(selectedIconDiv.style.top);
	var iconW = parseInt(selectedIconDiv.style.width);
	var iconH = parseInt(selectedIconDiv.style.height);
	
	if (iconX < 0 || iconX > boundsRht-iconW+4 ||
		iconY < 0 || iconY > boundsBtm-iconH+4 )	
	{
		removeIcon();
	}
	else {
		var selectedIconDiv = document.getElementById(selectedIcon);
		var iconX = parseInt(selectedIconDiv.style.left);
		var iconY = parseInt(selectedIconDiv.style.top);
		var dataFieldId = "data_" + selectedIcon.split("_")[1];
		var selectedDataField = document.getElementById(dataFieldId);
		var iconClass = (document.all && document.getElementById ? selectedIconDiv.className : selectedIconDiv.getAttribute("class"));
		updateDragPatch(iconClass,selectedIcon.split("_")[1],iconX,iconY);
	}
}

function moveIcon(e) {
	var selectedIconDiv = document.getElementById(selectedIcon);
	
	var iconX = parseInt(selectedIconDiv.style.left);
	var iconY = parseInt(selectedIconDiv.style.top);
	var iconW = parseInt(selectedIconDiv.style.width);
	var iconH = parseInt(selectedIconDiv.style.height);
	
	tempX1 = startX;
	tempY1 = startY;

	tempX2 = (document.all && document.getElementById) ? e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft : e.clientX;
	tempY2 = (document.all && document.getElementById) ? e.clientY + document.documentElement.scrollTop + document.body.scrollTop : e.clientY;
	
	var newX = iconX + (tempX2 - tempX1);
	var newY = iconY + (tempY2 - tempY1);
		
		selectedIconDiv.style.left = manageBounds("x", newX, iconW+4) + "px";
		selectedIconDiv.style.top = manageBounds("y", newY, iconH+4) + "px";

		updateTracker();

		startX = tempX2;
		startY = tempY2;
	
}

function insertIconText() {
	var selectedIconDiv = document.getElementById(selectedIcon);
	var editedLabelText = document.getElementById("label_text_edit").value;
	
	selectedIconDiv.removeChild(selectedIconDiv.childNodes[0]);
	selectedIconDiv.appendChild(document.createTextNode(editedLabelText));
	
	updateTracker();
}

function removeIcon() {
	if(selectedIcon != "") { // don't attempt if no icon is selected
		var sketchCanvas = document.getElementById("sketch_canvas");
		var selectedIconDiv = document.getElementById(selectedIcon);
		
		//remove session for patch
		var iconClass = (document.all && document.getElementById ? selectedIconDiv.className : selectedIconDiv.getAttribute("class"));
		removeDragPatch(iconClass,selectedIcon.split('_')[1]);
		
		sketchCanvas.removeChild(selectedIconDiv);
		
		removeTracker();
		
		selectedIcon = "";
		
	}
}

// create hidden field that tracks icon info
function createTracker(iconType, iconX, iconY, iconText, iconW, iconH) {
	var dataDiv = document.getElementById("sketch_data");
	
	// create div for icon tracking information
	var newDataDiv = document.createElement("div");
	newDataDiv.setAttribute("id", "patchdata_"+iconCount);
	newDataDiv.setAttribute("class", "patchdata_tracker");
	dataDiv.appendChild(newDataDiv);
	
	var patchData = document.getElementById('patchdata_'+iconCount);

	patchData.innerHTML = '<h4>Patch #'+iconCount+' Instructions:</h4>';
	
	// create field to track icon data for later reproduction
	var newDataField = document.createElement("input");
	newDataField.setAttribute("id", "data_"+iconCount);
	newDataField.setAttribute("name", "sketch_data[]");
	newDataField.setAttribute("type", "hidden");
	newDataField.setAttribute("value", iconType+"|"+iconX+"|"+iconY+"|"+iconText+"|"+iconW+"|"+iconH+"|"+iconCount);
	patchData.appendChild(newDataField);
	
	
	// create field to input instructions for patch
	var patchtype = iconType.split('_')[0];
	if( patchtype=='frontnumber2' || patchtype=='frontnumber4' ) {
		var info = '<input type="text" id="instructions_'+iconCount+'" name="instructions_'+iconCount+'" alt="Details of this award patch (color, style, etc.)." class="ihelp" size="25" onblur="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" />';
		info += '<br />';
		info += '<label for="ballcheck_'+iconCount+'" title="Would you like the zeros in this patch to be replaced with sports balls?" class="lhelp">Use Balls For Zeros:</label> ';
		info += '<input type="checkbox" class="checkbox" id="ballcheck_'+iconCount+'" name="ballcheck_'+iconCount+'" onclick="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" />';
		info += '<br />Ball Type: ';
		info += '<input type="text" id="balltype_'+iconCount+'" name="balltype_'+iconCount+'" alt="If the zeros are to be replaced with balls for this patch, what sports ball would you like them replaced by?" class="ihelp" size="15" onblur="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" />';
		patchData.innerHTML = patchData.innerHTML + info;
	}
	else if ( patchtype=='frontname' ) {
		var info = '<input type="text" id="instructions_'+iconCount+'" name="instructions_'+iconCount+'" alt="Generally the name you would like to appear." class="ihelp" size="25" onblur="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" />';
		patchData.innerHTML = patchData.innerHTML + info;
	}
	else if ( patchtype=='frontaward' ) {
		var info = '<input type="text" id="instructions_'+iconCount+'" name="instructions_'+iconCount+'" alt="Details of this award patch (color, style, etc.)." class="ihelp" size="25" onblur="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" />';
		patchData.innerHTML = patchData.innerHTML + info;
	}
	else if ( patchtype=='letter' ) {
		var info = '<table cellspacing="0" cellpadding="0" border="0">';
		info += '<tr><td>Felt Color</td><td>Thread Color</td></tr>';
		info += '<tr>';
		info += '<td><input type="text" size="12" name="felt_color_'+iconCount+'" alt="Color name for the felt of this swiss insert." class="ihelp" id="felt_color_'+iconCount+'" onblur="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" /></td>'
		info += '<td><input type="text" size="12" name="thread_color_'+iconCount+'" alt="Color name for the thread of this swiss insert." class="ihelp" id="thread_color_'+iconCount+'" onblur="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" /></td>'
		info += '</tr>';
		if( dealer_payment == false ) {
			info += '<tr><td colspan="2">Supplied By:<br />';
			info += '<input type="radio" class="radio" name="patch_supplied_'+iconCount+'" id="patch_supplied_customer_'+iconCount+'" value="customer" onclick="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" /><label for="patch_supplied_customer_'+iconCount+'"> Customer</label>&nbsp;';
			info += '<input type="radio" class="radio" name="patch_supplied_'+iconCount+'" id="patch_supplied_lettermansclub_'+iconCount+'" value="lettermansclub" onclick="updateDragPatchInstructions(\''+iconType+'\',\''+iconCount+'\');" /><label for="patch_supplied_lettermansclub_'+iconCount+'"> Lettermans Club</label>';
			info += '</td></tr>';
		}
		info += '</table>';
		patchData.innerHTML = patchData.innerHTML + info;
	}
	
	formEvents();
}

// store icon data in field - iconType|iconX|iconY|iconText|iconW|iconH
function updateTracker() {
	var selectedIconDiv = document.getElementById(selectedIcon);
	var iconX = parseInt(selectedIconDiv.style.left);
	var iconY = parseInt(selectedIconDiv.style.top);
	var iconW = parseInt(selectedIconDiv.style.width);
	var iconH = parseInt(selectedIconDiv.style.height);

	var dataFieldId = "data_" + selectedIcon.split("_")[1];
	var selectedDataField = document.getElementById(dataFieldId);
	var dataFieldValue = selectedDataField.getAttribute("value");
	var dataArr = dataFieldValue.split("|");
	
	var iconClass = (document.all && document.getElementById ? selectedIconDiv.className : selectedIconDiv.getAttribute("class"));

	dataArr[0] = iconClass;
	dataArr[1] = iconX;
	dataArr[2] = iconY;
	
	// update icon text
	if(selectedIconDiv.hasChildNodes()) {
		var iconText = selectedIconDiv.childNodes[0].data;
		
		dataArr[3] = iconText;
	}
	dataArr[4] = iconW;
	dataArr[5] = iconH;
	
	var newFieldValue = dataArr.join("|");
	selectedDataField.setAttribute("value", newFieldValue);

}

function removeTracker() {
	var dataDiv = document.getElementById("sketch_data");
	var dataFieldId = "patchdata_" + selectedIcon.split("_")[1];
	var selectedDataField = document.getElementById(dataFieldId);
	
	dataDiv.removeChild(selectedDataField);
	
}

function autoManageBounds() {
	var selectedIconDiv = document.getElementById(selectedIcon);
	var iconX = parseInt(selectedIconDiv.style.left);
	var iconY = parseInt(selectedIconDiv.style.top);
	var iconW = parseInt(selectedIconDiv.style.width);
	var iconH = parseInt(selectedIconDiv.style.height);
	
	selectedIconDiv.style.left = manageBounds("x", iconX, iconW);
	selectedIconDiv.style.top = manageBounds("y", iconY, iconH);
}

function manageBounds(axis, locValue, size) {
	var newLocValue;
	
	if(!size) { size = 32; }
	
	switch(axis) {
		case "y": // check y-axis bounds
			/*if(locValue >= boundsTop && (locValue+size) < boundsBtm )*/ { newLocValue = locValue; }
			/*else {
				if(locValue < boundsTop) newLocValue = boundsTop;
				if((locValue+size) >= boundsBtm) newLocValue = boundsBtm-size;
			}*/
			break;

		case "x": // check x-axis bounds
			/*if(locValue >= boundsLft && (locValue+size) < boundsRht )*/ { newLocValue = locValue; }
			/*else {
				if(locValue < boundsLft) newLocValue = boundsLft;
				if((locValue+size) >= boundsRht) newLocValue = boundsRht-size;
			}*/
			break;
	}
	
	return newLocValue;
}

function displayInfo(whichInfoBox, boxText, boxValue) {
	var thisInfo = document.getElementById("info"+whichInfoBox);
	thisInfo.setAttribute("value", boxText+boxValue);
}

function clearCanvas() {
	var sketchCanvas = document.getElementById("sketch_canvas");
	var dataDiv = document.getElementById("sketch_data");

	if(sketchCanvas.hasChildNodes()) {
		do {
			sketchCanvas.removeChild(sketchCanvas.childNodes[0])
			dataDiv.removeChild(dataDiv.childNodes[0])
		}
		while(sketchCanvas.hasChildNodes())
		
		// reset global vars
		iconCount = 1;
		selectedIcon = ""
	
		// displayInfo("01", "iconCount: ", iconCount);
		// displayInfo("02", "selectedIcon: ", selectedIcon);
	}
}

function init() {
	var sketchCanvas = document.getElementById("sketch_canvas");
	var sketchItems = sketchCanvas.getElementsByTagName("div");

	iconCount = sketchItems.length + 1;
	
	for(i=0; i<sketchItems.length; i++) {
		var sketchItem = sketchItems[i];
		
		// setup icon event listeners
		if(sketchItem.addEventListener) { sketchItem.addEventListener("mousedown", selectIcon, true); sketchItem.addEventListener("mousedown", iconDragStart, true); }
		else { sketchItem.attachEvent("onmousedown", selectIcon); sketchItem.attachEvent("onmousedown", iconDragStart); } // ie	
	}
}