/*******************************************************************************
 Copyright (c) 2005-2006 Jordy Rose
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 
 Except as contained in this notice, the name(s) of the above copyright holders
 shall not be used in advertising or otherwise to promote the sale, use or other
 dealings in this Software without prior authorization.
*******************************************************************************/

function setup () {
	// Preloading
	var selection = new Image();
	selection.src = "Images/table_selection_first.png";
	selection = new Image();
	selection.src = "Images/table_selection_middle.png";
	selection = new Image();
	selection.src = "Images/table_selection_last.png";
	selection = null;

	if (window.widget)
		widget.onhide = onHide;
		
//	toggleDebug();
	
	createGenericButton(document.getElementById("done"), getLocalizedString("Done"), hidePrefs, 177);
//	scrollerInit(document.getElementById("myScrollBar"), document.getElementById("myScrollTrack"), document.getElementById("myScrollThumb"));
	setupMainTable();
	setupBackTable();
	
	localizeHTML();
	
	if (window.dockyardPrefs)
		document.getElementById('shouldSwitchDashboard').checked = window.dockyardPrefs.shouldSwitchDashboard;
	
	if (window.dockyardPlugin)
		window.dockyardPlugin.hideBackSide();
}

function localizeHTML () {
	var localizedElements = document.getElementsByTagName("span");
	var count = localizedElements.length;
	var nextElement;
	for (var i = 0; i < count; i++) {
		nextElement = localizedElements[i];
		if (nextElement.className == "localized") {
			nextElement.innerHTML = getLocalizedString(nextElement.innerHTML);
		}
	}
}

function templateChanged (templateMenu) {
	if (templateMenu.value == "disabled") {
		beep();
		templateMenu.selectedIndex = 1;
	}
}

function changeToFirstDock () {
	if (!isShowingFront)
		hidePrefs();
	changeDock(allTheData[0]);
}

function changeDock (dockName) {
	if (setChange(dockName) && window.widget)
		widget.openURL('');
}

function addDock (dockName, dockTemplate, dashboardTemplate) {
	if (dockTemplate == "disabled" || dashboardTemplate == "disabled") {
		beep();
	} else if (window.dockyardPlugin) {
		window.dockyardPlugin.createDockWithNameAndFiles(dockName, dockTemplate.toLowerCase(), dashboardTemplate.toLowerCase());
	}
}

function renameSelectedDockTo (newName) {
	var dockSelectOptions = document.getElementById('dockSelect').options;
	
	var oldName = null;
	for (i = 0; i < dockSelectOptions.length; i++)
	{
		if (dockSelectOptions[i].selected)
		{
			if (oldName != null)
			{
				beep();
				return;
			}
			else
				oldName = dockSelectOptions[i].text;
		}
	}
	
	if (oldName == null)
	{
		beep();
		return;
	}
	else if (window.dockyardPrefs)
	{
		if (window.dockyardPrefs.renameDock(oldName, newName))
		{
			updateTables();
		}
		else
			beep();
	}
}

function deleteSelectedDocks () {
	var selected = new Array();
	var count = 0;
	
	var dockSelectOptions = document.getElementById('dockSelect').options;
	for (i = 0; i < dockSelectOptions.length; i++)
	{
		if (dockSelectOptions[i].selected)
		{
			selected[count] = i;
			++count;
		}
	}
	
	if (count == 0)
	{
		beep();
		return;
	}
	else if (window.dockyardPlugin)
		window.dockyardPlugin.deleteDocks(selected);
}

function setShouldSwitchDashboard (newShouldSwitch) {
	if (window.dockyardPrefs)
		window.dockyardPrefs.shouldSwitchDashboard = newShouldSwitch;
}

var currentDock = null;
var dockToChangeTo = null;
function setChange (dockName)
{
	if (dockName == currentDock) return false;
	moveSelectionToTag(dockName);
	if (window.dockyardPrefs)
		dockToChangeTo = dockName;
	else {
		currentDock = dockName;
		beep();
	}
	return true;
}

function onHide ()
{
	if (dockToChangeTo != null) {
		beep();
		if (window.dockyardPrefs)
			window.dockyardPrefs.changeDock(dockToChangeTo);
		dockToChangeTo = null;
	}
}

function beep ()
{
	if (window.dockyardPlugin)
		window.dockyardPlugin.beep();
	else if (window.console)
		console.log("beep");
}

