function $ (name) {
    return document.getElementById(name);
}

var AQI = new Object();

AQI.formState = {color: "#000000",
		 text: "Xyz",
		 orientation: "r",
		 font: "xyz"};

AQI.compState = {tpath: "",
		 id: 1};

AQI.updateFormState = function () {
    var fontMenu = $('fontSelect');

    AQI.formState.text = $('nameInput').value;
    AQI.formState.font = fontMenu.options[fontMenu.selectedIndex].value;
};

AQI.setColor = function (color) {
    AQI.formState.color = color;
    AQI.reqNewText(AQI.newTextColor);
};

AQI.setOrientation = function (orientation) {
    AQI.formState.orientation = orientation;
    AQI.reqNewText(AQI.newText);
};

// patches

AQI.patchFilename = function (id) {
    if (id < 10) {
	return 'patch0' + id + '.jpg';
    } else {
	return 'patch' + id + '.jpg';
    }
};

function Patch(id)
{
    this.id = id;
    this.filename = AQI.patchFilename(id);
    this.cropImg = new Image();
    this.patchImg = new Image();

    this.cropImg.src = this.cropUrl();
    this.patchImg.src = this.patchUrl();
}

Patch.baseUrl = 'http://static.aqi.wigflip.com/';

Patch.prototype.cropUrl = function () {
    return Patch.baseUrl + 'crops/' + this.filename;
};

Patch.prototype.patchUrl = function () {
    return Patch.baseUrl + 'patches/' + this.filename;
};

Patch.prototype.miniPatchUrl = function () {
    return Patch.baseUrl + 'thumbs/' + this.filename;
};

Patch.prototype.miniPatch = function () {
    return $('minipatch' + this.id);
};

Patch.prototype.select = function () {
    this.miniPatch().style.border = 'dashed 1px black';
    $('patchImg').src = this.patchUrl();
};

Patch.prototype.unselect = function () {
    this.miniPatch().style.border = 'solid 1px white';
};


AQI.patches = new Array(12);

AQI.createPatch = function (id) {
    return new Patch(id);
};

AQI.findPatch = function (id) {
    if (!this.patches[id]) {
	this.patches[id] = this.createPatch(id);
    } 

    return this.patches[id];
};

AQI.hoverPatch = function (id) {
    AQI.swatchPopop(id);
};

AQI.unHoverPatch = function (id) {
    AQI.cancelSwatchPopup();
    AQI.swatchPopupTimer = window.setTimeout(AQI.hideCrop, 250);
};

AQI.selectPatch = function (id) {
    var patch = AQI.findPatch(id);
    AQI.compState.id = id;
    if (AQI.selected) {
	AQI.selected.unselect();
    }

    patch.select();
    AQI.selected = patch;
};

AQI.hideCrop = function () {
    $('miniPatchImg').style.visibility = 'hidden';
};

AQI.showCrop = function () {
    $('miniPatchImg').style.visibility = 'visible';
};

AQI.swatchPopop = function (id) {
    var patch = AQI.findPatch(id);
    var callback = function () {
	$('miniPatchImg').src = patch.cropImg.src;
	AQI.showCrop();
    };

    if (AQI.swatchPopupTimer) {
	window.clearTimeout(AQI.swatchPopupTimer);
    }

    AQI.swatchPopupTimer = window.setTimeout(callback, 250);
};

AQI.cancelSwatchPopup = function () {
    if (AQI.swatchPopupTimer) {
	window.clearTimeout(AQI.swatchPopupTimer);
	AQI.swatchPopupTimer = null;
    }
};

AQI.debug = function (args) {
    var html = '';
    for (x in args) {
	html += x + ': ' + args[x] + '<br>';
    }

    $('debug').innerHTML = html;
}


function appinit () {
    var img = $('textImg');

    AQI.initImageDiv(img);
    AQI.selectPatch(1);
    
    for (var i = 1; i < 13; i++) {
	AQI.findPatch(i);
    }

    $('fontSelect').onchange = function () {
	AQI.reqNewText(AQI.newText);
    };

    $('nameInput').onkeydown = function (e) {
	if (!e) { e = window.event; }
	if (e.keyCode == 13) {
	    AQI.reqNewText(AQI.newText);
	}
    };

    $('nameInput').focus();
}

