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

function setCookie(name, value,	expires, path, domain, secure)
{
	document.cookie	= name + "=" + escape(value) +
		((expires) ? ";	expires=" +	expires.toGMTString() :	"")	+
		((path)	? "; path="	+ path : "") +
		((domain) ?	"; domain="	+ domain : "") +
		((secure) ?	"; secure" : "");
}

function isValidDate(mydate)
{
	return mydate.match(/^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/);
}

function is_email(email)
{
	var	reg	= /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]{2,}[.][a-zA-Z0-9]{2,4}$/
	var	reg2 = /[.@]{2,}/
	return ((reg.exec(email)!=null)	&& (reg2.exec(email)==null))
}

function getCheckedValue(radioObj)
{
	if (!radioObj)
	{
		return "";
	}

	var radioLength = radioObj.length;

	if (radioLength == undefined)
	{
		if (radioObj.checked)
		{
			return radioObj.value;
		}
		else
		{
			return "";
		}
	}
	for(var i = 0; i < radioLength; i++)
	{
		if (radioObj[i].checked)
		{
			return radioObj[i].value;
		}
	}

	return "";
}

function setCheckedValue(radioObj, newValue)
{
	if (!radioObj)
	{
		return;
	}

	var radioLength = radioObj.length;

	if (radioLength == undefined)
	{
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}

	for (var i = 0; i < radioLength; i++)
	{
		radioObj[i].checked = false;

		if (radioObj[i].value == newValue.toString())
		{
			radioObj[i].checked = true;
		}
	}
}

function getSelectedValue(selectObj)
{
	if (!selectObj)
	{
		return "";
	}

	return selectObj[selectObj.selectedIndex].value;
}

function setSelectedValue(selectObj, newValue)
{
	if (!selectObj)
	{
		return "";
	}

	for (var i=0; i < selectObj.length; i++)
	{
		if (selectObj[i].value == newValue)
		{
			selectObj[i].selected = true;
		}
	}
}

function checkImages(obj)
{
	if (!obj) obj = document;
	var images = obj.getElementsByTagName('img');
	var badImg = new Image();
	badImg.src = 'img/img-error.png';
	for (var i=0; i<images.length; i++)
	{
		var cpyImg = new Image();
		cpyImg.src = images[i].src;
		if (!cpyImg.height)
		{
		debugger;
			images[i].src = badImg.src;
		}
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;

	while (rgx.test(x1))
	{
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}

	return x1 + x2;
}

function formatPrice(price)
{
	if (price > 0)
	{
		return addCommas(price.toFixed(2)) + " &euro;";
	}
	else
	{
		return '-';
	}
}

//Recalcular precios y hacer que todos los selects de régimen de un hotel mantengan el mismo valor
function calculateHotelForm(form, changedBoard)
{
	if (!typeof form == 'object') return false;

	var quantities = $(form).select('select[name="quantity[]"]');
	var boards = $(form).select('select[name="board[]"]');
	var prices = $(form).select('span.precio');

	if (typeof changedBoard != 'object' && typeof boards[0] == 'object')
		changedBoard = boards[0];

	for (var i = 0; i < boards.length; i++)
	{
		if (typeof changedBoard == 'object' && boards[i] != changedBoard)
		{
			boards[i].selectedIndex = changedBoard.selectedIndex;
			if (typeof boards[i].updateReplacement == 'function') //selectReplacement.js
				boards[i].updateReplacement();
		}
		var price = parseFloat(boards[i].options[boards[i].selectedIndex].title);

		prices[i].update(formatPrice(parseFloat(price * $F(quantities[i]))));
	}
}

/**
*  Javascript string pad
*  http://www.webtoolkit.info/
**/
function pad(str, len, pad, dir) {

	var STR_PAD_LEFT = 1;
	var STR_PAD_RIGHT = 2;
	var STR_PAD_BOTH = 3;

	 str = String(str);
    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = STR_PAD_LEFT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case STR_PAD_BOTH:
                var right = Math.ceil((padlen = len - str.length) / 2);
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;

}

/* Ventanas popup */
var Popup =
{
	open: function(options)
	{
		this.options =
		{
			url: '#',
			title: '',
			scrollbars: 1,
			width: 300,
			height: 300,
			centered: true,
			top: 100,
			left: 100
		}

		Object.extend(this.options, options || {});

		if (this.options.centered)
		{
			this.options.top = screen.height/2-this.options.height/2;
			this.options.left = screen.width/2-this.options.width/2;
		}

		window.open(this.options.url, this.options.title, 'scrollbars='+this.options.scrollbars+',width='+this.options.width+',height='+this.options.height+',top='+this.options.top+',left='+this.options.left);
	}
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup)
{
	if ($(el).type && $(el).type.toLowerCase() == 'radio')
	{
		var radioGroup = $(el).name;
		var el = $(el).form;
	}
	else if ($(el).tagName.toLowerCase() != 'form')
	{
		return false;
	}

	var checked = $(el).getInputs('radio', radioGroup).find
	(
		function(re) {return re.checked;}
	);

	return (checked) ? $F(checked) : null;
}

/**
 * Ajax.Request.abort
 * extend the prototype.js Ajax.Request object so that it supports an abort method
 * http://blog.pothoven.net/2007/12/aborting-ajax-requests-for-prototypejs.html
 */
Ajax.Request.prototype.abort = function() {
	// prevent and state change callbacks from being issued
	this.transport.onreadystatechange = Prototype.emptyFunction;
	// abort the XHR
	this.transport.abort();
	// update the request counter
	if (this.options['onFailure']) {
		this.options['onFailure'](this.transport, this.json);
	}
	if (Ajax.activeRequestCount > 0) {
		Ajax.activeRequestCount--;
	}
};

/**
 *	AFFILIATES
 */
function validateAffiliate(event)
{
	var error = false;
	var msg = _aff_msg;
	if ($('affiliate_action').value == "disconnect") return true;

	if (!$F('affiliate_password').trim())
	{
		if (Scriptaculous) new Effect.Highlight($('affiliate_password'), {restorecolor:'#ffffff'});
		$('affiliate_password').focus();
		error = true;
	}
	if (!$F('affiliate_user').trim())
	{
		if (Scriptaculous) new Effect.Highlight($('affiliate_user'), {restorecolor:'#ffffff'});
		$('affiliate_user').focus();
		error = true;
	}

	return !error;
}

function showAffiliateLogin()
{
	if (Effect.Queue.effects.length) return;

	var focusUser = false;
	if (!$('affiliate-login').visible())
	{
		$('affiliate_user').value = '';
		$('affiliate_password').value = '';
		focusUser = true;
	}
	new Effect.toggle($('affiliate-login'), 'slide', {
		duration:0.4,
			afterFinish:function() {if (focusUser) $('affiliate_user').focus();}
		});
}

function disconnectAffiliate()
{
	$('affiliate_user').value == "";
    $('affiliate_password').value == ""
    $('affiliate_action').value = "disconnect";
    $('affiliates-login-form').submit();
}