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}";

	},
	

	objData:{a:{},c:{},t:'',l:''},

	activeDataName:'',
	activeDataFullname:'',
	activeClickPic:'',
	isUploading: false,
	isDeleting : false,

	srcData: {},
	isVideo: false,
    
	srcList:'',
	srcListSize:'',
	srcListSizeFull:'',

        selData: {},
	imgAlign:"",
	
	tsrcData:'',
	tsrcDataName:'',
	tpicShow:'',
	tpicShowFull:'',
	tvideoPic:'',

	init : function(ed) {

		this.watch('tsrcDataName',this.tsrcDataNameAction);
		this.watch('tsrcData',this.tsrcDataAction);
		this.watch('tpicShow',this.tpicShowAction);

		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.objData.t = 'pic';
			this.imgURL = dom.getAttrib(n, 'src');
			this.objData.a['click'] =  dom.getAttrib(n, 'alt');
			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');
			}

			
		}
// 		this.changeAppearance();
		this.loadData();
	},

////////////////////////////
tsrcDataNameAction: function(p,o,n){
	this.tsrcData = this.srcData.o[n]
},

tpicShowAction: function(p,o,n){
	this.previewData();
},

tpicShowFullAction: function(p,o,n){},


tsrcDataAction: function(p,o,n){

	var lst = tinyMCEPopup.dom.get("src_list_size");
	var lst2 = tinyMCEPopup.dom.get("src_list_size_full");
	var lstv = tinyMCEPopup.dom.get("src_list_vid_pic");
	lstv.options.length = 0;
	lst.options.length = 0;
	lst2.options.length = 0;
	var sp = 0; var sp2 = 0;
	
	if(typeof(this.tsrcData) != 'undefined'){
		var dl = this.tsrcData.l;

		tinyMCEPopup.dom.get("src_list_size").style.display = 'inline';
		tinyMCEPopup.dom.get("src_list_size_full").style.display = 'inline';
		tinyMCEPopup.dom.get("src_list_vid_pic").style.display = 'none';
		tinyMCEPopup.dom.get("align").disabled = false;

		for(var i = 0; i < dl.length; i++){
			var o = this.tsrcData.o[dl[i]];
			if(o.fullName == this.activeDataFullname){sp = i;}
			if(o.fullName == this.activeClickPic){sp2 = i;}
			lst.options[lst.options.length] = new Option(o.size, o.fullName);
			lst2.options[lst2.options.length] = new Option(o.size, o.fullName);
		}

		if(!this.activeClickPic){
			var sd = -1;
			for(var i = 0; i < lst2.options.length;i++){
				var txt = lst2.options[i].text;
				var s = (txt == 'Orig.')?9999999:parseInt(txt);
				if(s > sd ){
					sd = s;
					sp2 = i;
				}
			}
		}
		lst2.selectedIndex = sp2;
		lst.selectedIndex = sp;

		lst.onchange();lst2.onchange();
	}
		
},

/////////////////////////////

// 	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;
// 			}
// 		}
// 	},
	insert : function(file, title) {
		var ed = tinyMCEPopup.editor, t = this;

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

			tinyMCEPopup.close();
			return;
		}

		t.insertPicAndClose();

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

		tinyMCEPopup.restoreSelection();

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

		tinyMCEPopup.execCommand("mceBeginUndoLevel");
		
// 		if (!ed.settings.inline_styles) {
			args = {
				align : document.getElementById("align").value
			};
// 		} else {
// 			// Remove deprecated values
// 			args = {
// 				align : ''
// 			};
// 		}
	  
		tinymce.extend(args, {
			src : this.selData.lnk,
			alt : this.srcListSizeFull,
			style : this.imgAlign,
 			href : this.selData.lnk
		});

		el = ed.selection.getNode();

		
		// entfernen und neu einfuegen. Weil das advimagescale plugin sonst unerwuenschten nebeneffekt erzeugt
		if (el && el.nodeName == 'IMG') {
			ed.dom.remove(ed.selection.getNode());
// 			ed.dom.setAttribs(el, args);
		} //else {
