/*
 * PAF_UtilityClass provides information about the PAF instance,
 * the current page and the design.
 *
 * - gets included automatically in every design
 * - requiered for AjaxRequests
 * - useful for additional interaction on the page / with the kernel
 *
 */

PAF_AJAX_REQUEST = "AJAX";
PAF_HTTP_GET_REQUEST = "HTTP_GET";
PAF_HTTP_POST_REQUEST = "HTTP_POST";

function PAF_UtilityClass() {
    this._activePageId = -1;
    this._basePath = "/PAF/";
	this._multiUploader = new Object();

    this.getActivePageId = function() {
        return this._activePageId;
    };

    this.setActivePageId = function(aActivePageId) {
        this._activePageId = aActivePageId;
    };

    this.getBasePath = function(){
    	return this._basePath;
    };

    this.isNumeric = function (value) {
		if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
		return true;
	}

	this.clearForInput = function(aInputField, aDefaultValue){
		if (aInputField.value == aDefaultValue){
			aInputField.value = "";
		}
	}

	this.fillWithDefaults = function(aInputField, aDefaultValue){
		if (aInputField.value == ""){
			aInputField.value = aDefaultValue;
		}
	}

	this.refreshPageWithoutParameters = function(aPage){
		if(aPage == undefined){
			var vUrl = document.location.href;
			vUrl = vUrl.replace(/__.*/, '').replace(/\/[^\/]*$/, '') + '/';
			document.location.href = vUrl;
		}

	}

	this.installEditor = function(aIdTextarea, aTitle, aHeight, aWidth) {
		var Dom = YAHOO.util.Dom,
			Event = YAHOO.util.Event;

		var myConfig = {
			height: aHeight,
			width: aWidth,
			dompath: true,
			focusAtStart: false,
			handleSubmit: true
		};

		var myEditor = new YAHOO.widget.Editor(aIdTextarea, myConfig);
		myEditor._defaultToolbar.buttonType = 'basic';
		myEditor._defaultToolbar.titlebar = aTitle;
		myEditor.render();

	};

	this.installMultiUploader = function(aIdentifier, aFormName, aPHPSessionId){
		this._multiUploader[aIdentifier] = new PAF_MultiUploader(aIdentifier, aFormName, aPHPSessionId);
	}

	this.clearMultiUploaderList = function(aIdentifier){
		if (this._multiUploader[aIdentifier] != undefined){
		   this._multiUploader[aIdentifier].clearUploadList();
		}
	}

	this.destroyMultiUploader = function(aIdentifier){
		if (this._multiUploader[aIdentifier] != undefined){
		   this._multiUploader[aIdentifier].destroy();
		}
	}

	this.toggleAdminControls = function(){
		var vActionUrl = new PAF_AjaxUrl();
		vActionUrl.addParameter("kernel__action", 'ToggleAdminControls');
		$.get(vActionUrl.getUrl());
	}

	this.toggleGuestRegistration = function(aRadioInputField){
		vRadioNameRegexResult = aRadioInputField.name.match(/^([a-zA-Z0-9]*)__aInternalEvent$/g);
		if (vRadioNameRegexResult){
			var vModletUniqueId = RegExp.$1;

			
			if(aRadioInputField.value == 1){
				$("#" + vModletUniqueId + "__wrapper_aRegistrationForGuest").hide();
			}else{
				$("#" + vModletUniqueId + "__wrapper_aRegistrationForGuest").show();
			}
		}

		
	}
}

function PAF_AjaxUrl() {
    return new PAF_Url(PAF_AJAX_REQUEST);
}

function PAF_Url(aRequestType) {
    this._projectId = PAF_ACTIVE_PROJECT_ID;
    this._websiteId = PAF_ACTIVE_WEBSITE_ID;
    this._pageId = PAF_ACTIVE_PAGE_ID;
    this._type = aRequestType;
	this._baseUrl = PAF_BASE_URL;
	this._parameterArray = new Array();

    this.getUrl = function() {
    	var vUrl = '';
    	switch(this._type){
    		case PAF_AJAX_REQUEST:
	    		vUrl = this._baseUrl + 'ajax.php';
	    		vUrl = vUrl + '?aProjectId=' + this._projectId;
    			vUrl = vUrl + '&aWebsiteId=' + this._websiteId;
    			vUrl = vUrl + '&aPageId=' + this._pageId;
    			vUrl = vUrl + '&parameters=' + this._buildParameterString();
    	}

    	return vUrl;
    };

    this._buildParameterString = function(){
    	var vParameterString = '';
		for (var i in this._parameterArray) {
			vParameterString = vParameterString + i + '/' + this._parameterArray[i] + '/';
		}
		return vParameterString;
    }

    this.setPageId = function(aActivePageId) {
        this._activePageId = aActivePageId;
    };

    this.addParameter = function(aParameter, aValue){
    	this._parameterArray[aParameter] = aValue;
    }
}

