function redirect(url, new_window){
	if(new_window){
		window.open(url);
	}else{
		window.location.href=url;
	}
}

// Shortcut for redirect
function r(url, new_window){redirect(url)}

function DialogWait(phrase, title){
	Modalbox.show(DialogWaitContent(phrase), {title: title, width: 420});	
}

function DialogWaitContent(phrase){
	return '<div style="width: 100%; text-align: center" id="dialog_wait_content"><em>' + phrase + '</em><br /><img border="0" src="/img/spinner.gif" /></div>';
}

function DialogMessageContent(phrase){
	return '<div style="width: 100%; text-align: center"><em>' + phrase + '</em><br /><a href="#" onclick="Modalbox.hide();">Fenster schliessen</a></div>';
}

this.failure_highlight = { 
	startcolor: '#761F21',
	endcolor: '#EFEFEF' 
}

this.success_highlight = { 
	startcolor: '#D4FF8F',
	endcolor: '#EFEFEF' 
}

/*
 * A simple Hoover imitation
 * 
 * Adds the hoverclass to the element onmouseover
 * Removes the hoverclass to the element onmouseout
 * If hasLabel is true, the classes 'label' and 'label-hover' 
 * applied to the first decending element
 *
 * elements is an array of id's
 *
 * Sample
 * var fields = ['photo1', 'photo2', 'photo3'];
 * highlight(fields, 'my-hover', true);
 *
 *
 */
function highlight(elements, hoverClass, hasLabel){
	elements.each(function(e){
			Event.observe(e, 'mouseover', function(event) {
				$(e).addClassName(hoverClass);
				if(hasLabel){
					$(e).down().className = 'label-hover';
				}
			});

			Event.observe(e, 'mouseout', function(event) {
				$(e).removeClassName(hoverClass);
				if(hasLabel){
					$(e).down().className = 'label';
				}				
			});		
		}
	);
}



/*
 * Creates a Prototype Ajax Request.
 * Shows a DialoWait Window during execution
 *
 * IMPORTANT: This function shall be used if a longer execution time
 * is expected. It dont works when the reponse is to fast. Use
 * sleep(1) in your PHP Scripts to ensure that it works even with fast requests
 *
 * Important: The Response must start with the string "success" or "failure"
 *
 * Options are:
 *
 *	options = {
 *   	 // The url for the ajax request
 *		'url'                       : '/admin/categories/asset/1/type:smth',
 *       
 *       // The method of the request get || post
 *		'method'                    : 'get',
 *
 *       // The message to show during execution
 *		'message'            		: 'Aktualisiere Verknüpfung',
 *
 *       // In case that smth does wrong
 *		'failure_message'           : 'Aktion ist fehlgeschlagen',
 *
 *       // Text for successful request
 *		'success_message'           : 'Aktion erfolgreich'
 *
 *       // Executes on success
 *		'callback_success'           : 'dosmth'
 *
 *       // Executes on failure
 *		'callback_failure'           : 'dosmth'
 *
 *       // Executes on failure
 *		'debug'           			: true
 *	}
 *	
// sample
options = {
	'url'                       : '/de/product/buy/number:' + number_tickets,
	'method'                    : 'get',
	'title'                     : 'Produkte werden gekauft',
	'message'                   : 'Bitte haben Sie einen Augenblick Geduld während Ihre Lose erzeugt werden',
	'failure_message'           : 'Aktion ist fehlgeschlagen',
	'success_message'           : 'Aktion erfolgreich',
	'callback_success'          : 'showProductBought',
	'debug'           			: true
}						
DialogAjax(options);

 */
