var debugEl;
var hooks = [];
var layers = [];
var layer_increment = 0;
var presets = [];
var active = false;

presets[1] = '[[],[{"type":"text","shadow_color":"f5f500","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":-1,"shadow_blur":4,"shadow_spread":0,"layer_name":"Yellow"},{"type":"text","shadow_color":"e07b00","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":-4,"shadow_blur":8,"shadow_spread":0,"layer_name":"Orange"},{"type":"text","shadow_color":"ff1100","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":-5,"shadow_blur":16,"shadow_spread":0,"layer_name":"Red"}]]';
presets[2] = '[[],[{"type":"text","shadow_color":"ff1cff","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":3,"shadow_spread":0,"layer_name":"Layer 0"},{"type":"text","shadow_color":"b314b3","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":7,"shadow_spread":0,"layer_name":"Layer 1"},{"type":"text","shadow_color":"850d85","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":10,"shadow_spread":0,"layer_name":"Layer 2"},{"type":"text","shadow_color":"470b47","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":16,"shadow_spread":0,"layer_name":"Layer 3"},{"type":"text","shadow_color":"290029","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":23,"shadow_spread":0,"layer_name":"Layer 4"}]]';
presets[3] = '[[],[{"type":"text","shadow_color":"7700ff","shadow_inset":false,"shadow_offset_x":1,"shadow_offset_y":1,"shadow_blur":0,"shadow_spread":0,"layer_name":"Layer 5"},{"type":"text","shadow_color":"0040ff","shadow_inset":false,"shadow_offset_x":1,"shadow_offset_y":-1,"shadow_blur":0,"shadow_spread":0,"layer_name":"Layer 6"},{"type":"text","shadow_color":"ff0048","shadow_inset":false,"shadow_offset_x":-1,"shadow_offset_y":-1,"shadow_blur":0,"shadow_spread":0,"layer_name":"Layer 7"},{"type":"text","shadow_color":"ffdd00","shadow_inset":false,"shadow_offset_x":-1,"shadow_offset_y":1,"shadow_blur":0,"shadow_spread":0,"layer_name":"Layer 8"}]]';
presets[4] = '[[{"type":"box","shadow_color":"d7e854","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":30,"shadow_spread":7,"layer_name":"Glow"},{"type":"box","shadow_color":"c0d900","shadow_inset":true,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":3,"shadow_spread":0,"layer_name":"Inner glow"}],[]]';
presets[5] = '[[{"type":"box","shadow_color":"0fa37e","shadow_inset":false,"shadow_offset_x":-3,"shadow_offset_y":0,"shadow_blur":6,"shadow_spread":0,"layer_name":"Layer 6"},{"type":"box","shadow_color":"ff0033","shadow_inset":false,"shadow_offset_x":3,"shadow_offset_y":3,"shadow_blur":6,"shadow_spread":0,"layer_name":"Layer 5"},{"type":"box","shadow_color":"ffea00","shadow_inset":false,"shadow_offset_x":3,"shadow_offset_y":-3,"shadow_blur":6,"shadow_spread":0,"layer_name":"Layer 7"}],[]]';
presets[6] = '[[{"type":"box","shadow_color":"000000","shadow_inset":true,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":11,"shadow_spread":1,"layer_name":"Layer 0"}],[{"type":"text","shadow_color":"000000","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":5,"shadow_spread":0,"layer_name":"Layer 1"}]]';
presets[7] = '[[],[{"type":"text","shadow_color":"85f5d9","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":-1,"shadow_blur":4,"shadow_spread":0,"layer_name":"Light"},{"type":"text","shadow_color":"00ff8c","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":-4,"shadow_blur":8,"shadow_spread":0,"layer_name":"Mid"},{"type":"text","shadow_color":"003369","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":-5,"shadow_blur":16,"shadow_spread":0,"layer_name":"Dark"}]]';
presets[8] = '[[],[{"type":"text","shadow_color":"938cc9","shadow_inset":false,"shadow_offset_x":12,"shadow_offset_y":12,"shadow_blur":11,"shadow_spread":0,"layer_name":"Layer 0"},{"type":"text","shadow_color":"80bbd6","shadow_inset":false,"shadow_offset_x":-15,"shadow_offset_y":2,"shadow_blur":16,"shadow_spread":0,"layer_name":"Layer 1"},{"type":"text","shadow_color":"3c48d6","shadow_inset":false,"shadow_offset_x":3,"shadow_offset_y":-4,"shadow_blur":22,"shadow_spread":0,"layer_name":"Layer 2"},{"type":"text","shadow_color":"a3edff","shadow_inset":false,"shadow_offset_x":-6,"shadow_offset_y":10,"shadow_blur":27,"shadow_spread":0,"layer_name":"Layer 3"},{"type":"text","shadow_color":"ffffff","shadow_inset":false,"shadow_offset_x":0,"shadow_offset_y":0,"shadow_blur":11,"shadow_spread":0,"layer_name":"Layer 43"}]]';

