/**
 * Dialog
 * Prepare a dialogbox which display a html document
 */

function Dialog(game)
{
	this.game = game;
	this.id = 0;
	this.history = new Array();
	this.indexHistory = -1;
	
	//Pre-load the coin
	this.coinImage = new Image();
	this.coinImage.src = 'dialog/images/coin.gif';
}

/**
 * Open a dialogbox
 * @param title dialog title
 * @param src path of the html page to open
 */
Dialog.prototype.open = function(title, src)
{
	var dialog = this;

	//Get the dialog id
	this.id = this.game.nextDialogId++;
	
	//Create a dialogbox
	var dialogDiv = '<iframe id="'+this.id+'" name="f'+this.id+'" class="dialog" title="'+title+'" src="" frameborder="0"></iframe>';
	$("#dialog_container").append(dialogDiv);
	$("#"+this.id).dialog({width: "65%", height: "86%"});
	
	//Change the iframe position/size in the dialog box
	$("#"+this.id).css('margin-top', '0px');
	$("#"+this.id).css('margin-left', '8px');
	$("#"+this.id).css('margin-right', '8px');
	$("#"+this.id).css('margin-bottom', '8px');
	$("#"+this.id).width($("#"+this.id).parent().width()-16);
	var sibblingsHeight = 0; $("#"+this.id).siblings().each(function(){sibblingsHeight += $(this).height();});
	$("#"+this.id).height($("#"+this.id).parent().height()-sibblingsHeight-8);
	
	//Set the position
	$("#"+this.id).parents(".ui-dialog").css("left", "29%");
	$("#"+this.id).parents(".ui-dialog").css("top", "7%");
	
	//Colorize the title
	$("#"+this.id).parent().find(".ui-dialog-title").each(function() { dialog.setTextColor(this); } );
	
	//Add the question box
	$("#"+this.id).parent().find(".ui-dialog-titlebar-close:eq(0)").each(function()
	{
		//Create and get the question box
		$(this).after("<a style=\"-moz-user-select: none;\" unselectable=\"on\" href=\"#\" class=\"ui-dialog-titlebar-question\"><span style=\"-moz-user-select: none;\" unselectable=\"on\">?</span></a>");
		var questionBox = $(this).siblings(".ui-dialog-titlebar-question:eq(0)");
		
		//Hover effect
		questionBox.hover(function()
		{
			$(this).addClass("ui-dialog-titlebar-question-hover");
		},function()
		{
			$(this).removeClass("ui-dialog-titlebar-question-hover");
		});
		
		//Click effect
		questionBox.click(function()
		{
			if(!$(this).hasClass("ui-dialog-titlebar-empty"))
			{
				//Change the block appearance
				$(this).addClass("ui-dialog-titlebar-empty");
				
				//coin effect
				$("body:eq(0)").append("<div id=\"coin_"+dialog.id+"\" class=\"coin\">&nbsp;</div>");
				$("#coin_"+dialog.id).css("top",dialog.findPosY(this));
				$("#coin_"+dialog.id).css("left",dialog.findPosX(this));
				$("#coin_"+dialog.id).animate({ top: dialog.findPosY(this)-50 }, 200, "",function(){
					$(this).animate({ top: dialog.findPosY(this)+50 }, 200, "", function()
					{
						$(this).hide();
					});
				});
			}
		});
	});
	
	//Add the previous and next buttons
	$("#"+this.id).parent().find(".ui-dialog-titlebar-close:eq(0)").each(function()
	{
		//Create and get the previous button
		$(this).after("<a style=\"-moz-user-select: none;\" unselectable=\"on\" href=\"#\" class=\"ui-dialog-titlebar-previous\"><span style=\"-moz-user-select: none;\" unselectable=\"on\">&lt;</span></a>");
		var previousButton = $(this).siblings(".ui-dialog-titlebar-previous:eq(0)");
		//Hover effect
		previousButton.hover(function()
		{
			$(this).addClass("ui-dialog-titlebar-previous-hover");
		},function()
		{
			$(this).removeClass("ui-dialog-titlebar-previous-hover");
		});
		//Click action
		previousButton.click(function()
		{
			dialog.loadPage("", dialog.indexHistory-1);
		});
		
		//Create and get the next button
		$(this).after("<a style=\"-moz-user-select: none;\" unselectable=\"on\" href=\"#\" class=\"ui-dialog-titlebar-next\"><span style=\"-moz-user-select: none;\" unselectable=\"on\">&gt;</span></a>");
		var nextButton = $(this).siblings(".ui-dialog-titlebar-next:eq(0)");
		//Hover effect
		nextButton.hover(function()
		{
			$(this).addClass("ui-dialog-titlebar-next-hover");
		},function()
		{
			$(this).removeClass("ui-dialog-titlebar-next-hover");
		});
		//Click action
		nextButton.click(function()
		{
			dialog.loadPage("", dialog.indexHistory+1);
		});
	});
	
	//Load the content
	this.loadPage(src);
}