function PAF_DatePicker(aName, aShowDatePickerElement){

	this.dialog = null;
	this.calendar = null;
	this.seldate = null;
	this.test = null;
	this.context = aShowDatePickerElement;
	this.name = aName;

	this.Event = YAHOO.util.Event,
            Dom = YAHOO.util.Dom,
            this.dialog,
            this.calendar;

	this.showBtn = Dom.get(aShowDatePickerElement);

	this.init = function(){
		if (!this.dialog) {

			this.dialog = new YAHOO.widget.Dialog('caldialog_' + this.name, {
				visible:false,
				context:[this.context, "tl", "bl"],
				buttons:[ {text:"Reset", handler: PAF_DatePicker.resetHandler, isDefault:true}, {text:"Close", handler: this.closeHandler}],
				draggable:false,
				close:true
			});

			this.dialog.setHeader('Pick A Date');
			this.dialog.setBody('<div id="calcontainer_' + this.name + '"></div>');
			this.dialog.render(document.body);

			this.dialog.showEvent.subscribe(function() {
				if (YAHOO.env.ua.ie) {
					// Since we're hiding the table using yui-overlay-hidden, we
					// want to let the dialog know that the content size has changed, when
					// shown
					self.dialog.fireEvent("changeContent");
				}
			});
		}

		// Lazy Calendar Creation - Wait to create the Calendar until the first time the button is clicked.
		if (!this.calendar) {

			this.calendar = new YAHOO.widget.Calendar('calcontainer_' + this.name, {
				iframe:false,          // Turn iframe off, since container has iframe support.
				hide_blank_weeks:true  // Enable, to demonstrate how we handle changing height, using changeContent
			});

			this.calendar.render();

			this.calendar.selectEvent.subscribe(function() {
				if (self.calendar.getSelectedDates().length > 0) {

					self.seldate = self.calendar.getSelectedDates()[0];

					// Pretty Date Output, using Calendar's Locale values: Friday, 8 February 2008
//					var wStr = self.calendar.cfg.getProperty("WEEKDAYS_LONG")[self.seldate.getDay()];
					var dStr = String(self.seldate.getDate());
					dStr = (dStr.length == 1)?"0"+dStr:dStr;
					var mStr = String(self.seldate.getMonth()+1);
					mStr = (mStr.length == 1)?"0"+mStr:mStr;
					var yStr = self.seldate.getFullYear();

					Dom.get(self.name).value = dStr + "." + mStr + "." + yStr;
				} else {

					Dom.get(self.name).value = "";
				}
				self.dialog.hide();
			});

			this.calendar.renderEvent.subscribe(function() {
				// Tell Dialog it's contents have changed, which allows
				// container to redraw the underlay (for IE6/Safari2)
				self.dialog.fireEvent("changeContent");
			});
		}
	}
	this.show = function(){
		self = this;

		// Hide Calendar if we click anywhere in the document other than the calendar
        this.Event.on(document, "click", function(e) {
			var el = self.Event.getTarget(e);
			var dialogEl = self.dialog.element;
			if (el != dialogEl && !Dom.isAncestor(dialogEl, el) && el != self.showBtn && !Dom.isAncestor(self.showBtn, el)) {
				self.dialog.hide();
			}
		});

		this.seldate = this.calendar.getSelectedDates();

		if (this.seldate.length > 0) {
			// Set the pagedate to show the selected date if it exists
			this.calendar.cfg.setProperty("pagedate", this.seldate[0]);
			this.calendar.render();
		}

		this.dialog.show();
	};

}

