var ImageDialog = {
	preInit : function() {
		var url;

		tinyMCEPopup.requireLangPack();

		Config.artikelid = parent.entryid;
		Config.pagetype = parent.pagetpye;
		Config.imageListUrl = tinyMCEPopup.getParam("snstuff_img_url_list") || "/admin_list_pictures_json/{artikelid}";
		Config.uploadUrl = tinyMCEPopup.getParam("snstuff_img_url_upload") || "/{pagetype}/{artikelid}?sx_action=on_user_upload";
		Config.deleteUrl = tinyMCEPopup.getParam("snstuff_img_url_delete") || "/admin_kill_picture?name=articleimage/sn_computer/{artikelid}/{imgname}&id={artikelid}";
		Config.imageUrl = tinyMCEPopup.getParam("snstuff_img_url_image") || "/articleimage/{artikelid}/{imgname}";

	},

        imgURL: "",
	imgAlign:"",

	init : function(ed) {
		ImageDialog.ImageList = new ImageData();
		
		document.forms["uploadForm"].action = Config.getUploadUrl();

		var ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode();

		tinyMCEPopup.resizeToInnerSize();

		TinyMCE_EditableSelects.init();

		if ( n != null && typeof n != 'undefined' && n.nodeName == 'IMG') {
			this.imgURL = dom.getAttrib(n, 'src');
			this.selectByValue(document.getElementById('align'), this.getAttrib(n, 'align'));
			document.getElementById("insert").value = ed.getLang('update');
			this.imgAlign = dom.getAttrib(n, 'style');

			if (ed.settings.inline_styles) {
				// Move attribs to styles
				if (dom.getAttrib(n, 'align'))
					this.updateStyle('align');

				if (dom.getAttrib(n, 'hspace'))
					this.updateStyle('hspace');

				if (dom.getAttrib(n, 'border'))
					this.updateStyle('border');

				if (dom.getAttrib(n, 'vspace'))
					this.updateStyle('vspace');
			}
		}

		this.changeAppearance();
		this.showPreviewImage(this.imgURL, 1);
		this.loadImages();
	},


	selectOptions : function(){
		var n = tinyMCEPopup.editor.selection.getNode(), ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode();

		if(n.nodeName != 'IMG')
			  return;

		var srcLstSize = tinyMCEPopup.dom.get("src_list_size").options;
		var imgurl = this.imgURL;
		var imgname = imgurl.split("/").pop();

		// select image in selectbox
		var oname = ImageDialog.ImageList.getOrigNameOf(imgname);
		var slist = tinyMCEPopup.dom.get("src_list_size");
		slist.options.length = 0;

		ImageDialog.showImageSizeList({value:oname});
		
		this.selectInList(tinyMCEPopup.dom.get("src_list"),oname);
		this.selectInList(tinyMCEPopup.dom.get("src_list_size"),imgurl);
		this.showSelectedImage(tinyMCEPopup.dom.get("src_list_size"));
		this.selectInList(tinyMCEPopup.dom.get("src_list_size_full"),dom.getAttrib(n, 'href'));
	},

	showSelectedImage : function(obj){

		this.imgURL = obj.options[obj.selectedIndex].value;
		this.showPreviewImage(this.imgURL);
	},

	insert : function(file, title) {
		var ed = tinyMCEPopup.editor, t = this;

		if (this.imgURL === '') {
			if (ed.selection.getNode().nodeName == 'IMG') {
				ed.dom.remove(ed.selection.getNode());
				ed.execCommand('mceRepaint');
			}

			tinyMCEPopup.close();
			return;
		}

		t.insertAndClose();

	},

	insertAndClose : function() {
		var ed = tinyMCEPopup.editor, v, args = {}, el;

		tinyMCEPopup.restoreSelection();

		// Fixes crash in Safari
		if (tinymce.isWebKit)
			ed.getWin().focus();

		if (!ed.settings.inline_styles) {
			args = {
				vspace : document.getElementById("vspace").value,
				hspace : document.getElementById("hspace").value,
				border : document.getElementById("border").value,
				align : document.getElementById("align").value
			};
		} else {
			// Remove deprecated values
			args = {
				vspace : '',
				hspace : '',
				border : '',
				align : ''
			};
		}
		var lnk = document.getElementById("src_list_size_full").value;
		if(lnk == "auto."){
			lnk = ImageDialog.ImageList.getBiggest(document.getElementById("src_list").value)
		}
		tinymce.extend(args, {
			src : this.imgURL,
			alt : lnk,
			style : this.imgAlign,
 			href : lnk
		});

		el = ed.selection.getNode();

		tinyMCEPopup.execCommand("mceBeginUndoLevel");
		// entfernen und neu einfuegen. Weil das das advimagescale plugin sonst unerwuenschten nebeneffekt erzeugt
		if (el && el.nodeName == 'IMG') {
			ed.dom.remove(ed.selection.getNode());
// 			ed.dom.setAttribs(el, args);
		} //else {

			ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1});
			ed.dom.setAttribs('__mce_tmp', args);
			ed.dom.setAttrib('__mce_tmp', 'id', '');
			ed.undoManager.add();
