function check_tacisaccepted()
{
	var error_msg = "";
	
	if($('username').value.length == 0)
		error_msg = error_msg + 'Missing: user name.\n';
	if($('password').value.length == 0)
		error_msg = error_msg + 'Missing: password.\n';
	if($('tacisaccepted').checked){ /*nothing to do */ }
	else
		error_msg = error_msg + 'Please, read and accept term and conditions.\n';
			
	if(error_msg.length)
		alert(error_msg);
	else
		$('accountLogin').submit();
}

function deleteCookies(){
	// on confirm, delete username/password cookies and reload login form
	if(confirm("Click OK to delete all saved login information from this computer.\n\nYou will have to log in with your email address and password again if you delete the saved login information.\n\nClick cancel to keep your login data saved on this computer.")){
		location.href="index.php?action=account.login&deleteCookies=true";
	}
}

function ajaxFormPartRequest(checkForm, controller_elem, formElement, formpart, elemStyle, doReload, reloadPage, reloadElement)
{
	//example: ajaxFormPartRequest(true, 'index.php?action=admin.role.create', this.form, 'role', 'a_create_role:display,a_close_role:none,tr_role:none', true, 'index.php?action=admin.role.selection', 'userRoleSelection');
	
	if(checkForm.length && (checkForm == true || checkform == false))
		checkForm = checkForm;
	else
		checkForm = false;
	
	
	call_updater = true;
	
	if(checkForm && (formElement.length && formpart.length))
		call_updater = checkFormPartRequirements(formElement, formpart);
	
	//start db-update
	if(call_updater)
	{
		//start prepare parameter from form-parts for ajax-request
		var inputs = formElement.getElementsBySelector('select','textarea').concat(Form.getInputs(formElement));
		var js_parameter = new ArrayList();
		var reloadPage_parameter = "";
		inputs.each(
			function(inputElement)
			{ 
				if(inputElement.name.substr(0, formpart.length) == formpart)
				{
					key = inputElement.name.substr((formpart+"[").length, inputElement.name.length);
					key = key.substr(0, key.length-1);
					js_parameter.add(key+':::'+inputElement.value);
					if(key == "name") reloadPage_parameter = inputElement.value;
				}
			}
		);//end prepare parameter from form-parts for ajax-request
		
		//start ajax-requst for db update
		if(controller_elem.length > 0)
		{
			new Ajax.Request(controller_elem, 
				{
					parameters: { 'js_parameter' : js_parameter.toJson() },
			  		onComplete: function() 
					{  
						if(elemStyle.length) element_display(elemStyle);
						if(doReload == true)
						{
							if(reloadElement.length > 0 && reloadPage.length > 0)
							{	
								if(reloadPage_parameter.length == 0) reloadPage_parameter = "''";
							 	new Ajax.Updater(reloadElement, reloadPage, 
									{ 	
										parameters 	: {'partial' : 'true', 'name' : reloadPage_parameter }, 
										evalScripts : true, 
										evalJS 		: true 
									} 
								);
							}
						}
					}
				}
			);
		}//end ajax-requst for db update
	}//end db-update
}

function checkFormPartRequirements(formElement, formpart)
{
	formElement = $(formElement);
	var emptyInput = null;
	var inputs = formElement.getElementsBySelector('select','textarea').concat(Form.getInputs(formElement));

	inputs.each( 
		function(inputElement)
		{ 
			if(inputElement.name.substr(0, formpart.length) == formpart)
			{
				var emptyInputValue = (inputElement.type == 'checkbox') ? (inputElement.checked == false) : (inputElement.value == '');
		
				var activeElement = !parentElementHidden(inputElement) && (inputElement.disabled == false);
					
				if (!emptyInput && (inputElement.hasClassName('required') && emptyInputValue && activeElement)) {
					emptyInput = inputElement;
				}
		
		
				var validatorFunction = window['validate' + inputElement.id];
				if (!emptyInput && validatorFunction) {
					var valid = validatorFunction(inputElement);
					if (!valid) {
						emptyInput = inputElement;
					}
				};
	
				if (!emptyInput && inputElement.hasClassName('email') && activeElement) {
					var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
					if (!filter.test(inputElement.value)) {
						emptyInput = inputElement;
					}
				}
		
				if (!emptyInput && inputElement.hasClassName('min') && activeElement) {
					var relAttribute = Number(String(inputElement.getAttribute('rel')));
					if(inputElement.value < relAttribute) {
						emptyInput = inputElement;
					}
				}
			}
		} 
	);
		
	if (emptyInput) {
		emptyInput.focus();
		var container = emptyInput.up('tr') || emptyInput.up();
		new Effect.Highlight(container, {startcolor: '#FF0000'}); // , restorecolor: '#ffffff'
		return false;
	}
	
	return true;	
}