function PAF_MultiUploader(aIdentifier, aFormName, aPHPSessionId){
	this._identifier = aIdentifier;
	this._selectFileButtonDiv = this._identifier + "__uploaderUI";
	this._uploadButtonA = this._identifier + "__uploadButton";
	this._clearButtonA = this._identifier + "__clearButton";
	this._selectFileButtonImg = "/PAF/design/global/img/selectFileButton.png";
	this._fileHolderDiv = this._identifier + "__FileHolder";
	this._uploadURL = new PAF_AjaxUrl();
	this._uploadMethod = "POST";
	this._uploadParameterName = 'uploaded_file';
	this._formName = aFormName;
	this._phpSessionId = aPHPSessionId;
	this._selectFileButtonDiv = null;
	this._settings = {};

	this.createHTMLLayout = function(){
		var vUploaderWrapperDiv = document.createElement("div");
		var vFileListDiv = document.createElement("div");
		this._selectFileButtonDiv = document.createElement("div");
		var vUploadButtonDiv = document.createElement("div");
		var vClearButtonDiv = document.createElement("div");
		var vClearDiv = document.createElement("div");
		var vFileFieldSet = document.createElement("fieldset");
		var vFileFieldSetLegend = document.createElement("legend");
		var vFilesWrapper = document.createElement("div");
		var vDummy = document.createElement("div");
		var vUploadButtonA = document.createElement("a");
		var vClearButtonA = document.createElement("a");

		vFileListDiv.className="PAF_MultiUploader_FileList";
		vFileListDiv.id=this._identifier + "__FileList";
		this._selectFileButtonDiv.className="PAF_MultiUploader_FileSelectButton";
		this._selectFileButtonDiv.id=this._identifier + "__uploaderUI";
		vUploadButtonDiv.className="PAF_MultiUploader_UploadButton";
		vClearButtonDiv.className="PAF_MultiUploader_ClearButton";
		vClearDiv.style.clear="both";
		vFileFieldSet.className="PAF_MultiUploader_FileFieldSet";
		vFileFieldSetLegend.className="PAF_MultiUploader_FileFieldSetLegend";
		vFilesWrapper.className="PAF_MultiUploader_FilesWrapper";
		vFilesWrapper.id=this._identifier + "__FileHolder";
		vDummy.className="PAF_MultiUploader_Wrapper";
		vUploadButtonA.href="JavaScript:void(0);";
		vClearButtonA.href="JavaScript:void(0);";
		vUploadButtonA.id=this._identifier + "__uploadButton";
		vClearButtonA.id=this._identifier + "__clearButton";

		vDummy.appendChild(document.createTextNode("No Files selected"))
		vFilesWrapper.appendChild(vDummy);
		vFileFieldSetLegend.appendChild(document.createTextNode("Files"));
		vFileFieldSet.appendChild(vFileFieldSetLegend);
		vFileFieldSet.appendChild(vFilesWrapper);
		vFileListDiv.appendChild(vFileFieldSet);
		vUploadButtonDiv.appendChild(vUploadButtonA);
		vClearButtonDiv.appendChild(vClearButtonA);

		vUploaderWrapperDiv.appendChild(vFileListDiv);
		vUploaderWrapperDiv.appendChild(this._selectFileButtonDiv);
		vUploaderWrapperDiv.appendChild(vUploadButtonDiv);
		vUploaderWrapperDiv.appendChild(vClearButtonDiv);
		vUploaderWrapperDiv.appendChild(vClearDiv);

		document.getElementById(this._identifier).appendChild(vUploaderWrapperDiv);
	}

	this.createHTMLLayout();

	this.SWFUploader = null;

	this.destroy = function(){
	     this.SWFUploader.destroy();
	}

	this.clearUploadList = function(){

	    if(this.SWFUploader != null){
//		this.SWFUploader.clearUploadList();
	    }
	}

	this.install = function(){
		/*var vUploader = this.SWFUploader;*/

		/*
		if (this._YUI_MultiUploader._fileHolderDiv == null || this._YUI_MultiUploader._selectFileButtonDiv == null
				|| this._YUI_MultiUploader._uploadButtonA == null || this._YUI_MultiUploader._clearButtonA == null){
			alert('Missing DIVs: ' + this._fileHolderDiv + ' or ' + this._selectFileButtonDiv);
			return false;
		}


		$(this._YUI_MultiUploader._uploadButtonA).click(function(){ vUploader.uploadAllFiles(); });
		$(this._YUI_MultiUploader._clearButtonA).click(function(){ vUploader.clearUploadList(); });

		this._YUI_MultiUploader.addListener('contentReady', this._YUI_MultiUploader.handleContentReady);
		this._YUI_MultiUploader.addListener('fileSelect', this._YUI_MultiUploader.handleAddedToUploadList);
		this._YUI_MultiUploader.addListener('uploadProgress', this._YUI_MultiUploader.handleUploadProgress);
		this._YUI_MultiUploader.addListener('uploadComplete', this._YUI_MultiUploader.handleUploadComplete);
		this._YUI_MultiUploader.addListener('uploadError', this._YUI_MultiUploader.handleUploadError);
		this._YUI_MultiUploader.addListener('uploadCompleteData', this._YUI_MultiUploader.handleUploadCompleteData);*/

		this._settings = {
				flash_url : SWF_URL,
				upload_url: this._uploadURL.getUrl(),
				post_params: {
				    kernel__MultiUploader: this._formName,
				    kernel__formElementName: this._identifier,
				    kernel__PHPSESSID: this._phpSessionId
				},
				file_size_limit : "12 MB",
				file_types : "*.*",
				file_types_description : "All Files",
				file_upload_limit : 100,
				file_queue_limit : 0,
				file_post_name: 'kernel__uploaded_file',
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"
				},
				debug: false,
				prevent_swf_caching : true,

				// Button settings
				button_image_url: "/PAF/design/global/img/selectFileButton.png",
				button_width: "100",
				button_height: "28",
				button_placeholder_id: $(this._selectFileButtonDiv).attr('id'),
				button_disabled: false,
				file_queued_handler: this.fileQueuedHandler,
				upload_complete_handler: this.handleUploadComplete,
				upload_progress_handler: this.UploadProgressHandler,
				swfupload_loaded_handler: this.installFunctionality,
				file_queue_error_handler: this.QueueErrorHandler
				// The event handler functions are defined in handlers.js
				/*file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete	*/// Queue plugin event
			};

		this.SWFUploader = new SWFUpload(this._settings);


		this.SWFUploader._fileArray = new Array();
		this.SWFUploader._identifier = this._identifier;
		this.SWFUploader._uploadURL = this._uploadURL;
		this.SWFUploader._uploadMethod = this._uploadMethod;
		this.SWFUploader._uploadParameterName = this._uploadParameterName;
		this.SWFUploader._formName = this._formName;
		this.SWFUploader._phpSessionId = this._phpSessionId;

		this.SWFUploader._fileHolderDiv = document.getElementById(this._fileHolderDiv);
		this.SWFUploader._selectFileButtonDiv = document.getElementById(this._selectFileButtonDiv);
		this.SWFUploader._selectFileButtonImg = document.getElementById(this._selectFileButtonImg);
		this.SWFUploader._uploadButtonA = document.getElementById(this._uploadButtonA);
		this.SWFUploader._clearButtonA = document.getElementById(this._clearButtonA);

		var vUploader = this.SWFUploader;

		$(this.SWFUploader._uploadButtonA).click(function(){ vUploader.uploadAllFiles(); });
		$(this.SWFUploader._clearButtonA).click(function(){ vUploader.clearUploadList(); });

		return true;
	}

	this.QueueErrorHandler = function(file_object, error_code, message){
	    if(error_code == -110){
		alert('Die Datei ' + file_object.name + ' ist zu groß');
	    }
	}

	this.handleUploadComplete = function(aFile, serverData){
		this.refreshProgressBar(aFile.id, 100);
		if ($('#' + this._identifier + '__' + aFile.id).length > 0){
		    document.getElementById(this._identifier + '__' + aFile.id).className="PAF_MultiUploader_Wrapper_Success";
		    var vDeleteIcon = document.getElementById(this._identifier + '__' + aFile.id + "__deleteIcon");
		    vDeleteIcon.src="/PAF/design/global/img/icons/16/save.gif";
		}
		if (this._fileArray.length > 0){
			this.uploadFile(this._fileArray.shift());
		}
	}

	this.fileQueuedHandler = function(aFile){

	    if (this._fileArray.length == 0){
		this._fileHolderDiv.innerHTML="";
	    }


	    this._fileHolderDiv.appendChild(this.createListItem(aFile.id, aFile.name));
	    this._fileArray.push(aFile.id);

	}

	this.UploadProgressHandler = function(aFile, aBytesLoaded, aTotalBytes){
		var vProgress = Math.round(100*(aBytesLoaded/aTotalBytes));

		this.refreshProgressBar(aFile.id, vProgress);
	}

	this.installFunctionality = function(){


	this.createListItem = function(aFileId, aFileName){
		var vIdentifier = this;

		var vWrapper = document.createElement('div');
		vWrapper.id = this._identifier + "__" + aFileId;
		vWrapper.className="PAF_MultiUploader_Wrapper";

		var vFileNameDiv = document.createElement('div');
		vFileNameDiv.className="PAF_MultiUploader_FileName";

		var vFileDeleteDiv = document.createElement('div');
		vFileDeleteDiv.className="PAF_MultiUploader_FileDelete";

		var vDeleteIcon = document.createElement('img');
		vDeleteIcon.id=this._identifier + "__" + aFileId + '__deleteIcon';
		vDeleteIcon.src="/PAF/design/global/img/icons/16/delete.gif";

		if (!$(vDeleteIcon).click(function(){ vIdentifier.removeFileFromList(vIdentifier._identifier + "__" + aFileId); })){
			alert('Attach Listener failed...')
		}

		var vClearDiv = document.createElement('div');
		vClearDiv.style.clear="both";

		var vProgressBarDiv = document.createElement('div');
		vProgressBarDiv.className="PAF_MultiUploader_ProgressBar";
		vProgressBarDiv.id=this._identifier + "__" + aFileId + '__progressbar';

		vFileDeleteDiv.appendChild(vDeleteIcon);
		vFileNameDiv.appendChild(document.createTextNode(aFileName));

		vWrapper.appendChild(vFileNameDiv);
		vWrapper.appendChild(vFileDeleteDiv);
		vWrapper.appendChild(vClearDiv);
		vWrapper.appendChild(vProgressBarDiv);

		return vWrapper;
	}

	this.clearUploadList = function(){
		var vFile = null;

		while(vFile = this.getFile()){
		    this.cancelUpload(vFile.id);
		}
		this._fileArray.splice(0,this._fileArray.length);
		this.addNoFilesSelectedNotification();
	}

	this.addNoFilesSelectedNotification = function(){
		var vNoFilesSelectedNotification = document.createElement('div');
		vNoFilesSelectedNotification.className="PAF_MultiUploader_Wrapper";

		vNoFilesSelectedNotification.appendChild(document.createTextNode("No Files selected"));
		this._fileHolderDiv.innerHTML="";
		this._fileHolderDiv.appendChild(vNoFilesSelectedNotification);
	}

	this.removeFileFromList = function(aFileId){
		var vElements = aFileId.split('__');

		if (vElements.length != 2){
			alert('Wrong count of id-splitting: ' + vElements.length);
			return false;
		}

		this.cancelUpload(vElements[1]);

		for(var vFileIndex in this._fileArray){
			if (this._fileArray[vFileIndex] == vElements[1]){
				this._fileArray.splice(vFileIndex,1);
			}
		}

		this._fileHolderDiv.removeChild(document.getElementById(aFileId));

		if (this._fileArray.length == 0){
			this.addNoFilesSelectedNotification();
		}

		return true;
	}

	this.uploadAllFiles = function(){
		//this.setSimUploadLimit(this._fileArray.length);
		//console.log(this._fileArray);
		if (this._fileArray.length > 0){
			this.uploadFile(this._fileArray.shift());
		}
	}

	this.uploadFile = function(aFileId){
		document.getElementById(this._identifier + '__' + aFileId).className="PAF_MultiUploader_Wrapper_In_Progress";

		this.startUpload(aFileId);
	}

	this.refreshProgressBar = function(aFileId, aProgress){

		var vProgressBarElement = document.getElementById(this._identifier + "__" + aFileId + '__progressbar');
		var vProgressElement = document.createElement("div");

		vProgressElement.className='PAF_MultiUploader_Progress';
		vProgressElement.style.width=aProgress+"%";

		vProgressBarElement.innerHTML="";

		vProgressBarElement.appendChild(vProgressElement);
	}

}

	/*this._YUI_MultiUploader.checkForUploads = function(){
		this.uploadAllFiles();
		return false;
	}

	this._YUI_MultiUploader.submitFormIfUploadsDone = function(){
		if (this._fileArray.length == 0){
			return false;
		} else {
			return this.submitFormIfUploadsDone();
		}
	}

	this._YUI_MultiUploader.handleContentReady = function(aEvent){
		this.setAllowMultipleFiles(true);
	}

	this._YUI_MultiUploader.handleAddedToUploadList = function(aEvent){
		this._fileHolderDiv.innerHTML="";

		for (var vItem in aEvent.fileList) {
			this._fileHolderDiv.appendChild(this.createListItem(aEvent.fileList[vItem].id, aEvent.fileList[vItem].name));
			this._fileArray.push(aEvent.fileList[vItem].id);
		}
	}

	this._YUI_MultiUploader.handleUploadComplete = function(aEvent){
		this.refreshProgressBar(aEvent.id, 100);
		document.getElementById(this._identifier + '__' + aEvent.id).className="PAF_MultiUploader_Wrapper_Success";
		var vDeleteIcon = document.getElementById(this._identifier + '__' + aEvent.id + "__deleteIcon");
		vDeleteIcon.parentNode.removeChild(vDeleteIcon);
		if (this._fileArray.length > 0){
			this.uploadFile(this._fileArray.shift());
		}
	}

	this._YUI_MultiUploader.handleUploadProgress = function(aEvent){
		var vProgress = Math.round(100*(aEvent["bytesLoaded"]/aEvent["bytesTotal"]));

		this.refreshProgressBar(aEvent.id, vProgress);
	}

	this._YUI_MultiUploader.handleUploadError = function(aEvent){
		//alert(aEvent.status);
	}

	this._YUI_MultiUploader.handleUploadCompleteData = function(aEvent){
		//alert(aEvent.data);
	}

	this._YUI_MultiUploader.uploadAllFiles = function(){
		this.setSimUploadLimit(this._fileArray.length);

		if (this._fileArray.length > 0){
			this.uploadFile(this._fileArray.shift());
		}
	}

	this._YUI_MultiUploader.uploadFile = function(aFileId){
		document.getElementById(this._identifier + '__' + aFileId).className="PAF_MultiUploader_Wrapper_In_Progress";

		this.upload(aFileId,this._uploadURL.getUrl(),this._uploadMethod,
			{
				kernel__MultiUploader: this._formName,
				kernel__formElementName: this._identifier,
				kernel__PHPSESSID: this._phpSessionId
			}, 'kernel__uploaded_file');
	}

	this._YUI_MultiUploader.clearUploadList = function(){
		this.clearFileList();
		this._fileArray.splice(0,this._fileArray.length);
		this.addNoFilesSelectedNotification();
	}

	this._YUI_MultiUploader.refreshProgressBar = function(aFileId, aProgress){

		var vProgressBarElement = document.getElementById(this._identifier + "__" + aFileId + '__progressbar');
		var vProgressElement = document.createElement("div");

		vProgressElement.className='PAF_MultiUploader_Progress';
		vProgressElement.style.width=aProgress+"%";

		vProgressBarElement.innerHTML="";

		vProgressBarElement.appendChild(vProgressElement);
	}*/

	this.install();


}


