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

		tinyMCEPopup.requireLangPack();

		Config.artikelid = parent.entryid;
		Config.pagetype = parent.pagetype;
		//Config.imageListUrl = tinyMCEPopup.getParam("snstuff_img_url_list") || "/admin_list_pictures_json/{artikelid}";
		Config.imageListUrl = tinyMCEPopup.getParam("snstuff_img_url_list") || "{pagetype}?sx_action=on_image_list&id={artikelid}";
		//Config.uploadUrl = tinyMCEPopup.getParam("snstuff_img_url_upload") || "/{pagetype}/{artikelid}?sx_action=on_user_upload";
		Config.uploadUrl = tinyMCEPopup.getParam("snstuff_img_url_upload") || "{pagetype}?sx_action=on_image_upload&id={artikelid}";
		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") || "/on_image_preview/{artikelid}/{imgname}";

	},
	
	srcData:{},

	selectedData:'',

	srcMedia:'',
	media1:'',
	media2:'',
	
	selM1:'',
	selM2:'',
	
	videoW:undefined,
	videoH:undefined,

	selBigges: true,
	isUploading: false,
	isDeleting: false,

	init : function(ed) {

		tinyMCEPopup.dom.get("uploadForm").action = Config.getUploadUrl();
		tinyMCEPopup.dom.get("src_list_vid_pic_elm").style.display = 'none';
		tinyMCEPopup.dom.get("l_src_list_size").style.display = 'none';
		tinyMCEPopup.dom.get("l_src_list_vpic").style.display = 'none';

		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.selBigges = false;
			document.getElementById("insert").value = ed.getLang('update');
			var  imgURL = dom.getAttrib(n, 'src');
			if(n.className == 'snVideo'){
				this.selM2 = dom.getAttrib(n, 'alt');
				this.videoW = dom.getAttrib(n, 'width');
				this.videoH = dom.getAttrib(n, 'height');
				this.selM1 = dom.getAttrib(n, 'title');
			}else{
				
				this.selM2 = dom.getAttrib(n, 'alt')
				this.selM1 = imgURL.split('/').pop();
						
				var a = 'none';
				if (ed.settings.inline_styles) {
					if (!(a = dom.getStyle(n, 'float'))){
						a = dom.getStyle(n, 'vertical-align')
					}
				}
				if(!a){
					a = dom.getAttrib(n, 'align');
				}
				var al = tinyMCEPopup.dom.get("align");
				a = a.replace(/ /g,'');
				for(var i = 0; i < al.length; i++){
					if(al.options[i].value == a)
						al.selectedIndex = i;
				}
			}
		}
		
		tinyMCEPopup.dom.get("video_width").value = this.videoW;
		tinyMCEPopup.dom.get("video_height").value = this.videoH;
		this.loadData();
	},

	srcListAction: function(v){
		this.srcMedia = v;
		tinyMCEPopup.dom.get("src_list_size_elm").style.display = 'none';
		tinyMCEPopup.dom.get("src_list_size_full_elm").style.display = 'none';
		tinyMCEPopup.dom.get("src_list_vid_pic_elm").style.display = 'none';
		tinyMCEPopup.dom.get("l_src_list_size").style.display = 'none';
		tinyMCEPopup.dom.get("l_src_list_vpic").style.display = 'none';
		tinyMCEPopup.dom.get("align").disabled = true;
		
		if(this.srcMedia.indexOf(':') == -1){
			this.previewData();
			return;
		}
		var on = this.srcMedia.split(':');
		
		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");

		lst.options.length = 0;lst2.options.length = 0; lstv.options.length = 0;
			

	
		if(on[0] == 'pic'){
			tinyMCEPopup.dom.get("src_list_size_elm").style.display = 'inline';
			tinyMCEPopup.dom.get("src_list_size_full_elm").style.display = 'inline';
			tinyMCEPopup.dom.get("l_src_list_size").style.display = 'inline';
			
			tinyMCEPopup.dom.get("align").disabled = false;
			var obj = this.srcData.pic[on[1]];
			var m = undefined, m2 = undefined;
			for(var i = 0; i < obj.subpic.length; i++){
				obj.subpic[i].width = parseInt(obj.subpic[i].width);
				obj.subpic[i].height = parseInt(obj.subpic[i].height);
				

				var fname = obj.subpic[i].name;
				var wh = obj.subpic[i].width + ' X '+ obj.subpic[i].height;
				if( obj.subpic[i].isOrig ){
					wh += '*';
				}
				
				lst.options[lst.options.length] = new Option(wh, v+':'+i);
				lst2.options[lst2.options.length] = new Option(wh, v+':'+i);
				if(fname == this.selM1){lst.selectedIndex = lst.options.length-1;}
				if(fname == this.selM2){lst2.selectedIndex = lst2.options.length-1;}

				if(this.selBigges){
					if(!m || m && (obj.subpic[i].width < m.width && obj.subpic[i].height < m.height)){
						lst.selectedIndex = lst.options.length-1;
						m = obj.subpic[i];
					}
					if(!m2 || m2 && (obj.subpic[i].width > m2.width && obj.subpic[i].height > m2.height)){
						lst2.selectedIndex = lst2.options.length-1;
						m2 = obj.subpic[i];
					}
				}

			}

			this.selBigges = true;

			lst.onchange();lst2.onchange();
		}
		if(on[0] == 'vid'){
		        var obj = this.srcData.video[on[1]];
			tinyMCEPopup.dom.get("src_list_vid_pic_elm").style.display = 'inline';
			tinyMCEPopup.dom.get("video_width").value = this.videoW ? this.videoW:obj.width;
			tinyMCEPopup.dom.get("video_height").value = this.videoH ? this.videoH:obj.height;
			tinyMCEPopup.dom.get("l_src_list_vpic").style.display = 'inline';
			
			for(var e in this.srcData.pic){
				var pl = this.srcData.pic[e].subpic;
				lstv.options[lstv.options.length] = new Option('','');
				for(var i  = 0; i < pl.length; i++){
					lstv.options[lstv.options.length] = new Option(pl[i].name,'pic:'+e+':'+i);
					if(pl[i].name == this.selM2){lstv.selectedIndex = lstv.options.length-1;}
				}
			}
			lstv.onchange();
		}
	},

	media1Action: function(v){
		this.media1 = v;
		this.previewData();
	},

	media2Action: function(v){
		this.media2 = v;
	},


	previewData : function() {
		if (!this.srcMedia) {
			tinyMCEPopup.dom.setHTML('prev', '');
			document.getElementById("imgDelBtn").disabled = true;
			return;
		}
		var on;
		if(this.srcMedia.indexOf("vid:") != -1){
			on = this.srcMedia.split(':');
		}else{
			on = this.media1.split(':');
		}
		
		var u; var html = '';
		if(on[0] == 'pic'){
			var p = this.srcData.pic[on[1]].subpic[on[2]];
			u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(Config.getImageUrl(p.name,true));
			html = '<img id="previewImg" src="' + u + '" border="0" />';
			
		}else{
			var o = this.srcData.video[on[1]];
			var fvars = "file="+Config.getImageUrl(o.name,true);
			if(this.media1 && this.media1.indexOf(':') != -1){
				var m2 = this.media1.split(':');
				fvars += "&image="+Config.getImageUrl(this.srcData.pic[m2[1]].subpic[m2[2]].name,true);
			}
			fvars +="&autoload=false";
			html = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='350' height='280' id='"+o.name+"' name='"+o.name+"'>"
			      +"<param name='movie' value='/video/player-viral.swf'><param name='allowfullscreen' value='false'><param name='play' value='false'>"
			      +"<param name='flashvars' value='"+fvars+"'>"
			      +"<embed type='application/x-shockwave-flash' id='"+o.name+"' name='"+o.name+"' src='/video/player-viral.swf' width='400' height='250' "
			      +"allowscriptaccess='always' allowfullscreen='false' flashvars='"+fvars+"'/>"
			      +"</object>";
		     }
		document.getElementById("imgDelBtn").disabled = false
		tinyMCEPopup.dom.setHTML('prev', html);
	},
	

	insert:function(){
		var ed = tinyMCEPopup.editor, t = this
		if (!this.srcMedia) {
			if (ed.selection.getNode().nodeName == 'IMG') {
				ed.dom.remove(ed.selection.getNode());
				ed.execCommand('mceRepaint');
			}

			tinyMCEPopup.close();
			return;
		}
		////// insert/update

		tinyMCEPopup.restoreSelection();

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

		

		var args;
		var clazzName = 'noresize';
		if(this.srcMedia && this.srcMedia.indexOf('pic:') != -1){
			var m1 = this.media1.split(':');
			var m2 = this.media2.split(':');
			
			args = {'class':'noresize',
				'align': tinyMCEPopup.dom.get("align").value,
				'src': Config.getImageUrl(this.srcData.pic[m1[1]].subpic[m1[2]].name,true),
				'alt': this.srcData.pic[m2[1]].subpic[m2[2]].name,
				'style': "float:"+tinyMCEPopup.dom.get("align").value+";"
				 };
		}

		if(this.srcMedia && this.srcMedia.indexOf('vid:') != -1){
			var sm = this.srcMedia.split(':');
			var o = this.srcData.video[sm[1]];
			this.videoW = parseInt(tinyMCEPopup.dom.get("video_width").value);
			this.videoH = parseInt(tinyMCEPopup.dom.get("video_height").value);
			
			if(!this.videoH || this.videoH < 0){
			  this.videoH = o.height;
			}
			if(!this.videoW || this.videoW < 0){
			  this.videoW = o.width;
			}
			
			
			clazzName = 'snVideo';
			args = {'class':'snVideo',
				'align': tinyMCEPopup.dom.get("align").value,
				'src': tinyMCEPopup.getWindowArg("plugin_url")+'/images/trans.gif',
				'title': o.name,
				'width':this.videoW,
				'height':this.videoH
			}
			if(this.media1 && this.media1.indexOf(':') != -1){
				var m1 = this.media1.split(':');
				args.alt = this.srcData.pic[m1[1]].subpic[m1[2]].name;
			}
		}

		el = ed.selection.getNode();
		tinyMCEPopup.execCommand("mceBeginUndoLevel");
		if (el && el.nodeName == 'IMG') {
			ed.dom.remove(ed.selection.getNode());
		} 
		if(args){
			ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1});
