window.addEvent('domready', function(){

	loadImagePopup();

})

objDefaultValue = new Object();

function is_object( mixed_var ){

    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

function loadImagePopupFromWYSIWYG(strType,mediaId,mediaTagId) {

	CreatePauseOverlay('true');
		
	var injectIn = strType;
	
	$$('#pause_waiting').setStyle('visibility', 'hidden');
	
	var popupHtml = '<div class="popup-header">Afbeelding invoegen</div><div class="popup-text"></div><div class="popup-footer"></div>'; 
	
	new Element('div').set('html',popupHtml).addClass('image-popup').injectAfter($('pause_overlay')).makeDraggable({handle:$$('.popup-header')});
						
	if(mediaId!="")
	{
		getPopupHtml('mediaTagId=' + mediaTagId + '&mediaId=' + mediaId,injectIn);
	}
	else 
	{
		getPopupHtml('',injectIn);
	}
	
}


function loadImagePopup() {

	$$('.select_image').addEvent('click', function(e) {
			
		e.stop();	
			
		CreatePauseOverlay('true');
		
		var injectIn = this.get('injectIn');
		
		$$('#pause_waiting').setStyle('visibility', 'hidden');
		
		var popupHtml = '<div class="popup-header">Afbeelding invoegen</div><div class="popup-text"></div><div class="popup-footer"></div>'; 
		
		new Element('div').set('html',popupHtml).addClass('image-popup').injectAfter($('pause_overlay')).makeDraggable({handle:$$('.popup-header')});
				
		getPopupHtml('',injectIn);
				
		return false;
	
	});
	
	$$('.select_image_variables').addEvent('click', function(e) {
		
		e.stop();	
			
		CreatePauseOverlay('true');
		
		var injectIn = this.get('injectIn');
		
		$$('#pause_waiting').setStyle('visibility', 'hidden');
		
		var popupHtml = '<div class="popup-header">Afbeelding invoegen</div><div class="popup-text"></div><div class="popup-footer"></div>'; 
		
		new Element('div').set('html',popupHtml).addClass('image-popup').injectAfter($('pause_overlay')).makeDraggable({handle:$$('.popup-header')});
		
		var values = this.getProperties('attrWidth', 'attrHeight', 'attrVar', 'attrMediaId');
		objDefaultValue.values = values;
		getPopupHtml('width='+values.attrWidth+'&height='+values.attrHeight+'&variable='+values.attrVar,injectIn);
				
		return false;
	
	});
}

function getImage(imageId) {
	
	new Request({url: '/ajax/imagepopup/image.php', onSuccess: function (ResponseText,ResponseXML) {
		
		//alert(ResponseXML);
			
		var images = ResponseXML.getElementsByTagName('image');
		
		if(images.length)
		{
			//alert(images.length);
			
			//var intMediaId = ResponseXML.getElementsByTagName('id')[0].childNodes[0].nodeValue;
			var imageUrl = ResponseXML.getElementsByTagName('url')[0].childNodes[0].nodeValue;
			var imageHeight = ResponseXML.getElementsByTagName('height')[0].childNodes[0].nodeValue;
			var imageWidth = ResponseXML.getElementsByTagName('width')[0].childNodes[0].nodeValue;
			var fileName = ResponseXML.getElementsByTagName('filename')[0].childNodes[0].nodeValue;
			var mime = ResponseXML.getElementsByTagName('mime')[0].childNodes[0].nodeValue;
			var size = ResponseXML.getElementsByTagName('size')[0].childNodes[0].nodeValue;
			var thumb = ResponseXML.getElementsByTagName('thumb')[0].childNodes[0].nodeValue;
			
			
			var elmPreview = $$('.image-preview');
			
			elmPreview.getElement('a img').set('src',thumb);
			elmPreview.getElement('a').set('href',imageUrl);
			
			$$('#imageUrl').set('value',imageUrl);
			$$('#imageHeight').set('value',imageHeight).set('old',imageHeight);
			$$('#imageWidth').set('value',imageWidth).set('old',imageWidth);
			
			$$('.image-info').set('html',fileName + '<br />' + mime + '<br />' + size);
			
			//alert('Url ' + imageUrl + ' height: ' + imageHeight + ' width: ' + imageWidth);
			
		}
		else
		{
			var errors = ResponseXML.getElementsByTagName('error');
			
			if(errors) {
				
				var elmPreview = $$('.image-preview');
				
				elmPreview.getElement('a img').set('src','/images/no_image.jpg');
				elmPreview.getElement('a').set('href','/images/no_image.jpg');
				
				$$('#imageUrl').set('value','');
				$$('#imageHeight').set('value','');
				$$('#imageWidth').set('value','');
				
				$$('.image-info').set('html','<b>Error</b><br />Bestand kan niet gevonden worden.');
			}
		}
		
	}}).send('imageId=' + imageId);
	
}

function ratioResize(elm,otherElm) {
	
	elm.addEvent('keyup',function (e) {
				
		if($('imageRatio').get('checked'))
		{
			var oldSize = this.get("old");
			var newSize = this.get("value");
			
			var percent = ((newSize / oldSize) * 100);

			var imageWidth = otherElm.get('old');
			
			otherElm.set('value',Math.round((imageWidth * (percent / 100))));	
		}

	});
	
}

function createString(strSendPost, addObject)
{
	var addString = '';
	var str = '';
	
	var arr = new Array();
	
	var obj = new Object();
	
	var array=strSendPost.split("&");

	for(var i=0; i<array.length; i++)
	{
		var item = array[i];
		arrItem = item.split("=");
	
		obj[arrItem[0]] = arrItem[1];
	}

	for(var prop in addObject.values)
	{
		var value = addObject.values[prop];
		if(value)
		{
			var pos = prop.substring(0, 4);
			
			if(pos == 'attr')
			{
				prop = prop.substring(4, prop.length).toLowerCase();
			}

			if(obj[prop] == undefined)
			{
				obj[prop] = value;
			}

		}
	}
	
	for(var prop in obj)
	{
		arr.push(prop+'='+obj[prop])
	}

	str = arr.join('&',arr);

	return str;
}

function getPopupHtml (strSendPost,injectIn) {
	strSendPost = createString(strSendPost, objDefaultValue);

	var req = new Request({url: '/ajax/imagepopup/getImagePopup.php', onSuccess: function (ResponseText,ResponseXML) {
			
		var popUpTextElm = $(window.parent.document).getElement('.popup-text');
			
		popUpTextElm.set('html',ResponseText);

			
		ratioResize($$('#imageHeight'),$$('#imageWidth'));
		ratioResize($$('#imageWidth'),$$('#imageHeight'));
		
		
		$$('.tabmenu .list .txt a ').addEvent('click', function(e){
			var selectedElement = this.get('rel');
			$$('.list').removeClass('selected');
			this.getParent('div').getParent('div').addClass('selected');
			
			$('media').setStyle('display', 'none');
			$('internet').setStyle('display', 'none');
			$('local').setStyle('display', 'none');
			$(selectedElement).setStyle('display', 'block');
		});
		
		$$('#imageDrive').addEvent('submit',function (e) {
			
			//alert('form submit');
			
			setTimeout(function () {
				var intMediaId = parseInt(imageFrame.document.body.innerHTML);
				
				if(intMediaId>0)
				{
					getPopupHtml('mediaTagId=' + mediaTagId + '&mediaId=' + intMediaId,injectIn);
				}
			},1000);
		});
		
		
		var mediaTagId = $$('.popup-text #mediaTagId').get('value');
		
		$$('.popup-text .alignment img').addEvent('click',function (e) {
		
			var arrChilds = this.getParent('td').getChildren('img');
			
			arrChilds.each(function(el){
				var strChildSource = el.getProperty('src');
				
				var arrSource = strChildSource.split('/');
				var fileName = arrSource[arrSource.length-1];
				fileName = fileName.replace("selected-", "");
				
				el.setProperty('src', '/images/image-popup/'+fileName);
				
			});
			
			$$('.popup-text .alignment img').set('class','');

			var strSource = this.getProperty('src');
			
			var arrSource = strSource.split('/');
			var fileName = arrSource[arrSource.length-1];
			
			this.set('class','selected');
			
			this.setProperty('src', '/images/image-popup/selected-'+fileName);
		
		});

		if(is_object(injectIn))
		{
			// alert('object');

			// Is een object zal wel TinyMCE zijn dan..
			var ImageAltText = injectIn.altText;
			
			var node = injectIn.selection.getNode();
			var dom = injectIn.dom;
			
			/**
			 * Src van het gelecteerde image
			 */
			var imgSrc = dom.getAttrib(node, 'src');

			if(dom.getStyle(node, 'margin-bottom')==dom.getStyle(node, 'margin-top'))
			{
				var verticalspacing = dom.getStyle(node, 'margin-top').replace("px","");
			}
			
			if(dom.getStyle(node, 'margin-right')==dom.getStyle(node, 'margin-left'))
			{
				var horizontalspacing = dom.getStyle(node,'margin-right').replace("px","");
			}
			
			$$('.popup-text #imageAlt').set('value',ImageAltText);
			
			if(imgSrc!="")
			{
				$$('.popup-text #imageUrl').set('value',imgSrc);
			}
			
			$$('.popup-text #horizontalspacing').set('value',horizontalspacing);
			$$('.popup-text #verticalspacing').set('value',verticalspacing);
				
			if(dom.getStyle(node, 'float')=="right" || dom.getAttrib(node, 'align')=="right")
			{
				$$('.popup-text #alignRight').set('class','selected');

				var strSource = $$('.popup-text #alignRight').get('src');
				
				var d = strSource.toString();
				
				var arrSource = d.split('/');
				var fileName = arrSource[arrSource.length-1];
				$$('.popup-text #alignRight').setProperty('src', '/images/image-popup/selected-'+fileName);
				
			}
			else if(dom.getStyle(node, 'float')=="left" || dom.getAttrib(node, 'align')=="left")
			{
				$$('.popup-text #alignLeft').set('class','selected');
				
				var strSource = $$('.popup-text #alignLeft').get('src');
				
				var d = strSource.toString();
				
				var arrSource = d.split('/');
				var fileName = arrSource[arrSource.length-1];
				$$('.popup-text #alignLeft').setProperty('src', '/images/image-popup/selected-'+fileName);
				
			}
			else if(dom.getStyle(node, 'vertical-align')=="bottom")
			{
				$$('.popup-text #alignBottom').set('class','selected');
				
				var strSource = $$('.popup-text #alignBottom').get('src');
				var d = strSource.toString();
				
				var arrSource = d.split('/');
				var fileName = arrSource[arrSource.length-1];
				$$('.popup-text #alignBottom').setProperty('src', '/images/image-popup/selected-'+fileName);

			}

			/*if(dom.getStyle(node, 'vertical-align')=="right")
			{
				$$('.popup-text #alignRight').set('class','selected');
			}*/
		}

		cancelButton();
				
		$$('.popup-text #mediaItem').addEvent('click',function (e) {
			
			var mediaId = $$('.popup-text #mediaItem').get('value');
			var mediaTagId = $$('.popup-text #mediaTagId').get('value');
			
			getImage(mediaId);
			
			//getPopupHtml('mediaTagId=' + mediaTagId + '&mediaId=' + mediaId,injectIn);
			
		}); 

		$$('.popup-text #mediaTagId').addEvent('change',function (e) {

			var mediaTagId = $$('.popup-text #mediaTagId').get('value');
			
			getPopupHtml('mediaTagId=' + mediaTagId,injectIn);
			
		});
	
		mousePreview();
		
		if(is_object(injectIn))
		{
			if(injectIn.selection && injectIn.selection.getNode().nodeName=="IMG")
			{
				var selectedImageNode = injectIn.selection.getNode();
				var selectedImageHtml = injectIn.selection.getContent();
				
				//alert(nodeName);
				
				injectIn.execCommand('mceRemoveNode', true, injectIn.selection.getNode());
				
				//$$('.popup-text #imageUrl').set('value');
			}
		}
		
		$$('#cancelImage').addEvent('click',function(e) {
				
			if(is_object(injectIn))
			{					
				injectIn.selection.setContent(selectedImageHtml);
			
				//injectIn.execCommand('mceInsertContent', false, selectedImageHtml, {skip_undo : 1});
				//injectIn.execCommand('mceRepaint');
			}
			
		});
		
		$$('#saveImage').addEvent('click', function (e) {
			
			var align;
			
			var imageAlt = $$('.popup-text #imageAlt').get('value');
			var imageUrl = $$('.popup-text #imageUrl').get('value');
			var imageWidth = $$('.popup-text #imageWidth').get('value');
			var imageHeight = $$('.popup-text #imageHeight').get('value');
			var mediaId = $$('.popup-text #mediaItem').get('value');
			var verticalSpacing = $$('.popup-text #verticalspacing').get('value');
			var horizontalSpacing = $$('.popup-text #horizontalspacing').get('value');
			var resizeDefaultImage = $$('.popup-text #resizeDefaultImage').get('value');
			var resizeDefaultWidth = $$('.popup-text #resizeDefaultWidth').get('value');
			var resizeDefaultHeight = $$('.popup-text #resizeDefaultHeight').get('value');
		    var resizeDefaultVariable = $$('.popup-text #resizeDefaultVariable').get('value');

			
			//removeImagePopup();
			
			if($('imageRatio'))
			{
				var resizeKeepRatio = $('imageRatio').get('checked');
			}
			
			// Image kopie aanmaken
			new Request({url: '/ajax/imagepopup/resizeImage.php', onSuccess: function (ResponseText,ResponseXML) {
			
				//alert(ResponseText);
				//alert(ResponseXML);
			
				if(ResponseXML.getElementsByTagName('id')[0])
				{
					var intMediaId = ResponseXML.getElementsByTagName('id')[0].childNodes[0].nodeValue;
					var imageUrl = ResponseXML.getElementsByTagName('url')[0].childNodes[0].nodeValue;
					
					
				}
				else if($$('.popup-text #imageUrl'))
				{					
					var imageUrl = $$('.popup-text #imageUrl').get('value');
					
					//alert(imageUrl);
				}
				
				if(imageUrl!="error" && imageUrl!="undefined" && intMediaId!=0 && intMediaId!="undefined")
				{
					//width="' + imageWidth + '" height="' + imageHeight + '"
					
					var style = "";
					
					if(verticalSpacing!="")
					{
						style += "margin-top: " + verticalSpacing + "px;margin-bottom: " + verticalSpacing + "px;";
					}
					
					if(horizontalSpacing!="")
					{
						style += "margin-left: " + horizontalSpacing + "px;margin-right: " + horizontalSpacing + "px;";
					}
					
					if($$('.popup-text #alignLeft').get('class')=="selected")
					{
						//style += "float:left;";
						
						align = ' align="left" ';
					}
					else if($$('.popup-text #alignRight').get('class')=="selected")
					{
						//style += "float:right;";
						
						align = ' align="right" ';
					}
					else if($$('.popup-text #alignBottom').get('class')=="selected")
					{
						style += "vertical-align:bottom;";
					}
				
					if(!align)
					{
						align = "";
					}
				
					var html = '<img' + align + ' src="' + imageUrl + '" mediatagid="' + mediaTagId + '" mediaid="' + intMediaId + '"  alt="' + imageAlt + '" style="' + style + '" />';
		
					//alert(html);
		
					if(is_object(injectIn))
					{
						// Is een object zal wel TinyMCE zijn dan..
						// Probeer te inserten
						
						//alert('hier');
						
						//alert(html);
						
						
						//injectIn.execCommand('mceInsertContent', false, html, {skip_undo : 1});
						
						//if(selectedImageNode.nodeName="IMG")
						//{
							
							//injectIn.dom.remove(selectedImageNode);
						//}
						
						//injectIn.execCommand('mceRemoveNode', true, selectedImageNode);
						
						//
						injectIn.execCommand('mceInsertContent', false, html, {skip_undo : 1});
						injectIn.execCommand('mceRepaint');
					}
					else 
					{
						//html = '<input name="mediaId" readonly type="text" value="' + intMediaId + '" />';
						//$(injectIn).set('html',html);

						if(resizeDefaultImage == 'on')
						{
							if(ResponseXML.getElementsByTagName('id')[0])
							{
							var height = ResponseXML.getElementsByTagName('height')[0].childNodes[0].nodeValue;
							var width = ResponseXML.getElementsByTagName('width')[0].childNodes[0].nodeValue;
							}
							var html = '<img' + align + ' src="' + imageUrl + '" mediatagid="' + mediaTagId + '" mediaid="' + intMediaId + '"  alt="' + imageAlt + '" height="' + height + '" width="' + width + '" style="' + style + '" />';
							
							$(injectIn).set('value',html);
						}
						else
						{
							$(injectIn).set('value',imageUrl);
						}
					}
					
					removePopup();
				}
				else 
				{
					alert('er ging iets fout tijdens het aanmaken van de afbeelding (FILE: image-popup.js; LINE 275)');
					
					removePopup();
				}
	
			}}).send('newWidth=' + imageWidth + '&newHeight=' + imageHeight + '&mediaId=' + mediaId + '&ratio=' + resizeKeepRatio +'&resizeDefaultImage='+resizeDefaultImage+'&resizeDefaultWidth='+resizeDefaultWidth+'&resizeDefaultHeight='+resizeDefaultHeight+'&resizeDefaultVariable='+resizeDefaultVariable);
			
			
		});
		
	}}).send(strSendPost);
				
}




function resizeImage(pv_intWidth,pv_intHeight,pv_intMediaId) {
	
	new Request({url: '/ajax/imagepopup/resizeImage.php', onSuccess: function (ResponseText,ResponseXML) {
		
		
		return ResponseText;
	
	}}).send('newWidth=' + pv_intWidth + '&newHeight=' + pv_intHeight + '&mediaId=' + pv_intMediaId);
	
	
	return ResponseText;
}


function mousePreview() {
	
	var imageSrc = $$('.image-preview img').get('src');
	
	if(imageSrc!="")
	{
	
		/*$$('.image-preview').addEvent('mouseover',function (e) {
			
			$$('.image-preview').setStyles({
			    position: 'absolute',
			    width: '400px',
			    height: '400px' 
			});
			
			$$('.image-preview img').setStyles({
			   	width: 'auto',
			   	height: 'auto'
			});
		
		});*/
		
		/*$$('.image-preview').addEvent('mouseout',function (e) {
			
			$$('.image-preview').setStyles({
			    position: '',
			    width: '135px',
			    height: '135px' 
			});
			
			$$('.image-preview img').setStyles({
			   	width: '130px',
			   	height: '130px'
			});
		
		});*/
	}
	
}

function cancelButton() {
	// Cancel button
	
	$$('.popup-text .button_cancel').addEvent('click',function (e) {
	
		removePopup();
	
	});
}

function removeImagePopup() {
	$$('.image-popup').dispose();
	$('pause_waiting').setStyle('visibility', 'visible');
}

function removePopup() {
	$$('.image-popup').dispose();
	$$('#pause_overlay').setStyle('visibility', 'hidden');
	$('pause_waiting').setStyle('visibility', 'hidden');
}
