/* Set up logging: Log through the integration controller
 * if it exists; otherwise, log through the console
 */

var log;
if (typeof integrationController == "undefined") {
	integrationController = null;
	log = function(i) { console.log(i) };
} else {
	log = function(i) { integrationController.logMessage_(i) };
}


function switched(event) {
	var element = event.currentTarget;
	
	var identifier = $(element).attr('id');
	switchToToolWithIdentifier(identifier);
		
	return false;
}

function switchToToolWithIdentifier(identifier)
{
	var elementToSelectSelector = "#" + identifier;
	var bodySelector = elementToSelectSelector + '-body';
	var isSelected = $(elementToSelectSelector).hasClass("selected");
	
	if (isSelected == false) {
		// hide all the content on the right.
		$("*[data-content]").addClass("hidden");
		
		//  unselect all items on the left
		$("li").removeClass("selected");
		// select the new selection on the left
		$(elementToSelectSelector).addClass("selected");
		
		// show the appropriate content on the right
		$(bodySelector).removeClass("hidden");
	}
}


function shouldScrollToKSDiffInstallSection(theStep, theSectionName, theToolName) {
	if ($(theStep).hasClass("installed")) return false;
	if (integrationController) {
		return integrationController.shouldScrollToKSDiffInstallSection_toolName_(theSectionName, theToolName);
	}
	return false;
}

function scrollToKSDiffInstallSection() {
	openKSDiffSection();
}

function shouldRunScriptForInstallButtonInSection(theSectionName, theToolName) {
	if (integrationController) {
		return integrationController.shouldRunScriptForInstallButtonInSection_toolName_(theSectionName, theToolName);
	}
	return true;
}

function runScriptForStep(step) {
	
	var toolName = $(step).attr("data-install-tool");
	var sectionName = $(step).attr("id");
	if (sectionName == undefined)
		sectionName = "";
	
	if (shouldScrollToKSDiffInstallSection(step, sectionName, toolName)) {
		openKSDiffSection();
	}
	if (shouldRunScriptForInstallButtonInSection(sectionName, toolName) == false) { return; }
	
	// Determine what kind of action should be taken --
	// If the step has the 'installed' class, uninstall it
	// if possible (otherwise do nothing). If it doesn't
	// have that class, do nothing
	if ($(step).hasClass("installed")) {
		var uninstallTool = $(step).attr("data-uninstall-tool");
		if (uninstallTool == null) {
			// There doesn't seem to be anything to uninstall. do nothing.
			return false;
		}
		if (uninstallTool == "")
			uninstallTool = toolName;

		if (integrationController) {
			integrationController.runUninstallScript_(uninstallTool);			
		} else {
			log("This would now uninstall " + uninstallTool + ", but there is no controller");
			markAsUninstalled(uninstallTool);
		}
	} else {
		if (integrationController) {
			integrationController.runScript_(toolName);
		} else {
			log("This would now install " + toolName + ", but there is no controller available");
			markAsInstalled(toolName);
		}
	}
}

function openInstallPGKDownloadLinkForStep(theStep) {
	var toolName = $(theStep).attr("data-install-tool");
	var sectionName = $(theStep).attr("id");
	var isInstall = !($(theStep).hasClass("installed"));
	if (integrationController) {
		integrationController.openInstallPGKDownloadLinkForSection_toolName_isInstall_(sectionName, toolName, isInstall);
	}
}

function openPath(path) {
	if (integrationController)
		integrationController.openPath_(path);
	else
		log("This would open the path " + path + " in TextEdit.");
}

