/*
	Core JS library.
*/
if (window['loadFirebugConsole']) window.loadFirebugConsole();
else 
{
	if (!window['console']) {
		window.console = {};
		window.console.info = function(s){};
		window.console.log = function(s){};
		window.console.warn = function(s){};
		window.console.error = function(s){};
	}
}

// these are the textboxes to be converted to special ones
var convert_textboxes = 
{ 
	"TEXTBOX___125___TAGS01___24": "Tag Wording"
};
var valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-/ ,";

function window_init(e)
{
	var existingVal = "";
	jQuery("textarea").each(function(i){
		var ta = jQuery(this);
		if (typeof(convert_textboxes[ta.attr("name")])=="string") 
		{
			if (ta.val()===convert_textboxes[ta.attr("name")]) existingVal = "";
			else existingVal = ta.val();
		}
	});
	var existingValues = existingVal.split("");
	
	// get together the html for the containers
	var dogtags_rows = "";
	var cellIndex = 0;
	for( var row = 0; row < 5; row++ ) {
		for( var col = 0; col < 15; col++ ) {
			var val = (typeof(existingValues[cellIndex])=="undefined") ? "" : existingValues[cellIndex];
			dogtags_rows += '<div class="input_cell"><input type="text" maxlength="1" class="dogtag_letter" id="ltr_'+row+'_'+col+'" value="'+val+'" /></div>';
			cellIndex++;
		}
		dogtags_rows += '<br style="clear:both;" />';
		cellIndex++;
	}
	dogtags_rows += '<br class="clear" />';
	
	// drop it into the textboxes to be converted
	jQuery("textarea").each(function(i){
		var ta = jQuery(this);
		if (typeof(convert_textboxes[ta.attr("name")])=="string") {
			ta.parent().parent().html('\
			<td colspan="3">\
				<div class="dogtags_instructions">Print information exactly as you want to appear. Commas, periods &amp; spaces count as one space.</div>\
				<div class="dogtags_customizer">'+dogtags_rows+'</div>\
				<input type="hidden" id="'+ta.attr("name")+'" name="'+ta.attr("name")+'" />\
			</td>');
		}
	});
	
	// bind up keyup events
	jQuery(".dogtag_letter").bind("keydown", onTagsLetterKeydown);
	jQuery(".dogtag_letter").bind("keypress", onTagsLetterKeypress);
	jQuery(".dogtag_letter").bind("keyup", onTagsLetterKeyup);
	jQuery(".dogtag_letter").bind("focus", function(e){this.select();});
	
	updateHiddenFormField();
}

function onTagsLetterKeydown( e )
{
	// don't allow the form to be submitted via ENTER - this allows us to use Enter for line breaks.
	if (e.keyCode==13) e.preventDefault();
}

function isValidTypedChar( e )
{
	if (!e.charCode) k = String.fromCharCode(e.which);
	else k = String.fromCharCode(e.charCode);
	
	// if this is an invalid key, ignore it.
	if (valid_chars.indexOf(k) == -1) return false;
	
	// avoid pasting where possible
	if (e.ctrlKey&&k=='v') return false;
	
	return true;
}

function onTagsLetterKeypress( e )
{
	// ignore tab characters
	if ("|9|16|37|38|39|40|".indexOf("|" + e.keyCode + "|") > -1) return;
	
	if (!isValidTypedChar(e)) e.preventDefault();
}

function onTagsLetterKeyup( e )
{
	var field = jQuery(e.target);
	var iMaxLength = parseInt(field.attr("maxlength"), 10);
	field.val( field.val().toUpperCase() );
	
	updateHiddenFormField();
	
	// if they hit delete, then go back one field and empty it
	if (e.keyCode==8) jQuery("input", field.parent().prev()).val("").focus().select();
	
	// if enter was pressed, then drop down to the next line (if relevant)
	if (e.keyCode==13) {
		var letterCoords = field.attr("id").split("_");
		var row = parseInt(letterCoords[1], 10);
		if (letterCoords[1] < 4) {
			jQuery("#ltr_"+(row + 1)+"_0").focus();
		}
		return true;
	}
	
	// if the user tabs to the field, exit event handler. this will prevent movement if the field is already
	// filled in with the max number of characters
	if( isNaN(iMaxLength) || ("|9|16|37|38|39|40|".indexOf("|" + e.keyCode + "|") > -1) ) return true;
	
	// if the value is " " and we didn't hit space, then don't bother advancing - this will be an illegal char
	if ((field.val()=="" || field.val()==" ") && e.keyCode!=32) return true;
	
	if( field.val().length >= field.attr("maxlength") )
	{
		// because there are BR elements between the DIV cells, skip an extra step if this isn't a DIV.
		var nextDiv = field.parent().next();
		if (nextDiv.attr("tagName").toLowerCase()!="div") nextDiv = nextDiv.next();
		jQuery("input", nextDiv).focus().select();
	}
	
	return true;
}

function updateHiddenFormField() {
	var string = "";
	jQuery(".dogtag_letter").each(function(i){
		var letterCoords = jQuery(this).attr("id").split("_");
		var row = parseInt(letterCoords[1], 10);
		var col = parseInt(letterCoords[2], 10);
		if (row > 0 && col==0) string += "\r\n";
		if (jQuery(this).val().length > 0) string += jQuery(this).val();
		else string += " ";
	});
	
	for( var i in convert_textboxes ) {
		jQuery("#"+i).val(string);
	}
}

jQuery(document).bind('ready', window_init);
