/**
 * @author chuck
 */

var actualWord = new Array();
var completedWord
var modifying = false;

var line1len = 0;
var line2len = 0;
var line3len = 0;
var line4len = 0;
var line5len = 0;

var line1width = 0;
var line2width = 0;
var line3width = 0;
var line4width = 0;
var line5width = 0;

var line1height = 0;
var line2height = 0;
var line3height = 0;
var line4height = 0;
var line5height = 0;

var breaks = 0;
var last = 0;
var letterType = "alphabet";

actualWord.letter = new Array();
actualWord.file = new Array();
actualWord.widths = new Array();
actualWord.heights = new Array();

$(document).ready(function()
{
	var addWord = setInterval(function()
	{
		if(completedWord != undefined) 
		{
			if (!modifying) 
			{
				////console.log("comparing word")
				compareWords(completedWord);
			}
		}
		
		//if(actualWord.length == 0 && completedWord.length >= 1)
		//{
			//modifying = false;
		//}
		
	}, 5);
	
 	var saveCompletedWord = setInterval(function()
	{
		
		storeWord($("#lettersinput").attr("value"))
		
	}, 5);
	
	$("#lettersinput").keypress(function(e)
	{
		return restrictCharacters(this, e, alphaOnly);	
	});
	
	$("#lettersinput").focus();
	
});

function startSpinner()
{
	$("#spinner").show();
}

function stopSpinner()
{
	$("#spinner").hide();
}

function wordExists()
{
	if(actualWord.length > 0)
	{
		return true;
	}
}

function storeWord(word)
{
	completedWord = word.toUpperCase();
	
	//////console.log("completedWord = " + completedWord);
}

function compareWords(word)
{
	var	aw = actualWord;
	var cw = word.split("");
	var cp = 0;
	
	if(cw.length > aw.length)
	{
		var newamt = Math.abs(cw.length - aw.length);
		////console.log(newamt + " letters have been added to the completed word");
		
		for(var i = 0; i < cw.length; i++)
		{
			////console.log(cw[i]+" != "+aw[i])
			if(aw[i] == "newline")
			{
				continue;
			}
			else if(cw[i] != aw[i])
			{
				cp = i;
				break;
			}
		}
		modifying = true;
		startSpinner();
		//addLettersToStage(cp);
		getLetterFile(cp)
	}
	else if(cw.length < aw.length)
	{
		var newamt = Math.abs(aw.length - cw.length);
		////console.log(newamt + " letters have been removed from the completed word");
		
		for(var i = 0; i < aw.length; i++)
		{
			if(aw[i] == "newline" && cw[i] == "\n")
			{
				continue
			}
			else if (aw[i] == "newline" && cw[i] != "\n") 
			{
				cp = i;
				break;
			}
			else if (cw[i] != aw[i]) 
			{
				cp = i;
				break;
			}
		}
		modifying = true;
		startSpinner();
		removeLettersFromStage(cp);
		
		//console.log("actualWord = " + actualWord);
		//console.log("completedWord = " + completedWord); 
		
	}
	
}

function getLetterFile(cp)
{
	var letter = completedWord.charAt(cp);
	
	if(letter == "\n")
	{
		letter = "newline";
	}
	
	if(letter != "newline") 
	{
		if(letter == "?")
		{
			letter = "_QUESTION";
		}
		else if(letter == "!")
		{
			letter = "_EXCLAMATION";
		}
		else if(letter == "&")
		{
			letter = "_AMPERSAND";
		}
		else if(letter == ".")
		{
			letter = "_DOT";
		}
		else if(letter == ",")
		{
			letter = "_COMMA";
		}
		
		var rand = Math.floor(Math.random()*5000);
		////console.log("http://www.spellingchange.com/lib/Letters.php?rand="+rand+"&type="+letterType+"&letter=" + letter);
		$.getJSON("http://www.spellingchange.com/lib/Letters.php?rand="+rand+"&type="+letterType+"&letter=" + letter, function(data)
		{
			addLettersToStage(data.file, data.letter, cp)
		});
	}
	else
	{
		addBreakToStage(cp);
	}
}