// 		}

// ed.execCommand('mceRepaint');
		tinyMCEPopup.execCommand("mceEndUndoLevel");
		tinyMCEPopup.close();
	},

	getAttrib : function(e, at) {
		var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;

		if (ed.settings.inline_styles) {
			switch (at) {
				case 'align':
					if (v = dom.getStyle(e, 'float'))
						return v;

					if (v = dom.getStyle(e, 'vertical-align'))
						return v;

					break;

				case 'hspace':
					v = dom.getStyle(e, 'margin-left')
					v2 = dom.getStyle(e, 'margin-right');

					if (v && v == v2)
						return parseInt(v.replace(/[^0-9]/g, ''));

					break;

				case 'vspace':
					v = dom.getStyle(e, 'margin-top')
					v2 = dom.getStyle(e, 'margin-bottom');
					if (v && v == v2)
						return parseInt(v.replace(/[^0-9]/g, ''));

					break;

				case 'border':
					v = 0;

					tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
						sv = dom.getStyle(e, 'border-' + sv + '-width');

						// False or not the same as prev
						if (!sv || (sv != v && v !== 0)) {
							v = 0;
							return false;
						}

						if (sv)
							v = sv;
					});

					if (v)
						return parseInt(v.replace(/[^0-9]/g, ''));

					break;
			}
		}

		if (v = dom.getAttrib(e, at))
			return v;

		return '';
	},


	fillSelectList : function() {

		var dom = tinyMCEPopup.dom, lst = dom.get("src_list");

		lst.options.length = 0;

		lst.options[lst.options.length] = new Option('', '');
		ImageDialog.ImageList.fillListWithNames(lst);

	},

	showImageSizeList : function(obj){
		var dom = tinyMCEPopup.dom;
		var lst = dom.get("src_list_size");
		var lst2 = dom.get("src_list_size_full");

		if(obj.selectedIndex == 0){
			this.imgURL = "";
			lst.options.length = 0;
			lst2.options.length = 0;
			this.showPreviewImage();
		}else{
			
			lst.options.length = 0;
			ImageDialog.ImageList.fillListWithSizeOf(lst,obj.value);

			
			lst2.options.length = 0;
			lst2.options[lst2.options.length] = new Option("auto.","auto.");
			ImageDialog.ImageList.fillListWithSizeOf(lst2,obj.value);

			ImageDialog.showSelectedImage(document.getElementById("src_list_size"));
		}
	},



	resetImageData : function() {
// 		document.getElementById("width").value = document.getElementById("height").value = '';
	},


	updateImageData : function(img, st) {
		
		this.preloadImg = img;
	},

	changeAppearance : function() {
		var ed = tinyMCEPopup.editor, img = document.getElementById('alignSampleImg');

		if (img) {
			if (ed.getParam('inline_styles')) {
				ed.dom.setAttrib(img, 'style', ImageDialog.imgAlign);
			} else {
				img.align = document.getElementById("align").value;
				img.border = document.getElementById("border").value;
				img.hspace = document.getElementById("hspace").value;
				img.vspace = document.getElementById("vspace").value;
			}
		}
	},


	updateStyle : function(ty) {
		var dom = tinyMCEPopup.dom, st, v, img = dom.create('img', {style : ImageDialog.imgAlign});

		if (tinyMCEPopup.editor.settings.inline_styles) {
			// Handle align
			if (ty == 'align') {
				dom.setStyle(img, 'float', '');
				dom.setStyle(img, 'vertical-align', '');

				v = document.getElementById("align").value;
				if (v) {
					if (v == 'left' || v == 'right')
						dom.setStyle(img, 'float', v);
					else
						img.style.verticalAlign = v;
				}
			}

			// Handle border
			if (ty == 'border') {
				dom.setStyle(img, 'border', '');

				v = document.getElementById("border").value;
				if (v || v == '0') {
					if (v == '0')
						img.style.border = '0';
					else
						img.style.border = v + 'px solid black';
				}
			}

			// Handle hspace
			if (ty == 'hspace') {
				dom.setStyle(img, 'marginLeft', '');
				dom.setStyle(img, 'marginRight', '');

				v = document.getElementById("hspace").value;
				if (v) {
					img.style.marginLeft = v + 'px';
					img.style.marginRight = v + 'px';
				}
			}

			// Handle vspace
			if (ty == 'vspace') {
				dom.setStyle(img, 'marginTop', '');
				dom.setStyle(img, 'marginBottom', '');

				v = document.getElementById("vspace").value;
				if (v) {
					img.style.marginTop = v + 'px';
					img.style.marginBottom = v + 'px';
				}
			}

			// Merge
			ImageDialog.imgAlign = dom.serializeStyle(dom.parseStyle(img.style.cssText));
		}
	},


	showPreviewImage : function(u, st) {

		if (!u) {
			tinyMCEPopup.dom.setHTML('prev', '');
			document.getElementById("imgDelBtn").disabled = true;
			return;
		}

		if (!st && tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true))
			this.resetImageData();

		u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u);
		document.getElementById("imgDelBtn").disabled = false

		if (!st)
			tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this);" onerror="ImageDialog.resetImageData();" />');
		else
			tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this, 1);" />');
	},


	selectInList : function(list, val){

		var lst = list.options;
		var vimg = val.split("/").pop();

		for(var i = 0; i <  lst.length; i++){
			var oimg = lst[i].value.split("/").pop();

			if(oimg == vimg){
				list.selectedIndex = i;
			}
		}
	},