hooks['colorbutton_preview_background'] = function(hex, el){ $('#fieldset_preview').css({'background-color' : "#" + hex}); };
hooks['colorbutton_preview_box'] = function(hex, el){ $('#fieldset_preview textarea').css({'background-color' : "#" + hex}); };
hooks['colorbutton_preview_text'] = function(hex, el){ $('#fieldset_preview textarea').css({'color' : "#" + hex}); };
hooks['colorbutton_shadow_color'] = function(hex, el){ current_layer.shadow_color = "#" + hex; };
hooks['slider_blur'] = function(value){ current_layer.shadow_blur = value; };
hooks['slider_offset_x'] = function(value){ current_layer.shadow_offset_x = value; };
hooks['slider_offset_y'] = function(value){ current_layer.shadow_offset_y = value; };
hooks['slider_spread'] = function(value){ current_layer.shadow_spread = value; };
hooks['colorbutton_shadow_color'] = function(hex, el){ current_layer.shadow_color = hex; };

function ShadowLayer(is_text_layer)
{
	if(is_text_layer == true)
	{
		this.type = "text";
	}
	else
	{
		this.type = "box";
	}
	
	this.shadow_color = "000000";
	this.shadow_inset = false;
	this.shadow_offset_x = 0;
	this.shadow_offset_y = 0;
	this.shadow_blur = 0;
	this.shadow_spread = 0;
	this.layer_name = "";
}

function initialize()
{
	$('.colorfield .colorbutton').ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			var id_self = $(el).attr('id');
			$(el).parent().children('input').val(hex);
			$(el).css({'background-color': '#' + hex});
			
			if(hooks[id_self])
			{
				hooks[id_self](hex, el);
				update_preview();
			}
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor($(this).parent().children('input').val());
		},
		onShow: function (colpkr) {
			$(colpkr).fadeIn(500);
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).fadeOut(500);
			return false;
		}
	})
	.bind('keyup', function(){
		$(this).ColorPickerSetColor($(this).parent().children('input').val());
	});
	
	$('.sortable').sortable({
			placeholder: "listbox-item-placeholder",
			containment: "parent",
			distance: 8,
			update: function(){
				update_preview();
			}
		});
	$('.sortable').disableSelection();
	
	$('#setting_inset').buttonset();
	
	$('.slider').slider({
		slide: function(event, ui){
			$(ui.handle).parent().parent().children('input').val(ui.value);
			hooks[$(ui.handle).parent().attr('id')](ui.value);  // Run the specified hook
			update_preview();
		},
		min: 0,
		max: 30,
		
	});
	
	$('.slider-negative').slider({
		slide: function(event, ui){
			$(ui.handle).parent().parent().children('input').val(ui.value);
			hooks[$(ui.handle).parent().attr('id')](ui.value);  // Run the specified hook
			update_preview();
		},
		min: -30,
		max: 30,
		
	});
	
	$('.slider-field').children('input').change(function(){
		var slider_element = $(this).parent().children('.slider, .slider-negative');
		slider_element.slider("value", $(this).val());
		hooks[slider_element.attr('id')]($(this).val());  // Run the specified hook
		update_preview();
	});
	
	$('#input_inset, #input_outset').change(function(){
		//alert(0);
		if($('#input_inset:checked').val() !== undefined) 
		{
			current_layer.shadow_inset = true;
		}
		else
		{
			current_layer.shadow_inset = false;
		}
		
		update_preview();
	});
	
	$('#settings').hide();
	
	rebind();
}

function rebind()
{
	$('.listbox-item').click(function(){
		
		var layer_id = $(this).children('.layer-id').text();
		select_layer(layer_id)
	});
}

function add_layer(is_text_layer)
{
	if(is_text_layer == true)
	{
		var target = "#layers_text";
	}
	else
	{
		var target = "#layers_box";
	}
	
	var new_layer = new ShadowLayer(is_text_layer);
	layers[layer_increment] = new_layer;
	new_layer.layer_name = "Layer " + layer_increment;
	$(target).append('<li><div class="listbox-item" id="layer_item_' + layer_increment + '"><img src="images/handle.png" class=\"handle\">&nbsp;<span class="layer-id">' + layer_increment + '</span><span class="layer-title">' + new_layer.layer_name + '</span><div class="tools"><img src="images/rename.png" onclick="rename_layer(' + layer_increment + ');"><img src="images/delete.png" onclick="delete_layer(' + layer_increment + ');"></div></div></li>');
	
	layer_increment += 1;
	rebind();
	
	select_layer(layer_increment - 1);
	
	return layer_increment - 1;
}

