/************************************************************************ 
  Copyright 2011-2012, IceJS Team. All rights reserved.
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Update Freezer Team nor the names of its
        contributors may be used to endorse or promote products derived
        from this software without specific prior written permission.
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ***********************************************************************/ 

//#region User Mode
function parseScenarioInfo(dai)
{
	try
	{
		dai = JSON.parse(dai);
	}
	catch(e)
	{
		alert("JSON.parse failed: " + e.message);
		return {};
	}
	return dai;
}

function appendScenario(dai)
{
	appendRowToTable(parseScenarioInfo(dai));
	log.debug("Scenario added: " + dai.name);
}

function makeId(base, suffix)
{
	return base.replace(".", "") + suffix;
}

function appendScenarioRow(name)
{
	var table = document.getElementById("scenarioTable");
	var row = table.insertRow(table.rows.length);

	var nameCell = row.insertCell(0);
	nameCell.className = "scenarioTable";
	nameCell.style.textAlign = 'center';
	//nameCell.style.paddingLeft = "90px";
	nameCell.id = makeId(name, "ColumnScenario");
	
	var statusCell = row.insertCell(1);
	statusCell.className = "scenarioTable";
	statusCell.style.textAlign = 'center';
	statusCell.id = makeId(name, "ColumnStatus");
}

function appendRowToTable(scen)
{
	var table = document.getElementById("scenarioTable");
	var row = table.insertRow(table.rows.length);
	
	// scenario name cell
	var nameCell = document.getElementById(makeId(scen.name, "ColumnScenario"));
	//var img = document.createElement("img");
	//img.src = "../" + scen.icon;
	//img.align = "absmiddle";
	var linkNode = document.createElement("a");
	linkNode.href = scen.link;
	linkNode.style.color = "#555555";
	var textNode = document.createElement("b");
	textNode.innerText = scen.displayName;
	textNode.title = S("UI.ScenarioTooltip");
	linkNode.appendChild(textNode);
	//nameCell.appendChild(img);
	//nameCell.appendChild(document.createTextNode("  "));
	nameCell.appendChild(linkNode);

	// status cell
	var statusCell = document.getElementById(makeId(scen.name, "ColumnStatus"));
	if (scen.actions && scen.actions.length)
	{
		var markup = '<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">';
		var buttonGroupWidth = 140;
		if (scen.actions.length > 2)
		{
			buttonGroupWidth = 87 * scen.actions.length;
		}
		markup += '<div style="width: ' + buttonGroupWidth + 'px; margin: 5 0 0 0;">';
	
		for(var i = 0; i < scen.actions.length; i++)
		{
			var ai = scen.actions[i];
			
			var choice = '<input type="radio" name="' + scen.name + '" id="' + makeId(scen.name, ai.action) + '" value="' + ai.action + '" ' + (ai.active ? 'checked="checked"' : '') + 'onclick="document.body.skipChangeEvent=false;"/>';
			var label = '<label for="' + makeId(scen.name, ai.action) + '">' + S("UI." + ai.buttonName) + '</label>';

			markup += choice;
			markup += label;
		}
		
		markup += '</div>';
		markup += '</fieldset>';

		var statusId = '#' + makeId(scen.name, "ColumnStatus");
		$(statusId).append($(markup));
		$(statusId).trigger('create');
		
		// attach event handlers
		for(var i = 0; i < scen.actions.length; i++)
		{
			var ai = scen.actions[i];
			eval("var handler = function(e){if(!document.body.skipChangeEvent) {buttonClick('" + scen.name + "', '" + ai.action + "');}}");
			$('#' + makeId(scen.name, ai.action)).bind("change", handler);			
		}
	}
	else
	{
	  statusCell.innerHTML = scen.status;
	}
}

function appendFeedbackRowToTable()
{
	var table = document.getElementById("scenarioTable");
	var row = table.insertRow(table.rows.length);
	
	var cell = row.insertCell(0);
	cell.className = "scenarioTable";
	cell.style.textAlign = 'center';
	cell.colSpan = 2;

	var link = document.createElement("a");
	link.id = "feedbackLinkButton";
	
	cell.appendChild(link);		
	
	var markup = '<a href="http://www.updatefreezer.org/index.php?id=15" data-mini="true" data-inline="true" data-role="button" data-theme="e" title="' + S("UI.SendFeedbackTooltip") + '">' + S("UI.SendFeedbackLink") + '</a>';
	
	$("#feedbackLinkButton").append($(markup));
	$("#feedbackLinkButton").trigger('create');
}

function makeStatusString(statusObj)
{
	var statusText = "";
	for(var i = 0; i < statusObj.length; i++)
	{
		var s = statusObj[i];
		statusText += s.msg + "<br>";		
		log.debug(s.msg);
	}
	return statusText;
}