function changeType(type)
{
	letterType = type;
	regenerate();
}

function addBreakToStage(cp)
{
	actualWord.splice(cp, 0, "newline");
	actualWord.letter.splice(cp, 0, "newline");
	actualWord.file.splice(cp, 0, "newline");
	actualWord.widths.splice(cp, 0, "newline");
	actualWord.heights.splice(cp, 0, "newline");
		
	//////console.log("adding a break to the paragraph");
	$("#word").brF(cp);
	modifying = false;
	stopSpinner();
	
	resizeAllLetters();
}

function addLettersToStage(file, sletter, cp)
{
	var rand = Math.floor(Math.random()*5000);
	var letter = completedWord.charAt(cp);
	var wl = completedWord.length;
	var al = actualWord.length;
	
	////////console.log("Word = " + completedWord);
	////////console.log("Position = " + cp);
	////////console.log("File = " + file);
	////////console.log("Letter = " + letter);
	////////console.log("Server Letter = " + sletter);
	
	if (cp == 0 && al == 0) 
	{
		actualWord.push(letter);
		actualWord.letter.push(letter);
		actualWord.file.push(file);

		//////console.log("adding first letter of word at positon " + cp + ". Total word length = " + wl);
	
		//$("#word").image("http://www.spellingchange.com/lib/Letters.php?rand=" + rand + "&letter=" + letter, function()
		////console.log("http://www.spellingchange.com/"+letterType+"/" + sletter + "/" + file+"?rand=" + rand)
		$("#word").image("http://www.spellingchange.com/"+letterType+"/" + sletter + "/" + file+"?rand=" + rand, function()
		{
			////console.log("Image added to DOM")
			modifying = false;
			stopSpinner();
			$(this).fadeIn("fast");
			
			if($(this).width() >  600)
			{
				new_w = 437;
			}
			else
			{
				new_w = $(this).width();
			}	
			
			actualWord.widths.push(new_w);
			actualWord.heights.push(600);
			
			resizeAllLetters();

		}, letter);
	}
	else if (cp > 0) 
	{
		actualWord.splice(cp, 0, letter);
		actualWord.letter.splice(cp, 0, letter);
		actualWord.file.splice(cp, 0, file);
		
		if (letter == "\n") 
		{
			//////console.log("adding a break to the paragraph");
			$("#word").brF(cp);
			modifying = false;
			stopSpinner();
			$(this).fadeIn("fast");
		}
		else 
		{
			////console.log("adding letter to word at positon " + cp + ". Total word length = " + wl);
			//$("#word").imageF(cp, "http://www.spellingchange.com/lib/Letters.php?rand=" + rand + "&letter=" + letter, function()
			////console.log("http://www.spellingchange.com/"+letterType+"/" + sletter + "/" + file+"?rand=" + rand)
			$("#word").imageF(cp, "http://www.spellingchange.com/"+letterType+"/" + sletter + "/" + file+"?rand=" + rand, function()
			{
				////console.log("Image added to DOM")
				if (modifying == true) 
				{
					modifying = false;
					stopSpinner();
					$(this).fadeIn("fast");
					
					if ($(this).width() > 600) 
					{
						new_w = 437;
					}
					else 
					{
						new_w = $(this).width();
					}
					
					actualWord.widths.splice(cp, 0, new_w);
					actualWord.heights.splice(cp, 0, 600);
					resizeAllLetters();
				}
			}, letter);
		}
	}
	else if(cp == 0 && al >= 1)
	{
		actualWord.splice(cp, 0, letter);
		actualWord.letter.splice(cp, 0, letter);
		actualWord.file.splice(cp, 0, file);
	
		//////console.log("adding letter to begining of word at positon " + cp + ". Total word length = " + wl);
		
//		$("#word").imageN(cp, "http://www.spellingchange.com/lib/Letters.php?rand=" + rand + "&letter=" + letter, function()
		$("#word").imageN(cp, "http://www.spellingchange.com/"+letterType+"/" + sletter + "/" + file+"?rand=" + rand, function()
		{
			modifying = false;
			stopSpinner();
			$(this).fadeIn("fast");
			
			if($(this).width() >  600)
			{
				new_w = 437;
			}
			else
			{
				new_w = $(this).width();
			}	
			
			actualWord.widths.splice(cp, 0, new_w);
			actualWord.heights.splice(cp, 0, 600);
			
			resizeAllLetters();
		}, letter);
	}
	
	//////console.log("actualWord = " + actualWord);
	//////console.log("actualWord.letter = " + actualWord.letter);
	//////console.log("actualWord.file = " + actualWord.file);
	
	
}

