String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };


/*
 * Checks if browser is Internet Explorer
 * @author Tapio Savolainen
 */
function browserIsIE() {
	//should be pretty failsafe way to identify IE
	if(navigator.appName.toLowerCase().match('microsoft')) {
		return true;
	}
	return false;
}

function styleFixIE()
{
	if(browserIsIE()) //IE has serious issues with checkbox borders, remove them
	{
		$$('input[type=checkbox]').each(function(e) { e.setStyle({border: '0px solid black'}); });
		$$('input[type=radio]').each(function(e) { e.setStyle({border: '0px solid black'}); });
	}
}

/**
 * Handle custom date selection
 *
 * @author Markus Sytelä
 * @access public
 */
function customDates()
{
	var e = $('dateoptions');
	
	e.selectedIndex = e.length - 1;
	
	// Loop and match date_format in menu
	for (var i = 0; i < e.length; i++)
	{
		if (e.options[i].value == date_format)
		{
			e.selectedIndex = i;
			break;
		}
	}

	// Show/hide custom field
	if (e.selectedIndex == e.length - 1)
	{
		//showHide('custom_date', 1);
		$('custom_date').show();
	}
	else
	{
		//showHide('custom_date', -1);
		$('custom_date').hide();
	}

}

/** 
 * Redirects to given URL
 * 
 * @author Markus Sytelä
 * @access public
 * @param string url
 */
function redirect(url)
{
	window.location = url;
}

/**
 * Shows / hides selected div
 *
 * @author Markus Sytelä
 * @access public
 * @param string element
 * @param int status
 * @param string mode
 */
function showHide(element, status, mode)
{
	var element = $(element);

	if(element.visible() || mode === -1) 
		element.hide();
	else
	{
		if(mode) element.setStyle({display:mode});
		else element.show();
	}
}

/**
 * Asks user confirmation
 * @param field
 * @return
 */
function ask_confirmation(field, titles, messages, controls, urlBase)
{
	var action = $('action').getValue();

	// Check action type
	if (action != 'activate' && 
		action != 'disable' && 
		action != 'delete' && 
		action != 'meta_edit' &&
		action != 'class_edit')
	{
		return;
	}


	// Generate the URL
	var url = urlBase + action;
	var element = document.getElementsByName(field);
	
	var checkeds = 0;	
	for (var i = 0; i < element.length; i++)
	{
		if(element[i].checked)
		{
			checkeds++;
			url += '&' + field + '=' + element[i].value;
		}
	}
	
	if (action == 'class_edit')
	{
		url += '&class_id=' + $('class_edit').getValue();
	}
	
	if(checkeds == 0) {
		return;
	}
	
	var win = new Windows();
	win.confirm({msg: messages[action], title: titles[action], okLabel: controls['yes'], cancelLabel: controls['no'], onOk: url});
}

/**
 * Translates accented characters into ASCII equivalents,
 * optionally ignores öäå
 */
function strip_accents(str, scands) {
	/*
	 * TODO add more chars to be replaced, like ĆćĈĉČčĊċÇçḈḉȻȼƇƈɕ
	 */
	if(scands == undefined || scands == false) {
		//translate scandinavian chars too
		var s = "áàäãâåéèëêíìïîóòöõôøúùüûýÿ";
		var a = "aaaaaaeeeeiiiioooooouuuuyy";
	}
	else {
		//skip scandinavian chars (norweigian and danish people: I'm so sorry)
		var s = "áàãâéèëêíìïîóòõôøúùüûýÿ";
		var a = "aaaaeeeeiiiiooooouuuuyy";		
	}
	var size = s.length();
	for(var i = 0; i < size; i++) {
		str = str.replace(s.charAt(i), a.charAt(i));
		str = str.replace(s.toUpperCase().charAt(i), a.toUpperCase().charAt(i));
	}
	return str;
}

/**
 * checks if inspector and approver are set in a sane way.
 * because: inspector cannot publish content, so there's no
 * 		logical reason to set inspector while leaving approver
 * 		unset.
 * 
 * @param fieldInspector	id of inspector hiddenfield
 * @param fieldApprover		id of approver hiddenfield
 * @return boolean
 */
function check_workflow_sanity(fieldInspector, fieldApprover, errorToShow) 
{
	if(parseInt($(fieldInspector).getValue()) > 0 && parseInt($(fieldApprover).getValue()) == 0)
	{
		jQuery('#' + errorToShow).slideDown(animate_fast);
		return false;
	}
	jQuery('#' + errorToShow).slideUp(animate_fast);
	return true;
}

/**
 * Clears element from all childnodes.
 * @param e	Element we want cleansed!
 */
function clear_element(e) 
{
	if(e === undefined)
	{
		return;
	}
	
	while(e.hasChildNodes())
	{
		e.removeChild(e.firstChild);
	}
	
}
 
/**
 * Show an error for Ajax requests
 */
function ajax_failure(error)
{
	 if (error_occurred == true)
	 {
		 return;
	 }

	 if (win == undefined || !win)
	 {
		 var win = new Windows();
	 }

	 if (!error['title'] || !error['msg'])
	 {
		 error = ajax_failure_text;
	 }
	
	 win.confirm({msg: error['msg'], title: error['title'], okLabel: error['ok'], onOk: error['url']});
	 error_occurred = true;
}

/**
 * Prevents posting form when pressing ENTER key in given element
 */
function banEnterDud(event)
{
	var keyCode		= event.charCode || event.keyCode;
	var e			= Event.element(event);

	if (keyCode == Event.KEY_RETURN)
	{
		if(e.tagName.toLowerCase() === 'textarea')
			return;
		
		if(e.tagName.toLowerCase() === 'input' && e.getAttribute('type') === 'submit')
		{
			return;
		}

		event.stop();
	}
}