function PAF_ToggleMediaPool(aPrefix, aIdentifier){
    var vMediaPoolVisible = $('#' + aPrefix + '__' + aIdentifier  + '_media_pool').is(':visible');
    $('#' + aPrefix + '__' + aIdentifier  + '_media_pool').toggle('normal');



    if (vMediaPoolVisible){
	$('#' + aIdentifier + '_media_pool_browser input:checkbox:checked').each(function(aIndex){
		if (aIndex%2 == 0){
			var vImgBGClass='seletedImgWithBG';
		}else{
			var vImgBGClass='seletedImgWithoutBG';
		}
	   $('#' + aPrefix + '__' + aIdentifier  + '_selected_files').append($('<div class="selectedImg '+vImgBGClass+'" id="' + $(this).val() + '_selected_file">' + $('>span>a', $(this).parent()).html() + ' <img class="imageCorrect" src="/PAF/design/global/img//delete.gif" onclick="PAF_MediaPoolRemoveFileFromSelection(\'' + $(this).val() + '\');"></div>'));
	});
    } else {
	$('#' + aPrefix + '__' + aIdentifier  + '_selected_files').html('');
    }

}

function PAF_MediaPoolRemoveFileFromSelection(aIdItem){
    $('#' + aIdItem + '_checkbox').attr('checked', '');
    $('#' + aIdItem + '_selected_file').remove();
}

