function basename (path, suffix) {
    // Returns the filename component of the path  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/basename
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ash Searle (http://hexmen.com/blog/)
    // +   improved by: Lincoln Ramsay
    // +   improved by: djmix
    // *     example 1: basename('/www/site/home.htm', '.htm');
    // *     returns 1: 'home'
    // *     example 2: basename('ecra.php?p=1');
    // *     returns 2: 'ecra.php?p=1'
    var b = path.replace(/^.*[\/\\]/g, '');
    
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    
    return b;
}
//Namespace

//OK this was supposed to be beautiful and OOP, it did not turn out that way..
if(!HtmlEditor) var HtmlEditor = {};

jQuery.extend(HtmlEditor, {
	editor: function(element,options) {
		this._options = options;
		this._element = element;
		this.init();
	}
}
);

jQuery.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
};

jQuery.fn.HtmlEditor = function (options) {

  options = jQuery.extend({
	 tools: [
        {'tool': 'p', 'title': 'Löptext', 'css': 'HtmlEditor_paragraph_button'}, 
        {'tool': 'h1', 'title': 'Rubrik 1', 'css': 'HtmlEditor_h1_button'},
        {'tool': 'h2', 'title': 'Rubrik 2', 'css': 'HtmlEditor_h2_button'},
        {'tool': 'h3', 'title': 'Rubrik 3', 'css': 'HtmlEditor_h3_button'},
        {'tool': 'img', 'title': 'Bild', 'css': 'HtmlEditor_image_button'},
        {'tool': 'table', 'title': 'Tabell', 'css': 'HtmlEditor_table_button'},
        {'tool': 'a', 'title': 'Länk', 'css': 'HtmlEditor_link_button'},
        {'tool': 'unlink', 'title': 'Bryt länk', 'css': 'HtmlEditor_unlink_button'},
        {'tool': 'strong', 'title': 'Fet', 'css': 'HtmlEditor_bold_button'},
        {'tool': 'em', 'title': 'Kursiv', 'css': 'HtmlEditor_italic_button'},
        {'tool': 'youtube', 'title': 'Youtube', 'css': 'HtmlEditor_youtube_button'},
        {'tool': 'trash', 'title': 'Ta bort formatering', 'css': 'HtmlEditor_trash_button'},
        {'tool': 'addFile', 'title': 'Lägg till fil', 'css': 'HtmlEditor_addFile_button'},
         {'tool': 'form', 'title': 'Länka formulär', 'css': 'HtmlEditor_form_button'},
        {'tool': 'save', 'title': 'Spara', 'css': 'HtmlEditor_save_button'}
    	],
     action: function(){
     	alert('test');
     },
     dialogSelector: "#dialog"

  }, options);
  
	return this.each(function(){
		new HtmlEditor.editor(jQuery(this),options);
	});
}

