/*
    This is a set of Object which help implementing HTML controls for J-Painter.

    Copyright Igor Zhukovsky 2009 http://www.izhuk.com
*/

// Set the configuration properties appropriately
var config = {
  painter_name  : 'painter',  // defined by the <applet> attribute name
  icon_dir      : './icons/', // relative to the client's HTML page

  // the following items are used as button titles
  // you may translate them into a different langauge
  titles : {
	line        : 'Line',              arrow         : 'Arrow',
	arrow_dim   : 'Dimension Arrow',   arrow_path    : 'Path Arrow',
	curve       : 'Free Hand',         area          : 'Fill Area',
	rect        : 'Rectangle',         filled_rect   : 'Filled Rectnagle',
	round_rect  : 'Rounded rectangle', filled_round_rect : 'Filled Rounded rectangle',
	oval        : 'Oval',              filled_oval   : 'Filled Oval',
	polyline    : 'Polyline',          polygon       : 'Polygon',
	text        : 'Text',	           eraser        : 'Eraser',
	flood_fill  : 'Flood Fill',        color_picker  : 'Color Picker',
	select_rect : 'Select Rectangle',  select_area   : 'Select Area',

	stroke  : 'Stroke',
	texture : 'Fill pattern',
	
	'bold'  : 'bold',
	'italic': 'italic',

    	'clear' : 'Clear the drawing',
    	'undo'  : 'Undo the last action',
    	'redo'	: 'Redo the undone action',
    	'print'	: 'Print the drawing',
    	'save'  : 'Save the drawing'
  }
}

function ToolPanel(tools,rows,cols) { return _controlPanel('tool',tools,rows,cols); }

//function StrokePanel(strokes,rows,cols)   { return _controlPanel('stroke',strokes,rows,cols); }
//function TexturePanel(textures,rows,cols) { return _controlPanel('texture',textures,rows,cols); }

function _controlPanel(controlType,controls,rows,cols) {
    controlsArray = controls.split(',');
    var controlDefs = new Object();
    for(i=0; i < controlsArray.length; i++) {
	var control = trim(controlsArray[i]);
	controlDefs[control] = controlType+':'+control;
    }
    return new ControlPanel(controlDefs,rows,cols);
}

function ControlPanel(tools,rows,cols) {
    this.tools = tools;
    this.tooltips = false;
    this.rows = rows;
    this.cols = cols;
    this.icon_dir = config.icon_dir;

    // preload the icons
    var icons = new Array();
    var i = 0;
    for(tool in this.tools) {
	icons[i] = new Image();
        icons[i].src = this.icon_dir+tool+'.gif';
	i++;
    }
}

// Outputs control panel
ControlPanel.prototype.write = function() {
    var N = (this.rows * this.cols); // total number of cells
    var n = 0; // current cell
    var c = 0; // current column number
    var self = this;
    document.write('<table border="0" cellpadding="0" cellspacing="0">');
    for(tool in this.tools) {
	if (c==0) document.write('<tr>');
        document.write('<td><img id="'+tool+'" class="tool_normal" src="'+this.icon_dir+tool+'.gif"></td>');
	var el = document.getElementById(tool);
	el.onclick = function() { self.click(this.id); };
	if (tool in config.titles) {
	    el.title = config.titles[tool];
	}
	c++;
	if (c==this.cols) {
	    document.write('</tr>');
	    c = 0;
	}
	n++;
    }
    while (n < N) {
	if (c==0) document.write('<tr>');
	document.write('</td>&nbsp;<td>');
	c++;
	if (c==this.cols) {
	    document.write('</tr>');
	    c = 0;
	}
	n++;
    }
    document.write('</table>');
}

// Handles clicks on the tool buttons
ControlPanel.prototype.click = function(id) {
    for(tool in this.tools) {
    	var element = document.getElementById(tool);
    	element.className = (tool==id) ? 'tool_pressed' : 'tool_normal';
    }
    document.applets[config.painter_name].setMode(this.tools[id]);
}

//=========================== COLOR PANEL ===========================

// Defines the color panel buttons
function ColorPanel(colors,rows,cols) {
    this.colors = colors.split(',');
    for(var i=0; i < this.colors.length; i++) {
	this.colors[i] = trim(this.colors[i]);
    }
    this.rows = rows;
    this.cols = cols;
    this.icon_dir = config.icon_dir;
}