/*JS für Permission Geschichte*/
/*
var allow_selection = true;
var mouse_x = 0;
var mouse_y = 0;

	$(window).load(function() {
			var selection_stop_Timeout;
		    var selection_stop_Timeout_is_active = false;



			$("#sel_table").mousemove(function(e){
				mouse_x = e.pageX;
				mouse_y = e.pageY;
			});

			$("#dialog input.option_1")[0].onclick = function(){// Button alle auf ja
				$('.ui-selected input.option_1').each(function(e,ele){ele.checked=true;});
				hideDialog('delete_selection');
			};

			$("#dialog input.option_2")[0].onclick = function(){// Button alle auf nein
				$('.ui-selected input.option_2').each(function(e,ele){ele.checked=true;});
				hideDialog('delete_selection');
			};

			$("#dialog input.option_3")[0].onclick = function(){// Button alle auf n/a
				$('.ui-selected input.option_3').each(function(e,ele){ele.checked=true;});
				hideDialog('delete_selection');
			};

			$("#dialog input.option_4")[0].onclick = function(){// Button keine aktion mit der auswahl
				hideDialog('keep_selection');
			};

			$('#sel_table input').each(function(e,ele){//klick auf radio-button td bgcolor ändern
										ele.onclick = function(t){
											$(ele).parent().removeClass('color_option_1');
											$(ele).parent().removeClass('color_option_2');
											$(ele).parent().removeClass('color_option_3');
											newClass = "color_option_"+this.value;
											$(ele).parent().addClass(newClass);
										}

								  });

			$('#sel_table').selectable({ filter: 'td.value_td',delay: 100  });//selectable aktivieren

		    $('#sel_table').bind('selectablestart', function(event, ui) {//selectable-event -> displayDialog
				window.clearTimeout(selection_stop_Timeout);
				selection_stop_Timeout_is_active = false;
			});


			$('#sel_table').bind('selectablestop', function(event, ui) {//selectable-event -> displayDialog
				if(selection_stop_Timeout_is_active == false){
				    selection_stop_Timeout = window.setTimeout("displayDialog();",100);
			    }
			});

			//add select-function to each group-header
			$('th.group_header_0')[0].ondblclick = function(){
				if(allow_selection == true){
					$('td.group_0').addClass('ui-selected');
				};
				displayDialog();
			}

			$('th.group_header_1')[0].ondblclick = function(){
				if(allow_selection == true){
					$('td.group_1').addClass('ui-selected');
				};
				displayDialog();
			}

			$('th.group_header_2')[0].ondblclick = function(){
				if(allow_selection == true){
					$('td.group_2').addClass('ui-selected');
				};
				displayDialog();
			}

			//add select-function to each permission-header
			$('td.permission_header').each(function(e,ele){
				ele.ondblclick = function(me){
					if(allow_selection == true){
						$(ele).nextAll().addClass('ui-selected');
					};
				displayDialog();
				}
			})

			$('.radio').hide();
			$('.radioDescr').hide();


	});


	displayDialog = function(){//nach Auswahl Dialog anzeigen und selectable deaktivieren
		if($('td.ui-selected').length > 0){
			allow_selection = false;
			$('#sel_table').selectable('disable');
			$('#dialog')[0].style.marginTop=mouse_y-50+"px";
			$('#dialog')[0].style.marginLeft=mouse_x-175+"px";
			$("#dialog").show();
		}

	}

	hideDialog = function(mode){// alles noetige um den Dialog zuschließen + nachträgliche aktionen starten und selectable wieder aktivieren
		$("#dialog").hide();
		allow_selection = true;
		$('#sel_table').selectable('enable');
		if(mode == "delete_selection"){
		  $('td.ui-selected').removeClass('ui-selected');
		};
		update_colorful();
	}

	update_colorful = function(){//alle TDs anhand von ihren checked radio-Buttons einfärben
		$('td>input:checked').each(function(e,ele){
			input = $(ele);
			td = input.parent();
			td.removeClass('color_option_1');
			td.removeClass('color_option_2');
			td.removeClass('color_option_3');
			td.addClass('color_option_'+input[0].value);
		});
	};
*/