function checkedFormPart(formElement, formpart, isDisabled, isChecked)
{
	var inputs = formElement.getElementsBySelector('select','textarea').concat(Form.getInputs(formElement));
	inputs.each(
		function(inputElement)
		{ 
			if(inputElement.name.substr(0, formpart.length) == formpart)
			{ 
				if(isChecked == 'true')
					$(inputElement).checked = true;
				else if(isChecked == 'false')
					$(inputElement).checked = false;
			
				if(isDisabled == 'true')
					$(inputElement).disabled = true;
				else if(isDisabled == 'false')
					$(inputElement).disabled = false;
			}
		}
	);
}

function checkUncheck(elementId_checked, elementId_unchecked, formElementPart, isDisabled, isChecked, formElement)
{
	if($(elementId_checked).checked == true)
	{
		$(elementId_unchecked).checked = false;
		checkedFormPart(formElement, formElementPart, isDisabled, isChecked); 
	}
	else
		checkedFormPart(formElement, formElementPart, 'false', isChecked);
}

function checkMyForm(formObject, tableRelation)
{
	var retVal = false;
	
	var checkForm = checkFormRequirements(formObject, false);

	if(checkForm == true)
	{
		checkedFormPart(formObject, tableRelation, 'false', '');
		retVal = true;
	}
	return retVal;
}

function add_attachment(counter){
	// adapt the javascript link to the new count
	$('add_attachment_link').href="javascript:add_attachment(" + (counter + 1) + ");";
	// load the partial by AJAX to add another FUFF (file upload form field :-)
	new Ajax.Updater('attachments', 'index.php?action=publishing.order.attachment&partial=true', {
		method: 'get',
		insertion: Insertion.Bottom,
		parameters: {
			count: counter
		}
	});	
}

function set_calendar_range(range_type, value, calender_id) {
	// sets the range of the calender_id input element to value
	// intended to be called when the calendar picker control's lower date range needs to be restricted dynamically
	//	requires:
	//	- range_type: 	"low" or "high" -> determines which range is restricted
	//	- value: 		a date string in the format d-m-y (if other date formats need to be handled -> extend this function by passing an additional parameter for the date format and handle it ;-)
	//	- calender_id: 	the html element id of the calender picker input element of which the daterange will be restricted
	var classes = $(calender_id).className;
	var pattern = new RegExp('\\b' + 'range-' + range_type + '-\\S+\\b');
	var toBeRemoved = classes.match(pattern);
	if (toBeRemoved != null){
		// ok there already IS a range-low-something class -> remove it
		$(calender_id).removeClassName(toBeRemoved);
	}
	
	if (value != '' && value != 'from' && value != 'from'){
		// reformat the date string to y-m-d
		var date_parts = value.split('-');
		var new_date = date_parts[2] + '-' + date_parts[1] + '-' + date_parts[0];
	
		// now add the new classname for the lower range
		$(calender_id).addClassName('range-' + range_type + '-' + new_date);
		var classes = $(calender_id).className;
	}

	// now re-initialize the datepicker controls...
	datePickerController.create(typeof document.createElement);
}	

function calendar_reset(input_element, clearValue){
	if (input_element.value == "" || input_element.value == clearValue){
		alert('Please use the calendar symbol to choose a date.');		
	} else {
		var clear_input = confirm('Click OK to clear this date (or use the calendar symbol to choose a different date.)');
		if (clear_input) {
			input_element.value = clearValue;
		}
	}
}

function toggleProductionDetails(production_id){
	var detailDiv_id = production_id + '_detailDiv';
	var detailLi_id = production_id + '_detailLi';
	if($(detailDiv_id).style.display == 'none'){
		$(detailDiv_id).style.display='block';
		$(detailLi_id).removeClassName('closed');
	} else {
		$(detailDiv_id).style.display='none';
		$(detailLi_id).addClassName('closed');
	}
}


/* used by Media Database frontend Category Tree Class */

function toggleFolder(folderId, folderName) 
{
	if ($('img_'+folderId).src.endsWith('plus.gif')) {
		$('img_'+folderId).src		= 'images/icon_minus.gif';
		$('img_'+folderId).alt		= 'close '+folderName;
		$('img_'+folderId).title 	= 'close '+folderName;
		$('folderId_'+folderId).show();
		
	} else if ($('img_'+folderId).src.endsWith('minus.gif')) {
		try { $('img_'+folderId).src 	= 'images/icon_plus.gif'; } catch (e) {}
		try { $('img_'+folderId).alt	= 'open '+folderName; } catch (e) {}
		try { $('img_'+folderId).title 	= 'open '+folderName; } catch (e) {}
		try { $('folderId_'+folderId).hide(); } catch (e) {}
	}
}

