/*
 *
 * this module defines a AdPreview class, which represents dynamic window showing advert details
 * it uses AdInfoText.aspx service of mpmads application
 *
 */

function AdPreview(servicePath, postMouseoutDelay, previewCssID) {
	/*
		constructor takes three arguments, postDelay, indicating the delay before window diminishes after mouse-out,
		previewCssID argument, giving the CSS ID of HTML element representing Advert Preview window 
		and servicePath argument, giving path to the service, which takes url argument "id" indicating uid of advert,
		returning plaintext in the format of the example below.

		CAPTION:Podrobnosti;
		SUBMITTER:Zadavatel:Muž;
		AGE:Věk:24;
		HEIGHT:Výška:189;
		WEIGHT:Váha:80;
		COUNTRY:Země:Česká republika;
		REGION:Region:Středočeský kraj;
		MARITALSTATUS:Rodinný stav:Svobodný/á;
		WANTED:Hledá:Ženu;
		RANK:Hodnocení:0;
		VOTES:Počet hlasů:0;
		RANK_REGISTERED:Hodnocení registrovanými:0;
		VOTES_REGISTERED:Počet hlasů od registrovaných:0;
		IMGPATH:services/medium.aspx?id=236&thumb=1;
		IMGCOMMENT:já;
	*/


	/* CONSTRUCTOR AND PRIVATE MEMBER DEFINITIONS */

	var _service_uri = servicePath;	
	var _post_mouseout_delay = postMouseoutDelay;
	var _preview_id = previewCssID;
	var _previewElement = window.document.getElementById(previewCssID);	

	var _mouse = new Mouse();
	var _offsetX = 20;
	var _offsetY = -50;
	var _hideTimer;
	var _suppressExceptions = true;

	if (_previewElement == null) {
		throw new Error ("Element with specified ID (" + previewCssID + ") does not exists in the document.");
	}

	/* PRIVATE METHOD DEFINITIONS */

	function instantHide()
	{
		_previewElement.style.visibility = "hidden";
		_previewElement.style.display = "none";
	}
	function show(advert_uid)
	{
		clearTimeout(_hideTimer);
		var requestURL = _service_uri + "?id=" + advert_uid;
		_previewElement.innerHTML = "Loading...";
		
		doRequest(requestURL);
		_previewElement.style.visibility = "visible";
		_previewElement.style.display = "block";
		document.body.onmousemove = preview.updatePosition;
	}
	this.show = show;

	function doRequest(url) {
		var xmlhttp = false;
		if(window.XMLHttpRequest) {
			try {
				xmlhttp = new XMLHttpRequest();
			} catch(e) {
				xmlhttp = false;
				_previewElement.innerHTML =
					"<div align='center'><strong>Error</strong><br /><br>cannot create or handle request</div>";
			}
		} else {
			if(window.ActiveXObject) {
				try {
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e) {
					try {
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(e) {
						xmlhttp = false;
						_previewElement.innerHTML =
							"<div align='center'><strong>Error</strong><br /><br>cannot create or handle request</div>";
					}
				}
			}
		}

		try {
			xmlhttp.open("GET", url, true);
		} catch(e) {
			_previewElement.innerHTML =
				"<div align='center'><strong>Security block</strong><br /><br>data cannot be loaded from other domain</div>";
			return false;
		}
		xmlhttp.onreadystatechange=function() {
			requestReadyStateChangeHandler(xmlhttp);
		}
		xmlhttp.send(null);
		return false;
	}

	function requestReadyStateChangeHandler(xmlhttp) {
		try {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					_previewElement.innerHTML = parseText(xmlhttp.responseText);
					return true;
				} else {
					instantHide(); //hideMe()
					return false; //no error message				
					if (xmlhttp.status == 404) {
						if (_suppressExceptions == false) {
							alert ("Sorry, no response");
						}
						xmlhttp.abort();
					} else {
						return false;
					}
				}
			}
		} catch(e) {
			if (_suppressExceptions == false) {
				alert ("No images found or other error: " + e);
			}
		}
	}

	function parseText(rawResult)
	{
		function isOneValueKey(key_to_check)
		{
			var one_value_keys = [
				"SUBMITTER", "WANTED", "COUNTRY", "REGION", "AGE", "HEIGHT", "WEIGHT", "RANK", "RANK_REGISTERED",
				"VOTES", "VOTES_REGISTERED", "SIGN", "MARITALSTATUS"
			];
			for(var counter = 0; counter < one_value_keys.length; counter++) {
				if (key_to_check == one_value_keys[counter]) {
					return true;
				}
			}
			return false;
		}

		var returned = rawResult.substring(0, rawResult.length);
		var records = returned.split(";\n");
		var lastRec = records.length - 1;
		var maxImages = 1;
		var imageCounter = 0;

		var HTMLresult;

		for (var i=0; i < lastRec; i++)
		{
			var record = records[i].split(':');
			var key = record[0];
			var keyLocalized;
			var value;

			if (key == "CAPTION") {
				if (record[1] != null && record[1] != "") {
					keyLocalized = record[1];
				} else {
					keyLocalized = key;
				}
				HTMLresult = "<span>" + keyLocalized + "</span>\n";
			} else {
				if (isOneValueKey(key)) {
					if (record[1] != null && record[1] != "") {
						keyLocalized = record[1];
					} else {
						keyLocalized = key;
					}
					if (record[2] != null && record[2] != "") {
						value = record[2];
					}
					HTMLresult += "<span class = 'leftDetail'>" + keyLocalized +
						"</span>\n<span class = 'rightDetail'>" + value + "</span>\n<div class = 'cleaner'></div>\n";
				} else {
					if (key == "IMGPATH") {
						if (imageCounter < maxImages) {
							var imagePath = record[1];
							if (imagePath != null && imagePath != "") {
								HTMLresult +=
									"<img src=\"" + imagePath + "\" />";
								imageCounter++;
							}
						}
					}
				}
			}
		}
		return HTMLresult;
	}


	/* PUBLIC METHOD DEFINITIONS */

	function updatePosition(e)
	{
		var xPosition = _mouse.getX(e) + _offsetX;
		var yPosition = _mouse.getY(e) + _offsetY;

		if (ns6) {
			_previewElement.style.left = xPosition.toString() + 'px';
			_previewElement.style.top = yPosition.toString() + 'px';
		} else {
			_previewElement.style.posLeft = xPosition;
			_previewElement.style.posTop = yPosition;
		}
	}
	this.updatePosition = updatePosition;

	function delayedHide()
	{
		document.body.onmousemove = null;
		_hideTimer = self.setTimeout(instantHide, _post_mouseout_delay);
	}
	this.hide = delayedHide;
}