function add_layer_text()
{
	return add_layer(true);
}

function add_layer_box()
{
	return add_layer(false);
}

function select_layer(id)
{
	$('.listbox-item.selected').removeClass('selected');
	$('#layer_item_' + id).addClass("selected");
	
	current_layer = layers[id];
	
	if(current_layer.type == "box")
	{
		$('#setting_inset').show();
		$('#setting_spread').show();
	}
	else
	{
		$('#setting_inset').hide();
		$('#setting_spread').hide();
	}
	
	$('#settings_placeholder').hide();
	$('#settings').show();
	
	load_layer();
}


function select_first()
{
	var first_id = $('div.listbox-item:first').find('.layer-id').text();
	if(first_id == "")
	{
		$('#settings_placeholder').show();
		$('#settings').hide();
		active = false;
	}
	else
	{
		select_layer(first_id);
	}
}

function save_layers()
{
	var save_object = [];
	
	var entry_list = [];
	
	$('#layers_box div.listbox-item').each(function(index, el){
		var layer_id = $(this).find('.layer-id').text();
		var working_layer = layers[layer_id];
		entry_list.push(working_layer);
	});
	
	save_object[0] = entry_list.slice(0);
	
	var entry_list = [];
	
	$('#layers_text div.listbox-item').each(function(index, el){
		var layer_id = $(this).find('.layer-id').text();
		var working_layer = layers[layer_id];
		entry_list.push(working_layer);
	});
	
	save_object[1] = entry_list.slice(0);
	
	$('#dialog_save textarea').text($.toJSON(save_object));
	
	$('#dialog_save').dialog({
		resizable: false,
		modal: true,
		width: 500,
		height: 280
	});
}

function load_layers()
{
	var data = $.evalJSON($('#dialog_load textarea').val());
	parse_layers(data);
}

function parse_layers(jsondata)
{
	confirm_clear_layers();
	
	for(i in jsondata[0])
	{
		 var new_id = add_layer_box();
		 layers[new_id] = jsondata[0][i];
	}
	
	for(i in jsondata[1])
	{
		 var new_id = add_layer_text();
		 layers[new_id] = jsondata[1][i];
	}
	
	update_names();
	select_first();
	update_preview();
}

function load_layer()
{
	$('#input_offset_x').val(current_layer.shadow_offset_x);
	$('#slider_offset_x').slider("value", current_layer.shadow_offset_x);
	$('#input_offset_y').val(current_layer.shadow_offset_y);
	$('#slider_offset_y').slider("value", current_layer.shadow_offset_y);
	$('#input_blur').val(current_layer.shadow_blur);
	$('#slider_blur').slider("value", current_layer.shadow_blur);
	$('#input_shadow_color').val(current_layer.shadow_color);
	$('#colorbutton_shadow_color').css({'background-color': "#" + current_layer.shadow_color});
	
	if(current_layer.type == "box")
	{
		$('#input_spread').val(current_layer.shadow_spread);
		$('#slider_spread').slider("value", current_layer.shadow_spread);
		
		if(current_layer.shadow_inset == true)
		{
			$('#input_inset').attr("checked","checked").button("refresh");
		}
		else
		{
			$('#input_outset').attr("checked","checked").button("refresh");
		}
	}
}