function checkCategory(folderId)
{
	var returnValue = false;
  //check if something is set in the $_SESSION
  //if so, a notice will be show asking the user if he wants to search over the
  //entire database or just the selected folder
	new Ajax.Request("index.php?action=mediadb.mediadb.ajaxHasSearchSession", {
		parameters 	: 	{
			'categoryid' 	: 	folderId
		},
		onComplete 	: 	function(result) {
			if (result.responseText == "true") {
				
                $('ajax_content').innerHTML = '';
				$('bgfader')     .setStyle( { display : '' } );
				$('superoverlay').setStyle( { display : '' } );
				
				//for IE6: hide select's because they suck
		    	var paras = $A(document.getElementsByTagName('select'));
		    	paras.each(Element.toggle);
			
				new Ajax.Updater('ajax_content', "index.php?action=mediadb.search.confirm", {
					parameters 	: {
						'partial' 		: 	true,
						'categoryid'	: 	folderId,
						'returnto' 		: 	'mediadb.search.overview'
					},
					onComplete 	: 	function(result) {
						// return_categoryCheck(true);
					}
				});
			
			} else {
				new Ajax.Request('index.php?action=mediadb.mediadb.change_session', {
					parameters 	: 	{
						'categoryid' 	: folderId,
						'returnTo' 		: 'mediadb.search.overview',
						'search' 		  : 'new'
					},
					onComplete 	: function(result) {
						// window.location.reload();
						return_categoryCheck(true);
					}
				});
			}
		}
	});
	return returnValue;
}

function return_categoryCheck(returnValue)
{
	window.location.href="index.php?action=mediadb.search.overview";
}

function refreshSearch(folderId)
{
	$$('td.mediadbcategorypanel').each(
		function (elementTd) 
		{
			elementTd.setStyle( { backgroundColor: '' } );
		}
	);
	$('td_'+folderId).setStyle( { backgroundColor: '#ccc' } );
	/*
	new Ajax.Updater("mediadb_search", "index.php?action=mediadb.search.object", {
		parameters 	: {
			'partial' 		: true
		}
	});
	new Ajax.Updater("mediadb_result", "index.php?action=mediadb.search.result", {
		parameters 	: {
			'partial' 		: true
		}
	});
	*/
}

//* medida database frontend search/basket/etc. */
function getResults(formular)
{
	/*
	new Ajax.Request("index.php?action=mediadb.mediadb.ajax_set_search", {
		parameters: formular.serialize(),
		onComplete 	: 	function(transaction) {
			
			new Ajax.Updater('mediadb_result', "index.php?action=mediadb.search.result", {
				parameters 	: {
					'partial' 	: true
				}
			});
		
		}
	});
	return false;
	*/
}

function reload_result(page, order, dir)
{
	window.location.href = "index.php?action=mediadb.search.overview&pg="+page+"&att="+order+"&orderdir="+dir;
	/*
	new Ajax.Updater('mediadb_result', "index.php?action=mediadb.search.result", {
		parameters 	: 	{
			'partial' 	: true,
			'pg'		: page,
			'att'		: order,
			'orderdir' 	: dir
		}
	});
	*/
}

function addOverlert()
{
    // prepare the div to insert
    overlert = '<div id="overlert_curtain" onclick="removeOverlert()" style="display: none;"><div id="overlert_container"><div id="overlert_content"></div></div></div>';
    
     $('body').insert({
      top: overlert
    });
    
}

function showOverlert()
{
    if($('overlert_curtain') != null)
    {
        $('overlert_curtain').show();
    }    
}

function hideOverlert()
{
    if($('overlert_curtain') != null)
    {
        $('overlert_curtain').hide();
    }    
}

function removeOverlert()
{
    if($('overlert_curtain') != null)
    {
        $('overlert_curtain').remove();
    }
}

function fillOverlert(content)
{
    if($('overlert_content') != null)
    {
        $('overlert_content').innerHTML = content;
    }
}

function fillOverlertWithPartial(partial_url)
{
    if($('overlert_content') != null)
    {
    	new Ajax.Updater('overlert_content', 'index.php?action=' + partial_url, {
    		parameters 	: 	{
    			'partial' 	: true
    		}
    	});
    }
}

