/*************************************************************************************
Class WSGUI:
*************************************************************************************/
function WSGUI(wsEngine) {
	this.wsEngine = wsEngine;
}	
//----------------------------------------------------------------------------------
WSGUI.prototype.calcSuggestionsPosition = function(e, nSelectedIndex, popupElement) {
	var finalPoint = WSUtils.zeroPoint();
	//var mousePoint = WSUtils.getMousePoint(e);
	var element = WSDomUtils.getEventElement(e);
	var elmBounds = WSUtils.getElementBounds(element,true);
	var editorBounds = WSUtils.getElementBounds(this.wsEngine.editor.getInstance(),true);
	var editorViewport = WSUtils.getWindowBounds(this.wsEngine.editor.getWin());
	//var editorViewport = this.getEditorViewport();
	//var editorMargin = {left: 0, right: 0, top: 0, bottom: 0};
	//editorMargin.left = parseInt(WSDomUtils.getStyle(this.editor.getBody(), "margin-left"));
	//editorMargin.top  = parseInt(WSDomUtils.getStyle(this.editor.getBody(), "margin-top"));
	
	var editorScroll = WSUtils.getScrollXY(this.wsEngine.editor.getWin());
	
	//alert("mousePoint: x=" + mousePoint.x + ", y=" + mousePoint.y);
	//alert("editorBounds: x=" + editorBounds.x + ", y=" + editorBounds.y + ", h=" + editorBounds.h + ", w=" + editorBounds.w);
	//alert("elmBounds: x=" + elmBounds.x + ", y=" + elmBounds.y + ", h=" + elmBounds.h + ", w=" + elmBounds.w);
	//alert("editorViewport: x=" + editorViewport.x + ", y=" + editorViewport.y + ", h=" + editorViewport.h + ", w=" + editorViewport.w);
	//alert("editorScroll: x=" + editorScroll.x + ", y=" + editorScroll.y);	
	
	elmBounds.x += editorBounds.x - editorScroll.x;
	elmBounds.y += editorBounds.y - editorScroll.y;
	finalPoint.x = elmBounds.x;
	finalPoint.y = elmBounds.y + elmBounds.h + 3;

	/*
	elmBounds.x -= (editorViewport.x + editorScroll.x);
	elmBounds.y -= (editorViewport.y + editorScroll.y);
	finalPoint.x = editorBounds.x + elmBounds.x;
	finalPoint.y = editorBounds.y + elmBounds.y + elmBounds.h + 3;
	*/
	
	//alert("elmBounds 2: x=" + elmBounds.x + ", y=" + elmBounds.y + ", h=" + elmBounds.h + ", w=" + elmBounds.w);
	//finalPoint.x = mousePoint.x + editorBounds.x;

	//alert("editorViewport : x="+editorViewport.x+", y="+editorViewport.y+", h="+editorViewport.h+", w="+editorViewport.w);
	//alert("finalPoint: x="+finalPoint.x+", y="+finalPoint.y);
	//check if position is out of window bounds
	if (popupElement) {
		var windowBounds = WSUtils.getWindowBounds(window);
		var popupBounds  = WSUtils.getElementBounds(popupElement);
		//alert("popupBounds: x=" + popupBounds.x + ", y=" + popupBounds.y + ", h=" + popupBounds.h + ", w=" + popupBounds.w);
		//alert("windowBounds: x=" + windowBounds.x + ", y=" + windowBounds.y + ", h=" + windowBounds.h + ", w=" + windowBounds.w);
		//alert("(finalPoint.y > windowBounds.y + windowBounds.h - popupBounds.h) = (" + finalPoint.y+","+windowBounds.y+","+windowBounds.h+","+popupBounds.h+")");
		//alert(finalPoint.y+" > "+windowBounds.y+" + "+windowBounds.h+" - "+popupBounds.h);

		//Check if the popup menu exceeded the bottom border
		var lower_bound = windowBounds.y + windowBounds.h;
		if (finalPoint.y + popupBounds.h >= lower_bound) {
			finalPoint.y = lower_bound - popupBounds.h;
			//alert("(finalPoint.y,elmBounds.y) = (" + finalPoint.y + "," + elmBounds.y + ")");
			if (finalPoint.y < elmBounds.y + elmBounds.h && elmBounds.y - popupBounds.h > windowBounds.y) {
				finalPoint.y = elmBounds.y - popupBounds.h;
			}
		}

		//Check if the popup menu exceeded the right border		
		var right_bound  = windowBounds.x + windowBounds.w - popupBounds.w;
		finalPoint.x = Math.min(finalPoint.x , right_bound);
	}
	return finalPoint;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.getCustomId = function(id) {
	return new String(id + "_" + this.wsEngine.editorNumber);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.createUIElements = function() {
	WSDebug.log("Creating elements for popups...", "createWSElements");
	for (var sTagID in this.wsEngine.config.resultElementsInfo) {
		var oElement = document.createElement('div');
		var oRes = this.wsEngine.config.resultElementsInfo[sTagID];
		var id = this.getCustomId(oRes.id);
		oElement.id = id;
		oElement.name = name;
		oElement.className = oRes.className;
		oElement.style.position = 'absolute';
		oElement.style.zIndex = '200';
		oElement.style.display = 'none';
		this.wsEngine.editor.getInstance().parentNode.appendChild(oElement);
	}
	return true;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.removeUIElements = function() {
	WSDebug.log("Removing elements for popups", "removeWSElements");
	for (var sTagID in this.wsEngine.config.resultElementsInfo) {
		var oRes = this.wsEngine.config.resultElementsInfo[sTagID];
		var id = this.wsEngine.getCustomId(oRes.id);
		var oElement = document.getElementById(id);
		if (oElement) {
			oElement.parentNode.removeChild(oElement);
		}
	}
}
//----------------------------------------------------------------------------------
WSGUI.prototype.getSpecificResultElement = function(oResElement) {
	if (document) {
		var id = this.getCustomId(oResElement.id);
		return document.getElementById(id);
	}
	return null;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.getSuggestionsElement = function() {
	return this.getSpecificResultElement(this.wsEngine.config.resultElementsInfo.suggestions);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.getDictionaryElement = function() {
	return this.getSpecificResultElement(this.wsEngine.config.resultElementsInfo.dictionary);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.getFeedbackElement = function() {
	return this.getSpecificResultElement(this.wsEngine.config.resultElementsInfo.feedback);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.getProgressElement = function() {
	return this.getSpecificResultElement(this.wsEngine.config.resultElementsInfo.progress);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.displaySummaryNotice = function(wsSummary) {
	var sum = wsSummary.enrichments + wsSummary.spelling + wsSummary.grammar;
	if (sum == 0) {
		return;
	}
	var pStr = "<table id='wsSummaryNotice' cellspacing=0 cellpadding=0 border=0>" +
			   "<th class='header_li'>WhiteSmoke found:</th>";
					
	if (wsSummary.grammar > 0) {
		pStr += "<tr><td colspan=2 class='grammar_li'>" + 
				wsSummary.grammar + " grammar mistake" + 
				(wsSummary.grammar==1 ? "" : "s") + "</td></tr>";
	}
	if (wsSummary.enrichments > 0) {
		pStr += "<tr><td colspan=2 class='style_li'>" + 
				wsSummary.enrichments + " style enhancement" + 
				(wsSummary.enrichments==1 ? "" : "s") + "</td></tr>";
	}
	if (wsSummary.spelling > 0) {
		pStr += "<tr><td colspan=2 class='spelling_li'>" + 
				wsSummary.spelling + " spelling mistake" + 
				(wsSummary.grammar==1 ? "" : "s") + "</td></tr>";
	}
	if (wsSummary.scoreMsg != "") {
		pStr += "<tr><td>&nbsp;</td></tr>" + 
				//"<tr><td colspan=2 class='score_li'>WhiteSmoke Writing Index:<br/>" + 
				"<tr><td colspan=2 class='score_li'>" + wsSummary.scoreMsg + 
				//wsSummary.score + " out of 10" +
				"</td></tr>";
	}
	
	pStr += "</table>";
	
	

	var template = new WSTemplate(this.wsEngine.config.feedbackTemplate);
	var str  = template.evaluate({
					sMessage: pStr,
					okButton: '<HR><div id="ServerFeedbackOKButton"></div>'
					//okButton: '<div id="ServerFeedbackOKButton" style="float:right;"></div>'
					//downloadButton: '<div id="ServerFeedbackDownloadButton" style="float:left;"></div>'
				});
	this.showServerFeedback(str);
}	
//----------------------------------------------------------------------------------	
WSGUI.prototype.showMessageBox = function(html) {
	var oFeedback = this.getFeedbackElement();
	if (! oFeedback) {
		return false;
	}
	oFeedback.innerHTML = html;
	//alert(oFeedback.innerHTML);
	//Nifty("#"+oFeedback.id,"big");
	//alert(oFeedback.innerHTML);
	this.displayMessage(oFeedback);
}
//----------------------------------------------------------------------------------	
WSGUI.prototype.showServerFeedback = function(html) {
	//this.showMessageBox(html);
	//return;
	//this.editor.tryDisableDesignMode();
	var self = this;
	var oFeedback = this.getFeedbackElement();
	if (! oFeedback) {
		return false;
	}
	oFeedback.innerHTML = html;
	//alert("oFeedback.innerHTML\n" + oFeedback.innerHTML);
	var nodes = oFeedback.getElementsByTagName("div");
	
	for (var i=0; i<nodes.length; ++i) {
		//if (nodes[i].id == "bgBottomImg") {
		if (nodes[i].id == "ServerFeedbackOKButton") {
			/*var new_div = document.createElement('div');
			new_div.innerHTML = "<BR><HR>";
			new_div = nodes[i].appendChild(new_div);*/

			//We are not creating table directly, because table.innerHTML is read-only in IE.
			var new_div	= document.createElement('div');
			var inner = 
			  "<table cellspacing=0 cellpadding=0 style='width: 100%; margin:0; padding:0;'>" +
			  "<tr style='width: 100%;'>" +
				"<td style='width: 25%;'>" + 
				  "<button id='feedback_ok_button' name='feedback_ok_button'>OK</button>" +
				"</td>" + 
				"<td style='width: 10%;'>&nbsp;|&nbsp;</td>" + 
				"<td style='width: 65%;'>" + 
				  //"<a href='"+sLandingPage+"' onclick='javascript:onLandingPageClicked();' target='_blank' style='font-size: 100%;' id='feedback_upgrade_link' name='feedback_upgrade_link'>Find out how to improve!</a>" +
				  "<a style='font-size: 100%;' id='feedback_upgrade_link' name='feedback_upgrade_link'>Get the Full WhiteSmoke Writer 2011 Today !</a>" +
				"</td>" +
			  "</tr></table>";

			new_div.style.width = '100%';
			new_div.innerHTML = inner;
			new_div = nodes[i].appendChild(new_div);
			
			var ok_btn = document.getElementById("feedback_ok_button");
			if (ok_btn) {
				WSDomUtils.addEvent(ok_btn,'click',
							function() {
								WSDomUtils.hideElement(oFeedback);
								oFeedback.innerHTML = "";
								self.wsEngine.editor.setFocus();
				});
			}
			var get_btn = document.getElementById("feedback_upgrade_link");
			if (get_btn) {
				WSDomUtils.addEvent(get_btn,'click', function(){onLandingPageClicked();});
				//get_btn.href = sLandingPage;
				//get_btn.target="_new";
			}

			var clr_btn = document.getElementById("feedback_clear_button");
			if (clr_btn) {
				clr_btn.innerHTML = "Clear Text";
				WSDomUtils.addEvent(clr_btn,'click',
							function() {
								WSDomUtils.hideElement(oFeedback);
								oFeedback.innerHTML = "";
								self.wsEngine.editor.clearContent();
								self.wsEngine.editor.setFocus();
								//focus(self.wsEngine.editor);
				});
			}
			break;
		}
	}
	this.displayMessage(oFeedback);
	return true;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.displayMessage = function(oDisplayElement) {
	WSUtils.centerElement(oDisplayElement,window);
	WSDomUtils.showElement(oDisplayElement);
	return true;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showWarningMsg = function(warningMessage) {
	WSDebug.log("displayWarning");
	if (warningMessage.length <= 0) { // Display the warning
		return;
	}
	//alert("displayContent: this.warningMessage=\n" + this.warningMessage);
	//We have a message to display
	var tempMsg = "";
	if (warningMessage.indexOf("No changes were made") != -1) {
		tempMsg = this.wsEngine.config.noChangesMsg;
	}
	else {
		var start_idx = warningMessage.indexOf('"') + 1;
		var end_idx  = warningMessage.lastIndexOf('"');
		tempMsg = warningMessage.substr(start_idx, end_idx - start_idx);
		
		var tmp_elm = document.createElement('div');
		tmp_elm.innerHTML = tempMsg;
		var nodes = tmp_elm.getElementsByTagName('div');
		for (var i=0; i<nodes.length; ++i) {
			//alert("nodes["+i+"].className = " + nodes[i].className);
			if (nodes[i].className == "screenContent") { 
				//alert("screenContent\n" + nodes[i].innerHTML);
				tempMsg = nodes[i].innerHTML;
				break;
			}
		}
		delete tmp_elm;
		//tempMsg = tempMsg.replace(/ServerFeedbackXButton/, "");
		//alert("displayContent: tempMsg=\n" + tempMsg);
	}	
	var template = new WSTemplate(this.wsEngine.config.feedbackTemplate);
	var stripedMessage  = template.evaluate({
			sMessage: tempMsg,
			okButton: '<HR><div id="ServerFeedbackOKButton"></div>'
			//downloadButton: '<div id="ServerFeedbackDownloadButton"></div>'
		});
	this.showServerFeedback(stripedMessage);
	warningMessage = "";
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showExplanationMsg = function() {
	var template = new WSTemplate(this.wsEngine.config.feedbackTemplate);
	var msg  = template.evaluate({
			sMessage: this.wsEngine.config.explanationMsg,
			okButton: '<HR><div id="ServerFeedbackOKButton"></div>'
		});
	this.showServerFeedback(msg);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showErrorMsg = function(sResponseData) {
	var template = new WSTemplate(this.wsEngine.config.feedbackTemplate);
	var msg  = template.evaluate({
			sMessage: sResponseData,
			okButton: '<HR><div id="ServerFeedbackOKButton"></div>'
			//okButton: '<div id="ServerFeedbackOKButton"></div>',
			//downloadButton: '<div id="ServerFeedbackDownloadButton"></div>'
		});
	this.showServerFeedback(msg);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showLengthExceededMsg = function(sResponseData) {
	var template = new WSTemplate(this.wsEngine.config.feedbackTemplate);
	var stripedMessage  = template.evaluate({
			sMessage: this.wsEngine.config.getLengthExceededMsg(),
			okButton: '<HR><div id="ServerFeedbackOKButton"></div>'
			//okButton: '<div id="ServerFeedbackOKButton"></div>',
			//downloadButton: '<div id="ServerFeedbackDownloadButton"></div>'
		});
	this.showServerFeedback(stripedMessage);
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showProgressDialog = function(bShow) {
	WSDebug.log((bShow) ? "Showing progressDialog": "Hiding progressDialog", "showProgressDialog");
	if (! this.wsEngine.config.enableProgressWindow) {
		return;
	}	
	var oElement;
	var showProgress = (bShow) ? 1 : -1;
	if (this.config.globalProgressWindow) {
		if (bShow) {
			WSGlobalProgressWindow.addOpenProgressWindows(this.wsEngine.editor.id);
			if (WSGlobalProgressWindow.openProgessWindows.length < 2) {
				showProgress = 1;
				oElement = WSGlobalProgressWindow.globalProgessElement;
				if (!oElement) {
					oElement = this.getProgressElement();
				}
				WSGlobalProgressWindow.globalProgessElement = oElement;
			} else {
				showProgress = 0;
				return;
			}
		} else {
			WSGlobalProgressWindow.removeOpenProgressWindows(this.wsEngine.editor.id);
			if (WSGlobalProgressWindow.openProgessWindows.length == 0) {
				oElement = WSGlobalProgressWindow.globalProgessElement;
				if (!oElement) {
					oElement = this.getProgressElement();
				}
				showProgress = -1;
				WSGlobalProgressWindow.globalProgessElement = null;
			} else {
				showProgress = 0;
				return;
			}
		}
	} else {
		oElement = this.getProgressElement();
	}
	WSDebug.log("Will show with element " + oElement.toString(), "showProgressDialog");
	if (oElement) {
		if (showProgress == 1) {
			WSDebug.log("Will open pregresssdialog..", "showProgressDialog");
			this.hideSuggestions();
			this.hideDictionary();
			var editorFrameRect = WSUtils.getElementBounds(this.wsEngine.editor.getInstance());
			var dialogWidth = Math.max(196, editorFrameRect.w / 4);
			var dialogHeight = Math.max(58, editorFrameRect.h / 8);
			var t = new WSTemplate(this.wsEngine.config.progressWindow);
			sContent = t.evaluate({
				w: dialogWidth,
				h: dialogHeight
			});
			WSDomUtils.showElement(oElement);
			oElement.innerHTML = sContent;
			var elBounds = WSUtils.getElementBounds(oElement);
			if (this.wsEngine.config.globalProgressWindow) {
				var wbounds = WSUtils.getWindowBounds(self);
				oElement.style.left = (wbounds.x + (wbounds.w - elBounds.w) / 2) + "px";
				oElement.style.top = (wbounds.y + (wbounds.h - elBounds.h) / 2) + "px";
			} else {
				oElement.style.left = (editorFrameRect.x + (editorFrameRect.w - elBounds.w) / 2) + "px";
				oElement.style.top = (editorFrameRect.y + (editorFrameRect.h - elBounds.h) / 2) + "px";
			}
		} else if (showProgress == -1) {
			oElement.innerHTML = "";
			WSDomUtils.hideElement(oElement);
		}
		return true;
	} else {
		return false;
	}
}
//----------------------------------------------------------------------------------
WSGUI.prototype.displayDictionary = function(oDisplayElement) {
	var el = this.getSuggestionsElement();
	if (! WSDomUtils.isVisible(el)) {
		return;
	}	
	var b = WSUtils.getElementBounds(el);
	oDisplayElement.style.left = b.x + b.w + "px";
	oDisplayElement.style.top = b.y + "px";
	oDisplayElement.className = "wsDictionaryOn";
	oDisplayElement.style.display = "inline";
	oDisplayElement.style.visibility = "visible";
	return true;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.displaySuggestions = function(e, oDisplayElement, nSelectedIndex) {
	var targetPos = this.calcSuggestionsPosition(e, nSelectedIndex, oDisplayElement);
	//alert("displaySuggestions: nSelectedIndex=" + nSelectedIndex + ", targetPos.x="+targetPos.x+", targetPos.y="+targetPos.y);	
	oDisplayElement.style.left = (targetPos.x) + "px";
	oDisplayElement.style.top = (targetPos.y) + "px";
	WSDomUtils.showElement(oDisplayElement);
	return true;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showDictionaryResult = function() {
	var bSuggestionsPresent = true;
	var oDisplayElement = this.getDictionaryElement();
	if (!oDisplayElement) {
		bSuggestionsPresent = false;
		oDisplayElement = this.getSuggestionsElement();
		if (!oDisplayElement) {
			return false;
		}
	}
	var vSuggestions = this.wsEngine.stLastPointedInfo.vDictionary;
	if (vSuggestions.length <= 0) {}
	var sWord = this.wsEngine.stLastPointedInfo.sWord;
	var sContent = "";
	sContent += '<table class="wsDictionary">';
	sContent += '<tr>';
	sContent += '<td valign="top">';
	sContent += '<table>';
	sContent += '<th align="left" class="wsDictionaryHeader">Dictionary</th>';
	sContent += '<tr><td align="left" class="wsDictionaryValue">' + sWord + ':</td></tr>';
	if (vSuggestions.length <= 0) {
		sContent += '<tr><td style="font-style:italic;" class="wsDictionaryValue">no suggestions</td></tr>';
	}
	for (var i = 0; i < vSuggestions.length; ++i) {
		sContent += '<tr>';
		sContent += '<td class="wsDictionarySuggestion">';
		sContent += vSuggestions[i];
		sContent += '</td>';
		sContent += '</tr>';
	}
	sContent += '</table></td></tr></table>';
	oDisplayElement.innerHTML = sContent;
	var e = this.wsEngine.stLastPointedInfo.e;
	if (bSuggestionsPresent == false) {
		this.displaySuggestions(e, oDisplayElement, this.wsEngine.stLastPointedInfo.nIndex);
	} else {
		this.displayDictionary(oDisplayElement);
	}
	return true;
}
//----------------------------------------------------------------------------------
WSGUI.prototype.showTrialMessage = function(e) {
	alert("This version available to the full version only.\nTo register go to -> https://buy.whitesmoke.com/buynew/");
	return true;
}
//----------------------------------------------------------------------------------