$(document).ready(function() {
	// Convert buttons to jQuery-UI buttons to get proper mouse tracking
	$(".button").button();
	
	// convert these to jquery-ui buttons to get better :active tracking.
	$("#leftcol nav ul li").button();
	// This removes the ability for the element to allow selection of text outside of itself
	// For example, mouse down on the element, drag outside into the main area and if there's
	// selectable text there, it'll get selected. This stops that.
	$("#leftcol nav ul li").each(function(index, element){
		element.onmousedown = function(event) {
			return false;
		}
	});
	
	// Mark all headers as collapsible
	$("li").click(switched);
	
	// Add a 'with-code' class to all elements that have a code block
	$(".step:has(code)").addClass("with-code")

//	$(".hidden").each(function(i, element) { $(element).css("display", "none"); });
	// Add a click handler for every step with an install step
	$(".step[data-install-tool]").each(function(index, step) {
		
		var buttons = $(step).children(".expl").children(".button");
		buttons.click(function() { runScriptForStep(step); });
		
		var downloadButtons = $(step).children(".expl").children("#DownloadInstallerPKGButton");
		downloadButtons.each(function(index, button) {
			$(button).unbind('click'); // Remove the runScriptForStep() handler
			$(button).click(function() { openInstallPGKDownloadLinkForStep(step); });
						 
		});
	});

	// Add a different click handler for every step with an open path
	$(".button[data-path]").each(function(index, item) {
		$(item).click(function() { openPath($(item).attr("data-path")); })
	});
});


/* Callbacks from Objective-C */
function markAsInstalled(toolName) {
	//log(toolName + " is marked as installed");

	var elements = $("*[data-install-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).addClass("installed");
	});
	
	// Set the status for this tool.
	var buttons = $("*[data-status-tool='" + toolName.replace(/-.*/, "") + "']")
	buttons.each(function(index, item) {
		$(item).addClass("visible");
	});
	
	updateInstallUninstallScriptLocations();
}

function markAsUninstalled(toolName) {
	//log(toolName + " is marked as uninstalled");

	var elements = $("*[data-install-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("installed");
	});
	
	// Set the status for this tool.
	var VCS = toolName.replace(/-.*/, "");

	// Find the container that has this tool
	var tools = $("li:has(div.status[data-status-tool='" + VCS + "'])")
	tools.each(function(index, tool) {
		// Only remove the checkmark if there are no other things that have
		// installed this tool
		if ($("div.step.installed[data-install-tool^=" + VCS + "]").length == 0) {
			$(tool).find("div.status").removeClass("visible");
		}
	});
	
	updateInstallUninstallScriptLocations();
}

function scrollToTop() {
	// check if page is scrolled
	if ($(window).scrollTop() > 0) {
		openKSDiffSection();
		$.scrollTo({ top:0, left:0 }, "fast");
	} else {
		openKSDiffSection();
	};
}

function openKSDiffSection() {
	switchToToolWithIdentifier("ksdiff");
	pulsateKSDiffInstallInstructions();
};

// double pulse highlights the MAS install steps after scrolled to top
function pulsateKSDiffInstallInstructions() {
	$('#steps_pulsate').animate({boxShadow: '0 0 10px #4B93DF',}, 350).animate({boxShadow: '0 0 0 #fff'}, 350)
	.animate({boxShadow: '0 0 10px #4B93DF',}, 350).animate({boxShadow: '0 0 0 #fff'}, 350);
};

// Called from Obj-C after the integrationController is first set. Only called in Mac App Store builds.
function updateInstallUninstallScriptLocations() {
	if (integrationController) {
		var installKSDiffExecutablePath = integrationController.installKSDiffExecutablePath();
		var uninstallKSDiffExecutablePath = integrationController.uninstallKSDiffExecutablePath();

		var adminInstallCommand = "sudo \"" + installKSDiffExecutablePath + "\"";
		$(".terminal_install_command").html(adminInstallCommand);
		var adminUninstallCommand = "sudo \"" + uninstallKSDiffExecutablePath + "\"";
		$(".terminal_uninstall_command").html(adminUninstallCommand);
		
		var installKSDiffExecutableCommand = "\"" + installKSDiffExecutablePath + "\"" + " ~/Library/Application\\ Support/Kaleidoscope/bin";
		$(".install_path").html(installKSDiffExecutableCommand);
	}
}

function openAppleHelpAnchor(anchorName) {
	integrationController.openAppleHelpAnchor_(anchorName);
}
