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
		);
	}
}

var infoBox =
{
	init: function(name)
	{
		var container = new Element('div', {id:'infoBox_'+name, className:'infoBoxContainer'});
		var iframe = new Element('iframe');
		var content = new Element('div', {className:'infoBoxContent'});

		container.setStyle({
			display: 'none', width: '60em', height: '20em', position: 'absolute'
		});

		iframe.setStyle({
			width: '100%', height: '100%', border: '0', position: 'absolute', zIndex: 1
		});

		content.setStyle({
			position: 'absolute', zIndex: 2
		});

		container.insert(iframe).insert(content);

		$$('body')[0].insert(container);

		//Hacer la ventana arrastrable
		new Draggable(container, {
			scroll:window,
			starteffect:null,
			endeffect:null,
			onStart:container.setOpacity.bind(container,0.75),
			onEnd:container.setOpacity.bind(container,1)
		});

		return container;
	},

	open: function(name, url, position)
	{
		//Crear la ventana con los valores por defecto
		var container = $('infoBox_'+name);

		if (!container)
		{
			container = infoBox.init(name);

			var content = container.down('div');

			//Posicionarla junto al elemento que hizo el click
			if (parseInt(position['left']) && parseInt(position['top']))
			{
				container.setStyle({left:position['left']+30+'px', top:position['top']-50+'px'});
			}

		}
		else
		{
			var content = container.down('div');
			content.setOpacity(0.2);
		}


		//Rellenar la ventana con la petición ajax
		new Ajax.Request(url, {
			onSuccess:function(transport){
				if (transport.responseText)
				{
					content.setOpacity(1);
					content.update(transport.responseText);
					var resizeDuration = container.visible() ? 0.5 : 0;
					container.show();

					//Poner el ancho y alto de la ventana igual al del nuevo contenido
					//Si la ventana es nueva no hay efecto
					var dimensions = content.down().getDimensions();
					new Effect.Morph(container, {
						style:{
							width:dimensions['width']+2+'px',
							height:dimensions['height']+2+'px'
						},
						duration: resizeDuration
					});
					new Effect.Morph(content, {
						style:{
							width:dimensions['width']+'px',
							height:dimensions['height']+'px'
						},
						duration: resizeDuration
					});

					//Evento de cierre del botón close, si lo hay
					content.select('a.close').invoke('writeAttribute', 'href','#').invoke('observe', 'click', function(event){ container.remove(); event.stop(); });
				}
			}
		});
	},

	close: function(name)
	{
		var container = $('infoBox_'+name);
		if (container) container.remove();
	}
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
	{
		var expires = "";
	}

	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for (var i=0;i < ca.length;i++)
	{
		var c = ca[i];

		while (c.charAt(0)==' ')
		{
			c = c.substring(1,c.length);
		}

		if (c.indexOf(nameEQ) == 0)
		{
			return c.substring(nameEQ.length,c.length);
		}
	}

	return null;
}

function eraseCookie(name)
{
	createCookie(name, "", -1);
}

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

String.prototype.isAlpha = function()
{
	return /^[a-zA-Z]+$/.test(this);
}

String.prototype.isAlphaNum = function()
{
	return !/\W/.test(this);
}

String.prototype.isFloat = function()
{
	return /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/.test(this);
}

String.prototype.isEmail = function()
{
	return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(this);
}

String.prototype.isDate = function()
{
	return /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(this);
}

String.prototype.isDateTime = function()
{
	// Comprueba una fecha con hora opcional y segundos opcionales
	return /^(\d{1,2}\/\d{1,2}\/\d{4})?\s?(\d{2}:\d{2}(:\d{2})?)?$/.test(this);
}

String.prototype.isTime = function()
{
	return /^\d{1,2}:\d{2}$/.test(this);
}

String.prototype.isUrl = function()
{
	return /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(this);
}

String.prototype.isNumeric = function()
{
	return (!isNaN(this) && !/^\s+$/.test(this));
}

String.prototype.isCreditCard = function(cardType)
{
	var cardNumber = this.replace(/[^\d]/g, "");
	var isValid = false;

	switch (cardType)
	{
		case "mastercard" :

			isValid = /^5[1-5][0-9]{14}$/.test(cardNumber);
			break;

		case "visa" :

			isValid = /^4[0-9]{12}(?:[0-9]{3})?$/.test(cardNumber);
			break;

		case "amex" :

			isValid = /^3[47][0-9]{13}$/.test(cardNumber);
			break;

		case "diners" :

			isValid = /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/.test(cardNumber);
			break;

		case "discover" :

			isValid = /^6(?:011|5[0-9]{2})[0-9]{12}$/.test(cardNumber);
			break;

		case "jcb" :

			isValid = /^(?:2131|1800|35\d{3})\d{11}$/.test(cardNumber);
			break;
	}

	if (isValid)
	{
		var numberProduct;
		var numberProductDigitIndex;
		var checkSumTotal = 0;

		for (var digitCounter = cardNumber.length - 1; digitCounter >= 0; digitCounter--)
		{
			checkSumTotal += parseInt(cardNumber.charAt(digitCounter));
			digitCounter--;
			numberProduct = String((cardNumber.charAt(digitCounter) * 2));

			for (var productDigitCounter = 0; productDigitCounter < numberProduct.length; productDigitCounter++)
			{
				checkSumTotal += parseInt(numberProduct.charAt(productDigitCounter));
			}
		}

		isValid = (checkSumTotal % 10 == 0);
	}

	return isValid;
}

String.prototype.toDate = function()
{
	if(!this.isDate())
	{
		return null;
	}

	var date_s = this.split("/");
	var new_date = [date_s[1],date_s[0],date_s[2]];

	// Formato mm/dd/yyyy
	var dDate = new Date(new_date.join("/"));

	return dDate;

}

String.prototype.toDateTime = function()
{
	if(!this.isDateTime())
	{
		return null;
	}

	var newdate = /(?:(\d{1,2})\/(\d{1,2})\/(\d{4}))?\s?(?:(\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(this);

	for(var i=1; i < newdate.length; i++)
	{
		if (typeof newdate[i] != "string")
		{
			newdate[i] = "0";
		}
	}

	var returndate = new Date(newdate[3], newdate[2], newdate[1], newdate[4], newdate[5], newdate[6]);

	return returndate;
}

String.prototype.getDaysBetween = function(d)
{
	if(!d.isDate() || !this.isDate())
	{
		return;
	}

	var date2 = d.toDate();
	var date1 = this.toDate();

	return date1.getDaysBetween(date2);

}

Date.prototype.copy = function ()
{
	return new Date(this.getTime());
}

Date.prototype.getDaysBetween = function(d)
{
	var msPERDAY = 1000 * 60 * 60 * 24;
	var tmp = d.copy();
	tmp.setUTCHours(this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds(), this.getUTCMilliseconds());

	var time = tmp.getTime() - this.getTime();
	return time/msPERDAY;
}

Date.prototype.addDays = function(d)
{
	this.setDate(this.getDate() + parseInt(d, 10));
	return this;
}

Date.prototype.toStrDate = function()
{
	var day = parseInt(this.getDate(), 10);
	var month = parseInt(this.getMonth(), 10)+1;

	return (day < 10 ? "0"+day : day) + "/" + (month < 10 ? "0"+month : month) + "/" + this.getFullYear();
}