function hidePopup()
{
	$('superoverlay').setStyle( { display : 'none' } );
	$('bgfader')     .setStyle( { display : 'none' } );

	//for IE6: hide select's because they suck
    var paras = $A(document.getElementsByTagName('select'));
    paras.each(Element.show);

	return false;
}

function showTextInOverlert(textToShow)
{
    if($('overlert_curtain') == null)
    {
        addOverlert();
    }
    
    fillOverlert(textToShow);
    showOverlert();
}

//start:: display detail information about retailer
function showDetail(id, returnTo) 
{
    $('ajax_content').innerHTML = '';
	$('bgfader')     .setStyle( { display : '' } );
	$('superoverlay').setStyle( { display : '' } );

	//for IE6: hide select's because they suck
    var paras = $A(document.getElementsByTagName('select'));
    paras.each(Element.hide);


	new Ajax.Updater('ajax_content', "index.php?action=mediadb.result.details", {
		parameters 	: {
			'partial' 		: 	true,
			'id'			: 	id,
			'returnto' 		: 	returnTo
		}
	});
}

function addToNewTMOBasket(tmo_id, user_id)
{
    $('ajax_content').innerHTML = '';
	$('bgfader')     .setStyle( { display : '' } );
	$('superoverlay').setStyle( { display : '' } );
	
	new Ajax.Updater('ajax_content', "index.php?action=tmo.basket.addTMOToNew_form", {
		parameters 	: {
			'partial' 		: 	true,
			'tmo_id'		: 	tmo_id,
			'user_id' 		: 	user_id
		},
        // set the focus to the name input field when the form is loaded...
		onComplete          : function(result)
		                        {
		                            if($('newBasket_name') != null)
                                    {
    	                                $('newBasket_name').focus();
    	                            }
    	                        }
	});
}

function send_addTMOToNewBasket_form(form_id)
{
    // get the form data, serialize it
    form_data = $(form_id).serialize();

    // replace the form with a progress indicator...
    load_progress_indicator('ajax_content', '... saving your new TMO basket ...');

    // submit the form...
	new Ajax.Request('index.php?action=tmo.basket.saveNewBasketWithTMO', {
		parameters 	: 	{
            'partial'       : true,
			'form_data' 	: form_data
		},
		onComplete          : function(result){
		    // say how things went, and reload the basket-part of the added tmo in case of success...
            if(result.responseText == 'ok')
            {
                // replace all displayed object items --> get the (last) chosen subcategory and call showResults
                category_id = $('subcategory').innerHTML;
                showResults(category_id);


                // new Ajax.Request('index.php?action=tmo.object.replace', {
                //     parameters: {
                //         'partial':      true,
                //         'user_id':      form.user_id.value,
                //         'object_id':    form.object_id.value 
                //     },
                //     onComplete:         function(result)
                //                         {
                //                             $('object_item_' + form.object_id.value).replace(result.responseText);
                //                             PageMenu.initialize('tmo_filter_results');
                //                         }
                // });
                // output success message
                $('ajax_content').innerHTML = "The new basket has been created, with the object in it.";

            } else {
                // output error message
                $('ajax_content').innerHTML = "An error occurred while trying to create the new basket.<br><br>If the problem persists, please contact <a href='mailto:mam51@straumann.net'>technical support</a>.";
            }
        }
	});

    
    return false;
}

function addToTMOBasket(basket_id, object_id, user_id)
{
    // AJAX-call the partial that adds the object to the basket
    new Ajax.Request('index.php?action=tmo.basket.addObject', {
        parameters:     {
            'partial':      true,
            'basket_id':    basket_id,
            'object_id':    object_id
        },
        onComplete:         function(result)
                            {
                    		    // say how things went, and reload the basket-part of the added tmo in case of success...
                                if(result.responseText == 'ok')
                                {
                                    new Ajax.Request('index.php?action=tmo.object.replace', {
                                        parameters: {
                                            'partial':      true,
                                            'user_id':      user_id,
                                            'object_id':    object_id
                                        },
                                        onComplete:         function(result)
                                                            {
                                                                $('object_item_' + object_id).replace(result.responseText);
                                                                PageMenu.initialize('tmo_filter_results');
                                                            }
                                    });
                                    // output success message

                                    $('ajax_content').innerHTML = "<span class='tmo_flash_message'>The object has been added to the basket.</span>";

                                } else {
                                    // output error message
                                    $('ajax_content').innerHTML = "<span class='tmo_flash_message' style='background-color: red;'>An error occurred while trying to add the object to the basket.<br><br>If the problem persists, please contact <a href='mailto:mam51@straumann.net'>technical support</a>.</span>";
                                }
                            	$('bgfader')     .setStyle( { display : '' } );
                            	$('superoverlay').setStyle( { display : '' } );
                            }
    });
    
}