/** MediaPool-Funktionalität.
 *  TODO: Muss später dynamisch aus dem Modlet kommen
 *  SharedController - dynamisches Laden von JS & CSS
 */

function loadItemDetails(aModletUniqueId, aItemId, aParentId, aURL, aPrefix){

	var vActionUrl = new PAF_AjaxUrl();
	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_get_item_details');
	vActionUrl.addParameter(aModletUniqueId + "__item_id", aItemId);
	vActionUrl.addParameter(aModletUniqueId + "__parent_item_id", aParentId);

	//PAF_Tools.destroyMultiUploader(aPrefix + 'upload_files_container');
	// FIX For IE (otherwise an White Overlay due to synchronous ajax displayed)
	setTimeout("loadItemDetails2('"+aModletUniqueId +"','"+aItemId +"','"+aParentId +"','"+aURL +"','"+aPrefix + "')",1);

}

function loadItemDetails2(aModletUniqueId, aItemId, aParentId, aURL, aPrefix){
    var vActionUrl = new PAF_AjaxUrl();

	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_get_item_details');
	vActionUrl.addParameter(aModletUniqueId + "__item_id", aItemId);
	vActionUrl.addParameter(aModletUniqueId + "__parent_item_id", aParentId);

	if ($('#' + aModletUniqueId + 'uploader_div > #' + aPrefix + 'add_files_content').length > 0){
		PAF_Tools.clearMultiUploaderList(aPrefix + 'upload_files_container');
		$('#' + aModletUniqueId + 'uploader_hidden_div').append($('#' + aModletUniqueId + 'uploader_div > #' + aPrefix + 'add_files_content'));
	}

	$('#' + aPrefix + 'item_details_div').empty();

	$.ajax({
	    type: "GET",
	    async: false,
	    cache: false,
	    dataType: "html",
	    url: aURL + aModletUniqueId + "__mode/" + 'ajax_get_item_details/' + aModletUniqueId + "__item_id/" + aItemId + '/' + aModletUniqueId + "__parent_item_id/" + aParentId + '/' + aModletUniqueId + "__prefix/" + aPrefix,
	    complete: function(XMLHttpRequest, textStatus){

			$('#' + aPrefix + 'item_details_div').html(XMLHttpRequest.responseText);
			$('#' + aModletUniqueId + 'uploader_div').append($('#' + aModletUniqueId + 'uploader_hidden_div > div '));
		//setTimeout("$('#" + aPrefix + "item_details_div img').each(function(){$(this).attr('src', $(this).attr('src'))});",1);

	    }
	});
}