// Outputs control panel
ColorPanel.prototype.write = function() {
    var N = (this.rows * this.cols); // total number of cells
    var n = 0; // current cell
    var c = 0; // current column number
    var self = this;
    document.write('<table border="0" cellpadding="0" cellspacing="0">');
    for(i=0; i < this.colors.length; i++) {
	if (c==0) document.write('<tr>');
        document.write('<td bgcolor="'+this.colors[i]+'"><img id="color-'+i
			+'" class="color_normal" src="'+this.icon_dir+'color.gif"></td>');
	var el = document.getElementById('color-'+i);
	el.background = this.colors[i];
	el.onclick = function() { self.click(this.background); };
	c++;
	if (c==this.cols) {
	    document.write('</tr>');
	    c = 0;
	}
	n++;
    }
    while (n < N) {
	if (c==0) document.write('<tr>');
	document.write('</td>&nbsp;<td>');
	c++;
	if (c==this.cols) {
	    document.write('</tr>');
	    c = 0;
	}
	n++;
    }
    document.write('</table>');
}

// Handles clicks on the color buttons
ColorPanel.prototype.click = function(color) {
    for(i=0; i < this.colors.length; i++) {
	var id = 'color-'+i;
    	var el = document.getElementById(id);
    	el.className = (color==this.colors[i]) ? 'color_pressed' : 'color_normal';
    }    
    document.applets[config.painter_name].setMode('color:'+color);
}


//=========================== ACTIONS WRITER ===========================

function ActionPanel(actions,rows,cols) {
    this.actions = actions.split(',');
    for(var i=0; i < this.actions.length; i++) {
	this.actions[i] = trim(this.actions[i]);
    }
    this.rows = rows;
    this.cols = cols;
}

ActionPanel.prototype.write = function() {

    icon_dir = config.icon_dir;
    
    var N = (this.rows * this.cols); // total number of cells
    var n = 0; // current cell
    var c = 0; // current column number

    document.write('<table border="0" cellpadding="0" cellspacing="0">');
    for(var i=0; i < this.actions.length; i++) {
	if (c==0) document.write('<tr>');
        id = this.actions[i];
        mousedown = "this.className='tool_pressed'";
        mouseup   = "this.className='tool_normal'";
        document.write('<td><img id="'+id
		+'" class="tool_normal" onmousedown="'+mousedown+'" onmouseup="'+mouseup+'" '
        	+'src="'+icon_dir+id+'.gif"></td>');
	var el = document.getElementById(id);
	el.onclick = function() { document.applets[config.painter_name].doAction(this.id); };
	if (id in config.titles) {
	    el.title = config.titles[id];
	}
	c++;
	if (c==this.cols) {
	    document.write('</tr>');
	    c = 0;
	}
	n++;
    }
    while (n < N) {
	if (c==0) document.write('<tr>');
	document.write('</td>&nbsp;<td>');
	c++;
	if (c==this.cols) {
	    document.write('</tr>');
	    c = 0;
	}
	n++;
    }
    document.write('</table>');
}

function FontPanel(fontFaces,fontSizes) {
    this.font_faces = fontFaces.split(',');
    this.font_sizes = fontSizes.split(',');
    this.font_selected = '';
    this.size_selected = '';
}

FontPanel.prototype.write = function() {
    var self = this;
    var icon_dir = config.icon_dir;
    document.write('\
    <table border="0" cellpadding="0"><tr>\
	<td valign="top"><select id="font_name" style="font-family:Arial; font-size: 10px;">');
	for(var i=0; i < this.font_faces.length; i++) {
	    var option = this.font_faces[i];
	    var selected = (option==this.font_selected) ? 'selected="true"' : '';
	    document.write('<option value="'+option+'" '+selected+'>'+option+'</option>');
	}
	document.write('</select></td>\
	<td valign="top"><select id="font_size" style="font-family:Arial; font-size: 10px;">');
	for(var i=0; i < this.font_sizes.length; i++) {
	    var option = this.font_sizes[i];
	    var selected = (option==this.size_selected) ? 'selected="true"' : '';
	    document.write('<option value="'+option+'" '+selected+'>'+option+'</option>');
	}
	document.write('</select></td>\
	<td valign="top"><img id="font_bold" class="tool_normal" src="'+icon_dir+'bold.gif" title="'+config.titles.bold+'">\
<img id="font_italic" class="tool_normal" src="'+icon_dir+'italic.gif" title="'+config.titles.italic+'"></td>\
    </tr></table>\
    ');

     document.getElementById('font_name').onchange  = function() { self.changeFont(); };
     document.getElementById('font_size').onchange  = function() { self.changeFont(); };

     document.getElementById('font_bold').onclick   = function() {
		this.className = (this.className=='tool_normal') ? 'tool_pressed' : 'tool_normal';
		self.changeFont();
	};
     document.getElementById('font_italic').onclick = function() {
		this.className = (this.className=='tool_normal') ? 'tool_pressed' : 'tool_normal';
		self.changeFont();
	};
}

