// VARS
var baseIdx, sideIdx, sizeIdx, positionIdx, colorIdx, categoryIdx, baseIdxi, sideIdxi, sizeIdxi, positionIdxi, colorIdxi, categoryIdxi, product, layerIdx;
var currentLayerHandle = [];
var currentActivity = {};
var drawingWidth = 300;
var drawingHeight = 384;
var potentialWidth;
var potentialHeight;
var potentialX;
var potentialY;
var viewportWidth = 0;
var currentState = "inactive";

// TIMER FUNCTIONS
var renderTimer = null;
var textTimer = null;
var textTimerTick = 0;
var textTimerGuid = "";
var renderTick = 0;
var renderLevel = 0;
var renderImage = new Image();
var renderImageURL = "";
var validTick = "";

// INITIALIZE
Event.observe(window, 'load', initializeCosmo);
Event.observe(window, 'resize', resizeCosmo);

// BROWSER EVENTS
function initializeCosmo()
{
    // Index apparel
    baseIdx = idx(productBase);
    sideIdx = idx(productSides);
    sizeIdx = idx(productSize);
    positionIdx = idx(productPositions);
    colorIdx = idx(productColor);
    categoryIdx = idx(productCategory);   

    baseIdxi = idxi(productBase);
    sideIdxi = idxi(productSides);
    sizeIdxi = idxi(productSize);
    positionIdxi = idxi(productPositions);
    colorIdxi = idxi(productColor);
    categoryIdxi = idxi(productCategory);   
    
    // Defaults
    product = {};
    product["color"] = "natural";
    product["category"] = "mens_organic_tee";
    product["preview_side"] = "front";
    product["link_apparel_base"] = "11";
    product["current_layer"] = "";
    product["layers"] = [];
    layerIdx = {};
    
    
    Event.observe($('div_writable'), 'mousedown', writableMouseDown);
    Event.observe($('img_background'), 'mousedown', backgroundMouseDown);
    
    // See if we have an incoming product
    if ((window.location.hash != "") && (window.location.hash != "#"))
    {    
        var id = window.location.hash;
        if (id.startsWith("#")) id = id.substring(1);
        cosmoService("product_load",{"product":id},serviceResultProductLoad);
    }
    else
    {
        observeHandles();
        redrawSurface();
        initializeTimer();    
        initializeTextTimer();
    }
}
function resizeCosmo()
{
    if (viewportWidth != document.viewport.getWidth())
    {
        viewportWidth = document.viewport.getWidth();
        redrawSurface();
    }
}
function serviceResultProductLoad(transport, json)
{
    var m = eval("(" + transport.responseText + ")");
    if (m.status == "success")
    {
        if (m.object["product"]["color"])
        	product["color"] = m.object["product"]["color"];
        if (m.object["product"]["category"])
        	product["category"] = m.object["product"]["category"];
        product["preview_side"] = "front";
        product["layers"] = [];
        
        for (var k = 0; k < m.object.layers.length; k++)
        {
            var layer = m.object.layers[k];
            if (layer["type"] == "text")
            {
                appendText(layer);
            }
            else
            {
                appendImage(layer);
            }
        }
    }
    observeHandles();
    redrawSurface();
    initializeTimer(); 
    initializeTextTimer();
}