var isShowingFront = true;
//  Dashboard Code (from apple)
function showPrefs()
{
	if (window.dockyardPlugin)
		window.dockyardPlugin.showBackSide();

	var front = document.getElementById("front");
	var back = document.getElementById("back");

	if (window.widget)
		widget.prepareForTransition("ToBack");
       
	front.style.display="none";
	back.style.display="block";
	isShowingFront = false;
	exitflip(event);

	if (window.widget)
		setTimeout ('widget.performTransition();', 0);  
	if (shouldResetBackTable)
		setTimeout('setupBackTable();', 0);
}

function hidePrefs()
{
	// Added for Dockyard
	if (window.dockyardPlugin)
		window.dockyardPlugin.hideBackSide();
	
	var front = document.getElementById("front");
	var back = document.getElementById("back");
	
	if (window.widget)
		widget.prepareForTransition("ToFront");
      
	back.style.display="none";
	front.style.display="block";
	isShowingFront = true;

	if (window.widget)
		setTimeout ('widget.performTransition();', 0);
	if (shouldResetFrontTable)
		setTimeout('setupMainTable();', 0);
}

var flipShown = false;
var animation = {duration:0, starttime:0, to:1.0, now:0.0, from:0.0, firstElement:null, timer:null};

function mousemove (event)
{
	if (!flipShown)
	{
		if (animation.timer != null)
		{
			clearInterval (animation.timer);
			animation.timer  = null;
		}
 
		var starttime = (new Date).getTime() - 13;
 
		animation.duration = 500;
		animation.starttime = starttime;
		animation.firstElement = document.getElementById ('flip');
		animation.timer = setInterval ("animate();", 13);
		animation.from = animation.now;
		animation.to = 1.0;
		animate();
		flipShown = true;
	}
}
function mouseexit (event)
{
	if (flipShown)
	{
		// fade in the info button
		if (animation.timer != null)
		{
			clearInterval (animation.timer);
			animation.timer  = null;
		}

		var starttime = (new Date).getTime() - 13;

		animation.duration = 500;
		animation.starttime = starttime;
		animation.firstElement = document.getElementById ('flip');
		animation.timer = setInterval ("animate();", 13);
		animation.from = animation.now;
		animation.to = 0.0;
		animate();
		flipShown = false;
	}
}

function animate()
{
	var T;
	var ease;
	var time = (new Date).getTime();
   

	T = limit_3(time-animation.starttime, 0, animation.duration);

	if (T >= animation.duration)
	{
		clearInterval (animation.timer);
		animation.timer = null;
		animation.now = animation.to;
	}
	else
	{
		ease = 0.5 - (0.5 * Math.cos(Math.PI * T / animation.duration));
		animation.now = computeNextFloat (animation.from, animation.to, ease);
	}

	animation.firstElement.style.opacity = animation.now;
}

function limit_3 (a, b, c)
{
	return a < b ? b : (a > c ? c : a);
}

function computeNextFloat (from, to, ease)
{
	return from + (to - from) * ease;
}

// these functions are called when the info button itself receives onmouseover and onmouseout events

function enterflip(event)
{
	document.getElementById('fliprollie').style.display = 'block';
}

function exitflip(event)
{
	document.getElementById('fliprollie').style.display = 'none';
}

// Stolen from Stocks.wdgt/Stocks.js

function removeAllChildren (parent)
{
	while (parent.hasChildNodes())
		parent.removeChild(parent.firstChild);
}

var shouldResetFrontTable = false;
function updateTables()
{
	if (isShowingFront)
	{
		setupMainTable();
		shouldResetBackTable = true;
	}
	else
	{
		setupBackTable();
		shouldResetFrontTable = true;
	}
}