/**
 * Apply a different color for each letter of the text included in the DOM object.
 * @param domObj DOM objet which contains text
 */
Dialog.prototype.setTextColor = function(domObj)
{
	//Define constants
	var colors = new Array();
	colors["green"]  = "#00C800";
	colors["blue"]   = "#00D8F8";
	colors["yellow"] = "#F8C828";
	colors["red"]    = "#F83838";
	var colorsOrder = new Array("green", "blue", "yellow", "red", "yellow", "blue", "green", "red");
	
	//Get the object text
	var text = $(domObj).text();
	
	//Remove the original text
	$(domObj).html("");
	
	//Add the new text with the color
	var colorText = "<div style=\"position:absolute; top:0px; left:0px;\">";
	for(var i = 0; i < text.length; i++)
	{
		var color = colors[colorsOrder[i % colorsOrder.length]];
		colorText += "<span style=\"color:"+color+";\">"+text.charAt(i)+"</span>";
	}
	colorText += "</div>";
	
	//Add a contour
	$(domObj).append("<div style=\"position:absolute; top:1px; left:0px;\">"+text+"</div>");
	$(domObj).append("<div style=\"position:absolute; top:-1px; left:0px;\">"+text+"</div>");
	$(domObj).append("<div style=\"position:absolute; top:0px; left:1px;\">"+text+"</div>");
	$(domObj).append("<div style=\"position:absolute; top:0px; left:-1px;\">"+text+"</div>");
	
	//Add the color
	$(domObj).append(colorText);
	
	//fix an IE bug
	$(domObj).css("display", "block");
}

/**
 * Give the absolute X coordinate of an element (http://blog.firetree.net/2005/07/04/javascript-find-position/)
 * @param obj Object of the document
 * @return X coordinate
 */
Dialog.prototype.findPosX = function(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
	while(1) 
	{
		curleft += obj.offsetLeft;
		if(!obj.offsetParent)
			break;
		obj = obj.offsetParent;
	}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

/**
 * Give the absolute Y coordinate of an element (http://blog.firetree.net/2005/07/04/javascript-find-position/)
 * @param obj Object of the document
 * @return Y coordinate
 */
Dialog.prototype.findPosY = function(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
	while(1)
	{
		curtop += obj.offsetTop;
		if(!obj.offsetParent)
			break;
		obj = obj.offsetParent;
	}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}

/**
 * Load a page in the dialogbox
 * @param src path of the page to load
 */
Dialog.prototype.loadPage = function(src, newIndexHistory)
{
	var dialog = this;
	
	//if newIndexHistory is set, src is set to the right history path
	if(newIndexHistory !== undefined)
	{
		//Check if newIndexHistory is valid
		if(newIndexHistory < 0 || newIndexHistory >= dialog.history.length) return;
		
		//Set src and change dialog.indexHistory
		src = dialog.history[newIndexHistory];
		dialog.indexHistory = newIndexHistory;
	}
	
	//Load the page
	$("#"+this.id).attr('src', src);
	$("#"+this.id).load(src, {}, function()
	{
		//Detect if we have to add this src to the history
		if(newIndexHistory === undefined)
		{
			//Remove the history after dialog.indexHistory
			while(dialog.history.length > dialog.indexHistory+1) dialog.history.pop();
			
			//Save the page in the history
			dialog.history.push(src);
			dialog.indexHistory++;
		}
		
		//Get the page folder (note: useful only on the same server, due to ajax security)
		var folder = src.substr(0,src.lastIndexOf('/'));
	
		//Change the anchors behavior
		$(this).contents().find("a[@target=]").each(function()
		{
			//Redefine the click function of every anchor which doesn't have a target attribute
			$(this).click(function(e)
			{
				//Stop the normal link click
				e.preventDefault();
				
				//Get the linked page
				var linksrc = $(this).attr("href");
				
				//Check if the browser return the relative path or the absolute one
				if(linksrc.indexOf('http://') != -1 || linksrc.indexOf('file://') != -1)
				{
					//The absolute path must be converted into a relative one
					
					//Transform document.URL
					var docURL = document.URL;
					while(docURL.indexOf('\\') != -1) docURL = docURL.replace(/\\/,'/'); //replace \ by /
					docURL = docURL.substr(0,docURL.lastIndexOf('/')+1); //remove the current file name
					docURL = (docURL.indexOf('http://') != -1 || docURL.indexOf('file://') != -1) ? docURL.substr(7) : docURL ; //remove http:// or file://
					docURL = encodeURI(docURL); //encodeURI the string
					
					//remove the substring docURL from linksrc and remove everything before
					linksrc = linksrc.substr(linksrc.indexOf(docURL));
					linksrc = linksrc.replace(docURL, "");
				}
				
				//Load the linked page in the dialogbox
				dialog.loadPage(folder+"/"+linksrc);
			});
		});
	});
}

