function delete_layer(id)
{
	$('#dialog_confirm_deletion').find('.layer-name').text(layers[id].layer_name);
	
	$('#dialog_confirm_deletion').dialog({
		resizable: false,
		modal: true,
		buttons: {
			"Delete layer": function(){
				confirm_delete_layer(id);
				$(this).dialog("close");
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});
}

function confirm_delete_layer(id)
{
	layers[id] = null;
	$('#layer_item_' + id).parent().remove();
	select_first();
	update_preview();
}

function clear_layers()
{
	$('#dialog_confirm_clear').dialog({
		resizable: false,
		modal: true,
		buttons: {
			"Clear layers": function(){
				confirm_clear_layers();
				$(this).dialog("close");
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});
}

function confirm_clear_layers()
{
	$('.listbox-item').parent().remove();
	layers = [];
	update_preview();
	$('#settings').hide();
	$('#settings_placeholder').show();
	active = false;
}

function rename_layer(id)
{
	$('#dialog_rename input').val(layers[id].layer_name);
	
	$('#dialog_rename').dialog({
		resizable: false,
		modal: true,
		width: 500,
		height: 180,
		buttons: {
			"Rename": function(){
				confirm_rename_layer(id);
				$(this).dialog("close");
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});
}

function confirm_rename_layer(id)
{
	layers[id].layer_name = $('#dialog_rename input').val();
	update_names();
}

function update_preview()
{
	var entry_list = [];
	
	$('#layers_box div.listbox-item').each(function(index, el){
		var layer_id = $(this).find('.layer-id').text();
		var working_layer = layers[layer_id];
		entry_list.push(generate_box_shadow_entry(working_layer.shadow_color, 
			working_layer.shadow_offset_x, 
			working_layer.shadow_offset_y, 
			working_layer.shadow_blur,
			working_layer.shadow_spread,
			working_layer.shadow_inset));
	});
	
	var css_box = entry_list.join(", ");
	
	var entry_list = [];
	
	$('#layers_text div.listbox-item').each(function(index, el){
		var layer_id = $(this).find('.layer-id').text();
		var working_layer = layers[layer_id];
		entry_list.push(generate_text_shadow_entry(working_layer.shadow_color, 
			working_layer.shadow_offset_x, 
			working_layer.shadow_offset_y, 
			working_layer.shadow_blur));
	});
	
	var css_text = entry_list.join(", ");
	
	$('#preview').css({
		'box-shadow': css_box,
		'text-shadow': css_text
	});
	
	$('#preview').hide().show();
}

function update_names()
{
	for(i in layers)
	{
		$('#layer_item_' + i).children('.layer-title').html(layers[i].layer_name);
	}
}

function generate_code()
{
	var css_lines = [];
	
	var entry_list = [];
	
	$('#layers_box div.listbox-item').each(function(index, el){
		var layer_id = $(this).find('.layer-id').text();
		var working_layer = layers[layer_id];
		entry_list.push(generate_box_shadow_entry(working_layer.shadow_color, 
			working_layer.shadow_offset_x, 
			working_layer.shadow_offset_y, 
			working_layer.shadow_blur,
			working_layer.shadow_spread,
			working_layer.shadow_inset));
	});
	
	if(entry_list.length > 0)
	{
		css_lines.push(generate_box_shadow_line("", entry_list));
		css_lines.push(generate_box_shadow_line("webkit", entry_list));
		css_lines.push(generate_box_shadow_line("moz", entry_list));
		css_lines.push(generate_box_shadow_line("o", entry_list));
		css_lines.push(generate_box_shadow_line("ms", entry_list));
	}
	
	var entry_list = [];
	
	$('#layers_text div.listbox-item').each(function(index, el){
		var layer_id = $(this).find('.layer-id').text();
		var working_layer = layers[layer_id];
		entry_list.push(generate_text_shadow_entry(working_layer.shadow_color, 
			working_layer.shadow_offset_x, 
			working_layer.shadow_offset_y, 
			working_layer.shadow_blur));
	});
	
	if(entry_list.length > 0)
	{
		css_lines.push(generate_text_shadow_line("", entry_list));
		css_lines.push(generate_text_shadow_line("webkit", entry_list));
		css_lines.push(generate_text_shadow_line("moz", entry_list));
		css_lines.push(generate_text_shadow_line("o", entry_list));
		css_lines.push(generate_text_shadow_line("ms", entry_list));
	}
	
	$('#dialog_code textarea').text(css_lines.join("\n")).enableSelection();
	
	$('#dialog_code').dialog({
		resizable: false,
		modal: true,
		width: 500,
		height: 280
	});
}

function generate_text_shadow_line(prefix, entries)
{
	if(prefix)
	{
		prefix = "-" + prefix + "-";
	}
	
	return prefix + "text-shadow: " + entries.join(", ") + ";";
}

function generate_text_shadow_entry(color, offset_x, offset_y, blur)
{
	return offset_x + "px " + offset_y + "px " + blur + "px #" + color;
}

function generate_box_shadow_line(prefix, entries)
{
	if(prefix)
	{
		prefix = "-" + prefix + "-";
	}
	
	return prefix + "box-shadow: " + entries.join(", ") + ";";
}

function generate_box_shadow_entry(color, offset_x, offset_y, blur, spread, inset)
{
	if(inset)
	{
		is_inset = " inset";
	}
	else
	{
		is_inset = "";
	}
	
	return offset_x + "px " + offset_y + "px " + blur + "px " + spread + "px #" + color + is_inset;
}


function dialog_load()
{
	$('#dialog_load').dialog({
		resizable: false,
		modal: true,
		width: 500,
		height: 330,
		buttons: {
			"Load": function(){
				load_layers();
				$(this).dialog("close");
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});
}

function dialog_presets()
{
	$('#dialog_presets').dialog({
		resizable: true,
		modal: true,
		width: 600,
		height: 500,
		buttons: {
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});
}

function load_preset(id)
{
	parse_layers($.evalJSON(presets[id]));
	$('#dialog_presets').dialog("close");
}

$(function(){ initialize(); });