function storeMediaPoolItemDetails(aModletUniqueId, aItemId, aPrefix){
	var vActionUrl = new PAF_AjaxUrl();
	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_store_item_details');
	vActionUrl.addParameter(aModletUniqueId + "__item_id", aItemId);
	vActionUrl.addParameter(aModletUniqueId + "__descr", $('#edit_media_pool_item_' + aModletUniqueId).val());

	/*$.get(vActionUrl.getUrl(),
			function(text){
				$('#item_details_div').html(text);
			}
	);*/

	$('#' + aPrefix + 'media_pool_browser').PAF_TreeView('renameItem',{name: $('#' + aPrefix + 'edit_media_pool_item_' + aModletUniqueId).val()});
}

function getTreeStructure(){
	var vObject = $('#test > #media_pool_browser').PAF_TreeView('getStructure');

}

function MediaPool_addTags(aModletUniqueId, aItemId){
	var newTags = $.map($('#new_tags').val().split(','),function (aElement){
		return $.trim(aElement);
	});

	var vOldItems = null;
	var vAddedItems = null;

	$.each(newTags,function(aIndex, aElement){
		var vItemAlreadExists = false;
		var vOldContentExists = true;
		if (jQuery.trim($('#existing_tags').html()) == '-'){
			vOldContentExists = false;
		} else {
			vOldItems = $('#existing_tags>span>span');
		}
		if (vOldItems != null){
			vOldItems.each(function(aIndex2, aElement2){
				if (jQuery.trim($(aElement2).html()).toLowerCase() == jQuery.trim(aElement).toLowerCase()){
					vItemAlreadExists = true;
				}
			});
		}

		if (vItemAlreadExists || jQuery.trim(aElement) == ''){
			return;
		}

		if (vOldContentExists){
			$('#existing_tags').append('');
		} else {
			$('#existing_tags').html('');
		}


		$('#existing_tags').append($('<span class="tag_item"><span class="tag_item_name">' + jQuery.trim(aElement) + '</span><a href="JavaScript:void(0);" onclick="MediaPool_RemoveTagFromList(this);"><img src="/PAF/design/global/img/delete_small.gif" /></a></span>'))

		if (vAddedItems == null){
			vAddedItems = jQuery.trim(aElement);
		} else{
			vAddedItems = vAddedItems + ',' + jQuery.trim(aElement);
		}
	});

	$('#new_tags').val('');

	/*var vActionUrl = new PAF_AjaxUrl();
	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_store_tags');
	vActionUrl.addParameter(aModletUniqueId + "__item_id", aItemId);
	vActionUrl.addParameter(aModletUniqueId + "__tags", vAddedItems);

	$.get(vActionUrl.getUrl());*/
}

function MediaPool_StoreMediaPoolElement(aModletUniqueId, aUrl, aPrefix){
	var vAttributes={};
	var vItemDescr = $('#' + aPrefix + 'edit_media_pool_item_name').val();
	var vIdItem= $('#' + aPrefix + 'media_pool_item_id').val();
	var vIdParentItem = $('#' + aPrefix + 'parent_item_id').val();
	var vTags = '';
	$('#' + aPrefix + 'item_details_div .tag_item_name').each(function(aIndex, aElement){
		if (vTags != ''){
			vTags = vTags+','+$(aElement).html();
		} else {
			vTags = $(aElement).html();
		}
	});

	var vCategories = '';
	$('#' + aPrefix + 'item_details_div #category_tree input:checkbox:checked').each(function(aIndex, aElement){
		if (vCategories != ''){
			vCategories = vCategories+','+$(aElement).val();
		} else {
			vCategories = $(aElement).val();
		}
	});

	var vActionUrl = new PAF_AjaxUrl();
	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_store_media_pool_element');
	vActionUrl.addParameter(aModletUniqueId + "__item_id", vIdItem);
	vActionUrl.addParameter(aModletUniqueId + "__parent_item_id", vIdParentItem);
	vActionUrl.addParameter(aModletUniqueId + "__item_descr", vItemDescr);
	vActionUrl.addParameter(aModletUniqueId + "__categories", vCategories);
	vActionUrl.addParameter(aModletUniqueId + "__tags", vTags);

	/*$.get(aUrl + aModletUniqueId + "__mode/" + 'ajax_store_media_pool_element/' + aModletUniqueId + "__item_id/" + vIdItem + '/' + aModletUniqueId + "__parent_item_id/" + vIdParentItem + '/' + aModletUniqueId + "__item_descr/" + vItemDescr + '/' + aModletUniqueId + "__categories/" + vCategories + '/' + aModletUniqueId + "__tags/" + vTags + '/' + aModletUniqueId + "__prefix/" + aPrefix,
		function(text){
		$('#' + aPrefix + 'media_pool_item_id').val($('span:first',text).attr('id'));
		$('#' + aPrefix + 'media_pool_browser').PAF_TreeView('replaceItem', text);
	});*/
	//$('#' + aPrefix + 'save_button').attr('disabled', 'disabled').val('Wird gespeichert...');



	$('input:[name="' + aPrefix + '_attributes"], textarea:[name="' + aPrefix + '_attributes"]').each(function(){
		vAttributes[aModletUniqueId + '__' + $(this).attr('id')] = $(this).attr('value');
	});
	vAttributes[aModletUniqueId + "__item_descr"] = vItemDescr;

    $.ajax({
        type: "POST",
        async: false,
		data: (vAttributes),
        url: aUrl + aModletUniqueId + "__mode/" + 'ajax_store_media_pool_element/' + aModletUniqueId + "__item_id/" + vIdItem + '/' + aModletUniqueId + "__parent_item_id/" + vIdParentItem + '/' + aModletUniqueId + "__categories/" + vCategories + '/' + aModletUniqueId + "__tags/" + vTags + '/' + aModletUniqueId + "__prefix/" + aPrefix + '/',

        success: function(text){
	    var vID = $('span:first',text).attr('id').split('_');

            $('#' + aPrefix + 'media_pool_item_id').val(vID[1]);
            $('#' + aPrefix + 'media_pool_browser').PAF_TreeView('replaceItem', text);
			//$('#' + aPrefix + 'save_button').removeAttr('disabled').val('Speichern');
        }
    });
}