function removeLettersFromStage(cp)
{
	//alert("completedWord.length = " + completedWord.length)
	if(completedWord.length == 1)
	{
		//alert("actualWord.length = " + actualWord.length)
		if(actualWord.length > 1 && completedWord.charAt(0) != actualWord[0])
		{
			//console.log("Different")
			actualWord = new Array();
			actualWord.letter = new Array();
			actualWord.file = new Array();
			actualWord.widths = new Array();
			actualWord.heights = new Array();
			actualWord.heights = new Array();
			$("#word").empty();
			modifying = false;
			stopSpinner();
		}
	}
	
	if (completedWord == "") 
	{
		////////console.log("Words has been completely erased");
		actualWord = new Array();
		actualWord.letter = new Array();
		actualWord.file = new Array();
		actualWord.widths = new Array();
		actualWord.heights = new Array();
		$("#word").empty();
		modifying = false;
		stopSpinner();
	}
	else 
	{
		////////console.log("removing letter from word at positon " + cp);
		actualWord.splice(cp, 1);
		actualWord.letter.splice(cp, 1);
		actualWord.file.splice(cp, 1);
		actualWord.widths.splice(cp, 1);
		actualWord.heights.splice(cp, 1);
		$($("#word > *").get(cp)).remove();
		modifying = false;
		stopSpinner();
		resizeAllLetters();
	}

}