function removeFromTMOBasket(basket_id, object_id, user_id)
{
    if(confirm('Click on OK to remove this object from the basket.'))
    {
        // AJAX-call the partial that adds the object to the basket
        new Ajax.Request('index.php?action=tmo.basket.removeObject', {
            parameters:     {
                'partial':      true,
                'basket_id':    basket_id,
                'object_id':    object_id
            },
            onComplete:         function(result)
                                {
                        		    // say how things went, and reload the basket-part of the removed tmo in case of success...
                                    if(result.responseText == 'ok')
                                    {
                                        new Ajax.Request('index.php?action=tmo.object.replace', {
                                            parameters: {
                                                'partial':      true,
                                                'user_id':      user_id,
                                                'object_id':    object_id
                                            },
                                            onComplete:         function(result)
                                                                {
                                                                    $('object_item_' + object_id).replace(result.responseText);
                                                                    PageMenu.initialize('tmo_filter_results');
                                                                }
                                        });
                                        // output success message

                                        $('ajax_content').innerHTML = "<span class='tmo_flash_message'>The object has been removed from the basket.</span>";

                                    } else {
                                        // output error message
                                        $('ajax_content').innerHTML = "<span class='tmo_flash_message' style='background-color: red;'>An error occurred while trying to remove the object from the basket.<br><br>If the problem persists, please contact <a href='mailto:mam51@straumann.net'>technical support</a>.</span>";
                                    }
                                	$('bgfader')     .setStyle( { display : '' } );
                                	$('superoverlay').setStyle( { display : '' } );
                                }
        });
    }
}

function mediadb_showObjectRequest(objectId, returnTo) 
{
    $('ajax_content').innerHTML = '';
	$('bgfader')     .setStyle( { display : '' } );
	$('superoverlay').setStyle( { display : '' } );

	// for IE6: hide select's because they suck
    var paras = $A(document.getElementsByTagName('select'));
    paras.each(Element.toggle);

	new Ajax.Updater('ajax_content', "index.php?action=mediadb.result.object_request", {
		parameters 	: {
			'partial' 		: 	true,
			'objectId'		: 	objectId,
			'returnto' 		: 	returnTo
		}
	});
}

function tmo_showObjectRequest(objectId) 
{
    $('ajax_content').innerHTML = '';

	$('bgfader')     .setStyle( { display : '' } );
	$('superoverlay').setStyle( { display : '' } );

	// for IE6: hide select's because they suck
    var paras = $A(document.getElementsByTagName('select'));
    paras.each(Element.toggle);

	new Ajax.Updater('ajax_content', "index.php?action=tmo.object.request_form", {
		parameters 	: {
			'partial' 		: 	true,
			'objectId'		: 	objectId
		},
        onComplete          :   function(result)
                                {
                                    if($('usage_declaration') != null)
                                    {
                                        $('usage_declaration').focus();
                                    }    
                                }
	});
}

function todo_requestedObject_request(requestedObjectId, requestedAction, returnTo) 
{
    $('ajax_content').innerHTML = '';
	$('bgfader')     .setStyle( { display : '' } );
	$('superoverlay').setStyle( { display : '', width : '980px', left : '475px' } );

	//for IE6: hide select's because they suck
    var paras = $A(document.getElementsByTagName('select'));
    paras.each(Element.toggle);

	new Ajax.Updater('ajax_content', "index.php?action=todo.requestedobject.request", {
		parameters 	: {
			'partial' 			: 	true,
			'hash'				: 	requestedObjectId,
			'requestedAction'	: 	requestedAction,
			'returnTo' 			: 	returnTo
		},
		evalScripts : true,
		evalJs		: true
	});
}

function todo_requestedtmo_request(requestedObjectId, requestedAction, returnTo) 
{
    $('ajax_content').innerHTML = '';
	$('bgfader')     .setStyle( { display : '' } );
	$('superoverlay').setStyle( { display : '', width : '980px', left : '475px' } );

	//for IE6: hide select's because they suck
    var paras = $A(document.getElementsByTagName('select'));
    paras.each(Element.toggle);

	new Ajax.Updater('ajax_content', "index.php?action=todo.requestedtmo.request", {
		parameters 	: {
			'partial' 			: 	true,
			'hash'				: 	requestedObjectId,
			'requestedAction'	: 	requestedAction,
			'returnTo' 			: 	returnTo
		},
		evalScripts : true,
		evalJs		: true
	});
}

