/**
 * Supports: "FKey" | "FKeySet"
 * 
 * @constructor
 * @extends Agent
 * @param {String}
 *            id This Agent's id
 */
function PopupAgent(id) {

	this.prefixRecordModifyDiv = "panel_recordModifyDiv_";
	this.prefixModalOverlay = "modal-overlay_";

	if (id) { // prevents prototype declarations creating these attribs &
		// methods
		this.init(id);
		this.popupWindow = null; // set when popup window opens, reset to
		// null when closing

		// procedure callbacks implemented in modRec, filter & collection
		// this.update = AgentPCB.update;
	}

	this.isStable = function() { // is closed
		// if the popup is open there may be unsaved modifications
		try {
			return (!this.popupWindow || this.popupWindow.closed != false)
		} catch (e) {
			return true
		}
	}

	this.getObj = function() {
		return $(this.id)
	}

	this.cancel = function() {
		this.popupWindow = false;

//		var parentFieldRef = this.fieldRef;
//		var panelAgent = Manager.getAgent("panel_" + parentFieldRef);
//		Manager.setAgentFocus(panelAgent);
		
		this.removeModalWindow();
	}
	
	this.removeModalWindow = function() {
		$j("#" + this.prefixRecordModifyDiv + this.fieldRef).css("display", "none");
		$j("#" + this.prefixRecordModifyDiv + this.fieldRef).removeClass("modal-window");
		$j("#" + this.prefixRecordModifyDiv + this.fieldRef).html("");
		
		$j("#" + this.prefixModalOverlay + this.fieldRef).remove();
		
		Manager.zIndexCurrent = Manager.zIndexCurrent - 102;
	}
	
	// this.openPopup = function(href) {
	// // check that modifier is not already open
	// if (this.isStable()) {
	// // open popup
	// this.popupWindow = openPositionedPopup(href, Manager.getWinName(this.id),
	// this.getObj())}}

	this.openPopup = function(href) {
		
		// div id where the new popup show in
		var slideDivId = this.prefixRecordModifyDiv + this.fieldRef;

		var overlayId = "modal-overlay_" + this.fieldRef;

		// Create our overlay object
		// var overlay = $j("#modal-overlay");
		var overlay = $j("<div id='" + overlayId + "'></div>");

		var modalWindow;
		if ($(slideDivId)) {
			modalWindow = $j("#" + slideDivId);
		} else {
			modalWindow = $j("<div id='" + slideDivId
					+ "' class='panel'></div>");
		}
		// Create our modal window
		// var modalWindow = $j(slideDivId);

		// set new popup window postion
		var buttonDivId = "#" + this.id.replace("popup_", "sug_");
		if (!$j(buttonDivId).get(0)){
			buttonDivId = "#" + this.id;
		}
		
		
		var slidePostionX = getAbsPos($j(buttonDivId).get(0), 'Left');
		var slidePostionY = getAbsPos($j(buttonDivId).get(0), 'Top') + 16;

		$j("body").append(overlay);
		overlay.addClass("modal-overlay");

		overlay.css("opacity", 0.3);
		// Set the css and fade in our overlay
		overlay.show();
		
		
		var modalLoad = $j("<div id='modal-load'></div>");
		modalLoad.css("top", slidePostionY);
		modalLoad.css("left", slidePostionX);
		modalLoad.css("z-index", 10000);
		$j("body").append(modalLoad);
		

		$j.post(href, function(htmlToShow) {
			modalWindow.css("display", "none").html(htmlToShow);

			modalWindow.addClass("modal-window");

			$j(this).addClass("modal-image");
			$j("body").append(modalWindow);
			
			if (slidePostionX+ modalWindow.outerWidth() > $j(document).width()-16) {
//				slidePostionX = $j(document).width() - 16 - modalWindow.outerWidth() ;
				slidePostionX = 16;
			} 
			
			modalWindow.css("left", slidePostionX);
			modalWindow.css("top", slidePostionY);
			// alert(" set " + slidePostionX + " " + slidePostionY);
			
			$j("#modal-load").remove();
			modalWindow.fadeIn(50);
			$j(slideDivId).fadeIn(400);
			Manager.zIndexCurrent = Manager.zIndexCurrent + 102;

			modalWindow.css("z-index", Manager.zIndexCurrent);
			overlay.css("z-index", Manager.zIndexCurrent - 2);
			this.popupWindow = true;
			
			//When the DOM will be modified and the HTML updated, we can adjust UI (for "User Interface") and apply the rules, if there is so:
			$j(document).ready(function(){
				//see utils.js, to avoid suggestions from the Form History of the web browser
				// which could interfere with suggestion UI of some FKey fields.
				clearBrowserTextInputHistory();
				
				//see ruleManager.js:
				preCheckAndAdjustUI();
				checkAllRulesAndFieldValues();
			});
				
		}, "html");
	}

	this.closePopup = function() {
		if (!this.isStable())
			this.cancel();
	}

	/**
	 * Called by popup window onSubmit. Submits new value to server.
	 */
	this.sendRequest = function(recId) {
		var isOK = true;
		
		if (this.fieldType == 'FKeySet' && this.recId) {
			Manager.getAgent('link_' + this.fieldRef).addFKey(recId);
			
			var xeFKeySet = Manager.getAgent('link_' + this.fieldRef).getExistingFKeySet();
			if (!xeFKeySet) xeFKeySet = new XMLElement('FKeySet');
			var xmlValue = xeFKeySet.toXML();
			var xeValue = new ParsedXMLElement(xmlValue);
			var xeCommand = this.xeSetFieldValue(xeValue);
			var xeWidgetResult = this.xeWidgetResult(xeCommand);
			isOK = this.update(xeWidgetResult, recId);
			
		} else if (this.fieldType == 'Parent' && this.recId) {
			var xmlValue = (recId && recId != '') ? '<Parent recId="' + recId + '"/>'
					: '<NullValue/>';
			var xeValue = new ParsedXMLElement(xmlValue);

			var xeCommand;
			if (this.recId) {
				xeCommand = this.xeSetFieldValue(xeValue);
			} else if (this.mmrId) {
				xeCommand = this.xeMMRSetFieldValue(xeValue);
				if (this.blockField)
					xe.setAttribute('blockFieldPSId', this.blockField);
				if (this.mainTable)
					xe.setAttribute('mainTablePSId', this.mainTable);
			} else {
				xeCommand = this.xeGetPSValueLabel(xeValue, {
					dateFormat : 'long'
				});
			}
			var xeWidgetResult = this.xeWidgetResult(xeCommand);
			isOK = this.update(xeWidgetResult);
		} else {
			var xmlValue = (recId && recId != '') ? '<FKey recId="' + recId + '"/>'
					: '<NullValue/>';
			var xeValue = new ParsedXMLElement(xmlValue);

			var xeCommand;
			if (this.recId) {
				xeCommand = this.xeSetFieldValue(xeValue);
			} else if (this.mmrId) {
				xeCommand = this.xeMMRSetFieldValue(xeValue);
				if (this.blockField)
					xe.setAttribute('blockFieldPSId', this.blockField);
				if (this.mainTable)
					xe.setAttribute('mainTablePSId', this.mainTable);
			} else {
				xeCommand = this.xeGetPSValueLabel(xeValue, {
					dateFormat : 'long'
				});
			}
			var xeWidgetResult = this.xeWidgetResult(xeCommand);
			isOK = this.update(xeWidgetResult);
		}
		
		return isOK;
	}

	this.update = function(xeWidgetResult, recId) {
		// display label for suggestion or lkTable Agent
		var rLabel = this.getResultLabel(xeWidgetResult);

		if ($('sug_' + this.fieldRef) && this.fieldType == "FKey") {
			$('sug_' + this.fieldRef).value = rLabel;
		} else if ($('dd_' + this.fieldRef)) {
			Manager.getAgent('dd_' + this.fieldRef).newOption(xeWidgetResult, recId);
		} else if ($('label_' + this.fieldRef) && (this.fieldType == "FKey" || this.fieldType == "Parent")) {
			$j('#label_' + this.fieldRef).html(rLabel);
		}
		
		// display error message in popup
		var errorMsg = this.getErrorMsg(xeWidgetResult);
		if (errorMsg && errorMsg != '') {
			this.displayErrorMsgInPopup(errorMsg);
			return false;
		} else {
			this.removeModalWindow();
				
			$j("#error_" + this.fieldRef).css("display", "none");
				
			// a timeout is required by Mozilla in order to release the onClick event
			setTimeout('Manager.getAgentWithId("' + this.id + '").closePopup()', 100);
				
			return true;
		}
	}

	this.displayErrorMsgInPopup = function(errorMsg) {
		// if (!this.isStable) { // popup win is open
		// var pw = this.popupWindow;
		// var oDiv = pw.$("errorMsg");
		oDiv = $("errorMsg");
		if (oDiv) { // DIV exists
			oDiv.innerHTML = errorMsg;
			oDiv.style.display = (errorMsg != null && errorMsg != '') ? '' : 'none';
			// if (pw.resizePopup) pw.resizePopup();
		}
		// }
	}

	this.toString = function() {
		return 'PopupAgent: {agentPrefix: ' + this.agentPrefix + '; fieldRef: ' + this.fieldRef + '}'
	}
}

PopupAgent.prototype = new Agent();