//////////////////////////////// Helper ////////////////////////////

	loadImages: function(){
		var xmlHttp = this.getXMLHttpRequest();
		if(xmlHttp){
			xmlHttp.open('GET', Config.getImageListUrl(), true);
			xmlHttp.onreadystatechange = function () {

			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			    ImageDialog.parseAndSet(xmlHttp.responseText);
			}
		    };
		    xmlHttp.send(null);
		}
	},

	deleteImage: function(url){
		var xmlHttp = this.getXMLHttpRequest();
		if(xmlHttp){
			xmlHttp.open('GET', url, true);
			xmlHttp.onreadystatechange = function () {

			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			    ImageDialog.actionStop();
			}
		    };
		    xmlHttp.send(null);
		}
	},

	getXMLHttpRequest: function(){
		var xmlHttp = null;
		// Mozilla, Opera, Safari sowie Internet Explorer (ab v7)
		if (typeof XMLHttpRequest != 'undefined') {
		    xmlHttp = new XMLHttpRequest();
		}
		if (!xmlHttp) {
		    // Internet Explorer 6 und älter
		    try {
			xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");
		    } catch(e) {
			try {
			    xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
			    xmlHttp  = null;
			}
		    }
		}
		return xmlHttp;
	},

	ImageList: null,

	parseAndSet: function(xml){
	    var obj = eval('(' + xml + ')');

	    ImageDialog.ImageList.clear()

	    // parse loaded JSON object & create new object
	    for(var i = 0; i < obj.length; i++){
		  var size = obj[i].Size;
		  var lnk = obj[i].Link;
		  var imgnameFull = lnk.split("/").pop();
		  
		  imgname = imgnameFull.replace("_"+size,"");

		  var lnk_test = lnk.split("/");

		  if(lnk_test.length == 1 &&lnk_test.shift() != "http:"){
			  lnk = Config.getImageUrl(lnk);
		  }

		  if(size == 0)
			  size = "Orig.";

		   ImageDialog.ImageList.add(imgname, lnk, size, imgnameFull);
	    }


	this.fillSelectList();
	this.selectOptions();
	},

	selectByValue: function (obj, value, add_custom, ignore_case) {
		if (!obj)
			return;

		var found = false;
		for (var i=0; i<obj.options.length; i++) {
			var option = obj.options[i];

			if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
				option.selected = true;
				found = true;
			} else{
				option.selected = false;
			}
		}

		if (!found && add_custom && value != '') {
			var option = new Option(value, value);
			option.selected = true;
			obj.options[sel.options.length] = option;
			obj.selectedIndex = obj.options.length - 1;
		}

		return found;
	},

	doDeleteImg : function(){
		var img = document.getElementById("src_list_size").value.split("/").pop();
		
		document.getElementById("imgDelBtn").disabled = true;
		document.getElementById("waitImg").style.visibility = "visible";
		ImageDialog.isDeleting = true;
		ImageDialog.deleteImage(Config.getDeleteUrl(img));

	},

	isUploading : false,
	isDeleting : false,

	uploadStart : function(){
	    ImageDialog.isUploading = true;
	    document.getElementById("waitImg").style.visibility = "visible";
	    document.getElementById("uploadSubmit").disabled = true;
	},

	actionStop : function(){

	    
	    if(ImageDialog.isUploading){

		    document.getElementById("waitImg").style.visibility = "hidden";
		    document.getElementById("uploadSubmit").disabled = false;
		    document.getElementById("fileField").disabled = false;
		    document.getElementById("fileField").value = "";
		    this.loadImages();
		    ImageDialog.isUploading = false;
	    }
  
	    if(ImageDialog.isDeleting){
		    document.getElementById("waitImg").style.visibility = "hidden";
		    document.getElementById("imgDelBtn").disabled = false;

		    this.loadImages();

		    ImageDialog.isDeleting = false;
	    }

// 	    var http_status=507;
// 	    var http_message='507 Insufficient Storage';
// 	    var error_message='Upload zu gross, bitte maximal 2 MB hochladen.';

	    var iFrame = document.getElementById('actionTarget').contentWindow;

	    if(typeof iFrame.error_message != 'undefined'){
		  alert(iFrame.error_message);
	    }

	}

};