function todo_requestedobject_check_statusmessage(returnTo)
{
	var return_val = false;
	if($('status_message').value.length == 0) {
		return_val = false;
	} 
	else {
		var check_value = "";
		for(i = 0; i < $('status_message').value.length; i++) {
			if ($('status_message').value.charAt(i) != " ") {
				check_value = check_value + $('status_message').value.charAt(i);
			}
		}
		
		if (check_value.length == 0) {
			return_val = false;
		}
		else {
			return_val = true;
		}
	}

	if (return_val == false) {
		alert('Please enter a reason for refusal');
	}
	else {
		todo_requestedobject_set_action('denied');
	//	$('requestedobjects_action').submit();
	}

	return return_val;
}

function todo_requestedobject_set_action(action)
{
	$('status').value = action;
	$('requestedobjects_action').submit();
}


function basket_addToNew(elementUl, id)
  {
	$(elementUl.id).hide();
	$('show_newBasketForm_'+id).show();
	new Ajax.Updater('show_newBasketForm_'+id, "index.php?action=mediadb.mediadb.basket",
    {
		  parameters 	:
      {
  			'partial' 	: true,
			  'objectid' 	: id
		  }
	  }
  );
}


var pagepanel = new Object();

pagepanel.init = function() {
	var panels = $('panels');
	if (panels) {
		panels.parentNode.removeChild(panels);
		document.body.appendChild(panels);
	}


};

pagepanel.open = function(panel, anchor) {
	panel = $(panel);
	anchor = $(anchor);

	var position = Position.cumulativeOffset(anchor);
	panel.style.position = 'absolute';
	panel.style.left = position[0] - 210 + 'px';
	panel.style.top = (position[1] - 65) + 'px';
	panel.show();
};

/* Collection */

var Collection = new Object();

Collection.addToNew = function(anchor, assetId) {
	var panel = $('add-collection');
	var form = panel.down('form');
	form['asset[id]'].value = assetId;
	form['collection[name]'].value = '';
	form.onsubmit = function() {
		form.request({onComplete:function() {
			document.location.reload();
		} });
		return false;
	};
	pagepanel.open(panel, anchor);
};

Collection.addAllToNew = function(anchor, objectIds) {
	var panel = $('add-collection');
	var form = panel.down('form');
	form['asset[objectIds]'].value = objectIds;
	form['collection[name]'].value = '';
	form.onsubmit = function() {
		form.request({onComplete:function() {
			document.location.reload();
		} });
		return false;
	};
	pagepanel.open(panel, anchor);
};

Collection.added = function() {
	//
};

Collection.newWithContent = function(form, returnAction, returnValue) {
	if (!checkFormRequirements(form)) {
		return;
	}

	var container = 'documents';
	var updaterUrl = 'index.php?partial=true&action=default.' + returnAction + '&id=' + returnValue;

	form.request({
		onComplete: function(){
			Modalbox.hide();
			new Ajax.Updater(container, updaterUrl, { onComplete: function() {
				PageMenu.initialize(container);
			} });
		}
	});
};

/* Asset */

var Asset = new Object();

Asset.removeKeyword = function(anchor) {
	var panel = $('image-keywords');
	var params = $H({ partial: 'true', keyword_line: anchor.rev });
	var url = anchor.href + '&' + params.toQueryString();
	new Ajax.Updater(panel, url, {});
};

Asset.newKeyword = function(sender, assetId) {
	var anchor = sender.down('img');
	var value = '';
	var params = { context: 'asset', value: assetId };
	Keyword.initPanel(anchor, value, params, Asset.refreshKeywords.bind(assetId));
};

Asset.refreshKeywords = function() {
	var panel = $('image-keywords');
	var url = 'index.php?partial=true&action=admin.asset.keywords&ids=' + this;
	new Ajax.Updater(panel, url, {});
};

Asset.refreshThumbnail = function(sender, assetId) {
	var container = 'view_thumbnail_cont_' + assetId;
	var requestUrl = sender.href + '&partial=true';
	var updaterUrl = 'index.php?partial=true&action=default.asset.thumbnail&id=' + assetId;
	new Ajax.Request(requestUrl, { onComplete: function() {
		new Ajax.Updater(container, updaterUrl, { onComplete: function() {
			PageMenu.initialize(container);
		} });
	} });
};

var Document = new Object();

Document.addFilesToCollection = function(sender, documentId, documentversionId) {
	var container = 'view_document_cont_' + documentId;
	var requestUrl = sender.href + '&partial=true';
	var updaterUrl = 'index.php?partial=true&action=default.document.show&id=' + documentId + '&documentversion_id=' + documentversionId;
	new Ajax.Request(requestUrl, { onComplete: function() {
		new Ajax.Updater(container, updaterUrl, { onComplete: function() {
			PageMenu.initialize(container);
		} });
	} });
};