function DialogAjax(options){
	
	valid = true;
	['title', 'message', 'url', 'method', 'success_message', 'failure_message'].each(function(key){
		if(eval("options." + key) == undefined){
			valid = false;
		}
	});
	
	if(!valid){
		debug('Missing Option');
		return
	}
	var url = options.url;

	new Ajax.Request(url, {
		method: options.method,
	  	onSuccess: function(transport) {
		
			if(options.debug  != undefined && options.debug != false){
				debug(transport.responseText)
			}		
			
			if(transport.responseText.startsWith('success')){
				$('dialog_wait_content').highlight(this.success_highlight);
				$('dialog_wait_content').update(options.success_message);
				//$(options.update_container).fade({ duration: 2.5 });
				if(!options.callback_success  != undefined )
					eval(options.callback_success + "();");
				
			}else{
				
				//$('content').update(transport.responseText);
				$('dialog_wait_content').highlight(this.failure_highlight);
				$('dialog_wait_content').update(options.failure_message);
				if(options.callback_failure != undefined)
					eval(options.callback_failure + "();");
			}		
				
			RctTimer.executeDelayed('Modalbox.hide()', 3);	
	  	},
		onFailure: function(transport){
			alert(transport.responseText);
			Modalbox.hide();
		},
		onCreate: function(transport){
			DialogWait(options.message, options.title);			
		}		
	});
	
	
}

function ModalImage(url, title, width, height){
	
	if(width==null){
		width = document.viewport.getWidth() -50;
	}
	
	if(height == null){
		height = document.viewport.getHeight() -50;
	}
	
	Modalbox.show('<div onclick="Modalbox.hide()" style="width: 100%; text-align: center; cursor: pointer"><img style="cursor: pointer" src="'+url+'"></div>', 
					{
						title: title,
						width: width,
						height: height
					}
	);
}

function validateNotEmpty(data){
	var has_empty_fields = false;
	data.each(function (e){
		if($F(e).empty()){
			has_empty_fields = true;
		}
	});
	
	if(has_empty_fields == false){
		return true;
	}else{
		return false;
	}	
}

function makeNumeric(field){
	val = field.value;
	val = val.gsub("[^(0-9.,)]","");
	val = val.gsub(",",".");
	field.value = val;
	if(isNaN(field.value)){
		field.value = parseFloat(field.value);
	}
}

function makeInteger(field){
	makeNumeric(field);
	if(isNaN(parseInt(field.value))){
		field.value = "";
	}else{
		field.value = parseInt(field.value);
	}
	
}

/*
 * set an alternate class for each row in the table 
 * use the CSS classes 'row' and 'altrow'
 *
 */
function alternateRows(table){
	for (var i=0; i < $(table).rows.length; i++) {
		if(i % 2 == 0)
			$(table).rows[i].className = 'altrow';
		else
			$(table).rows[i].className = 'row';
			
	};	
}

/*
 * Writes a debug message to the div 'debug.
 *
 */
function debug(string){
	// do not disturb the script
	if(!$('debug')){
		return;
	}
	
	$('debug').update(string);
}

function updateBackgroundImage(target, img){
	target.style.backgroundImage = 'url('+img+')';
}


/*
 * Creates a Prototype Ajax Request.
 * This method runs the Ajax Request, during the request it shows a update message,
 * On success it changes the text of the update message and hides it slowly
 *
 * Important: The Response must start with the string "success" or "failure"
 *
 * Options are:
 *
 *	options = {
 *   	 // The url for the ajax request
 *		'url'                       : '/admin/categories/asset/1/type:smth',
 *       
 *       // The method of the request get || post
 *		'method'                    : 'get',
 *
 *	     // The id of the div or span that shall displayed during the ajax request
 *		'update_container'          : 'message',
 *
 *       // The message to show during execution
 *		'update_message'            : 'Aktualisiere Verknüpfung',
 *
 *       // In case that smth does wrong
 *		'failure_message'           : 'Aktion ist fehlgeschlagen',
 *
 *       // Text for successful request
 *		'success_message'           : 'Aktion erfolgreich'
 *
 *       // Executes on success
 *		'callback_success'           : 'dosmth'
 *
 *       // Executes on failure
 *		'callback_failure'           : 'dosmth'
 *
 *       // Executes on failure
 *		'debug'           			: true
 *	}
 *	
 */