//Constructor 
HtmlEditor.editor.prototype.init = function() {

	if (jQuery.browser.msie) {
    	this._Browser = new HtmlEditor.Explorer(this);
  	}
  	else if(jQuery.browser.opera){
  		this._Browser = new HtmlEditor.Opera(this);
  	}
  	else {
  		this._Browser = new HtmlEditor.Mozilla(this);
  	}
  	
  	wrappingElement = jQuery("<div class='HtmlEditor_editor'></div>")
  
	this._element.wrap(wrappingElement);
	
	//Undviker skuggning i bindningarna till click..
	var editor = this;
	
	//Dialog setup:
	jQuery(editor._options.dialogSelector).dialog({
	    autoOpen: false,
	    width: 300,
	    hide: 'slide',
	    show: 'slide',
	    draggable: false,
	    title: "Infoga bild",
	    buttons: {
	    	"Stäng": function() { 
	    		$(this).dialog("close"); 
	    	} 
	    }
	});
	
	
	//Toolbar creation
	var toolbarDiv = jQuery('<div class="clearer"></div>').addClass('HtmlEditor_toolbar');
	
	jQuery.each(this._options.tools, function(i,val){
		var button = jQuery('<button></button>').addClass(val.css);
		button.attr('title',val.title);
		toolbarDiv.append(button);
		//Bind button, well if I were a nice programmer i wouldnt have done like 100 lines of 
		// switch case.. but iam not.
		
		switch(val.tool){
			case "p":
				button.click(function(event){
					editor._Browser.doFormat("insertParagraph");
				});
				break;
			
			case "h1":
				button.click(function(){
					selectedNode = editor._Browser.selected();
					if(selectedNode.tagName.toLowerCase()=="h1"){
						jQuery(selectedNode).replaceWith("<p>" + jQuery(selectedNode).html()+ "</p>");
					} else editor._Browser.doFormat("formatBlock","<h1>");
				});
				break;
			
			case "h2":
				button.click(function(){
					selectedNode = editor._Browser.selected();
					if(selectedNode.tagName.toLowerCase()=="h2"){
						jQuery(selectedNode).replaceWith("<p>" + jQuery(selectedNode).html()+ "</p>");
					} else editor._Browser.doFormat("formatBlock","<h2>");

				});
				break;
			case "h3":
				button.click(function(){
					selectedNode = editor._Browser.selected();
					if(selectedNode.tagName.toLowerCase()=="h3"){
						jQuery(selectedNode).replaceWith("<p>" + jQuery(selectedNode).html()+ "</p>");
					} else editor._Browser.doFormat("formatBlock","<h3>");

				});
				break;
			case "img":
				button.click(function(){
					editor._Browser.saveSelection();
					//editor._Browser.restoreSelection();
					jQuery(editor._options.dialogSelector).dialog('option','title', 'Infoga bild');
					jQuery(editor._options.dialogSelector).dialog('option','width', 600);
					jQuery(editor._options.dialogSelector).dialog('option','height', 400);
					
					jQuery(editor._options.dialogSelector).dialog('option','draggable', true);
					
					
					jQuery(editor._options.dialogSelector).dialog('open');
					
					jQuery(editor._options.dialogSelector).dialog('option','buttons', {
						"Infoga bild": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
							//editor._Browser.restoreSelection();

							dialogDiv = jQuery(editor._options.dialogSelector);
							img = jQuery('.HtmlEditor_imagePreviewer', dialogDiv);
							img = jQuery('img', img);
							editor._Browser.doFormat("insertImage",img.get(0).src);
						},
						
						"Infoga vänster justerad": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
							//editor._Browser.restoreSelection();
							
							var dialog = jQuery(editor._options.dialogSelector);
							
							var img = jQuery('.HtmlEditor_imagePreviewer', dialog);
							img = jQuery('img', img);
							img.addClass('leftjustified');
						
							editor._Browser.doFormat("insertHTML",img.outerHTML());
						
						},
						
						"Infoga höger justerad": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
							//editor._Browser.restoreSelection();
							
							var dialog = jQuery(editor._options.dialogSelector);
							
							var img = jQuery('.HtmlEditor_imagePreviewer', dialog);

							img = jQuery('img', img);
							img.addClass('rightjustified');
						
							editor._Browser.doFormat("insertHTML",img.outerHTML());

						},
						
						"Ladda upp nytt": function () {
							window.open("/fileUploader/",null, "height=400,width=400,status=no,toolbar=no,menubar=no,location=no");
						},
						
						"Avbryt": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
						}
						
						
					});
					
					
					div = jQuery("<div class='HtmlEditor_imageBrowser'></div>")
					imgPrev = jQuery("<div class='HtmlEditor_imagePreviewer'></div>");
					
					jQuery(div).fileTree({root: "/", script: "/fileview/"},function(file){
							//var image = jQuery("<img src='" + file + "'/>");
							image = new Image()
							image.src = file;
							imgPrev.html(image);
						});

					jQuery(editor._options.dialogSelector).html(div)
					jQuery(editor._options.dialogSelector).append(imgPrev);
					
				});
				break;
			
			case "table":
				button.click(function(){
					editor._Browser.saveSelection();
				
					jQuery(editor._options.dialogSelector).dialog('option','title', 'Infoga tabell')
					jQuery(editor._options.dialogSelector).dialog('option','width', 500);
					jQuery(editor._options.dialogSelector).dialog('option','height', 300);
						
					jQuery(editor._options.dialogSelector).dialog('option','draggable', true);
					var numOfRows = jQuery("<input type='text'></input>");
					var numOfCols = jQuery("<input type='text'></input>");
					var rows = jQuery("<label>Rader: </label>");
					var cols = jQuery("<label>Kolumner: </label>");
					rows.append(numOfRows);
					cols.append(numOfCols);
					
					jQuery(editor._options.dialogSelector).dialog('option','buttons', {
						"Avbryt": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
						}, 
						"Infoga": function() {
							var res = "<table>\n";
							for(var i=0;i<numOfRows.val();i++){
								res += "<tr>\n";
									
								for(var c=0;c<numOfCols.val();c++){
									res += "   <td>&nbsp;" + c + "&nbsp;</td>\n";
								}
									
								res+= "</tr>\n";
							}
							
							res += "</table>";
							
							
							
							jQuery(editor._options.dialogSelector).dialog('close');
							editor._Browser.restoreSelection();
							
							editor._Browser.doFormat("insertHTML",res);
						}
						});
					jQuery(editor._options.dialogSelector).html(rows);
					jQuery(editor._options.dialogSelector).append(cols);
					
					jQuery(editor._options.dialogSelector).dialog('open');
					
				
				});
				break;
			
			case "a":
				button.click(function(){
					editor._Browser.saveSelection();
				
					jQuery(editor._options.dialogSelector).dialog('option','title', 'Infoga länk')
					jQuery(editor._options.dialogSelector).dialog('option','width', 200);
					jQuery(editor._options.dialogSelector).dialog('option','height', 140);
						
					jQuery(editor._options.dialogSelector).dialog('option','draggable', true);
					
					jQuery(editor._options.dialogSelector).dialog('option','buttons', {
						"Avbryt": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
						}});

					jQuery(editor._options.dialogSelector).dialog('open');
					input = jQuery("<input type='text'></input>")
					
					input.keypress(function(e){
						if(e.keyCode == 13){
							e.preventDefault();
							jQuery(editor._options.dialogSelector).dialog('close')
							editor._Browser.restoreSelection();
							editor._Browser.doFormat("createLink",this.value);
						}
					});
					
					jQuery(editor._options.dialogSelector).html(input)

				
				});
				break;
			case "unlink":
				button.click(function(){
					editor._Browser.doFormat("unlink");
				});
				break;
			case "strong":
				button.click(function(){
					editor._Browser.doFormat("bold");
				});
				break;
			
			case "em":
				button.click(function(){
					editor._Browser.doFormat("italic");
				});
				break;
			
			case "youtube":
				button.click(function(){
					editor._Browser.saveSelection();
					
					jQuery(editor._options.dialogSelector).dialog('option','title', 'Klistra in Youtube')
					jQuery(editor._options.dialogSelector).dialog('option','width', 200);
					jQuery(editor._options.dialogSelector).dialog('option','height', 140);
						
					jQuery(editor._options.dialogSelector).dialog('option','draggable', true);
					
					jQuery(editor._options.dialogSelector).dialog('option','buttons', {
						"Avbryt": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
						}});

					jQuery(editor._options.dialogSelector).dialog('open');
					
					input = jQuery("<input type='text'></input>")
					
					input.keypress(function(e){
						if(e.keyCode == 13){
							e.preventDefault();
							jQuery(editor._options.dialogSelector).dialog('close')
							editor._Browser.restoreSelection();
							//Lite hårdkod
							//var dom = $(this.value);
                   			//var width = $(dom).attr("width");
                   			//var mult = 460/width;
                   			//width = 460
                   			
                  			//var height = Math.round(Number($(dom).attr("height") * mult));
                  			
                  		 	/*var html = "<img class='youtubePlaceHolder' src='/~petha443/sif/Directory/images/youtube.jpg'"
							+ " alt='" + src + "'" 
							+ " height='" + height +"'"
							+ " width ='" + width + "'"
							+ "/>";
						*/
							editor._Browser.doFormat("insertHTML",this.value);

						}
					});
									
					jQuery(editor._options.dialogSelector).html(input)

				
				});
				break;
				
			case "trash":
				button.click(function(){
					editor._Browser.doFormat("removeFormat");
				});
				break;
				
			case "addFile":
				button.click(function(){
					editor._Browser.saveSelection();
						
					jQuery(editor._options.dialogSelector).dialog('option','title', 'Infoga länk');
					jQuery(editor._options.dialogSelector).dialog('option','width', 550);
					jQuery(editor._options.dialogSelector).dialog('option','height', 300);
					
					jQuery(editor._options.dialogSelector).dialog('option','draggable', true);
					
					jQuery(editor._options.dialogSelector).dialog('option','buttons', {
						"Infoga fillänk": function() {	
							dialogDiv = jQuery(editor._options.dialogSelector);
							file = jQuery('.HtmlEditor_filePreviewer', dialogDiv).html();
							jQuery(editor._options.dialogSelector).dialog('close')
							editor._Browser.restoreSelection();
							editor._Browser.doFormat("createLink",file);
						},
				
						"Ladda upp nytt": function () {
							window.open("/fileUploader/",null, "height=400,width=400,status=no,toolbar=no,menubar=no,location=no");
						},
						
						"Stäng": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
						}
						
						
					});

					
					
					div = jQuery("<div class='HtmlEditor_fileBrowser'></div>")
					imgPrev = jQuery("<div class='HtmlEditor_filePreviewer'></div>");
					
					jQuery(div).fileTree({root: "/", script: "/fileview/"},function(file){						
							imgPrev.html(file);
						});

					jQuery(editor._options.dialogSelector).html(div)
					jQuery(editor._options.dialogSelector).append(imgPrev);
					jQuery(editor._options.dialogSelector).dialog('open');
					
					
				});
				break;
			case "form":
				button.click(function(e){
				var dialogContent = $("<div></div>");
				
				var textInput = $('<input type="text" > </input>');
				var text = $("<label>Tex: </label>").append(textInput);
				var dropDownInput = $('<select></select>');

				dialogContent.append(text);
				
				jQuery.get("_action/availableForms",function(data){
					$(data).each(function(index){
					dropDownInput.append($('<option value="' + data[index].formLink + '">' + data[index].name + '</option>'));
					});
				},"json");
				
				dialogContent.append(dropDownInput);
				
				editor._Browser.saveSelection();
					
					jQuery(editor._options.dialogSelector).dialog('option','title', 'Länk till formulär')
					jQuery(editor._options.dialogSelector).dialog('option','width', 400);
					jQuery(editor._options.dialogSelector).dialog('option','height', 400);
						
					jQuery(editor._options.dialogSelector).dialog('option','draggable', true);
					
					jQuery(editor._options.dialogSelector).dialog('option','buttons', {
						"Infoga form-länk": function(){
						
							jQuery(editor._options.dialogSelector).dialog('close')
							editor._Browser.restoreSelection();
						
							//Gör a href link class=formLink här
							var a = $('<a href="' + dropDownInput.val() + '" class="formLink">'+textInput.val() + '</a>' );
							editor._Browser.doFormat("insertHTML",a.outerHTML());

							
						},
						"Avbryt": function() {
							jQuery(editor._options.dialogSelector).dialog('close');
						}});

					jQuery(editor._options.dialogSelector).dialog('open');						
					jQuery(editor._options.dialogSelector).html(dialogContent)
					
				});
				break;
					
			case "save":
				button.click(function(e){	
					editor._options.action(editor._element.html());
				});
		}
		
	});

	//Lägger till toolbar
	this._element.after(toolbarDiv);
	this._element.get(0).contentEditable = true;

	//Spara undan toolbaren.. 
	this._toolbar = toolbarDiv;
		
};