var Documentfile = new Object();

Documentfile.refreshFiles = function(sender, documentId, documentversionId, from) {
	var container = 'view_documenfiles_cont_' + documentId;
	var requestUrl = sender.href + '&partial=true';
	var updaterUrl = 'index.php?partial=true&action=default.documentversion.files&id=' + documentversionId + '&from=' + from;
	new Ajax.Request(requestUrl, { onComplete: function() {
		new Ajax.Updater(container, updaterUrl, { onComplete: function() {
			PageMenu.initialize(container);
		} });
	} });
};


/* Keyword */

var Keyword = {
	anchor: null,
	params: {},
	callback: Prototype.emptyFunction,

	initPanel: function(anchor, title, value, params, callback) {
		var position = Position.cumulativeOffset(anchor);
		var panel = $('add-keyword');
		var form = panel.down('form');
		panel.down('span.title').update(title);
		Keyword.anchor = anchor;
		Keyword.params = params;
		Keyword.callback = callback;
		$('keyword_name').value = value;
		form.onsubmit = function() { Keyword.add(form); return false; };
		panel.style.position = 'absolute';
		panel.style.left = position[0] + 1 + 'px';
		panel.style.top = (position[1] - 1) + 'px';
		panel.show();
	},

	add: function(form) {
		var url = form.action;
		var params = $H(form.serialize(true)).merge(Keyword.params);
		var completed = function() {
			Keyword.refreshList();
			Keyword.callback(Keyword.anchor, form);
		};
		new Ajax.Request(url, {parameters:params, onComplete:completed});
		Element.hide('add-keyword');
	},

	remove: function(token) {
		var params = {
			category_name: token.down('label').firstChild.nodeValue,
			keyword_name: token.down('span.value').firstChild.nodeValue,
			path:  token.up('li').title
		};
		var url = 'index.php?action=admin.keyword.remove&partial=true';
		new Ajax.Request(url, {parameters:params});
		token.remove();
	},

	destroy: function(anchor, message) {
		if (confirm(message) == true) {
			new Ajax.Request(anchor.href, {onComplete:Keyword.refreshList});
		}
		else {
			return false;
		}
	},

	close: function(panel) {
		panel.hide();
	},

	refreshList: function() {
		var container = $('keyword_container');
		if (container) {
			var url = 'index.php?action=admin.keyword.list&partial=true';
			new Ajax.Updater('keyword_container', url);
		}
	}
};


//Preview Popups
var image_is_showing = false;
var imgSize = 400;
function mediadbSearch_showImage(e,img_id)
{
	$('img_preview').setStyle( { 'display' : '' } );

	if (!e) {
    	var e = window.event;
	}

	if(!image_is_showing) {
    	var posx = 0;
    	var posy = 0;
		//html n body must allready exist or this wont work
		var bodyW = document.documentElement.clientWidth;
		var bodyH = document.documentElement.clientHeight;

		if (!e) {
			var e = window.event;
		}
		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
			bodyW = document.documentElement.clientWidth;
			bodyH = document.documentElement.clientHeight;
		} else if (e.clientX || e.clientY) { //IE
			posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
			bodyW = document.viewport.getWidth();
			bodyH = document.viewport.getHeight();
		}

		posx +=10;

		// Y zentrieren
		if((posy+200) >= bodyH) {
			posy = (bodyH-(imgSize+20));
		} else if((posy-200) <= 0) {
			posy = 10;
		} else {
			posy -=200;
		}

		$('img_preview').setStyle( {
			'left'    : posx + 'px',
        	'top'     : posy + 'px'
		} );

		//show the picture
		new Ajax.Updater('img_preview', 'index.php?action=mediadb.search.imagedetails', {
			parameters : {
				'image_id': img_id,
				'partial' : 'true'
			}
		} );
		image_is_showing = true;
	}

	//for IE6: hide select's because they suck
	var paras = $A(document.getElementsByTagName('select'));
	paras.each(Element.toggle);
}