AQI.initImageDiv = function (img) {
    var base = $('patchImg');
    var drag = new Draggable();
    drag.attachTo(img);
    drag.ondragbegin = function () {
	img.style.cursor = 'move';
	this.data.imageOrigin = Point.fromElementLayout(img);
    };

    drag.ondragend = function () {
	img.style.cursor = 'pointer';
    };

    var patchpoint = Point.fromElementLayoutCenter(base);
    patchpoint.toStyleCenterOf(img);
    img.style.visibility = 'visible';
    
    var imgBox = Box.fromElementLayout(img);
    var patchBox = Box.fromElementLayout(base).constrict(10, 10, 70, 10);
    var constrainer = imgBox.constrainedInto(patchBox);

    drag.ondragmotion = function (delta) {
	var p = this.data.imageOrigin.add(delta).constrainedTo(constrainer);
	p.toStyleOf(img);
    };
};


AQI.reqNewText = function (callback) {
    AQI.updateFormState();
    var state = AQI.formState;

    $('saveButton').disabled = false;

    if (state.text != "") {
	var args = {f: state.font,
		    o: state.orientation,
		    t: state.text,
		    c: state.color};

	AQI.showSpinner();
	Util.ajaxCall("/aqi/textxml",
		      args,
		      callback);
    }
};

AQI.newText = function (text) {
    AQI.compState.tpath = text.tpath;
    var callback = function (url) {
	var img = $('textImg');
	img.style.width = text.width + 'px';
	img.style.height = text.height + 'px';
	Util.browser.aqiUpdateImage(text, img);
	AQI.initImageDiv(img);
	AQI.hideSpinner();
    };

    AQI.onImageLoad(text.url, callback);
};


AQI.onImageLoad = function (url, callback) {
    var img = new Image();
    img.onload = function () { callback(url) };
    img.src = url;
};
    

MSIEBrowser.prototype.aqiUpdateImage = function (text, img) {
    img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + text.url + '",sizingMethod="crop")';
};

MozBrowser.prototype.aqiUpdateImage = function (text, img) {
    img.style.backgroundImage = 'url(' + text.url + ')';
};


AQI.newTextColor = function (text) {
    AQI.compState.tpath = text.tpath;
    var callback = function (url) {
	var img = $('textImg');
	img.style.width = text.width + 'px';
	img.style.height = text.height + 'px';
	Util.browser.aqiUpdateImage(text, img);
	AQI.hideSpinner();
    };

    AQI.onImageLoad(text.url, callback);
};


AQI.textOffset = function () {
    var img = $('textImg');
    var base = $('patchImg');

    return new Point(img.offsetLeft - base.offsetLeft,
		     img.offsetTop - base.offsetTop);
};
    
AQI.showResult = function (response) {
    var alt = 'The Alzheimer&#039;s Art Quilt Initiative: Raising Awareness &#038; Funding Research';
    AQI.hideSpinner();
    $('saverDownloadLink').href = response.url;
    $('saverHtmlCode').value = "<a href='http://www.alzquilts.org/patch.html' title='" + alt + "'><img height=450 width=140 alt='" + alt + "' border=0 src='" + response.url + "'></a>";
    $('savers').style.visibility = 'visible';
};

AQI.hideResult = function () {
    $('savers').style.visibility = 'hidden';
};

AQI.requestSave = function () {
    var offset = AQI.textOffset();
    var args = {tx: offset.x,
		ty: offset.y,
		id: AQI.compState.id,
		tpath: AQI.compState.tpath};
    
    AQI.hideResult();

    AQI.showSpinner();
    Util.ajaxCall('/aqi/compose', args, AQI.showResult);
};


AQI.showSpinner = function () {
    $('spinnerImg').style.display = 'block';
};

AQI.hideSpinner = function () {
    $('spinnerImg').style.display = 'none';
};



window.onload = appinit;