var allTheData = null;
function setupMainTable()
{
	if (window.dockyardPrefs)
		allTheData = window.dockyardPrefs.dockNames();
	else
		allTheData = ["Default", "Developer", "Multimedia", "Test1", "test2", "3", "4", "5", "6", "7", "8"];
	
	var c = allTheData.length;
	var container = document.getElementById('tbody');
	removeAllChildren(container);		

	for (var i=0; i<c; ++i)
	{
		var data = allTheData[i];
		var row = createRow (data);
		container.appendChild (row);
	}
	
	//set the bottom of table to correct class
	if (c < 2) c = 2;
	document.getElementById('tableBottom').setAttribute ("class", (c%2) != 0 ? "tableBottomLight" : "tableBottomDark");
	
	// fill in the backgorund
	container = document.getElementById('tableContainer');
	removeAllChildren(container);		

	c = c - 2;
	var light = true;
	for (var i = 0; i < c; ++i)
	{
		var div = document.createElement ('div');
		div.setAttribute  ("class", light ? "tableRowDark" : "tableRowLight");
		container.appendChild (div);
		light = !light;
	}
	
	if (currentDock != null) {
		scrollContent(SCROLLBAR_TOP);
		calculateAndShowThumb();
	} else {
		calculateAndShowThumb(document.getElementById('dockTable'));
	}
	
	if (window.dockyardPrefs)
		currentDock = window.dockyardPrefs.currentDock;
	else
		currentDock = allTheData[0];
	moveSelectionToTag(currentDock);
	
	shouldResetFrontTable = false;
}

function createRow (object)
{
	var row = document.createElement('tr');
	
	row.setAttribute ("class", "dockRow");
	row.setAttribute ("onclick", "changeDock(this.tag)");
	row.setAttribute ("tag", object);
	
	var td = document.createElement ('td');
	td.setAttribute ("class", "dockName");
	td.appendChild (document.createTextNode(object));
	row.appendChild (td);
	
	return row;
}

function setupBackTable()
{
	if (window.dockyardPrefs)
		allTheData = window.dockyardPrefs.dockNames();
	else
		allTheData = ["Default", "Developer", "Multimedia", "Test1", "test2", "3", "4", "5", "6", "7", "8"];
	
	var c = allTheData.length;
	var container = document.getElementById('dockSelect');
	removeAllChildren(container);

	for (var i=0; i<c; ++i)
	{
		var data = allTheData[i];
		var row = createOption (data);
		if (i % 2 == 0)
			row.setAttribute("class", "dockOptionEven");
		container.appendChild (row);
	}
	
	shouldResetBackTable = false;
}

function createOption (object)
{
	var option = document.createElement('option');
	
	option.setAttribute ("class", "dockOptionOdd");
//	option.setAttribute ("value", object);
	
	option.appendChild(document.createTextNode(object));
		
	return option;
}

var currentSelection = null;
var currentSelectionOriginalID;

function moveSelectionToTag (tag)
{
	var index;
	var offset=1;
	var c = allTheData.length;
	for (index=0; index < c; ++index)
	{
		if (allTheData[index] == tag)
			break;
	}
	if (index == c) index = 0;

	var newSelection;
	
	switch (index)
	{
		case 0:
//			offset = 0;
			newSelection = document.getElementById("tableTop");
			break;

		case c - 1:
			newSelection = document.getElementById("tableBottom");
			break;
			
		default:
			newSelection = document.getElementById("tableContainer").childNodes.item(index - 1);
			break;
	}

	if (newSelection != currentSelection && newSelection != null) {
		if (currentSelection != null)
			currentSelection.id = currentSelectionOriginalID;
		
		currentSelectionOriginalID = newSelection.id;
		newSelection.id = "selection";
		currentSelection = newSelection;
	}
	
	// top is 5px;
	// had to add an offset. The top is at 5px, but the others needed
	// to go down by one pixel
//	selection.style.top = (25*index+5+offset).toString() + "px";
//	selection.style.display = "block";
}

// Taken from HelloWelt Developer example

/*

Copyright _ 2005, Apple Computer, Inc.  All rights reserved.
NOTE:  Use of this source code is subject to the terms of the Software
License Agreement for Mac OS X, which accompanies the code.  Your use
of this source code signifies your agreement to such license terms and
conditions.  Except as expressly granted in the Software License Agreement
for Mac OS X, no other copyright, patent, or other intellectual property
license or right is granted, either expressly or by implication, by Apple.

*/


// getLocalizedString() pulls a string out an array named localizedStrings.  Each language project
// directory in this widget contains a file named "localizedStrings.js", which, in turn, contains
// an array called localizedStrings.  This method queries the array of the file of whichever language
// has highest precidence, according to the International pane of System Preferences.

function getLocalizedString(key)
{
    try {
        var ret = localizedStrings[key];
        if (ret === undefined)
            ret = key;
        return ret;
    } catch (ex) {}
    return key;
}