// 		if(this.srcList){
			ed.execCommand('mceInsertContent', false, '<img class="noresize" 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();
	},

	insertVideoAndClose: function(){
		var html = "";
	},
	
	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;
				}
			}
			// Merge
			ImageDialog.imgAlign = dom.serializeStyle(dom.parseStyle(img.style.cssText));
		}
	},

	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;
	},

	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;
			}
		}

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

		return '';
	},
	srcListAction: function(v){

		this.srcList = v;
		var lst = tinyMCEPopup.dom.get("src_list_size");
		var lst2 = tinyMCEPopup.dom.get("src_list_size_full");
		var lstv = tinyMCEPopup.dom.get("src_list_vid_pic");
		lstv.options.length = 0;
		lst.options.length = 0;
		lst2.options.length = 0;
		var sp = 0; var sp2 = 0;

		if(this.srcData.data[v]){
			if(this.srcData.data[v].type == 'pic'){
				tinyMCEPopup.dom.get("src_list_size").style.display = 'inline';
				tinyMCEPopup.dom.get("src_list_size_full").style.display = 'inline';
				tinyMCEPopup.dom.get("src_list_vid_pic").style.display = 'none';
				tinyMCEPopup.dom.get("align").disabled = false;
				var d = this.srcData.data[v].lst;

				for(var i = 0; i < d.length; i++){
					if(d[i].fullName == this.activeDataFullname){sp = i;}
					if(d[i].fullName == this.activeClickPic){sp2 = i;}

					lst.options[lst.options.length] = new Option(d[i].size, d[i].fullName);
					lst2.options[lst2.options.length] = new Option(d[i].size, d[i].fullName);
				}

				if(!this.activeClickPic){
					var sd = -1;
					for(var i = 0; i < lst2.options.length;i++){
						var txt = lst2.options[i].text;
						var s = (txt == 'Orig.')?9999999:parseInt(txt);
						if(s > sd ){
							sd = s;
							sp2 = i;
						}
					}
				}
				lst2.selectedIndex = sp2;
				lst.selectedIndex = sp;
					

				this.srcListSize = lst.options[lst.selectedIndex].value;
				this.srcListSizeFull = lst2.options[lst2.selectedIndex].value;
				lst.onchange();
			}else{
				tinyMCEPopup.dom.get("src_list_size").style.display = 'none';
				tinyMCEPopup.dom.get("src_list_size_full").style.display = 'none';
				tinyMCEPopup.dom.get("src_list_vid_pic").style.display = 'inline';
				tinyMCEPopup.dom.get("align").disabled = true;

				this.selData = this.srcData.data[v].lst[0];

				var d = this.srcData;
				for(var i = 0; i < d.imgLst.length; i++){
					if(this.srcData.data[d.imgLst[i]].type != 'pic'){continue;}
					var pl = this.srcData.data[d.imgLst[i]].lst;
					lstv.options[lstv.options.length] = new Option('','');
					for(var j = 0; j < pl.length; j++){
						if(pl[j].fullName == this.srcListSize){ sp = lst.options.length};
						lstv.options[lstv.options.length] = new Option(pl[j].fullName,pl[j].fullName);
					}
				}
				lstv.selectedIndex = sp;
				lstv.onchange();
			}
		}
		
		
	},

	picSizeAction:function(v){
		this.srcListSize = v;
		this.selData = {};
		if(this.srcData.data[this.srcList]){
			var lst = this.srcData.data[this.srcList].lst;
			for(var i = 0; i < lst.length; i++){
				if(lst[i].fullName == v){
					this.selData = lst[i];
					break;
				}
			}
		}
		this.previewData(this.selData);
	},

	videoPicAction: function(v){
		this.srcListSize = v;
	},

	picSizeFullAction:function(v){
		this.srcListSizeFull = v;
	},

	previewData : function() {

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

// 		if (tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true))
// 			this.resetImageData();
		var o = this.tsrcData.o[this.tpicShow];
		var u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(o.lnk);
		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);" />');
			tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="" />');
	},
//////////////////////////////// Helper ////////////////////////////

	loadData: 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);
		}
	},

	deleteData: 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);
		}
	},

	doDeleteImg : function(){
		var img = this.srcListSize;;
		
		document.getElementById("imgDelBtn").disabled = true;
		document.getElementById("waitImg").style.visibility = "visible";
		ImageDialog.isDeleting = true;
		ImageDialog.deleteData(Config.getDeleteUrl(img));

	},

	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;
	},

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

	    this.srcData = {'l':[],'o':{},'t':''};
	    
	    var id = 0;
	    // parse loaded JSON object & create new object

	    this.activeDataFullname = (this.imgURL)?this.imgURL.split('/').pop():undefined;

	    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.";

		if(typeof(this.srcData.o[imgname]) == 'undefined'){
			this.srcData.l.push(imgname);
			this.srcData.o[imgname] = {'l':[],'o':{},'t':''};
			this.srcData.o[imgname]['t'] = obj[i].Type;
		}
		    
		
		this.srcData.o[imgname].o[imgnameFull] =  {'name':imgname, 'fullName':imgnameFull, 'size':size,'lnk':lnk};
		this.srcData.o[imgname].l.push(imgnameFull);


		if(imgnameFull == this.activeDataFullname){ this.activeDataName = imgname;}
	   }
////////////

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

		lst.options.length = 0;

		lst.options[lst.options.length] = new Option('', '');
		var d = this.srcData;
		var sp = 0;
		for(var i = 0; i < d.l.length; i++){
			if(d.l[i] == this.activeDataName){
				sp = i+1;
			}
			lst.options[lst.options.length] = new Option(d.l[i], d.l[i]);
		}
		lst.selectedIndex = sp;
		lst.onchange();
	},

	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.loadData();
		    ImageDialog.isUploading = false;
	    }
  
	    if(ImageDialog.isDeleting){
		    document.getElementById("waitImg").style.visibility = "hidden";
		    document.getElementById("imgDelBtn").disabled = false;

		    this.loadData();

		    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);
	    }
	}
	



};


////////////////////////////////////////////////////

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