function resizeAllLetters()
{
	////////console.log("resizing word");
	
	breaks = 0;
	line1len = 0;
	line1width = 0;
	line1height = 0;
	for (var i = 0; i < actualWord.length; i++) 
	{
		if (actualWord[i] == "newline") 
		{
			breaks++;
			last = i;
			break;
		}
		else 
		{
			line1len++;
			line1width += actualWord.widths[i];
			line1height += actualWord.heights[i];
		}
	}
	
	if (breaks == 1) 
	{
		line2len = 0;
		line2width = 0;
		line2height = 0;
		for (var i = last+1; i < actualWord.length; i++) 
		{
			if (actualWord[i] == "newline") 
			{
				breaks++;
				last = i;
				break;
			}
			else 
			{
				line2len++;
				line2width += actualWord.widths[i];
				line2height += actualWord.heights[i];
			}
		}
	}
	else
	{
		line2len = 0;
		line2width = 0;
		line2height = 0;
	}
	
	if (breaks == 2) 
	{
		line3len = 0;
		line3width = 0;
		line3height = 0;
		for (var i = last+1; i < actualWord.length; i++) 
		{
			if (actualWord[i] == "newline") 
			{
				breaks++;
				last = i;
				break;
			}
			else 
			{
				line3len++;
				line3width += actualWord.widths[i];
				line3height += actualWord.heights[i];
			}
		}
	}
	else
	{
		line3len = 0;
		line3width = 0;
		line3height = 0;
	}
	
	if (breaks == 3) 
	{
		line4len = 0;
		line4width = 0;
		line4height = 0;
		for (var i = last+1; i < actualWord.length; i++) 
		{
			if (actualWord[i] == "newline") 
			{
				breaks++;
				last = i;
				break;
			}
			else 
			{
				line4len++;
				line4width += actualWord.widths[i];
				line4height += actualWord.heights[i];
			}
		}
	}
	else
	{
		line4len = 0;
		line4width = 0;
		line4height = 0;
	}
	
	if (breaks == 4) 
	{
		line5len = 0;
		line5width = 0;
		line5height = 0;
		for (var i = last+1; i < actualWord.length; i++) 
		{
			if (actualWord[i] == "newline") 
			{
				breaks++;
				last = i;
				break;
			}
			else 
			{
				line5len++;
				line5width += actualWord.widths[i];
				line5height += actualWord.heights[i];
			}
		}
	}
	else
	{
		line5len = 0;
		line5width = 0;
		line5height = 0;
	}
	
	var lengths = new Array();
	lengths[0] = line1width;
	lengths[1] = line2width;
	lengths[2] = line3width;
	lengths[3] = line4width;
	lengths[4] = line5width;
	
	
	////////console.log("Line 1 length = " + line1width);
	//////////console.log("Line 2 length = " + line2width);
	//////////console.log("Line 3 length = " + line3width);
	//////////console.log("Line 4 length = " + line4width);
	//////////console.log("Line 5 length = " + line5width);
	
	//////////console.log("lengths = " + lengths)
	//////////console.log("GET MAX = " + lengths.getMax())
		
	//var w = 600/lengths.getMax() + "px";
	
	var pct_w = 600 / lengths.getMax();
	////////console.log("Resize pct = " + pct_w);
	var new_h = 0;
	
	for (var i = 0; i < actualWord.file.length; i++) 
	{
		//new_h = actualWord.heights[i] * pct_w;
		new_h = 600 * pct_w;
		$($("#word").children()[i]).attr({"height": new_h});
	}
	
	//////////console.log("pct_w = " + pct_w);
	
	//$("#word > .letter").css({"width":w});
	//$("#word > .space").css({"width":w*.3, "height":"50px"});
}

function changeAlign(align)
{
	$("#word").css({"textAlign" : align})
	$("#lettersinput").css({"textAlign" : align})
}

Array.prototype.getMax = function()
{
	var max = Number.MIN_VALUE, v, len = this.length, i = 0;
	for (; i < len; ++i)
	if (typeof (v = this[i]) == 'number')
	max = Math.max(max, v);
	return max;
}


// Plugins for adding images to stage
$.fn.image = function(src, f, letter){
	return this.each(function(){
		
		if(letter != " ")
		{
			fucksafari = "letter";
		}
		
		//////////console.log("plugin letter = " + letter)
		
		$("<img />").appendTo(this).attr({"src": src, "class": fucksafari}).load( f ).click(function()
		{
			regenerateInd(0)
		});
	});
};

$.fn.imageN = function(cp, src, f, letter){
	return this.each(function(){
		if(letter != " ")
		{
			fucksafari = "letter";
		}
		
		////////console.log("letter = " + letter)
		
		$("<img />").insertBefore($("#word img").get(cp)).attr({"src": src,	"class": fucksafari}).load( f ).click(function()
		{
			regenerateInd(cp)
		});
		
	});
};

$.fn.imageF = function(cp, src, f, letter){
	return this.each(function(){
		if(letter != " ")
		{
			fucksafari = "letter";
		}
		else
		{
			////////console.log("SPACE DETECTED");
			fucksafari = "space";
		}
		
		$("<img />").insertAfter($("#word > *").get(cp-1)).attr({"src": src, "class": fucksafari}).load( f ).click(function()
		{
			regenerateInd(cp)
		});
		
	});	
};

// Plugins for adding divs to stage
$.fn.br = function(f)
{
	return this.each(function()
	{
		$("<p class='brclass' />").appendTo(this);
	});
};

$.fn.brF = function(cp, f)
{
	return this.each(function()
	{
		$("<p class='brclass' />").insertAfter($("#word > *").get(cp-1));
	});
};