// 			ed.dom.get('__mce_tmp').className = clazzName;
			ed.dom.setAttribs('__mce_tmp', args);
			ed.dom.setAttrib('__mce_tmp', 'id', '');
		}
		ed.undoManager.add();
		tinyMCEPopup.execCommand("mceEndUndoLevel");
		tinyMCEPopup.close();
	},
//////////////////////////////// Helper ////////////////////////////

	loadData: function(){
		var lst = tinyMCEPopup.dom.get("src_list");
		lst.options.length = 0;
		lst.options[lst.options.length] = new Option('Lade Medienliste...','');
		lst.disabled = true;
		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 dl = "";
		if(this.srcMedia.indexOf("pic:") != -1){
			var m = this.media1.split(':');
			dl = Config.getDeleteUrl(this.srcData.pic[m[1]].subpic[m[2]].name);
		}else{
			var m = this.srcMedia.split(':');
			dl = Config.getDeleteUrl(this.srcData.video[m[1]].name);
		}
		document.getElementById("imgDelBtn").disabled = true;
		document.getElementById("waitImg").style.visibility = "visible";
		ImageDialog.isDeleting = true;
		ImageDialog.deleteData(dl);

	},

	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 = obj;
	    
		// parse loaded JSON object & create new object

		var lst = tinyMCEPopup.dom.get("src_list");
		lst.options.length = 0;
		lst.options[lst.options.length] = new Option('','');
		if(obj.pic){

			lst.options[lst.options.length] = new Option('------  Bilder  -----','');
			for(var e in obj.pic){
				if(obj.pic[e].name && obj.pic[e].name.length > 0){
					var p = obj.pic[e];
					obj.pic[e].subpic.push({name:p.name,width:p.width,height:p.height,isOrig:true});
				}
				lst.options[lst.options.length] = new Option(e,'pic:'+e);
				if(this.selM1 && this.selM1.toLowerCase().indexOf(e.toLowerCase()) != -1){lst.selectedIndex = lst.options.length-1;}
			}
		}
		
		if(obj.video && obj.video.length > 0){
			lst.options[lst.options.length] = new Option('------  Videos  -----','');
			for(var i = 0; i < obj.video.length; i++){
				lst.options[lst.options.length] = new Option(obj.video[i].name,'vid:'+i);
				if(this.selM1 == obj.video[i].name){lst.selectedIndex = lst.options.length-1;}
			}
		}
		tinyMCEPopup.dom.get("src_list").disabled = false;
		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);