// UI EVENTS
function setCategoryColor(category, color)
{
    product["category"] = category;
    product["color"] = color;
    hideApparelMenuAlt();
    activateTimer();
    redrawSurface();
}
function selectCategory()
{ 
    product["category"] = $('select_category').options[$('select_category').selectedIndex].value;
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function selectColor()
{
    product["color"] = $('select_color').options[$('select_color').selectedIndex].value;
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function selectSide(apiSide)
{
    product["preview_side"] = apiSide;
    product["current_layer"] = "";
    hideHandles();
    
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function uploadText(guid)
{
    if (guid == "")
    {
        $('form_text').submit();       
        $('form_text').reset();
    }
    else
    {
        $(guid + '_form_text').submit();       
    }
}
function appendText(layer)
{
    // Add layer info
    if (!layer["side"])
	    layer["side"] = product["preview_side"];

    // Append layer
    product["layers"].push(layer);
    layerIdx[layer["guid"]] = product["layers"].length - 1;
    
    // Create image
    var singleImg = document.createElement("img");
    singleImg.src = layer["image"];
    singleImg.id = layer["guid"];
    singleImg.style.display = "none";
    singleImg.style.cursor = "move";
    singleImg.style.position = "absolute";
    singleImg.style.zIndex = 100 + product["layers"].length * 2 + 3;
    $('box').appendChild(singleImg);    

    // Create inactive image
    var blankImg = document.createElement("img");
    blankImg.src = "/images/spacer.gif";
    blankImg.id = layer["guid"] + "_spacer";
    blankImg.style.cursor = "move";
    blankImg.style.position = "absolute";
    blankImg.style.zIndex = 100 + product["layers"].length * 2 + 2;
    blankImg.style.visibility = "hidden";
    $('box').appendChild(blankImg); 
    
    // Observe image
    Event.observe(blankImg, 'mousedown', blankMousedown);
    Event.observe(blankImg, 'dblclick', blankDblclick);
    Event.observe(singleImg, 'mousedown', previewMousedown);
    Event.observe(singleImg, 'dblclick', previewDblclick);    
        
    // Update iframe
    $('iframe_upload').src = "about:blank";
    
    // Refresh screen
    currentState = "active";
    activateTimer();
    redrawSurface();
}

function initializeTextTimer()
{
    textTimer = setTimeout("textTimerUpdate()", 600);
}
function activateTextTimer(guid)
{   
    var lastTick = new Date().getTime();
    textTimerGuid = guid;
    textTimerTick = lastTick + 600;
}    
function deactivateTimer()
{
    textTimerTick = 0;    
    textTimerGuid = "";
}
function textTimerUpdate()
{
    var lastTick = new Date().getTime();
    if ((textTimerTick > 0) && (lastTick > textTimerTick) && (textTimerGuid != "") && (product["current_layer"] == textTimerGuid))
    {
    	uploadText(textTimerGuid);
    	textTimerTick = 0;
    }
    textTimer = setTimeout("textTimerUpdate()", 600);
}

function updateText(layer)
{
    // Add layer info
    layer["side"] = product["preview_side"];
    $(layer["guid"]).src = layer["image"];

    // Save positioning
    layer["position_x"] = product["layers"][layerIdx[layer["guid"]]]["position_x"];
    layer["position_y"] = product["layers"][layerIdx[layer["guid"]]]["position_y"];
    layer["position_width"] = product["layers"][layerIdx[layer["guid"]]]["position_width"];
    layer["position_height"] = 100;//product["layers"][layerIdx[layer["guid"]]]["position_height"];
    product["layers"][layerIdx[layer["guid"]]] = layer;
	
    // Update iframe
    $('iframe_upload').src = "about:blank";
    
    // Refresh screen
    currentState = "active";
    activateTimer();
    redrawSurfaceLight();
}
function uploadImage()
{
    // Submit form
    $('form_upload').submit();    
    
    // Start timer
    startRetrieveTimer();
    
    $('form_upload').reset();
}
function appendImage(layer)
{
	if (layer["guid"])
	{
		// Add layer info
		if (!layer["side"])
			layer["side"] = product["preview_side"];

		// Append layer
		product["layers"].push(layer);
		layerIdx[layer["guid"]] = product["layers"].length - 1;

		// Create image
		var singleImg = document.createElement("img");
		singleImg.src = layer["image"];
		singleImg.id = layer["guid"];
		singleImg.style.display = "none";
		singleImg.style.cursor = "move";
		singleImg.style.position = "absolute";
		singleImg.style.zIndex = 100 + product["layers"].length * 2 + 3;
		$('box').appendChild(singleImg);    

		// Create inactive image
		var blankImg = document.createElement("img");
		blankImg.src = "/images/spacer.gif";
		blankImg.id = layer["guid"] + "_spacer";
		blankImg.style.cursor = "move";
		blankImg.style.position = "absolute";
		blankImg.style.zIndex = 100 + product["layers"].length * 2 + 2;
		blankImg.style.visibility = "hidden";
		$('box').appendChild(blankImg);

		// Observe image
		Event.observe(blankImg, 'mousedown', blankMousedown);
		Event.observe(blankImg, 'dblclick', blankDblclick);
		Event.observe(singleImg, 'mousedown', previewMousedown);
		Event.observe(singleImg, 'dblclick', previewDblclick);    

		// Update iframe
		$('iframe_upload').src = "about:blank";
		product["current_layer"] = layer["guid"];

		// Refresh screen
		currentState = "active";
		activateTimer();
		redrawSurface();
	}
}

function selectLayer(guid)
{
    product["current_layer"] = guid;
    product["preview_side"] = product["layers"][layerIdx[guid]]["side"];
    currentState = "active";
    activateTimer();
    redrawSurface();
    renderHandles(product["current_layer"]);
}
function changeLayerSide(guid, side)
{
    product["layers"][layerIdx[guid]]["side"] = side;
    product["preview_side"] = side;
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function centerLayer(guid)
{
    product["layers"][layerIdx[guid]]["position_x"] = 15;
    product["layers"][layerIdx[guid]]["position_y"] = 10;
    product["layers"][layerIdx[guid]]["position_width"] = 70;
    product["layers"][layerIdx[guid]]["position_height"] = 80;
    
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function removeLayer(guid)
{
    // Remove child image
    $('box').removeChild($(guid));
    $('box').removeChild($(guid + "_spacer"));
    
    // Find layer
    for (var k = 0; k < product["layers"].length; k++)
    {
        if (product["layers"][k]["guid"] == guid)
        {
            var removed = product["layers"].splice(k, 1);
            break;
        }
    }
    if (product["layers"].length > 0)
        product["current_layer"] = product["layers"][0]["guid"];
    else
        hideHandles();
    
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function setTextColor(guid, color)
{
    if (guid == "")
    {
        $("color").value = color;
        $("color_sample").style.backgroundColor = color;
    }
    else
    {
        $(guid + "_color").value = color;
        $(guid + "_color_sample").style.backgroundColor = color;
        uploadText(guid);
    }
}



// SCREEN UPDATES
function isNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
	        IsNumber = false;
   }
   return IsNumber;
}
function strippedProductJSON()
{
	var clonedJSON = Object.toJSON(product);
	eval("var cloned = " + clonedJSON);
	
	if (cloned["current_layer"]) delete cloned["current_layer"];
	for (var k = 0; k < cloned["layers"].length; k++)
	{
		if (cloned["layers"][k]["filename"]) delete cloned["layers"][k]["filename"];
		if (cloned["layers"][k]["image"]) delete cloned["layers"][k]["image"];
		if (cloned["layers"][k]["image_navigation"]) delete cloned["layers"][k]["image_navigation"];
		if (cloned["layers"][k]["image_width"]) delete cloned["layers"][k]["image_width"];
		if (cloned["layers"][k]["image_height"]) delete cloned["layers"][k]["image_height"];
		if (cloned["layers"][k]["position_halign"]) delete cloned["layers"][k]["position_halign"];
		if (cloned["layers"][k]["position_valign"]) delete cloned["layers"][k]["position_valign"];
		if (cloned["layers"][k]["text_align"]) delete cloned["layers"][k]["text_align"];
		
		if (cloned["layers"][k]["color_r"]) delete cloned["layers"][k]["color_r"];
		if (cloned["layers"][k]["color_g"]) delete cloned["layers"][k]["color_g"];
		if (cloned["layers"][k]["color_b"]) delete cloned["layers"][k]["color_b"];		
		
		if (cloned["layers"][k]["position_x"] && isNumeric(cloned["layers"][k]["position_x"])) cloned["layers"][k]["position_x"] = parseFloat(cloned["layers"][k]["position_x"]).toFixed(2);
		if (cloned["layers"][k]["position_y"] && isNumeric(cloned["layers"][k]["position_y"])) cloned["layers"][k]["position_y"] = parseFloat(cloned["layers"][k]["position_y"]).toFixed(2);
		if (cloned["layers"][k]["position_width"] && isNumeric(cloned["layers"][k]["position_width"])) cloned["layers"][k]["position_width"] = parseFloat(cloned["layers"][k]["position_width"]).toFixed(2);
		if (cloned["layers"][k]["position_height"] && isNumeric(cloned["layers"][k]["position_height"])) cloned["layers"][k]["position_height"] = parseFloat(cloned["layers"][k]["position_height"]).toFixed(2);
		
	}

	var uri = encodeURIComponent(Object.toJSON(cloned));
	return uri;
}
function displayError(error)
{
	
}
function debugAlt(msg)
{
	$('msg2').innerHTML = msg;
}
function debugProduct()
{
    var msg = Object.toJSON(product);
    $('msg_link').innerHTML = "<a href='/image3.php?full_product=" + strippedProductJSON() + "'>" + "image link" + "</a>";
    debugAll(msg);
}
function redrawSurface()
{    
    fillCategorySelection();
    fillColorSelection();
    fillProductBase();
    fillSideSelection();
    fillSizeSelection();
    
    fillLayers();
    fillBackground();
    setAjaxLocation();
    
    drawDrawingBorder();
    
    debugProduct();
    
    if (currentState == "active")
        drawActiveSurface();
    else
        drawInactiveSurface();        
}
function redrawSurfaceLight()
{    
    fillBackground();    
    setAjaxLocation();
    drawDrawingBorder();    
    debugProduct();
    
    if (currentState == "active")
        drawActiveSurface();
    else
        drawInactiveSurface();        
}
function setAjaxLocation()
{
	var position = Position.cumulativeOffset($('box'));
	$('ajax_loader').style.left = (position[0] + 279) + "px";
	$('ajax_loader').style.top = (position[1] + 5) + "px";
}
function drawActiveSurface()
{
    validTick = "";
    $("div_foreground").style.display = "none";    
    $("div_foreground").innerHTML = "";
    displayActiveImages();
}
function drawInactiveSurface()
{
    $("div_foreground").style.display = "block";
    var position = Position.cumulativeOffset($('box'));
    $("div_foreground").style.left = position[0] + "px";
    $("div_foreground").style.top = position[1] + "px";
    displayInactiveImages();
}

function displayActiveImages()
{
    var position = Position.cumulativeOffset($('box'));
    var sideId = 0;
    for (var k = 0; k < baseIdxi[product["link_apparel_base"]][7].length; k++)
    {
        sideId = baseIdxi[product["link_apparel_base"]][7][k];
        if (sideIdxi[sideId][1] == product["preview_side"])
            break;
    }    
    for (var k = 0; k < product["layers"].length; k++)
    {
        var layer = product["layers"][k];
        $(layer["guid"] + "_spacer").style.display = "none";
        if (layer["side"] == product["preview_side"])
        {                   
            if ((!layer["position_width"]) || (!layer["position_height"]))
            {
                layer["position_halign"] = "center";
                layer["position_valign"] = "top";
                layer["position_x"] = 15;
                layer["position_y"] = 10;
                layer["position_width"] = 70;
                layer["position_height"] = 80;
            }

            var sideRealX = ((sideIdxi[sideId][5] / 100) * drawingWidth);
            var sideRealY = ((sideIdxi[sideId][6] / 100) * drawingHeight);
            var sideRealWidth = ((sideIdxi[sideId][7] / 100) * drawingWidth);
            var sideRealHeight = ((sideIdxi[sideId][8] / 100) * drawingHeight);

            // How much space can our position take up.
            var positionRealX = (layer["position_x"] / 100) * sideRealWidth;
            var positionRealY = (layer["position_y"] / 100) * sideRealHeight;
            var positionRealWidth = (layer["position_width"] / 100) * sideRealWidth;
            var positionRealHeight = (layer["position_height"] / 100) * sideRealHeight;

            // Figure out real position
            var position_ratio = positionRealWidth / positionRealHeight;
            var image_ratio = layer["image_width"] / layer["image_height"];

            // Figure out how big our image will be.
            var imageRealWidth = 0;
            var imageRealHeight = 0;
            var imageRealX = 0;
            var imageRealY = 0;

            if (image_ratio > position_ratio) // original is wider than new
            {
                imageRealWidth = positionRealWidth;
                imageRealHeight = positionRealWidth / image_ratio;
            }
            else
            {
                imageRealWidth = positionRealHeight * image_ratio;
                imageRealHeight = positionRealHeight;
            }

            // Depending on alignment, where should it go?
            if ((layer["position_halign"]) && (layer["position_halign"] == "left"))
            {
                imageRealX = sideRealX + positionRealX;
            }
            else if ((layer["position_halign"]) && (layer["position_halign"] == "right"))
            {
                imageRealX = sideRealX + positionRealX + positionRealWidth - imageRealWidth;
            }
            else
            {
                imageRealX = sideRealX + positionRealX + (positionRealWidth - imageRealWidth) / 2;
            }

            // Vertical
            if ((layer["position_valign"]) && (layer["position_valign"] == "middle"))
            {
                imageRealY = sideRealY + positionRealY + (positionRealHeight - imageRealHeight) / 2;
            }
            else if ((layer["position_valign"]) && (layer["position_valign"] == "bottom"))
            {
                imageRealY = sideRealY + positionRealY + positionRealHeight - imageRealHeight;
            }
            else
            {
                imageRealY = sideRealY + positionRealY;
            }                

            // IF CURRENT LAYER, SELECT IT
            var layerImg = $(layer["guid"]);
            layerImg.style.left = px(position[0] + Math.round(imageRealX));
            layerImg.style.top = px(position[1] + Math.round(imageRealY));
            layerImg.style.width = px(Math.round(imageRealWidth));
            layerImg.style.height = px(Math.round(imageRealHeight));
            layerImg.style.display = "";
            layerImg.style.visibility = "visible";

            if (layer["guid"] == product["current_layer"])
                renderHandles(layer["guid"]);
        }
        else
        {
            $(layer["guid"]).style.visibility = "hidden"; 
        }
    }    
}

function displayInactiveImages()
{
    var position = Position.cumulativeOffset($('box'));
    var sideId = 0;
    
    // What side
    for (var k = 0; k < baseIdxi[product["link_apparel_base"]][7].length; k++)
    {
        sideId = baseIdxi[product["link_apparel_base"]][7][k];
        if (sideIdxi[sideId][1] == product["preview_side"])
            break;
    }    
    
    // Hide all real images
    for (var k = 0; k < product["layers"].length; k++)
    {
        var layer = product["layers"][k];
        $(layer["guid"]).style.display = "none";
    }    
    
    // Position spacers
    for (var k = 0; k < product["layers"].length; k++)
    {
        var layer = product["layers"][k];
        if (layer["side"] == product["preview_side"])
        {                   
            if ((layer["position_width"]) && (layer["position_height"]))
            {

            }
            else
            {
                layer["position_halign"] = "center";
                layer["position_valign"] = "top";
                layer["position_x"] = 10;
                layer["position_y"] = 10;
                layer["position_width"] = 80;
                layer["position_height"] = 60;
            }

            var sideRealX = ((sideIdxi[sideId][5] / 100) * drawingWidth);
            var sideRealY = ((sideIdxi[sideId][6] / 100) * drawingHeight);
            var sideRealWidth = ((sideIdxi[sideId][7] / 100) * drawingWidth);
            var sideRealHeight = ((sideIdxi[sideId][8] / 100) * drawingHeight);

            // How much space can our position take up.
            var positionRealX = (layer["position_x"] / 100) * sideRealWidth;
            var positionRealY = (layer["position_y"] / 100) * sideRealHeight;
            var positionRealWidth = (layer["position_width"] / 100) * sideRealWidth;
            var positionRealHeight = (layer["position_height"] / 100) * sideRealHeight;

            // Figure out real position
            var position_ratio = positionRealWidth / positionRealHeight;
            var image_ratio = layer["image_width"] / layer["image_height"];

            // Figure out how big our image will be.
            var imageRealWidth = 0;
            var imageRealHeight = 0;
            var imageRealX = 0;
            var imageRealY = 0;

            if (image_ratio > position_ratio) // original is wider than new
            {
                imageRealWidth = positionRealWidth;
                imageRealHeight = positionRealWidth / image_ratio;
            }
            else
            {
                imageRealWidth = positionRealHeight * image_ratio;
                imageRealHeight = positionRealHeight;
            }

            // Depending on alignment, where should it go?
            if ((layer["position_halign"]) && (layer["position_halign"] == "left"))
            {
                imageRealX = sideRealX + positionRealX;
            }
            else if ((layer["position_halign"]) && (layer["position_halign"] == "right"))
            {
                imageRealX = sideRealX + positionRealX + positionRealWidth - imageRealWidth;
            }
            else
            {
                imageRealX = sideRealX + positionRealX + (positionRealWidth - imageRealWidth) / 2;
            }

            // Vertical
            if ((layer["position_valign"]) && (layer["position_valign"] == "middle"))
            {
                imageRealY = sideRealY + positionRealY + (positionRealHeight - imageRealHeight) / 2;
            }
            else if ((layer["position_valign"]) && (layer["position_valign"] == "bottom"))
            {
                imageRealY = sideRealY + positionRealY + positionRealHeight - imageRealHeight;
            }
            else
            {
                imageRealY = sideRealY + positionRealY;
            }                

            // IF CURRENT LAYER, SELECT IT
            var layerImg = $(layer["guid"] + "_spacer");
            layerImg.style.left = px(position[0] + Math.floor(imageRealX));
            layerImg.style.top = px(position[1] + Math.floor(imageRealY));
            layerImg.style.width = px(Math.floor(imageRealWidth));
            layerImg.style.height = px(Math.floor(imageRealHeight));
            layerImg.style.display = "";
            layerImg.style.visibility = "visible";

            if (layer["guid"] == product["current_layer"])
                renderHandles(layer["guid"] + "_spacer");
        }
        else
        {
            $(layer["guid"]).style.visibility = "hidden";
        }
    }    
}
function fillCategorySelection()
{
    // Find all possible values
    var categoryUsed = {};
    for (var k = 0; k < productBase.length; k++)
    {
        categoryUsed[productBase[k][5]] = true;
    }
    
    // Clear current dropdown
    $("select_category").options.length = 0;

    // Loop through all categories
    optionCount = 0;
    //$('select_category').options[0] = new Option("select ", "");
    for (var k = 0; k < productCategory.length; k++)
    {
        if (categoryUsed[productCategory[k][0]])
        {
            $('select_category').options[optionCount] = new Option(productCategory[k][2], productCategory[k][1]);

            if (product["category"] == productCategory[k][1])
                $('select_category').selectedIndex = optionCount;

            optionCount++;
        }
    }
}
function fillColorSelection()
{
    // What is the current category value
    var currentCategory = $('select_category').options[$('select_category').selectedIndex].value;
    var currentCategoryId = categoryIdx[currentCategory][0];
    var matchFound = 0;
    
    // Find all possible values
    var colorUsed = {};
    for (var k = 0; k < productBase.length; k++)
    {
        if (productBase[k][5] == currentCategoryId)
            colorUsed[productBase[k][4]] = true;
    }

    // Clear current dropdown
    $("select_color").options.length = 0;

    // Loop through all categories
    optionCount = 0;
    for (var k = 0; k < productColor.length; k++)
    {
        if (colorUsed[productColor[k][0]])
        {
            $('select_color').options[optionCount] = new Option(productColor[k][2], productColor[k][1]);
            if (product["color"] == productColor[k][1])
            {
                $('select_color').selectedIndex = optionCount;
                matchFound = 1;
            }
            optionCount++;
        }
    }
    if (matchFound == 0)
        product["color"] = $('select_color').options[$('select_color').selectedIndex].value;
}
function fillProductBase()
{
    var currentCategoryId = categoryIdx[product["category"]][0];
    var currentColorId = colorIdx[product["color"]][0];
    for (var k = 0; k < productBase.length; k++)
    {
        if ((productBase[k][5] == currentCategoryId) && (productBase[k][4] == currentColorId))
        {
            product["link_apparel_base"] = productBase[k][0];
            if ($("span_price"))
            {
            	// How many sides? 
            	var hasFront = false;
            	var hasReverse = false;
				for (var m = 0; m < product["layers"].length; m++)
				{
					var layer = product["layers"][m];
					if (layer["side"] == "front")
						hasFront = true;
					if (layer["side"] == "reverse")
						hasReverse = true;
				}            
				if (hasFront && hasReverse)
            		$("span_price").innerHTML = ("$" + (parseFloat(productBase[k][3]) + 3).toFixed(2));
            	else
            		$("span_price").innerHTML = ("$" + (parseFloat(productBase[k][3])).toFixed(2));
			}
            return;
        }
    }
    product["link_apparel_base"] = 0;
}
function fillSideSelection()
{
    var sidesText = "";
    // Loop through all sides
    for (var k = 0; k < baseIdxi[product["link_apparel_base"]][7].length; k++)
    {
        var s = baseIdxi[product["link_apparel_base"]][7][k];
        if (sidesText != "")
            sidesText += ", ";
        sidesText += "<a href='javascript:selectSide(\"" + sideIdxi[s][1] + "\");'>" + sideIdxi[s][4] + "</a>"
    }
    $('side_wrapper').innerHTML = "View " + sidesText;
}
function fillSizeSelection()
{
    var sizesText = "";
    // Loop through all sides
    for (var k = 0; k < baseIdxi[product["link_apparel_base"]][6].length; k++)
    {
        var s = baseIdxi[product["link_apparel_base"]][6][k];
        sizesText += "<div style='font-size: 11px; padding-top: 2px;'><input size='2' name='quantity_" + sizeIdxi[s][1] + "' id='quantity_" + sizeIdxi[s][1] + "'> " + sizeIdxi[s][2] + "</div>"
    }
    $('size_wrapper').innerHTML = sizesText;
}
function fillLayers()
{
    var layerText = "";
    for (var k = 0; k < product["layers"].length; k++)
    {
        var layer = product["layers"][k];
        if (layer["type"] == "text")
        {
            if (product["current_layer"] == layer["guid"])
            {
                var thisLayer = $("template_text").innerHTML + "";
                
                if (layer["side"] == "reverse")
                    thisLayer = thisLayer.replace(/DISPLAY/g, "Move to <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"front\");'>Front</a> ");
                else
                    thisLayer = thisLayer.replace(/DISPLAY/g, "Move to <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"reverse\");'>Reverse</a>");
                thisLayer = thisLayer.replace(/TITLE/g, layer["filename"]);
                thisLayer = thisLayer.replace(/GUID/g, layer["guid"]);
                thisLayer = thisLayer.replace(/LAYERTEXT/g, layer["text"]);
                thisLayer = thisLayer.replace(/CYAN/g, "#" + layer["color"]);
                thisLayer = thisLayer.replace("\"" + layer["font_family"] + "\"", "\"" + layer["font_family"] + "\" selected");
                layerText += thisLayer;
            }
            else
            {
                var thisLayer = $("template_text_off").innerHTML + "";
                if (layer["side"] == "reverse")
                    thisLayer = thisLayer.replace(/DISPLAY/g, "Move to <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"front\");'>Front</a> ");
                else
                    thisLayer = thisLayer.replace(/DISPLAY/g, "Move to <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"reverse\");'>Reverse</a>");
                thisLayer = thisLayer.replace(/TITLE/g, layer["filename"]);
                thisLayer = thisLayer.replace(/GUID/g, layer["guid"]);
                thisLayer = thisLayer.replace(/LAYERTEXT/g, layer["text"]);
                thisLayer = thisLayer.replace(/CYAN/g, "#" + layer["color"]);
                thisLayer = thisLayer.replace("\"" + layer["font_family"] + "\"", "\"" + layer["font_family"] + "\" selected");
                layerText += thisLayer;
            }
        }
        else
        {
            var thisLayer = $("template_image").innerHTML + "";
            thisLayer = thisLayer.replace(/IMAGE_URL/g, layer["image_navigation"]);
            //thisLayer = thisLayer.replace(/DISPLAY/g, "Show on <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"front\");'>Front</a>, <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"reverse\");'>Reverse</a>");
			if (layer["side"] == "reverse")
				thisLayer = thisLayer.replace(/DISPLAY/g, "Move to <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"front\");'>Front</a> ");
			else
				thisLayer = thisLayer.replace(/DISPLAY/g, "Move to <a href='javascript:changeLayerSide(\"" + layer["guid"] + "\",\"reverse\");'>Reverse</a>");
            
            thisLayer = thisLayer.replace(/TITLE/g, layer["filename"]);
            thisLayer = thisLayer.replace(/GUID/g, layer["guid"]);
            layerText += thisLayer;
        }        
    }
    if (product["layers"].length == 0)
    {
        $("layers_none").style.display = "block";
    }
    else
    {
        $("layers_none").style.display = "none";
    }
    
    $("layers").innerHTML = layerText;
}

function fillBackground()
{
    var sideUrl = "";
    var currentUrl = $("img_background").src + "";
    currentUrl = currentUrl.replace(/https?\:\/\/www\.skreened\.com/,"").replace(/https?\:\/\/skreened\.com/,"");
    
    // Figure out side    
    for (var k = 0; k < baseIdxi[product["link_apparel_base"]][7].length; k++)
    {
        var sideId = baseIdxi[product["link_apparel_base"]][7][k];
        if ((sideIdxi[sideId][1] == product["preview_side"]) || (sideUrl == ""))
        {
            sideUrl = "/apparel/" + sideIdxi[sideId][9];
            if (sideIdxi[sideId][1] == product["preview_side"])
                break;
        }
    }    
    if (currentUrl != sideUrl)
    {
        Event.observe($("img_background"), 'load', fillBackgroundLoaded);
        startLoadingGraphic("fillBackground");
        $("img_background").src = sideUrl;        
    }
}
function fillBackgroundLoaded()
{
    cancelAllLoadingGraphic();
    Event.stopObserving($("img_background"), 'load', fillBackgroundLoaded);
}

var writableX = 0;
var writableY = 0;
var writableWidth = 0;
var writableHeight = 0;
    
function drawDrawingBorder()
{
    var writable = $('div_writable');
    var position = Position.cumulativeOffset($('box'));
    var dimensions = Element.getDimensions($('box'));

    var sideId = 0;
    for (var k = 0; k < baseIdxi[product["link_apparel_base"]][7].length; k++)
    {
        sideId = baseIdxi[product["link_apparel_base"]][7][k];
        if (sideIdxi[sideId][1] == product["preview_side"])
            break;
    }

    writableX = sideIdxi[sideId][5];
    writableY = sideIdxi[sideId][6];
    writableWidth = sideIdxi[sideId][7];
    writableHeight = sideIdxi[sideId][8];

    writable.style.left = px(position[0] + Math.round((writableX / 100) * drawingWidth));
    writable.style.top = px(position[1] + Math.round((writableY / 100) * drawingHeight));
    writable.style.width = px(Math.round((writableWidth / 100) * drawingWidth));
    writable.style.height = px(Math.round((writableHeight / 100) * drawingHeight));    
}

// HANDLES
function renderHandles(guid)
{
    var fullOffset = Position.cumulativeOffset($(guid));
    var fullSize = Element.getDimensions($(guid));

    if (fullOffset[0] > 0)
    {
        $('handle_topleft').style.display = "block";
        $('handle_topright').style.display = "block";
        $('handle_bottomright').style.display = "block";
        $('handle_bottomleft').style.display = "block";

        $('handle_topleft').style.left = px(fullOffset[0]);
        $('handle_topleft').style.top = px(fullOffset[1]);

        $('handle_bottomright').style.left = px(fullOffset[0] + fullSize['width'] - 8);
        $('handle_bottomright').style.top = px(fullOffset[1] + fullSize['height'] - 8);

        $('handle_topright').style.top = px(fullOffset[1]);
        $('handle_topright').style.left = px(fullOffset[0] + fullSize['width'] - 8);

        $('handle_bottomleft').style.left = px(fullOffset[0]);
        $('handle_bottomleft').style.top = px(fullOffset[1] + fullSize['height'] - 8);
    }
} 
function hideHandles()
{
    $('handle_topleft').style.display = "none";
    $('handle_topright').style.display = "none";
    $('handle_bottomright').style.display = "none";
    $('handle_bottomleft').style.display = "none";    
}
function observeHandles()
{
    Event.observe($('handle_topleft'), 'drag', function() {return false;}, false);
    Event.observe($('handle_topleft'), 'mousedown', handleTopLeftMousedown, false);

    Event.observe($('handle_topright'), 'drag', function() {return false;}, false);
    Event.observe($('handle_topright'), 'mousedown', handleTopRightMousedown, false);

    Event.observe($('handle_bottomleft'), 'drag', function() {return false;}, false);
    Event.observe($('handle_bottomleft'), 'mousedown', handleBottomLeftMousedown, false);

    Event.observe($('handle_bottomright'), 'drag', function() {return false;}, false);
    Event.observe($('handle_bottomright'), 'mousedown', handleBottomRightMousedown, false);
}    


var startOffsetX = 0;
var startOffsetY = 0;

var imageOffsetX = 0;
var imageOffsetY = 0;
var imageOffsetWidth = 0;
var imageOffsetHeight = 0;

// TOP LEFT HANDLE
function handleTopLeftMousedown(evt)
{
    currentState = "active";
    validTick = "";
	redrawSurfaceLight();
        
    // Set starting points
    var contentPosition = Position.cumulativeOffset($(product["current_layer"]));
    var contentDimensions = Element.getDimensions($(product["current_layer"]));
    startOffsetX = Event.pointerX(evt);
    startOffsetY = Event.pointerY(evt);
    imageOffsetX = contentPosition[0];
    imageOffsetY = contentPosition[1];
    imageOffsetWidth = contentDimensions["width"];
    imageOffsetHeight = contentDimensions["height"];
    updatePotential(contentPosition[0], contentPosition[1], contentDimensions["width"], contentDimensions["height"]);

    // Set events
    $('body').style.cursor = "nw-resize";
    Event.observe(document, 'mousemove', handleTopLeftMousemove, false);
    Event.observe(document, 'mouseup', handleTopLeftMouseup, false);
    Event.stop(evt);

    deactivateTimer();
}
function handleTopLeftMousemove(evt)
{
    var contentRatio = product["layers"][layerIdx[product["current_layer"]]]["image_width"] / product["layers"][layerIdx[product["current_layer"]]]["image_height"];
    var newPositionX = Event.pointerX(evt) - (startOffsetX - imageOffsetX);
    var newPositionY = Event.pointerY(evt) - (startOffsetY - imageOffsetY);
    var newDimensionWidth = imageOffsetX + imageOffsetWidth - newPositionX;
    var newDimensionHeight = imageOffsetY + imageOffsetHeight - newPositionY;
    var newRatio = newDimensionWidth / newDimensionHeight;

    // Force dimension constraints
    if (contentRatio > newRatio)
        newDimensionHeight = newDimensionWidth / contentRatio;
    else
        newDimensionWidth = newDimensionHeight * contentRatio;

    // Make sure valid
    if ((isInWritable(imageOffsetX + imageOffsetWidth - newDimensionWidth,
        imageOffsetY + imageOffsetHeight - newDimensionHeight, newDimensionWidth, newDimensionHeight)) &&
        (newDimensionWidth > 15) && (newDimensionHeight > 15))
    {
    	$(product["current_layer"]).style.left = px(imageOffsetX + imageOffsetWidth - newDimensionWidth);
    	$(product["current_layer"]).style.top = px(imageOffsetY + imageOffsetHeight - newDimensionHeight);
    	$(product["current_layer"]).style.width = px(newDimensionWidth);
    	$(product["current_layer"]).style.height = px(newDimensionHeight);
    	
        updatePotential(imageOffsetX + imageOffsetWidth - newDimensionWidth, imageOffsetY + imageOffsetHeight - newDimensionHeight, newDimensionWidth, newDimensionHeight);
        moveHandles(imageOffsetX + imageOffsetWidth - newDimensionWidth, imageOffsetY + imageOffsetHeight - newDimensionHeight, newDimensionWidth, newDimensionHeight);
    }
}
function handleTopLeftMouseup(evt)
{
	var contentDimensions = Element.getDimensions($(product["current_layer"]));
	updateLayerPosition(product["current_layer"], potentialX, potentialY, potentialWidth, potentialHeight);
	renderHandles(product["current_layer"]);
    Event.stopObserving(document, 'mousemove', handleTopLeftMousemove, false);
    Event.stopObserving(document, 'mouseup', handleTopLeftMouseup, false);
    $('body').style.cursor = "default";
    activateTimer();
} 

// TOP RIGHT HANDLE
function handleTopRightMousedown(evt)
{
    currentState = "active";
    validTick = "";
	redrawSurfaceLight();
        
    // Set starting points
    var contentPosition = Position.cumulativeOffset($(product["current_layer"]));
    var contentDimensions = Element.getDimensions($(product["current_layer"]));
    startOffsetX = Event.pointerX(evt);
    startOffsetY = Event.pointerY(evt);
    imageOffsetX = contentPosition[0];
    imageOffsetY = contentPosition[1];
    imageOffsetWidth = contentDimensions["width"];
    imageOffsetHeight = contentDimensions["height"];
    updatePotential(contentPosition[0], contentPosition[1], contentDimensions["width"], contentDimensions["height"]);

    // Set events
    $('body').style.cursor = "ne-resize";
    Event.observe(document, 'mousemove', handleTopRightMousemove, false);
    Event.observe(document, 'mouseup', handleTopRightMouseup, false);
    Event.stop(evt);

    deactivateTimer();
}
function handleTopRightMousemove(evt)
{
    var contentRatio = product["layers"][layerIdx[product["current_layer"]]]["image_width"] / product["layers"][layerIdx[product["current_layer"]]]["image_height"];
    var newPositionX = imageOffsetX; //Event.pointerX(evt) - (startOffsetX - imageOffsetX);
    var newPositionY = Event.pointerY(evt) - (startOffsetY - imageOffsetY);
    var newDimensionWidth = Event.pointerX(evt) + (imageOffsetX + imageOffsetWidth - startOffsetX) - imageOffsetX; //     imageOffsetX + imageOffsetWidth - newPositionX;
    var newDimensionHeight = imageOffsetY + imageOffsetHeight - newPositionY;
    var newRatio = newDimensionWidth / newDimensionHeight;

    // Force dimension constraints
    if (contentRatio > newRatio)
        newDimensionHeight = newDimensionWidth / contentRatio;
    else
        newDimensionWidth = newDimensionHeight * contentRatio;

    // Make sure valid
    if ((isInWritable(newPositionX,
        imageOffsetY + imageOffsetHeight - newDimensionHeight, newDimensionWidth, newDimensionHeight)) &&
        (newDimensionWidth > 15) && (newDimensionHeight > 15))
    {
    	$(product["current_layer"]).style.left = px(newPositionX);
    	$(product["current_layer"]).style.top = px(imageOffsetY + imageOffsetHeight - newDimensionHeight);
    	$(product["current_layer"]).style.width = px(newDimensionWidth);
    	$(product["current_layer"]).style.height = px(newDimensionHeight);
    	
        updatePotential(newPositionX, imageOffsetY + imageOffsetHeight - newDimensionHeight, newDimensionWidth, newDimensionHeight);
        moveHandles(newPositionX, imageOffsetY + imageOffsetHeight - newDimensionHeight, newDimensionWidth, newDimensionHeight);
    }
}
function handleTopRightMouseup(evt)
{
	var contentDimensions = Element.getDimensions($(product["current_layer"]));
	updateLayerPosition(product["current_layer"], potentialX, potentialY, potentialWidth, potentialHeight);
	renderHandles(product["current_layer"]);
    Event.stopObserving(document, 'mousemove', handleTopRightMousemove, false);
    Event.stopObserving(document, 'mouseup', handleTopRightMouseup, false);
    $('body').style.cursor = "default";
    activateTimer();
} 

// BOTTOM LEFT HANDLE
function handleBottomLeftMousedown(evt)
{
    currentState = "active";
    validTick = "";
	redrawSurfaceLight();
        
    // Set starting points
    var contentPosition = Position.cumulativeOffset($(product["current_layer"]));
    var contentDimensions = Element.getDimensions($(product["current_layer"]));
    startOffsetX = Event.pointerX(evt);
    startOffsetY = Event.pointerY(evt);
    imageOffsetX = contentPosition[0];
    imageOffsetY = contentPosition[1];
    imageOffsetWidth = contentDimensions["width"];
    imageOffsetHeight = contentDimensions["height"];
    updatePotential(contentPosition[0], contentPosition[1], contentDimensions["width"], contentDimensions["height"]);

    // Set events
    $('body').style.cursor = "ne-resize";
    Event.observe(document, 'mousemove', handleBottomLeftMousemove, false);
    Event.observe(document, 'mouseup', handleBottomLeftMouseup, false);
    Event.stop(evt);

    deactivateTimer();
}
function handleBottomLeftMousemove(evt)
{
    var contentRatio = product["layers"][layerIdx[product["current_layer"]]]["image_width"] / product["layers"][layerIdx[product["current_layer"]]]["image_height"];
    var newPositionX = Event.pointerX(evt) - (startOffsetX - imageOffsetX);
	var newPositionY = imageOffsetY;
    var newDimensionWidth = imageOffsetX + imageOffsetWidth - newPositionX;
	var newDimensionHeight = Event.pointerY(evt) + (imageOffsetY + imageOffsetHeight - startOffsetY) - imageOffsetY;
	var newRatio = newDimensionWidth / newDimensionHeight;

    // Force dimension constraints
    if (contentRatio > newRatio)
        newDimensionHeight = newDimensionWidth / contentRatio;
    else
        newDimensionWidth = newDimensionHeight * contentRatio;

    // Make sure valid
    if ((isInWritable(imageOffsetX + imageOffsetWidth - newDimensionWidth,
        newPositionY, newDimensionWidth, newDimensionHeight)) &&
        (newDimensionWidth > 15) && (newDimensionHeight > 15))
    {
    	$(product["current_layer"]).style.left = px(imageOffsetX + imageOffsetWidth - newDimensionWidth);
    	$(product["current_layer"]).style.top = px(newPositionY);
    	$(product["current_layer"]).style.width = px(newDimensionWidth);
    	$(product["current_layer"]).style.height = px(newDimensionHeight);
    	
        updatePotential(imageOffsetX + imageOffsetWidth - newDimensionWidth, newPositionY, newDimensionWidth, newDimensionHeight);
        moveHandles(imageOffsetX + imageOffsetWidth - newDimensionWidth, newPositionY, newDimensionWidth, newDimensionHeight);
    }
}
function handleBottomLeftMouseup(evt)
{
	var contentDimensions = Element.getDimensions($(product["current_layer"]));
	updateLayerPosition(product["current_layer"], potentialX, potentialY, potentialWidth, potentialHeight);
	renderHandles(product["current_layer"]);
    Event.stopObserving(document, 'mousemove', handleBottomLeftMousemove, false);
    Event.stopObserving(document, 'mouseup', handleBottomLeftMouseup, false);
    $('body').style.cursor = "default";
    activateTimer();
} 

// BOTTOM RIGHT HANDLE
function handleBottomRightMousedown(evt)
{
    currentState = "active";
    validTick = "";
	redrawSurfaceLight();
        
    // Set starting points
    var contentPosition = Position.cumulativeOffset($(product["current_layer"]));
    var contentDimensions = Element.getDimensions($(product["current_layer"]));
    startOffsetX = Event.pointerX(evt);
    startOffsetY = Event.pointerY(evt);
    imageOffsetX = contentPosition[0];
    imageOffsetY = contentPosition[1];
    imageOffsetWidth = contentDimensions["width"];
    imageOffsetHeight = contentDimensions["height"];
    updatePotential(contentPosition[0], contentPosition[1], contentDimensions["width"], contentDimensions["height"]);

    // Set events
    $('body').style.cursor = "nw-resize";
    Event.observe(document, 'mousemove', handleBottomRightMousemove, false);
    Event.observe(document, 'mouseup', handleBottomRightMouseup, false);
    Event.stop(evt);

    deactivateTimer();
}
function handleBottomRightMousemove(evt)
{
    var contentRatio = product["layers"][layerIdx[product["current_layer"]]]["image_width"] / product["layers"][layerIdx[product["current_layer"]]]["image_height"];
    var newPositionX = imageOffsetX;
    var newPositionY = imageOffsetY;
    var newDimensionWidth = Event.pointerX(evt) + (imageOffsetX + imageOffsetWidth - startOffsetX) - imageOffsetX;
    var newDimensionHeight = Event.pointerY(evt) + (imageOffsetY + imageOffsetHeight - startOffsetY) - imageOffsetY;
    var newRatio = newDimensionWidth / newDimensionHeight;

    // Force dimension constraints
    if (contentRatio > newRatio)
        newDimensionHeight = newDimensionWidth / contentRatio;
    else
        newDimensionWidth = newDimensionHeight * contentRatio;

    // Make sure valid
    if ((isInWritable(newPositionX,
        newPositionY, newDimensionWidth, newDimensionHeight)) &&
        (newDimensionWidth > 15) && (newDimensionHeight > 15))
    {
    	$(product["current_layer"]).style.left = px(newPositionX);
    	$(product["current_layer"]).style.top = px(newPositionY);
    	$(product["current_layer"]).style.width = px(newDimensionWidth);
    	$(product["current_layer"]).style.height = px(newDimensionHeight);
    	
        updatePotential(newPositionX, newPositionY, newDimensionWidth, newDimensionHeight);
        moveHandles(newPositionX, newPositionY, newDimensionWidth, newDimensionHeight);
    }
}
function handleBottomRightMouseup(evt)
{
	var contentDimensions = Element.getDimensions($(product["current_layer"]));
	updateLayerPosition(product["current_layer"], potentialX, potentialY, potentialWidth, potentialHeight);
	renderHandles(product["current_layer"]);
    Event.stopObserving(document, 'mousemove', handleBottomRightMousemove, false);
    Event.stopObserving(document, 'mouseup', handleBottomRightMouseup, false);
    $('body').style.cursor = "default";
    activateTimer();
} 








function updatePotential(x, y, width, height)
{
    potentialWidth = width;
    potentialHeight = height;
    potentialX = x;
    potentialY = y;
} 
function displayOutline(x, y, width, height)
{
    $('handle_outline').style.display = "block";
    $('handle_outline').style.left = px(x);
    $('handle_outline').style.top = px(y);
    $('handle_outline').style.width = px(width);
    $('handle_outline').style.height = px(height);
}    

function updateLayerPosition(id, x, y, width, height)
{
    $(id).style.left = px(x);
    $(id).style.top = px(y);
    $(id).style.width = px(width);
    $(id).style.height = px(height);

    var writablePosition = Position.cumulativeOffset($("div_writable"));
    var writableDimensions = Element.getDimensions($("div_writable"));
    var contentPosition = Position.cumulativeOffset($(id));
    var contentDimensions = Element.getDimensions($(id));
    
    var position = Position.cumulativeOffset($('box'));
    var rWritableX = position[0] + (writableX / 100) * drawingWidth;
    var rWritableY = position[1] + (writableY / 100) * drawingHeight;
    var rWritableWidth = (writableWidth / 100) * drawingWidth;
    var rWritableHeight = (writableHeight / 100) * drawingHeight;    
        
    product["layers"][ layerIdx[id] ]["position"] = "custom";
    product["layers"][ layerIdx[id] ]["position_x"] = (x - rWritableX) / (rWritableWidth) * 100;
    product["layers"][ layerIdx[id] ]["position_y"] = (y - rWritableY) / (rWritableHeight) * 100;
    product["layers"][ layerIdx[id] ]["position_width"] = width / (rWritableWidth) * 100;
    product["layers"][ layerIdx[id] ]["position_height"] = height / (rWritableHeight) * 100;
    
    if (product["layers"][ layerIdx[id] ]["position_x"] <= 0)
    	product["layers"][ layerIdx[id] ]["position_x"] = 0.51;
    if (product["layers"][ layerIdx[id] ]["position_y"] <= 0)
    	product["layers"][ layerIdx[id] ]["position_y"] = 0.51;
    if (product["layers"][ layerIdx[id] ]["position_width"] > 98.98)
    	product["layers"][ layerIdx[id] ]["position_width"] = 98.98;
    if (product["layers"][ layerIdx[id] ]["position_height"] > 98.98)
    	product["layers"][ layerIdx[id] ]["position_height"] = 98.98;
    
}    
function hideOutline()
{
    $('handle_outline').style.display = "none";
}    
function moveHandles(x, y, width, height)
{
    // Stretch
    $('handle_outline').style.left = px(x);
    $('handle_outline').style.top = px(y);
    $('handle_outline').style.width = px(width);
    $('handle_outline').style.height = px(height);

    // Move top left
    $('handle_topleft').style.left = px(x);
    $('handle_topleft').style.top = px(y);

    // Move top right
    $('handle_topright').style.left = px(x + width - 8);
    $('handle_topright').style.top = px(y);

    // Move bottom left
    $('handle_bottomleft').style.left = px(x);
    $('handle_bottomleft').style.top = px(y + height - 8);

    // Move top right
    $('handle_bottomright').style.left = px(x + width - 8);
    $('handle_bottomright').style.top = px(y + height - 8);
}

// UPLOAD TIMER
var retrieveTimerID;
var timerOn = 1;
function startRetrieveTimer()
{
    retrieveTimerID = setTimeout("retrieveUploadStatus()", 500);
    $("upload_status").style.display="block";
    return true;
}
function retrieveUploadStatus()
{
    // Request url
    var url = "/process/statistics/" + $("upload_session").value;
    var a = new Ajax.Request(url, {method: 'get', onSuccess: retrieveUploadStatusSuccess});
}
function retrieveUploadStatusSuccess(transport, json)
{
    var m = eval(transport.responseText);
    if (m.status == "success")
    {
        var current = parseInt(m.current);
        var total = parseInt(m.total);
        var percent = 100 * (current / total);
        $("upload_percent").innerHTML = percent.toFixed(0) + "% complete.";

        if ((current < total) && (timerOn))
        {
            retrieveTimerID = setTimeout("retrieveUploadStatus()", 500);
        }
        else
        {
            $("upload_percent").innerHTML = "Complete.";
            retrieveTimerID = setTimeout("hideUploadStatus()", 1000);
        }
    }
    else
    {
        $("upload_percent").innerHTML = "There was an error. Please try again.";
    }
}
function hideUploadStatus()
{
    $("upload_status").style.display="none";
}


// Loading graphic
function startLoadingGraphic(key)
{
    currentActivity[key] = new Date().getTime();
    $("ajax_loader").style.display = "block";
}
function cancelLoadingGraphic(key)
{
    var isComplete = true;
    currentActivity[key] = "";
    for (var k in currentActivity) 
    {
        if (currentActivity[k] != "")
            isComplete = false;
    }    
    if (isComplete)
        $("ajax_loader").style.display = "none";
}
function cancelAllLoadingGraphic()
{
    //for (var key in currentActivity) 
    //{
    //    currentActivity[key] = "";
    //}
    $("ajax_loader").style.display = "none";
}
function blankMousedown(evt)
{
    currentState = "active"
    validTick = "";

    var child = Event.element(evt);
    product["current_layer"] = child.id;
    if (product["current_layer"].indexOf("_spacer") > 0)
        product["current_layer"] = product["current_layer"].substring(0, 20);
    redrawSurfaceLight();            

    // Record offsets within content
    var fullOffset = Position.cumulativeOffset(child);
    currentLayerHandle = [Event.pointerX(evt) - fullOffset[0], Event.pointerY(evt) - fullOffset[1]];

    // Add events for mouseup and mousemove
    Event.observe(document, 'mousemove', previewMousemove, false);
    Event.observe(document, 'mouseup', previewMouseup, false);
    Event.stop(evt);

    deactivateTimer();        
}
function blankDblclick(evt)
{

}
function previewMousedown(evt)
{
    var child = Event.element(evt);
    validTick = "";

    // If spacer layer, rewrite guid
    product["current_layer"] = child.id;

    // Record offsets within content
    var fullOffset = Position.cumulativeOffset(child);
    currentLayerHandle = [Event.pointerX(evt) - fullOffset[0], Event.pointerY(evt) - fullOffset[1]];

    // Shift to account for border
    renderHandles(product["current_layer"]);

    // Add events for mouseup and mousemove
    Event.observe(document, 'mousemove', previewMousemove, false);
    Event.observe(document, 'mouseup', previewMouseup, false);
    Event.stop(evt);

    deactivateTimer();
}
function previewDblclick(evt)
{
    var child = Event.element(evt);
    var layerMax = 0;
    validTick = "";
    var layerGuid = "";
    for (var k = 0; k < product["layers"].length; k++)
    {
        if ($(product["layers"][k]["guid"]).style.zIndex > layerMax)
        {
            layerMax = $(product["layers"][k]["guid"]).style.zIndex;
            layerGuid = product["layers"][k]["guid"];
        }
    }
    if (layerGuid != "")
    {
        $(child.id).style.zIndex = layerMax + 2;
        $(child.id + "_spacer").style.zIndex = layerMax + 1;
    }
    currentState = "active";
    activateTimer();
    redrawSurface();
}
function previewMousemove(evt)
{
    var writablePosition = Position.cumulativeOffset($("div_writable"));
    var writableDimensions = Element.getDimensions($("div_writable"));

    var layerPosition = Position.cumulativeOffset($(product["current_layer"]));
    var layerDimensions = Element.getDimensions($(product["current_layer"]));

    if (!layerPosition) return;
    if (!layerDimensions) return;

    if (isInWritable(Event.pointerX(evt) - currentLayerHandle[0] + 1,
        Event.pointerY(evt) - currentLayerHandle[1] + 1,
        layerDimensions["width"] - 2,
        layerDimensions["height"] - 2))
    {
        $(product["current_layer"]).style.left = px(Event.pointerX(evt) - currentLayerHandle[0]);
        $(product["current_layer"]).style.top = px(Event.pointerY(evt) - currentLayerHandle[1]);
        renderHandles(product["current_layer"]);
    }
    else
    {
        if (Event.pointerX(evt) < layerPosition[0])
            currentLayerHandle[0] = 0;
        else if (Event.pointerX(evt) > layerPosition[0] + layerDimensions["width"])
            currentLayerHandle[0] = layerDimensions["width"] - 1;
        else
            currentLayerHandle[0] = Event.pointerX(evt) - layerPosition[0];

        if (Event.pointerY(evt) < layerPosition[1])
            currentLayerHandle[1] = 0;
        else if (Event.pointerY(evt) > layerPosition[1] + layerDimensions["height"])
            currentLayerHandle[1] = layerDimensions["height"] - 1;
        else
            currentLayerHandle[1] = Event.pointerY(evt) - layerPosition[1];
    }
}
function previewMouseup(evt)
{
    var child = Event.element(evt);
    Event.stopObserving(document, 'mousemove', previewMousemove);
    Event.stopObserving(document, 'mouseup', previewMouseup);
    var contentPosition = Position.cumulativeOffset($(product["current_layer"]));
    var contentDimensions = Element.getDimensions($(product["current_layer"]));
    updateLayerPosition(product["current_layer"], contentPosition[0], contentPosition[1], contentDimensions["width"], contentDimensions["height"]);
    debugProduct();
    activateTimer();
}
// UTILITY FUNCTIONS
function debugAll(message)
{
    $("msg").innerHTML = message;
}
function px(str) { return str + "px"; }
function idx(arr)
{
    var a = {};
    for (var k = 0; k < arr.length; k++)
        a[arr[k][1]] = arr[k];
    return a;
}
function idxi(arr)
{
    var a = {};
    for (var k = 0; k < arr.length; k++)
        a[arr[k][0]] = arr[k];
    return a;
}
function msg(m)
{
    $("msg").innerHTML = m + "<br>" + $("msg").innerHTML;
} 
function isInWritableXY(x, y)
{
    return isInWritable(x, y, 1, 1);
}
function isInWritable(x, y, width, height)
{
    var writablePosition = Position.cumulativeOffset($("div_writable"));
    var writableDimensions = Element.getDimensions($("div_writable"));

    if ((x > writablePosition[0]) &&
       (x + width < writablePosition[0] + writableDimensions["width"]) &&
       (y > writablePosition[1]) &&
       (y + height < writablePosition[1] + writableDimensions["height"]))
    {
        return true;
    }
    else
    {
        return false;
    }
}


function initializeTimer()
{
    renderTimer = setTimeout("timerUpdate()", 500);
}
function activateTimer()
{   
    var lastTick = new Date().getTime();
    renderTick = lastTick + 1500;
    validTick = "";
}    
function deactivateTimer()
{
    renderTick = 0;
    cancelAllLoadingGraphic();
    //cancelLoadingGraphic("renderTimer");
}
function timerUpdateLoaded()
{
    var position = Position.cumulativeOffset($('img_background'));
    $("div_foreground").style.left = (position[0]) + "px";
    $("div_foreground").style.top = (position[1]) + "px";
    $("div_foreground").style.display = "block";  
    currentState = "inactive";
    redrawSurface();
    renderLevel = 0;    
}
var latestImg;
function timerUpdate()
{
    var lastTick = new Date().getTime();
    if ((renderTick > 0) && (lastTick > renderTick))
    {
        var url = "/image3.php?full_product=" + strippedProductJSON();
        renderLevel++;
                
        var img = new Image();
        Event.observe(img, 'load', function (event) 
        { 
            if (latestImg.className == validTick)
            {
                $("div_foreground").innerHTML = "";
                var position = Position.cumulativeOffset($('box'));
                
                $("div_foreground").style.left = (position[0]) + "px";
                $("div_foreground").style.top = (position[1]) + "px";
                $("div_foreground").style.display = "block";  
                $("div_foreground").appendChild(latestImg);
                
                Event.observe(latestImg, 'mousedown', foregroundMouseDown);
                currentState = "inactive";
                redrawSurfaceLight();
                renderLevel = 0;
            }
            cancelAllLoadingGraphic();
        });

        startLoadingGraphic("renderTimer");
        img.src = url;
        img.className = renderTick + "";
        validTick = renderTick + "";
        latestImg = img;       

        renderTick = 0;
    }
    renderTimer = setTimeout("timerUpdate()", 500);        
}


function foregroundMouseDown(evt)
{ 
    product["current_layer"] = "";
    hideHandles();
}
function backgroundMouseDown(evt)
{
    product["current_layer"] = "";
    hideHandles();
}
function writableMouseDown(evt)
{
    product["current_layer"] = "";
    hideHandles();
}