//Explorer specific code
//
//
HtmlEditor.Explorer = function(edit) {
    this._editorInstance = edit;
};

HtmlEditor.Explorer.prototype.doFormat = function(cmd, arg) {
	//Vi måste kolla om vi arbetar i "vår" ruta
	if(cmd=='insertHTML') {	
		var range = document.selection.createRange();
		range.pasteHTML(arg);
		return;
	}
	document.execCommand(cmd,false, arg);
}

HtmlEditor.Explorer.prototype.saveSelection = function(){
	var sel = document.selection;
	this._range = sel.createRange();

}

HtmlEditor.Explorer.prototype.restoreSelection = function() {
	this._editorInstance._element.focus();
	this._range.select();
}


HtmlEditor.Explorer.prototype.selected = function() {
   	var sel = document.selection;
   	var rng = sel.createRange();
   	var el = rng.parentElement();
   	return el;
};



//Opera specific code
//
//
HtmlEditor.Opera = function(edit) {
    this._editorInstance = edit;
};

HtmlEditor.Opera.prototype.doFormat = function(cmd, arg) {
	//Vi måste kolla om vi arbetar i "vår" ruta

	document.execCommand(cmd,false, arg);
}

HtmlEditor.Opera.prototype.saveSelection = function(){
	var sel = window.getSelection();
	var range = sel.getRangeAt(0);

	this._rangeStartOffset = range.startOffset;
	this._rangeStartContainer = range.startContainer;
	
	this._rangeEndOffset = range.endOffset;
	this._rangeEndContainer = range.endContainer;

}