FontPanel.prototype.changeFont = function() {
    document.applets[config.painter_name].setMode('font:'+this.getFont());
}

FontPanel.prototype.getFont = function() {
    var font_name_select = document.getElementById('font_name');
    var font_size_select = document.getElementById('font_size');
    var font_name = font_name_select.options[font_name_select.selectedIndex].value;
    var font_size = font_size_select.options[font_size_select.selectedIndex].value;

    var style = 0;
    if (document.getElementById('font_bold').className=='tool_pressed') style += 1;
    if (document.getElementById('font_italic').className=='tool_pressed') style += 2;
    var styles = new Array('plain','bold','italic','bolditalic');

    return font_name+'-'+styles[style]+'-'+font_size;
}


function isspace(c) { return (c==' ') || (c=='\t') || (c=='\n') || (c=='\r'); }

function trim(s) {
    while ((s.length > 0) && isspace(s.charAt(0)))
	s = s.substr(1,s.length-1);
    while ((s.length > 0) && isspace(s.charAt(s.length-1)))
	s = s.substr(0,s.length-1);
    return s;
}


//====================== Drop Down Lists ======================
var ddlist_visible   = 0;
var ddlist_hidetimer = 0;

// open hidden layer
function ddlist_show(id) {	
    // cancel close timer
    ddlist_cancel_hide_time();

    // close old layer
    if(ddlist_visible) ddlist_visible.style.visibility = 'hidden';

    // show new layer
    ddlist_visible = document.getElementById(id);
    ddlist_visible.style.visibility = 'visible';
}

// close showed layer
function ddlist_hide() { if(ddlist_visible) ddlist_visible.style.visibility = 'hidden'; }

// run close timer
function ddlist_hide_time() { ddlist_hidetimer = window.setTimeout(ddlist_hide, 250); }

// cancel close timer
function ddlist_cancel_hide_time() {
    if (ddlist_hidetimer) {
	window.clearTimeout(ddlist_hidetimer);
	ddlist_hidetimer = null;
    }
}

function DropDownList(menu_id,item_list) {
    this.menu_id = menu_id;
    this.title = config.titles[menu_id];
    this.painter_key = 'stroke';
    this.items = item_list.split(',');
    this.current_item = 0;
}

DropDownList.prototype.getIconSrc = function(id) { return config.icon_dir+id+'.gif'; }

DropDownList.prototype.write = function() {
    document.write('<span><a href="javascript:void(0);" onclick="ddlist_show(\''+this.menu_id+'\')" onmouseout="ddlist_hide_time()">');
    document.write('<img id="'+this.menu_id+'_select" src="'+this.getIconSrc(this.items[this.current_item])+'" border="1" title="'+this.title+'"></a><br/>');
    document.write('<div id="'+this.menu_id+'" class="dd_list_layer" onmouseover="ddlist_cancel_hide_time()" onmouseout="ddlist_hide_time()">');
 
    for(var i=0; i < this.items.length; i++) {
        var item_id = this.items[i];
	document.write('<a href="javascript:ddlist_hide()" id="'+item_id+'" ><img src="'+this.getIconSrc(item_id)+'" border="0"></a>');
    }
    document.write('</div></span>');

    var self = this;
    for(var i=0; i < this.items.length; i++) {
        var item_id = this.items[i];
	var el = document.getElementById(item_id);
	el.onclick = function() { self.click(this.id); }
    }
}

DropDownList.prototype.click = function(id) {
    this.current_item = 0;
    for(var i=0; i < this.items.length; i++) {
	if (id==this.items[i]) {
	    this.current_item = i;
	    break;
	}
    }
    var el = document.getElementById(this.menu_id+'_select');
    if (el) el.src = this.getIconSrc(id);
    
    //window.alert(this.menu_id+":"+id);
    document.applets[config.painter_name].setMode(this.menu_id+":"+id);
}

function StrokeList(strokes) {
    return new DropDownList('stroke',strokes);
}

function TextureList(textures) {
    return new DropDownList('texture',textures);
}

