/*
	Copyright 2008 Egmont Serieforlaget AS

	Developed by Escio AS - http://www.escio.no/
*/
function eXWord_Display(ePuzzle, eXWord) {
	this.ePuzzle = ePuzzle;

	this.eXWord = eXWord;
	this.eXWord.painter = this;

	this.ePuzzle.initPuzzleArea();

	this.eXWordTable	= document.createElement('table');

	this.height = 700;
	this.width = 600;


	this.useRGBa = false;
	if((BrowserDetect.browser == 'Firefox') && (BrowserDetect.version >= 3)) { this.useRGBa = true;}
	if((BrowserDetect.browser == 'Safari')) { this.useRGBa = true;}
	if((BrowserDetect.browser == 'Chrome')) { this.useRGBa = true;}

	this.cellR = 226;
	this.cellG = 183;
	this.cellB = 255;

	this.wordR = 74;
	this.wordG = 74;
	this.wordB = 255;

	this.initXWordElement = function() {
		var baseId = this.ePuzzle.puzzleContainer;

		this.eXWordTable.id		= baseId + '_xword';

		this.ePuzzle.puzzleArea.appendChild(this.eXWordTable);
	}

	this.buildXWord = function() {
		var xWord	= this.eXWord.xWord;
		var baseId	= this.ePuzzle.puzzleContainer;

		// Calculate color components
		this.cellR = hex2R(xWord.colors.selectedCell);
		this.cellG = hex2G(xWord.colors.selectedCell);
		this.cellB = hex2B(xWord.colors.selectedCell);

		this.wordR = hex2R(xWord.colors.selectedWord);
		this.wordG = hex2G(xWord.colors.selectedWord);
		this.wordB = hex2B(xWord.colors.selectedWord);

		
		// Build table
		var grid	= xWord.grid;

		if(xWord.dimensions) {
			var dimensions = xWord.dimensions;
			this.width = dimensions.width;
			this.height = dimensions.height;
		}

		this.cellWidth = ((this.width)/grid[0]);
		this.cellHeight = ((this.height)/grid[1]);

		if(xWord.offsetTop > 0) {
			this.height += xWord.offsetTop;
		}

		if(this.totalWidth || this.totalHeight) {
			if(this.totalHeight) $(baseId+'_wrapper').setStyle({height: this.totalHeight + 'px'});

			if(this.totalWidth) {
				$(baseId+'_wrapper').setStyle({width: this.totalWidth + 'px'});
			}

			$(baseId+'_wrapper').setStyle({overflow: 'hidden'});
		}

		this.sizeFactor	= (this.cellHeight > this.cellWidth) ? this.cellWidth : this.cellHeight;
		this.letterSize	= Math.round((this.sizeFactor/4)*2.3);
		this.padding	= Math.round((this.sizeFactor/4)*0.6);

		var tBody	= document.createElement('tbody');

		this.eXWordTable.appendChild(tBody);
		this.eXWordTable.style.width = this.width + 'px';
		this.eXWordTable.style.height = parseInt(this.height + 1) + 'px';
		this.eXWordTable.style.overflow	= 'hidden';

		Element.extend(this.eXWordTable);
		var imagePath = this.eXWord.domain+"/"+xWord.images.puzzleImage;
		var strBackground = "transparent url("+imagePath+") no-repeat left top"
		this.eXWordTable.setStyle({
			background: strBackground
		});

		if(BrowserDetect.browser == 'Safari') {
			this.eXWordTable.style.height = parseInt(this.height + 5) + 'px';
		}

		//if(BrowserDetect.browser == 'Firefox')	{ if(BrowserDetect.version >= 3) {} }
		//if(BrowserDetect.browser == 'Explorer')	{ if(BrowserDetect.version >= 7) {} }

		// Add empty row for header image
		if(xWord.offsetTop > 0) {
			eXWordTableRow = tBody.insertRow(tBody.rows.length);
			eXWordTableRow.style.height = parseInt(parseInt(xWord.offsetTop-1)) + 'px';
			eXWordTableRow.style.borderWidth = '0px';
		}

		// BUILD eXWord TABLE DEFINED BY grid
		for(tableY = 0; tableY < grid[1]; tableY++) {
			eXWordTableRow = tBody.insertRow(tBody.rows.length);
			eXWordTableRow.style.borderWidth = '0px';

			var rowHeight = Math.floor(this.cellHeight*(tableY+1)) - Math.floor(this.cellHeight*tableY);

			for(tableX = 0; tableX < grid[0]; tableX++) {
				var cellNumber = ((tableY*grid[0])+tableX);

				var eXWordTableCell = eXWordTableRow.insertCell(eXWordTableRow.cells.length);
				eXWordTableCell.id = this.ePuzzle.puzzleContainer + '_' + cellNumber;

				var cellWidth = Math.floor(this.cellWidth*(tableX+1)) - Math.floor(this.cellWidth*tableX);

				eXWordTableCell.style.width = cellWidth + 'px';
				eXWordTableCell.style.height = rowHeight + 'px';

				eXWordTableCell.style.textAlign = 'left';
				eXWordTableCell.style.verticalAlign = 'top';
				eXWordTableCell.style.padding = '0px';

				Element.extend(eXWordTableCell);
				eXWordTableCell.setStyle({
					borderWidth:	'0px 0px 0px 0px',
					borderStyle:	'none'
				});

				if(xWord.cells) {
					if(xWord.cells[cellNumber+1]) {
						var cell = xWord.cells[cellNumber+1];
						eXWordTableCell.style.background = 'transparent';

						if(cell['type']) {
							eXWordTableCell.definedType = cell['type'];

							if(cell['type'] == 'clue') {
							}
						}

						if(cell['top-bar']) {
							eXWordTableCell.definedTopBar = cell['top-bar'];
						}

						if(cell['left-bar']) {
							eXWordTableCell.definedLeftBar = cell['left-bar'];
						}
					}
				}
			}
		}

		this.eXWordTable.style.borderWidth = '0px';
		this.eXWordTable.style.borderStyle = 'none';
		this.eXWordTable.style.borderCollapse = 'collapse';

		// Prepare structured clue array
		xWord.orderedClues = new Array();
		xWord.orderedClues[0] = new Array();
		xWord.orderedClues[1] = new Array();

		currentXWord = this;
		xWord.words.each(function(word, index) {
			currentXWord.buildLetterCells(word, index)
		});

		$(baseId+'_loader').setStyle({display: 'none'});
		$(baseId).setStyle({display: 'block'});
		$(baseId+'_xword').setStyle({visibility: 'visible'});
	}

	var errorShown = false;

	this.buildLetterCells = function(word, index) {
		var xWord = this.eXWord.xWord;
		var grid = xWord.grid;

		// FIND INCREMENT VALUE
		// clue[0] == 0 => ACROSS
		// clue[0] == 1 => DOWN
		var increment = word[0] ? grid[0] : 1;

		// CREATE ACTIVE CELLS
		for(var i = 0; i < word[2]; i++) {
			var cellId = this.ePuzzle.puzzleContainer + '_' + ((word[1]-1) + (i*increment));
			var cell = $(cellId);
			if(cell.childNodes.length == 0) {
				var cellInput = document.createElement('input');

				cellInput.id = cellId + '_input';

				cell.appendChild(cellInput);

				try {
					$(cellId+'_input').words = new Array();

					if(BrowserDetect.browser == 'Explorer') {
						$(cellId+'_input').setStyle({
							position:		'relative',
							background:		'none',
							borderWidth:	'0px',
							textAlign:		'center',
							fontFamily: 	'Comic Sans MS, Comic Sans Serif, Arial',
							fontSize:		this.letterSize + 'px',
							fontWeight:		'bold',
							textTransform:	'uppercase',
							padding:		'5px 0px 0px 0px',
							width:			cell.style.width,
							height:			(parseInt(cell.style.height) - parseInt(this.padding)) + 'px'
						});
					} else{
						$(cellId+'_input').setStyle({
							position:		'relative',
							background:		'none',
							borderWidth:	'0px',
							textAlign:		'center',
							fontFamily: 	'Comic Sans MS, Comic Sans Serif, Arial',
							fontSize:		this.letterSize + 'px',
							fontWeight:		'bold',
							textTransform:	'uppercase',
							padding:		this.padding + 'px 0px 0px 0px',
							width:			cell.style.width,
							height:			(parseInt(cell.style.height) - parseInt(this.padding)) + 'px'
						});
					}
				} catch(e) {
					if(!errorShown) {
						alert(dumpObj(e));
						errorShown = true;
					}
				}

				var cellColor = 'transparent';
				if($(cellId).definedColor) {
					cellColor = $(cellId).definedColor;
				}

				$(cellId).setStyle({
					borderWidth:	'0px 0px 0px 0px',
					borderStyle:	'none'
				});

				if($(cellId).definedTopBar == 'true') {
					$(cellId).setStyle({
						borderTopWidth: '3px'
					});
				}

				if($(cellId).definedLeftBar == 'true') {
					$(cellId).setStyle({
						borderLeftWidth: '3px'
					});
				}

				Event.observe(cellId+'_input','click',this.eXWord.eventListener.bindAsEventListener(this.eXWord));
				Event.observe(cellId+'_input','keypress',this.eXWord.eventListener.bindAsEventListener(this.eXWord));
				Event.observe(cellId+'_input','keyup',this.eXWord.eventListener.bindAsEventListener(this.eXWord));
			}

			$(cellId+'_input').words.push(word);
		}
	}

	this.selectCell = function() {
		var selectedCell = this.eXWord.selectedCell;

		this.setCaretPosition(selectedCell);

		if(this.useRGBa) {
			$(selectedCell.id).up().setStyle({
				background:		'rgba('+this.cellR+','+this.cellG+','+this.cellB+',0.4) none repeat scroll 0 0'
			});
		} else {
			$(selectedCell.id).up().setStyle({
				background:		this.eXWord.xWord.colors.selectedCell,
				opacity:		'0.4'
			});
		}
	}

	this.setCaretPosition = function(inputElement) {
		if(document.selection) {
			inputElement.focus();
			var selection = document.selection.createRange();
			selection.moveStart('character', -inputElement.value.length);
			selection.moveStart('character', inputElement.value.length);
			selection.moveEnd('character', 0);
			selection.select();
		} else if(inputElement.selectionStart || inputElement.selectionStart == '0') {
			inputElement.selectionStart = inputElement.value.length;
			inputElement.selectionEnd = inputElement.value.length;
			inputElement.focus();
		}
	}

	this.focusCaret = function() {
		var selectedCell = this.eXWord.selectedCell;

		if(selectedCell) selectedCell.focus();
	}

	this.selectWord = function() {
		var xWord = this.eXWord.xWord;
		var grid = xWord.grid;
		var word = this.eXWord.selectedWord;

		var clueId = this.ePuzzle.puzzleContainer + '_clues_' + word[0] + '_' + word[1];
		if($(clueId)) {
			$(clueId).setStyle({
				background:		xWord.colors.selectedWord,
				opacity:		'0.4'
			});
		}

		var increment = word[0] ? grid[0] : 1;
		for(i = 0; i < word[2]; i++) {
			var cellId = this.ePuzzle.puzzleContainer + '_' + ((word[1]-1) + (i*increment));

			if(this.useRGBa) {
				$(cellId).setStyle({
					background:		'rgba('+this.wordR+','+this.wordG+','+this.wordB+',0.4) none repeat scroll 0 0'
				});
			} else {
				$(cellId).setStyle({
					background:		xWord.colors.selectedWord,
					opacity:		'0.4'
				});
			}
		}

		if(xWord.userId > 0) {
			if(this.eXWord.xWord.actions.solve) this.ePuzzle.enableButton('solveWordButton');
			if(this.eXWord.xWord.actions.solve) this.ePuzzle.enableButton('solveLetterButton');
		}
	}

	this.deSelectWord = function() {
		var xWord = this.eXWord.xWord;
		var grid = xWord.grid;
		var word = this.eXWord.selectedWord;

		if(word) {
			var clueId = this.ePuzzle.puzzleContainer + '_clues_' + word[0] + '_' + word[1];
			if($(clueId)) {
				$(clueId).setStyle({
					background:		'none',
					opacity:		'1'
				});
			}

			var increment = word[0] ? grid[0] : 1;
			for(i = 0; i < word[2]; i++) {
				var cellId = this.ePuzzle.puzzleContainer + '_' + ((word[1]-1) + (i*increment));

				$(cellId).setStyle({
					background:		'transparent',
					opacity:		'1'
				});
			}
		}
	}

	this.findWrittenWord = function(word) {
		var xWord = this.eXWord.xWord;
		var grid = xWord.grid;
		var writtenWord = '';

		var increment = word[0] ? grid[0] : 1;
		for(i = 0; i < word[2]; i++) {
			var inputId = this.ePuzzle.puzzleContainer + '_' + ((word[1]-1) + (i*increment) + '_input');

			var inputValue = $(inputId).value;
			if(inputValue == '') {
				writtenWord += ' ';
			} else {
				writtenWord += inputValue;
			}
		}

		return writtenWord;
	}

	this.getCharacter = function() {
		var selectedCell = this.eXWord.selectedCell;

		var prefix	= this.ePuzzle.puzzleContainer + '_';
		var postfix	= '_input';

		var cellNumber = stringPart(selectedCell.id,prefix.length,(selectedCell.id.length - postfix.length)-prefix.length);
		var cellLetter = selectedCell.value;

		var result = new Array();
		result.push(cellNumber);
		result.push(cellLetter);

		return result;
	}

	this.setCharacter = function(cellNumber, character) {
		var baseId = this.ePuzzle.puzzleContainer;
		var inputId = baseId + '_' + (cellNumber-1) + '_input';

		if($(inputId)) {
			var match = this.eXWord.charSet.match(character.capitalize());
			if(match && (match != null)) {
				if(($(inputId).value != '') && ($(inputId).value != ' ')) {
					if($(inputId).value.toLowerCase() != character.toLowerCase()) {
						this.markError(cellNumber);
					}
				}

				$(inputId).value = character.toLowerCase();
			} else {
				$(inputId).value = '';

				if(character != ' ') {
					this.markError(cellNumber);
				}
			}
		}
	}

	this.markError = function(cellNumber) {
		var baseId = this.ePuzzle.puzzleContainer;
		var cellId = baseId + '_' + (cellNumber-1);

		$(cellId).setStyle({
			background:		'#FF7575',
			opacity:		'0.4'
		});
	}

	this.newState = function() {
		var stateMessage = '';

		var baseId = this.ePuzzle.puzzleContainer;

		if(this.eXWord.state == 'IDLE') {
			$(baseId+'_loader').setStyle({display: 'none'});
			$(baseId).setStyle({display: 'block'});

			stateMessage += this.eXWord.stateMessage;
		}

		if(this.eXWord.state == 'ERROR') {
			$(baseId+'_loader').setStyle({display: 'none'});
			$(baseId).setStyle({display: 'block'});

			stateMessage += 'FEIL:<br/>'+this.eXWord.errorMessage;
		}

		if(this.eXWord.xWord && (this.eXWord.xWord.userId > 0)) {
			if(this.eXWord.saveState == 'CHANGED') {
				if(this.eXWord.xWord.actions.save) if(this.ePuzzle.enableButton('saveButton')) this.focusCaret();
			} else {
				if(this.ePuzzle.disableButton('saveButton')) this.focusCaret();
			}

			if(this.eXWord.xWord.actions.solve) this.ePuzzle.enableButton('solveButton');

			if(this.eXWord.xWord.startTs > 0) {
				stateMessage += 'Påbegynt: ' + tsToDate(this.eXWord.xWord.startTs);
				stateMessage += '<br>';
			}

			if(this.eXWord.xWord.endTs > 0) {
				stateMessage += 'Innlevert: ' + tsToDate(this.eXWord.xWord.endTs) + '<br>';
			 	stateMessage += 'Poeng: ' + this.eXWord.xWord.score;

				this.ePuzzle.disableButton('submitButton');
			} else {
				if(this.eXWord.xWord.actions.submit) this.ePuzzle.enableButton('submitButton');
			}
		} else {
			this.ePuzzle.disableButton('submitButton');
			this.ePuzzle.disableButton('solveButton');
		}

		this.ePuzzle.setStatus(stateMessage);
	}
}