function emailFriend()
{
	var wordFiles = JSON.encode(actualWord.file);
	////////console.log("wordFiles = " + wordFiles);
	
	document.location = "email-a-friend.php?w=" + wordFiles;
}


function downloadWord()
{
	var wordFiles = JSON.encode(actualWord.file);
	
	document.location = "http://www.spellingchange.com/download-your-word.php?w=" + wordFiles;
}

function makeShirt()
{
	var wordFiles = JSON.encode(actualWord.file);
	////////console.log("wordFiles = " + wordFiles);
	
	document.location = "make-your-own-tshirt.php?w=" + wordFiles
}

function makePostCard()
{
	var wordFiles = JSON.encode(actualWord.file);
	////////console.log("wordFiles = " + wordFiles);
	
	document.location = "make-your-own-postcard.php?w=" + wordFiles
}

function makePoster()
{
	var wordFiles = JSON.encode(actualWord.file);
	////////console.log("wordFiles = " + wordFiles);
	
	document.location = "make-your-own-poster.php?w=" + wordFiles
}

function makeSticker()
{
	var wordFiles = JSON.encode(actualWord.file);
	////////console.log("wordFiles = " + wordFiles);
	
	document.location = "make-your-own-sticker.php?w=" + wordFiles
}

function regenerate(letterFile)
{
	////////console.log("Regenerating Word");
		
	for(var i = 0; i < actualWord.file.length; i++)
	{
		if (actualWord.letter[i] != "newline") 
		{
			getLetterRandom(actualWord.letter[i], i);
		}
	}
}

function regenerateInd(pos)
{
	////////console.log("Regenerating Word");
		
	getLetterRandom(actualWord.letter[pos], pos);
}

function getLetterRandom(letter, num)
{
	var rand = Math.floor(Math.random()*5000);
	
	if(letter == "?")
	{
		nletter = "_QUESTION";
	}
	else if(letter == "!")
	{
		nletter = "_EXCLAMATION";
	}
	else if(letter == "&")
	{
		nletter = "_AMPERSAND";
	}
	else if(letter == ".")
	{
		nletter = "_DOT";
	}
	else if(letter == ",")
	{
		nletter = "_COMMA";
	}
	else
	{
		nletter = letter;
	}
	
	$.getJSON("http://www.spellingchange.com/lib/Letters.php?letter=" + nletter + "&type=" + letterType + "&rand="+rand, function(data)
	{
		swapLetter(data.file, data.letter, num)
	});
}

function swapLetter(file, letter, num)
{
	var rand = Math.floor(Math.random()*5000);
	actualWord.file[num] = file;
	startSpinner();

	$($("#word").children()[num]).attr({"src":"http://www.spellingchange.com/lib/Letters.php?letter=" + letter + "&file=" + file + "&rand=" + rand + "&type=" + letterType}).load( function(){
		stopSpinner();
	} )
}

// Restrict text input characters
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z\.!,\?&]/g;

function restrictCharacters(myfield, e, restrictionType) 
{
	if (!e) var e = window.event
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);

	// if they pressed esc... remove focus from field...
	if (code==27) { this.blur(); return false; }
	
	characters = ['%', '$', '('];
	
	for (var i = 0, l = characters.length; i < l; i++) 
	{
		if (e.charCode == characters[i].charCodeAt(0)) 
		{
			return false;
		}
	}

	//////////console.log("character = " + character);
	// ignore if they are press other keys
	// strange because code: 39 is the down key AND ' key...
	// and DEL also equals .
	
	if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && code!=39 && code!=32 && code!=13) 
	{
		if (character.match(restrictionType)) 
		{
			//////////console.log("matches");
			return true;
		} 
		else 
		{
			//////////console.log("no matches");
			return false;
		}
	}
}

// TextArea Limit
function limitTextarea(el,maxLines,maxChar){
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
//alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){ 
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}

function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}

Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};