/*
	Class:    	MooCard
	Version:  	1.0.4
	Built For:  MooTools 1.2
*/

var _RESIZE_DURATION 		= 400; 		// Duration of height and width resizing (ms)
var _INITIAL_WIDTH			= 250;		// Initial width of the box (px)
var _INITIAL_HEIGHT			= 250;		// Initial height of the box (px)
var _EVAL_SCRIPTS			= false;	// Option to evaluate scripts in the response text
var _EVAL_RESPONSE			= false;	// Option to evaluate the whole response text
var _CONTENTS_WIDTH 		= 500;		// Actual width of the box (px)
var _CONTENTS_HEIGHT		= 400;		// Actual height of the box (px)

var viewMode;
var sUrlControllerPage;

var MooCard = new Class({
	
	//implements
	Implements: [Options, Events],

	//options
	options: {
		yourOption: '',
		sUrlControllerPage: '',
		resizeDuration: 	_RESIZE_DURATION,
		initialWidth: 		_INITIAL_WIDTH,	
		initialHeight: 		_INITIAL_HEIGHT,
		contentsWidth: 		_CONTENTS_WIDTH,
		contentsHeight: 	_CONTENTS_HEIGHT,
		resizeTransition:	false,
		evalScripts: 		_EVAL_SCRIPTS,
		evalResponse: 		_EVAL_RESPONSE,
		viewMode:			false,
		sSite:				''
	},
	
	//initialization
	initialize: function(options) {

		//set options
		this.setOptions(options);

		this.eventPosition = this.position.bind(this);

		this.setup(true);

		// anchors moocard
		this.anchors = [];
		$A($$('a')).each(function(el){
			if(el.rel && el.href && el.rel.test('^MooCard', 'i')) {
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);

		// init

		// overlay 
		this.overlay = new Element('div').setProperty('id', 'mc_overlay').injectInside(document.body);
		this.overlay.setStyles({top: Window.getScrollTop()+'px', height: Window.getHeight()+'px'});

		this.overlay.set('opacity', '0');

		// add event listeners
		this.eventKeyDown = this.keyboardListener.bind(this);
		document.addEvent('keydown', this.eventKeyDown);
//		this.overlay.addEvent('click', this.close.bindWithEvent(this));

		// center element
		this.center = new Element('div').setProperty('id', 'mc_center').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);

		this.contents = new Element('div').setProperty('id', 'mc_contents').injectInside(this.center);
		this.contents.setStyle('opacity', '0');
		
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: new Fx.Tween(this.overlay,{property:'opacity',duration:500}).set(0),
			resize: new Fx.Morph(this.center, {duration: this.options.resizeDuration, transition: Fx.Transitions.Sine.easeOut, onComplete:nextEffect}),
			contents: new Fx.Tween(this.contents,{property:'opacity',duration:500, onComplete:nextEffect})
		};

		this.ajaxRequest = Class.empty;

		
		this.viewmode = this.options.viewMode;		// set viewmode
		this.firstview = this.options.firstView;	// first view?
		this.cardid = this.options.cardid;			// card id
		this.sSite = this.options.sSite;			// site id

		// url controller page
		this.sUrlControllerPage = this.options.sUrlControllerPage;

		// show stampnote only once
		this.showstampnote = 'true';
		if (this.viewmode == 'true') this.showstampnote = 'false';

	},


	click: function(link) {
		return this.open (link.href, link.title, link.rel);
	},

	setup: function(open) {
		
		var elements = $A($$('object'));
		elements.extend($$(window.ActiveXObject ? 'select' : 'embed'));
		elements.each(function(el){ el.style.visibility = open ? 'hidden' : ''; });
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		window[fn]('resize', this.eventPosition);

		this.step = 0;

	},

	open: function(sLinkHref, sLinkTitle, sLinkRel) {
		
		this.step = 0;
	
		this.href = sLinkHref;
		this.title = sLinkTitle;
		this.rel = sLinkRel;

		this.position();

//		this.top = Window.getScrollTop() + (Window.getHeight() / 15);
//		this.center.setStyles({top: this.top+'px', display: ''});
		
		this.center.setStyles({display: ''});

		// default stamp
		this.stampid = 'stamp-01';

		//new
		this.fx.overlay.start(0.8);

		return this.loadContents(sLinkHref);
	},

	position: function() {
//		alert("top: " + Window.getScrollTop());
//		alert("height: " + Window.getHeight());
		this.overlay.setStyles({top: Window.getScrollTop()+'px', height: Window.getHeight()+'px'});

		this.top = Window.getScrollTop() + (Window.getHeight() / 15);
		this.center.setStyles({top: this.top+'px'});

	},

	loadContents: function() {

		if(this.step) return false;
		this.step = 1;

		// check to see if there are specified dimensions
		// if not, fall back to default values
		var aDim = this.rel.match(/[0-9]+/g);
		this.options.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defContentsWidth;
		this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defContentsHeight;

		this.center.className = 'mc_loading';
		
		// AJAX call here
		var nextEffect = this.nextEffect.bind(this);
		var ajaxFailure = this.ajaxFailure.bind(this);

//alert(this.href + "&t=" + new  Date().getTime());

		this.ajaxRequest = new Request.HTML({
			method: 'get',
			url: this.href + "&t=" + new  Date().getTime(),
			update: this.contents,
			onRequest: function() { /*alert('Request made. Please wait...');*/ },
			onComplete: nextEffect,
			onFailure: ajaxFailure
		}).send();

		return false;
	},


	ajaxFailure: function (){
		alert("failure");
//		this.contents.setHTML('');
//		this.error.clone().injectInside(this.contents);
//		this.nextEffect();
//		this.center.setStyle('cursor', 'pointer');
//		this.bottom.setStyle('cursor', 'pointer');
//		this.center.onclick = this.bottom.onclick = this.close.bind(this);		
	},


	keyboardListener: function(event) {
		// close the MooCard on esc key
		// event = new Event (event);

		if ((event.key == 'esc')) {
			this.close();
			event.stop();
		}		
	},


	register: function() {
	
		this.cardmotif = $('mc_card_motif');
		this.navfront = $('ecard-vorderseite-navigation-div');

		// Link Close
		this.linkclose = $('mc_link_close');
		this.linkclose.addEvent('click', this.close.bindWithEvent(this));

		this.linkcloseback = $('mc_link_close_back');
		this.linkcloseback.addEvent('click', this.close.bindWithEvent(this));

		// Link Back
		this.divback		= $('ecard-rueckseite-div');
		this.linkshowback	= $('mc_link_back');
		this.linkshowback.addEvent('click', this.ShowBack.bindWithEvent(this));

		// Link Front
		this.linkshowfront	= $('mc_link_front');
		this.linkshowfront.addEvent('click', this.ShowFront.bindWithEvent(this));

		// Send Card
		this.sendcard		= $('mc_send');

		this.stampnote = $('ecard-rueckseite-briefmarken-hinweis-div');

		// Stamp
		this.stamp			= $('stamp');

		if (this.viewmode == 'false') {

			// Send Card/Event
			this.sendcard.addEvent('click', this.SendCard.bindWithEvent(this));

			// Add click event if not ie6
			if (!Browser.Engine.trident4) this.stamp.addEvent('click', this.SelectStamp.bindWithEvent(this));
			this.stampdiv		= $('ecard-rueckseite-briefmarken-auswahl-outer-div');

		} else {

			this.sendcard.style.visibility = 'hidden';
			this.stamp.style.cursor = 'default';

		}

		// error
		this.alert			= $('error');


		if (Browser.Engine.trident4) {	// IE6
				this.stamp.style.cursor = 'default';
		}


	},


	ShowFront: function() {

		this.divback.set('tween', {duration: '300'});
		this.divback.tween('opacity', [1, 0]);

//		this.stampnote.style.visibility = 'hidden';
		
		return false;
	},


	ShowBack: function() {

		this.divback.style.opacity = 0;
		this.divback.style.visibility = 'visible';

		this.divback.set('tween', {duration: '300', onComplete: this.ShowStampHint()});
		this.divback.tween('opacity', [0, 1]);

		return false;
/*
		this.divback.style.opacity = 0;
		this.divback.style.visibility = 'visible';

		var fx_divback = new Fx.Tween(this.divback, {
			property: 'opacity',
			duration: 300, 
//			onComplete: this.ShowStampHint(),
			transition: Fx.Transitions.Quart.easeInOut
		});

		fx_divback.start.pass([0,1], fx_divback);
*/

	},


	ShowStampHint: function() {

		if (this.showstampnote == 'true') {

			this.stampnote.style.visibility = 'visible';

			// fade out note
			this.note_fx = new Fx.Tween(this.stampnote, {
				property: 'opacity',
				duration: 500, 
				transition: Fx.Transitions.Quart.easeInOut
			});

			this.note_fx.start.pass([1,0], this.note_fx).delay(5000);	// wait 5 sec, then fade it out

			this.showstampnote = 'false';
		}

	},

	HideStampHint: function() {
//		this.stampnote.style.visibility = 'hidden';
	},


	SendCard: function(mode) {

		var sError = this.DoChecks();

//		this.cardmotif.style.opacity	= 0;
//		this.navfront.style.opacity		= 0;
//		this.divback.style.opacity		= 0.2;

		this.cardmotif.setStyle('opacity', 0);
		this.navfront.setStyle('opacity', 0);
		this.divback.setStyle('opacity', 0.2);

		this.alert.style.display = 'block';
		this.alert.style.opacity		= 1;

		if (sError != '') {

			this.alert.set('html', sError);

			this.closealert		= $('close_alert');
			this.closealert.addEvent('click', this.CloseAlert.bindWithEvent(this));
			
			return false;
		}

		// Hide buttons
		this.sendcard.style.visibility = 'hidden';
		this.linkcloseback.style.visibility = 'hidden';
		this.linkshowfront.style.visibility = 'hidden';

		// AJAX call

		var ajaxFailure = this.ajaxFailure.bind(this);
		var DoSend = this.DoSend.bind(this);
		var sendSuccess = this.sendSuccess.bind(this);

//		href = 'http://dev2.columbus-interactive.de/modules/moocard/index.php?m=send';
		href = this.sUrlControllerPage + '?m=send&s=' + this.sSite;

		// get data
		var aCard = this.cardmotif.src.split("/");
		var sCard = aCard[aCard.length - 1];

		this.ajaxRequest = new Request.HTML({
			method: 'post',
			url: href,
			data: {'fn_from': $('fn_from').value, 'ln_from': $('ln_from').value, 'mail_from': $('mail_from').value, 'fn_to': $('fn_to').value, 'ln_to': $('ln_to').value, 'mail_to': $('mail_to').value, 'card': sCard, 'stamp': this.stampid + ".png", 'text': $('mc_text').value},
			update: this.alert,
			onRequest: DoSend,
//			onRequest: function() { /*alert('Request made. Please wait...');*/ },
			onComplete: sendSuccess,
//			onComplete: function()	{ alert('huhu'); },
//			onComplete: function(response) {alert(response);},
			onFailure: ajaxFailure
		}).send();


		return false;
	},


	DoChecks: function() {

		var sReturn = '<b style="color:#ee0000;">Es sind Fehler aufgetreten</b><br /><br />';
		var bError = false;

		var fnfrom = $('fn_from');
		if (fnfrom.value == '')	{
			bError = true;
			sReturn += 'Bitte Vorname des Absenders angeben! <br />';
		}

		var lnfrom = $('ln_from');
		if (lnfrom.value == '')	{
			bError = true;
			sReturn += 'Bitte Nachname des Absenders angeben! <br />';
		}


		var mailfrom = $('mail_from');
		if (mailfrom.value == '')	{
			bError = true;
			sReturn += 'Bitte die E-Mail des Absenders angeben! <br />';
		} else {
			if (!this.CheckEmail(mailfrom.value))	{
				bError = true;
				sReturn += 'Bitte prüfen Sie die E-Mail des Absenders! <br />';
			}
		}

		var fnto = $('fn_to');
		if (fnto.value == '')	{
			bError = true;
			sReturn += 'Bitte Vorname des Empfängers angeben! <br />';
		}

		var lnto = $('ln_to');
		if (lnto.value == '')	{
			bError = true;
			sReturn += 'Bitte Nachname des Empfängers angeben! <br />';
		}

		var mailto = $('mail_to');
		if (mailto.value == '')	{
			bError = true;
			sReturn += 'Bitte die E-Mail des Empfängers angeben! <br />';
		} else {
			if (!this.CheckEmail(mailto.value))	{
				bError = true;
				sReturn += 'Bitte prüfen Sie die E-Mail des Empfängers! <br />';
			}
		}

		var msg = $('mc_text');
		if (msg.value == '')	{
			bError = true;
			sReturn += 'Bitte eine Nachricht angeben! <br />';
		} 

		sReturn += '<br /><br /><a href="#" id="close_alert" style="z-index:999;">Fehlermeldung schließen</a>';

		if (!bError) {
			sReturn = '';
		}

		return sReturn;
	},


	CheckEmail: function(sEmail) {

		var regEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		if (!regEx.test(sEmail)) {
			return false;
		}

		return true;
	},

	DoSend: function() {

		this.wait = $('wait');
		this.wait.style.display = 'block';

	},


	sendSuccess: function() {

		this.wait.style.display = 'none';

		// register link close_card
		this.closecard = $('close_card');
		this.closecard.addEvent('click', this.close.bindWithEvent(this));

	},


	CloseAlert: function() {
		this.alert.style.display	= 'none';

//		this.divback.style.opacity	= 1;
		this.divback.setStyle('opacity', 1);

//		this.cardmotif.style.opacity	= 1;
//		this.navfront.style.opacity		= 1;
		this.cardmotif.setStyle('opacity', 1);
		this.navfront.setStyle('opacity', 1);

		return false;

	},


	nextEffect: function() {

		switch (this.step++){
		case 1:

			this.center.className = '';

			if (this.center.clientHeight != this.contents.offsetHeight){
				this.fx.resize.start({height: this.options.contentsHeight});
				break;
			}

			this.step++;

		case 2:

			if(this.center.clientWidth != this.contents.offsetWidth) {
				this.fx.resize.start({width: this.options.contentsWidth, marginLeft: -this.options.contentsWidth/2});
				break;
			}

			this.step++;

		case 3:
			this.contents.setStyles({'width': this.options.contentsWidth+'px', 'height': this.options.contentsHeight+'px'});

			this.fx.contents.start(1);
			this.step = 0;
//			break;
		case 4:
			this.register();

		case 5:

		if (this.firstview == '1') {

			href = this.sUrlControllerPage + '?m=fv&id=' + this.cardid + '&s=' + this.sSite;

			this.ajaxRequest = new Request.HTML({
				method: 'get',
				url: href + "&t=" + new  Date().getTime(),
//				update: this.contents,
				onRequest: function() { /*alert('Request made. Please wait...');*/ },
				onComplete: function(response) { /*alert(response);*/ }
//				onFailure: ajaxFailure
			}).send();

		}
//			if (this.activeImage) this.prevLink.style.display = '';
//			if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
//			this.step = 0;
		}
	},


	SelectStamp: function() {
//		alert("Select Stamp");
		this.stampdiv.style.visibility = 'visible';

		this.aStamps = $$('img.stamp');
		iCount = this.aStamps.length;

		for (i=0; i<iCount; i++) {
			this.aStamps[i].addEvent('click', this.ChangeStamp.bindWithEvent(this, this.aStamps[i]));
		}

	},


	ChangeStamp: function(ev, element) {

//alert(element.id);
//alert(this.stamp.src);

		this.stamp.src = element.src;
		this.stampdiv.style.visibility = 'hidden';

		this.stampid = element.id;

		return false;
	},

	close: function() {

		// remove
//		this.center.setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'})

		this.center.style.display = 'none';

		this.contents.set('text', '');

		// fade overlay out
		this.overlay.set('tween', {duration: '500'});
		this.overlay.tween('opacity', [0.8, 0]);

		// remove events
		document.removeEvent('keydown', this.eventKeyDown);

		this.step = 0;

		if (this.viewmode == 'true') {
			this.viewmode = 'false';
			this.firstview = '0';
		}

		return false;
	}

});

/*
//once the DOM is ready
window.addEvent('domready', function() {

});
*/