function MediaPool_StoreMediaPool(aModletUniqueId, aURL, aPrefix){
	var vAttributes={};
	var vDescr = $('#' + aPrefix + 'edit_media_pool_name').val();
	var vIdItem= $('#' + aPrefix + 'media_pool_id').val();

	var vActionUrl = new PAF_AjaxUrl();
	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_store_media_pool');
	vActionUrl.addParameter(aModletUniqueId + "__id", vIdItem);
	//vActionUrl.addParameter(aModletUniqueId + "__descr", vDescr);
	vAttributes[aModletUniqueId + "__descr"] = vDescr;

	/*$.get(aURL + aModletUniqueId + "__mode/" + 'ajax_store_media_pool/' + aModletUniqueId + "__id/" + vIdItem + '/' + aModletUniqueId + "__descr/" + vDescr + '/' + aModletUniqueId + "__prefix/" + aPrefix, function(text){
		$('#' + aPrefix + 'media_pool_id').val($('span:first',text).attr('id'));
		$('#' + aPrefix + 'media_pool_browser').PAF_TreeView('replaceItem', text);
	});*/

    $.ajax({
        type: "POST",
        async: false,
	data: (vAttributes),
        url: aURL + aModletUniqueId + "__mode/" + 'ajax_store_media_pool/' + aModletUniqueId + "__id/" + vIdItem + '/' + aModletUniqueId + "__prefix/" + aPrefix,
        success: function(text){
	    var vLongId = $('span:first',text).attr('id').split('_');

            $('#' + aPrefix + 'media_pool_id').val(vLongId[1]);
            $('#' + aPrefix + 'media_pool_browser').PAF_TreeView('replaceItem', text);
        }
    });
}

function MediaPool_RemoveTagFromList(aLinkItem){
	$(aLinkItem).parent().remove();
	var vTags = $('#existing_tags>span');
	$('#existing_tags').html('');
	if (vTags.length == 0){
		$('#existing_tags').html('-');
	} else {
		vTags.each(function(aIndex, aElement){
			if (aIndex != 0){
				$('#existing_tags').append('').append(aElement);
			} else {
				$('#existing_tags').append(aElement);
			}
		});
	}
}

function MediaPool_StoreParentItem(aModletUniqueId, aItemId, aParentItemId, aUrl){
	var vActionUrl = new PAF_AjaxUrl();
	vActionUrl.addParameter(aModletUniqueId + "__mode", 'ajax_store_parent_item');
	vActionUrl.addParameter(aModletUniqueId + "__item_id", aItemId);
	vActionUrl.addParameter(aModletUniqueId + "__parent_item_id", aParentItemId);

	/*$.get(aUrl + aModletUniqueId + "__mode/" + 'ajax_store_parent_item/' + aModletUniqueId + "__item_id/" + aItemId + '/' + aModletUniqueId + "__parent_item_id/" + aParentItemId,
		function (text){

	});*/

    $.ajax({
        type: "GET",
        async: false,
        url: aUrl + aModletUniqueId + "__mode/" + 'ajax_store_parent_item/' + aModletUniqueId + "__item_id/" + aItemId + '/' + aModletUniqueId + "__parent_item_id/" + aParentItemId,
        success: function(text){

        }
    });
}

function MediaPool_RemoveItem(aModletIdentifier, aPrefix){
	if ($('>ul',$('#' + aPrefix + 'media_pool_browser a.selected').parent().parent()).length > 0){
		Check = confirm("Dieser Ordner enthält Dateien, welche gelöscht würden. Wollen Sie diesen Ordner wirklich löschen?");
		if (Check == false)
			return;
	}

	$('#' + aPrefix + 'media_pool_browser').PAF_TreeView('removeItem');
}

function MediaPool_ToggleDetailsArea(aIdArea){

	if( $('#' + aIdArea).css("display") == "none" ) {
		$('#' + aIdArea).show();
		$('#' + aIdArea + '_arrow').attr('src','/PAF/design/global/img/arrow-down.gif');

	} else {
		$('#' + aIdArea).hide();
		$('#' + aIdArea + '_arrow').attr('src','/PAF/design/global/img/arrow-right.gif');
	}
	/*
                    $('#' + aIdArea).show();

                    $('#' + aIdArea + '_arrow').attr('src','/PAF/design/global/img/arrow-down.gif');

               }, function() { // same here

                    $('#' + aIdArea).show();

                    $('#' + aIdArea + '_arrow').attr('src','/PAF/design/global/img/arrow-right.gif');

               });*/
}

/* globale Fuktion zum ein und ausblenden von Layer mit Iconwechsel*/
function showHideLayer(myLayer,myImageId,imageVisible,imageInVisible){
	if(document.getElementById(myLayer).style.display=='none'){
		document.getElementById(myLayer).style.display='';
		document.getElementById(myImageId).src=imageVisible;
	}else{
		document.getElementById(myLayer).style.display='none';
		document.getElementById(myImageId).src=imageInVisible;
	}
}
/* globale Fuktion zum ein und ausblenden von Layer mit Iconwechsel*/