function setScenarioInfo(scen)
{
	scen = parseScenarioInfo(scen);
	
	if (scen.actions && scen.actions.length)
	{
	 	document.body.skipChangeEvent = true;
		for(var i = 0; i < scen.actions.length; i++)
		{
			var ai = scen.actions[i];
			if (ai.active)
			{
				$('#' + makeId(scen.name, ai.action)).attr("checked", ai.active).checkboxradio("refresh");
				break;
			}
	  	}
	}
}

function clearButtonStatus(scen)
{
	scen = parseScenarioInfo(scen);
	
	if (scen.actions && scen.actions.length)
	{
	 	document.body.skipChangeEvent = true;
		for(var i = 0; i < scen.actions.length; i++)
		{
			var ai = scen.actions[i];
			$('#' + makeId(scen.name, ai.action)).attr("checked", false).checkboxradio("refresh");
	  	}
	}
}

function appendTopButtons()
{
	var markup = '<fieldset data-mini="true">';
	markup += '<a href="uicmd://disableall" data-mini="true" data-inline="true" data-role="button" data-icon="minus" title="' + S("UI.DisableAllButtonTooltip") + '">' + S("UI.DisableAllButton") + '</a>';
	markup += '<a href="uicmd://restoreall" data-mini="true" data-inline="true" data-role="button" data-icon="back" title="' + S("UI.RestoreButtonTooltip") + '">' + S("UI.RestoreButton") + '</a>';
	markup += '<a href="uicmd://close" data-mini="true" data-inline="true" data-role="button" data-icon="delete" title="' + S("UI.CloseButtonTooltip") + '">' + S("UI.CloseButton") + '</a>';
	markup += '</fieldset>';
	
	$("#topButtons").append($(markup));
	$("#topButtons").trigger('create');
}

function appendBottomButtons()
{
	var panel = document.getElementById("bottomButtons");

	if (panel)
	{
		var link = document.createElement("a");
		link.href = "uicmd://openlog";
		link.innerHTML = S("UI.OpenLogLink");
		link.title = S("UI.OpenLogTooltip");
		panel.appendChild(link);
		panel.appendChild(document.createTextNode(" | "));
	
		var link = document.createElement("a");
		link.href = "uicmd://license";
		link.innerHTML = S("UI.LicenseButton");
		link.title = S("UI.LicenseButtonTooltip");
		panel.appendChild(link);	
		panel.appendChild(document.createTextNode(" | "));

		var link = document.createElement("a");
		link.href = "uicmd://remove";
		link.innerHTML = S("UI.RemoveButton");
		link.title = S("UI.RemoveButtonTooltip");
		var bold = document.createElement("b");
		bold.appendChild(link);
		panel.appendChild(bold);
	}
}

//#endregion

function buttonClick(name, action)
{
	log.debug("Running: " + name + "/" + action);
	document.pendingActionButtonId = name + ".Action";
	window.location.href = "uicmd://execute?{name:'"+ name +"',action:'" + action + "'}";
}

//#region Locale
function setElementText(name, id)
{
	var el = document.getElementById(name);
	if (el)
	{
		while(el.hasChildNodes()) el.removeChild(el.firstChild);
		el.innerHTML = S(id);
	}
}

function setElementTitle(name, id)
{
	var el = document.getElementById(name);
	if (el)
	{
		el.title = S(id);
	}
}

function setInfoPanelContents(htmlText)
{
	var el = document.getElementById('infoPanelContents');
	if (el)
	{
		infoPanelContents.innerHTML = htmlText;
	}
}

function setInfoPanelHeader(id)
{
	setElementText("infoPanelHeader", id);
}

function setLocale()
{
	if (Util && Util.Locale)
	{
		setElementText("UpdaterColumn", "UI.UpdaterColumn");
		setElementText("ActionColumn", "UI.ActionColumn");
		setElementTitle("pageLabel", "UI.UpdateFreezerTooltip");
	}
}

function S(str)
{
	if (Util.Locale.Strings[str] != undefined)
	{
		return Util.Locale.Strings[str];
	}
	return "No such string loaded: " + str;
}

function SF(str, args)
{
	return S(str).format(args);
}

String.prototype.format = function (args) {
	var str = this;
	return str.replace(String.prototype.format.regex, function(item) {
		var intVal = parseInt(item.substring(1, item.length - 1));
		var replace;
		if (intVal >= 0) {
			replace = args[intVal];
		} else if (intVal === -1) {
			replace = "{";
		} else if (intVal === -2) {
			replace = "}";
		} else {
			replace = "";
		}
		return replace;
	});
};

String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");

//#endregion