function ajaxUpdate(options){
	
	new Ajax.Request(options.url, {
		
		method: options.method,
	  	onSuccess: function(transport) {
		
			if(options.debug  != undefined && options.debug != false){
				debug(transport.responseText)
			}
		
			if(transport.responseText.startsWith('success')){
				$(options.update_container).highlight();
				$(options.update_container).update(options.success_message);
				$(options.update_container).fade({ duration: 2.5 });
				if(!options.callback_success  != undefined )
					eval(options.callback_success + "();");
			}else{
				//$('content').update(transport.responseText);
				alert(options.failure_message);
				if(options.callback_failure != undefined)
					eval(options.callback_failure + "();");
			}
			$(options.update_container).fade({ duration: 2.5 });
	  	},
		onFailure: function(transport){
			if(options.debug  != undefined && options.debug != false){
				debug(transport.responseText)
			}
			alert(transport.responseText);
		},
		onCreate: function(transport){
			$(options.update_container).show();
			$(options.update_container).update(options.update_message);
		}
	});
}

/*
 * Creates a Prototype Ajax Request for updating checkboxes.
 * Usually fired at the onclick event. This method runs the 
 * Ajax Request, during the request it shows a update message,
 * On success it changes the label of the checkbox and hides update message
 *
 * Important: The Response must start with the string "success" or "failure"
 *
 * Options are:
 *
 *	<script type="text/javascript" charset="utf-8">
 *
 *		options = {
 *			// The url for the ajax request
 *			'url' 						: '/admin/clients/toggle/' + <?= $client['Client']['id'] ?> + '/field:post_identified',
 *
 *          // The method of the request get || post
 *			'method'  					: 'get',
 *
 *	        // The Id of the checkbox
 *			'checkbox'  				: 'post_identified',
 *
 *           // The Id of the label that corresponds to the checkbox
 *			'checkbox_label'    		: 'post_identified_status',
 *
 *           // The value of the label when the checkbox is checked
 *			'checkbox_label_checked'    : 'Yes, we can',
 *
 *           // The value of the label when the checkbox is checked 
 *			'checkbox_label_unchecked'  : 'Sorry, we can not',
 *
 *          // The id of the div or span that shall displayed during the ajax request
 *			'update_container' 			: 'message_post_identified',
 *
 *			// Common failure message
 *			'failure_message'  			: 'Uuuhmmm something went wrong'
 *		}
 *	</script>
 *
 * A complete example:
 *
 *	<script type="text/javascript" charset="utf-8">
 *		options = {
 *			'url'                       : '/admin/clients/toggle/10/',
 *			'method'                    : 'get',
 *			'checkbox'                  : 'post_identified',
 *			'checkbox_label'            : 'post_identified_status',
 *			'checkbox_label_checked'    : 'Ja',
 *			'checkbox_label_unchecked'  : 'Nein',
 *			'update_container'          : 'message_post_identified',
 *			'failure_message'           : 'Aktion ist fehlgeschlagen'
 *		}
 *	</script>
 *	
 *	<input checked='checked' onclick="ajaxCheckbox(options)" type="checkbox" name="post_identified" value="1" id="post_identified">
 *	<span id="post_identified_status">Ja</span>
 *	<span id="message_post_identified" style="display: none">aktualisiere Posteingang...</div>
 *
 */
function ajaxCheckbox(options){

	new Ajax.Request(options.url, {
		method: options.method,
	  	onSuccess: function(transport) {
			//alert(transport.responseText);
			if(transport.responseText.startsWith('success')){
				if($(options.checkbox).checked){
					$(options.checkbox_label).update(options.checkbox_label_checked);
				}else{
					$(options.checkbox_label).update(options.checkbox_label_unchecked);
				}
				$(options.update_container).highlight();
			}else{
				alert(options.failure_message);
			}
			$(options.update_container).fade();
	  	},
		onFailure: function(transport){
			alert(options.failure_message);
		},
		onCreate: function(transport){
			$(options.update_container).show();
		}
	});	
}

// Utility function for scheduled operations
// currently is only the executeDelayed function implemented
var RctTimer = {

	// string that contains the callback function call.
	// e.g. myclass.doSmth()
	callback: null,
	
	// handle to prototypes PeriodicalExecuter
	pe: null,
	
	// private function
	// executes the callback and stops the timer
	executeOnce: function(pe){
		eval(RctTimer.callback);
		pe.stop();
	},
	
	// execute the function "callback" with a delay of "seconds"
	executeDelayed: function(callback, seconds){
		RctTimer.callback = callback;
		RctTimer.pe = new PeriodicalExecuter(RctTimer.executeOnce, seconds);
	}
	
}