HtmlEditor.Opera.prototype.restoreSelection = function() {
	var range = document.createRange();
	range.setStart(this._rangeStartContainer, this._rangeStartOffset);
	range.setEnd(this._rangeEndContainer, this._rangeEndOffset);
	var selection = window.getSelection();
	this._editorInstance._element.focus();
	selection.addRange(range);
}


HtmlEditor.Opera.prototype.selected = function() {
   	var sel = document.selection;
   	var rng = sel.createRange();
   	var el = rng.parentElement();
   	return el;
};




//Mozilla and Safari for the moment..
// They seems to support more or less the same typ of selections
// Actually Opera uses the same, but the focus calls needs to be in this perticular order
// for safari to work, mozilla doesnt care.. So either I make a new class for Safari, change the order
// and keeps this one for Mozilla while still keeping the one for Opera.. Ill guess more things will fckp later..
HtmlEditor.Mozilla = function(edit) {
    this._editorInstance = edit;


};

HtmlEditor.Mozilla.prototype.doFormat = function(cmd, arg) {
	//Vi måste kolla om vi arbetar i "vår" ruta

 	document.execCommand("styleWithCSS",false,false);
	document.execCommand(cmd,false, arg);
}

HtmlEditor.Mozilla.prototype.saveSelection = function(){
	var sel = window.getSelection();
	var range = sel.getRangeAt(0);
	this._rangeStartOffset = range.startOffset;
	this._rangeStartContainer = range.startContainer;
	
	this._rangeEndOffset = range.endOffset;
	this._rangeEndContainer = range.endContainer;

}

HtmlEditor.Mozilla.prototype.restoreSelection = function() {
	var range = document.createRange();
	range.setStart(this._rangeStartContainer, this._rangeStartOffset);
	range.setEnd(this._rangeEndContainer, this._rangeEndOffset);
	var selection = window.getSelection();
	selection.addRange(range);
	this._editorInstance._element.focus();
}

HtmlEditor.Mozilla.prototype.selected = function() {
	var sel = window.getSelection();
	var data = sel.getRangeAt(0).toString();
    var node = sel.focusNode;    
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);

};