/////////////////////////////////////////////////////////////////////////////////
function ImageData(){
	this.list = new Array();
}

ImageData.prototype.add = function(n,u,s ,fn){
	if(typeof this.list[n] == 'undefined'){
		this.list[n] = new  Array();
	}

	this.list[n][this.list[n].length] = {url:u, size:s, fullname:fn};

}
ImageData.prototype.clear = function(){
	this.list = new Array();
}
ImageData.prototype.getBiggest = function(n){

	if(typeof this.list[n] == 'undefined')
		return;

	var lst = this.list[n];
	var b = "";
	var s = -1;
	for(var i = 0; i < lst.length; i++){

		if(lst[i].size == "Orig."){
			return lst[i].url;
		}

		if( parseInt(lst[i].size) > parseInt(s) ){
			s = lst[i].size;
			b = lst[i].url;
		}
	}
	return b;
}

ImageData.prototype.getUrlOf = function(img){
	for(n in this.list){
		var lst = this.list[n];
		for(var i = 0; i < lst.length; i++){
			if(lst[i].fn == img){
				return lst[i].url;
			}
		}
	}
}

ImageData.prototype.getOrigNameOf = function(img){

	for(n in this.list){
		var lst = this.list[n];
		for(var i = 0; i < lst.length; i++){

			if(lst[i].fullname == img){
				return n;
			}
		}
	}
}

ImageData.prototype.fillListWithNames = function(list){
	for(n in this.list){
		list.options[list.options.length] = new Option(n, n);
	}
}

ImageData.prototype.fillListWithSizeOf = function(list, img){
	
	var lst = this.list[img];
	for(var i = 0; i < lst.length; i++){		
		list.options[list.options.length] = new Option(lst[i].size, lst[i].url);
		
	}
}

ImageData.prototype.fillList = function(l){
	
	for(n in this.list){
		var lst = this.list[n];
// 		if(list.options.length > 0){
			l.options[l.options.length] = new Option("","");
// 		}

		for(var i = 0; i < lst.length; i++){
			l.options[l.options.length] = new Option(lst[i].fullname, lst[i].url);
		}
	}
}
////////////////////////////////////////////////////

ImageDialog.preInit();
tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