function mediadbSearch_showVisual(e,img_id)
{
	$('img_preview').setStyle( { 'display' : '' } );

	if (!e) {
    	var e = window.event;
	}

	if(!image_is_showing) {
    	var posx = 0;
    	var posy = 0;
		//html n body must allready exist or this wont work
		var bodyW = document.documentElement.clientWidth;
		var bodyH = document.documentElement.clientHeight;

		if (!e) {
			var e = window.event;
		}
		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
			bodyW = document.documentElement.clientWidth;
			bodyH = document.documentElement.clientHeight;
		} else if (e.clientX || e.clientY) { //IE
			posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
			bodyW = document.viewport.getWidth();
			bodyH = document.viewport.getHeight();
		}

		posx +=10;

		// Y zentrieren
		if((posy+200) >= bodyH) {
			posy = (bodyH-(imgSize+20));
		} else if((posy-200) <= 0) {
			posy = 10;
		} else {
			posy -=200;
		}

		$('img_preview').setStyle( {
			'left'    : posx + 'px',
        	'top'     : posy + 'px'
		} );

		//show the picture
		new Ajax.Updater('img_preview', 'index.php?action=mediadb.search.visualdetails', {
			parameters : {
				'image_id': img_id,
				'partial' : 'true'
			}
		} );
		image_is_showing = true;
	}

	//for IE6: hide select's because they suck
	var paras = $A(document.getElementsByTagName('select'));
	paras.each(Element.toggle);
}

function museumSearch_showImage(e,img_id)
{
	$('img_preview').setStyle( { 'display' : '' } );

	if (!e) {
    	var e = window.event;
	}

	if(!image_is_showing) {
    	var posx = 0;
    	var posy = 0;
		//html n body must allready exist or this wont work
		var bodyW = document.documentElement.clientWidth;
		var bodyH = document.documentElement.clientHeight;

		if (!e) {
			var e = window.event;
		}
		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
			bodyW = document.documentElement.clientWidth;
			bodyH = document.documentElement.clientHeight;
		} else if (e.clientX || e.clientY) { //IE
			posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
			bodyW = document.viewport.getWidth();
			bodyH = document.viewport.getHeight();
		}

		posx +=10;
		
		//position correction by bvo
		posx = posx - 500;
		
		// Y zentrieren
		if((posy+200) >= bodyH) {
			posy = (bodyH-(imgSize+20));
		} else if((posy-200) <= 0) {
			posy = 10;
		} else {
			posy -=200;
		}

		$('img_preview').setStyle( {
			'left'    : posx + 'px',
        	'top'     : posy + 'px'
		} );

		//show the picture
		new Ajax.Updater('img_preview', 'index.php?action=mediadb.search.imagedetails', {
			parameters : {
				'image_id': img_id,
				'partial' : 'true'
			}
		} );
		image_is_showing = true;
	}

	//for IE6: hide select's because they suck
	var paras = $A(document.getElementsByTagName('select'));
	paras.each(Element.toggle);
}



function mediadbSearch_hideImage()
{
	if(image_is_showing) {
		$('img_preview').setStyle( { 'display' : 'none' } );

		new Ajax.Updater('img_preview', 'index.php?action=mediadb.search.imagedetails', {
			parameters : {
				'partial' : 'true'
			}
		} );
		image_is_showing = false;
	}
	//for IE6: hide selects because they suck
	var paras = $A(document.getElementsByTagName('select'));
	paras.each(Element.toggle);
}

function choose_recipient(stuffToShow)
{
	// used to choose the recipient when sending a high-res PDF to 'someone else'
	// shows the hidden div referred to b stuffToShow, and hides any of the other choices
	
	// all right, let's go then: first, find all the choices that need to be hidden and do just that: hide 'em!
	var stuff_to_hide = $$('div.recipient-choice');
	stuff_to_hide.each(function(hideMe){
		hideMe.setStyle({fontWeight: 'normal'});
		hideMe.hide();		
	}
		);
	
	//... and reveal the chosen stuff:
	$(stuffToShow).show();
	$(stuffToShow).previous('a').setStyle({fontWeight: 'bold'});
}

function clear_radiobuttons()
{
	// if there is text in the text field -> clear all radiobuttons
	if(document.approve_else.free_email.value != ''){
		var radiobuttons = $$('input.radio');
		radiobuttons.each(function(radio){
			radio.checked = false;
		});
	}
}

function clear_freeEmail(radiobutton)
{
	// clears the text input for the free email address entry if the radiobutton was selected
	if(radiobutton.checked == true){
		document.approve_else.free_email.value = '';
	}
}

function load_progress_indicator(indicator_target, text_message){
	// loads a progress indicator gif into the html container element represented by target (->id)
	// if text is not empty, a text message is also displayed (and yes, that message is whatever is in text_message ;-)
	var	gfx = "images/iwc/default/progress_wheel_bw.gif";

	var output = "<div style='width: 100%; text-align: center;'>";

	if (text_message != ""){
		output += text_message + "<br><br>";
	}

	output += "<img align='center' src='" + gfx + "'" + "></div>";

	$(indicator_target).innerHTML = output;
}
