/* eye-candy-functions */
var InputDescription = Class.create({
	id: null,
	originalType: 'text',
	description: null,
	elem: null,
	descActive: false,	
	initialize: function (input_elem, desc_text) {
		this.elem = $(input_elem);
		this.id = this.elem.getAttribute('id');
		this.description = desc_text;
		this.originalType = this.elem.readAttribute('type');
		this.showDescription();
		this.elem.observe('focus', this.removeDescription.bind(this));
		this.elem.observe('blur', this.showDescription.bind(this));
	},
	showDescription: function () {
		var currentVal = $F(this.id);
		if (currentVal.length == 0 ||
				currentVal == this.description) {
			// Changing the input-type in IE does not work :-( TODO: replacement via DOM
			//this.elem.writeAttribute({'type': 'text'});
			this.elem.addClassName('input-description');
			this.elem.setValue(this.description);
			this.descActive = true;
		}
	},
	removeDescription: function () {
		if (this.descActive) {
			//this.elem.writeAttribute({'type': this.originalType});
			this.elem.removeClassName('input-description');
			this.elem.clear();
		}
	}
	
	
});

/* universal popup/lightbox window which loads content by ajax.
	 can be misused to display static content: if url is null, then token is inserted as string into the box. */
var ModalDialog = {
	id: null,
	box: null,
	show: function(url, token, width, height) {
		if (this.id != null) {
			this.close();
		}
		Flash.clear();
		body = $(document.body);

		this.id = 'modal-dialog-window';
		document.body.insert("<div id='lb-shadow'></div><div id='" + this.id + "' class='lb-container'>"+
								"<table width='100%' height='100%'><tr><td align='center' valign='center'><img src='/images/spin_big.gif' /></td></tr></table></div>");
		$('lb-shadow').setStyle(
				{ width: body.getWidth() + "px", 
				//height: document.viewport.getHeight() + "px" }).
				height: body.getHeight() + "px" }).
			observe('click', function() { this.close(); }.bind(this));
		//Effect.Appear('lb-shadow');
		this.box = $(this.id);
		/*x = (viewport.getWidth() - this.box.getWidth()) / 2;
		y = (viewport.getHeight() - this.box.getHeight()) / 2;
		this.box.setStyle({ left: x + "px", top: y + "px" });*/
		this.center();
		
		if (url != null) {
			new Ajax.Updater(this.id, url, {onComplete: function() { ModalDialog.center(); }, asynchronous:true, evalScripts:true , parameters:'authenticity_token=' + encodeURIComponent(token)
				               });
		} else {
			$(this.id).update(token).insert({ 'top' : '<a href="#" id="modal-dialog-close">Close</a>'});
			$('modal-dialog-close').observe('click', function () { this.close(); }.bind(this));
			$(this.id).setStyle({ 'width': width + 'px', 'height': (height + 30)+ 'px'});
			window.setTimeout(function () { this.center(); }.bind(this), 100);
//			this.center();
		}
	},

	center: function()  {
		viewport = $(document.viewport);
		x = (viewport.getWidth() - this.box.getWidth()) / 2 + (viewport.getScrollOffsets()["left"]);
		y = (viewport.getHeight() - this.box.getHeight()) / 2 + (viewport.getScrollOffsets()["top"]);
		this.box.setStyle({ left: x + "px", top: y + "px" });
	},
	
	close: function() {
		Effect.Fade('lb-shadow', {
						duration: 0.5, 
						afterFinish: function() {
            	$('lb-shadow').remove();
        		} });
		Effect.BlindUp(this.id, { 
		        duration: 0.5,
						afterFinish: function() {
            	$(this.id).remove();
							this.id = null;
        		}.bind(this) });
	}
};

var VideoLightbox = Class.create({
	embedded: null,
	width: 640,
	height: 480,
	initialize: function(element) {
		var vid_id = element.readAttribute('data-youtube');
		this.embedded = '<object width="' + this.width + '" height="' + this.height + '">' +
										'<param name="movie" value="http://www.youtube.com/v/' + vid_id + '&hl=de_DE&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999">' +
										'</param>' +
										'<param name="allowFullScreen" value="true"></param>' +
										'<param name="allowscriptaccess" value="always"></param>' +
										'<embed src="http://www.youtube.com/v/' + vid_id + '&hl=de_DE&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + this.width + '" height="' + this.height + '"></embed>' + 
										'</object>'

		var link = element.wrap('a', { 'href': '#', 'class': 'yt-thumb' })
		link.insert( { 'bottom' : '<div>' + element.readAttribute('data-description') + '</div>' });
		if (element.hasClassName('last')) { link.addClassName('last'); }
		link.observe('click', function () {
			ModalDialog.show(null, this.embedded, this.width, this.height);
		}.bind(this));
	}
});

/* methods for inserting a flash-message after the page has loaded */
var Flash = {
	display: function(t, msg) {
		this.clear();
		f = $('flash-js');
		f.insert({ after: new Element('div', {id: 'flash-' + t}).update(msg) });
	},
	clear: function() {
		var notice = $('flash-notice');
		var error = $('flash-error');
		if (notice) { notice.remove(); }
		if (error) { error.remove(); }
	}
}

var EventMenu = Class.create({
	menuDiv: null,
	eventId: null,
	currentTimer: null,
	isOpen: false,
	insideMenu: false,
	insideEv: false,
	replySpace: null,
	initialize: function(eventId, enableHover) {
		this.eventId = eventId;
		this.menuDiv = $('evm-' + eventId);
		this.replySpace = $('ev-reply-' + eventId);
		ev = $('ev-' + eventId);

		if (enableHover) {
			Event.observe(this.menuDiv, 'mouseover', function(event) {	this.insideMenu = true;	}.bind(this));	
			Event.observe(this.menuDiv, 'mouseout', function(event) {	this.insideMenu = false; }.bind(this));


			Event.observe(ev, 'mouseover', function(event) {
				this.insideEv = true;
				this.showMenu();
		  	//this.currentTimer = setTimeout(this.showMenu.bind(this),500);

			}.bind(this));	
			Event.observe(ev, 'mouseout', function(event) {
				//clearTimeout(this.currentTimer);
		 	  //this.currentTimer = setTimeout(this.hideMenu.bind(this),500);
				if (!this.insideMenu) { this.insideEv = false; this.hideMenu(); }
			}.bind(this));
		}

	},
	showMenu: function () {
		this.menuDiv.show();
	},
	hideMenu: function () {
		this.menuDiv.hide();
	},
	busy: function(show) {
		$('ev-submit-' + this.eventId).toggle();
		$('ev-submit-busy-' + this.eventId).toggle();
	},
	showComments: function(show) {
		var rc = $("ev-reply-counter-" + this.eventId);
		$('ev-replies-show-' + this.eventId).toggle();
		$('ev-replies-hide-' + this.eventId).toggle();
		tl = $('timeline');
		if (show) {
			if (rc) { Effect.BlindUp(rc, { duration: 0.5 }); }
			Effect.BlindDown("ev-replies-" + this.eventId);			

			// timeline-tag only exists in chat-window, then scroll
			// to make comment-field visible
			if (tl) {
				h = $('ev-' + this.eventId).viewportOffset()[1];
				if (h > 0) { new Effect.Tween(tl, tl.scrollTop, h, 'scrollTop'); }
			}
		} else {
			if (rc) { Effect.BlindDown(rc); }
			Effect.BlindUp("ev-replies-" + this.eventId);
			if (tl) {	new Effect.Tween(tl, tl.scrollTop, 0, { delay: 1.0 }, 'scrollTop');	}
		}
	},
	insertComment: function(request) {
		var rid = "anim" + Math.floor(Math.random() * 10000);
		this.replySpace.insert({ 'bottom': 
					'<div id="' + rid + '" style="display: none;">' + request.responseText + '</div>'});
		Effect.BlindDown(rid);
		$('ev-input-' + this.eventId).clear();
	}
});


var OrderHighlighter = Class.create({
	orders: null,
	initialize: function(id) {

		//this.orders = $$('.' + id);
		this.orders = $$('tr[data-ticket-hash=' + id + ']');
		this.orders.each(
			function (e) { 

				e.observe('mouseover', 
					function (event) { this.orders.invoke("addClassName", "hl"); }.bind(this))

				e.observe('mouseout', 
					function (event) { this.orders.invoke("removeClassName", "hl"); }.bind(this))


			}.bind(this)
		);
	}
});


/* Show native order id and raw data for account managers */
var AdminOrderDetails = Class.create({
	order_id: null,
	initialize: function(element) {
		this.order_id = element.getAttribute('data-order-id');
		html = new Element('div', { 'style': 'position: relative'}).appendChild(new Element('div', { 'class': 'admin order-details',
			'id': 'order-details-' + this.order_id, 'style': 'display: none;' }))
		element.insert({ after: html });
		details = element.getAttribute('data-order-details').evalJSON(true);
		$('order-details-' + this.order_id).update(
			'Order ID: ' + this.order_id + '<br />' +
			'ext_order_id: ' + details.ext_order_id + '<br />' +
			'ext_ticket_id: ' + details.ext_ticket_id + '<br />' +
			'amount: ' + details.lots + '<br />'
		);
		element.observe('mouseover', 
			function (event) { $('order-details-' + this.order_id).show(); }.bind(this));
		element.observe('mouseout', 
			function (event) { $('order-details-' + this.order_id).hide(); }.bind(this));
		element.observe('click', 
			function (event) { window.location.href = '/admin/orders/show/' + this.order_id }.bind(this));

	}
});

/*
	is called when user opens the signup form.
	detect the time zone with javascript and set the
	selection box accordingly.
*/
function predictTimeZoneOnSignup() {
	var d = new Date();
	// try to detect dst- lets look at the tz offset in 6 months...
	var d_dst = new Date("1/" + (1 + (d.getUTCMonth() + 5) % 12) + '/' + d.getUTCFullYear());
	var hours_off = Math.max(d.getTimezoneOffset(), d_dst.getTimezoneOffset()) / 60;
	var tzstr = '(GMT' + (hours_off > 0 ? "-" : "+");
	hours_off = Math.abs(hours_off);
	// yes, this breaks for exotic time zones which aren't on hourly boundaries, i.e. Newfoundland
	tzstr += (hours_off > 9 ? hours_off : "0" + hours_off) + ":00" + ')'

	var tzselect = $('user_time_zone_id');
	for (var i = 0; i < tzselect.length; i++) {
		if (tzselect.item(i).innerText.substr(0, 11) == tzstr) {
			tzselect.selectedIndex = i;
			return;
		}
	}
}


var QuoteRefresher = {
	quoteElements: null,
	quotes: null,
	c: 0,
	setup: function () {
	 	this.quoteElements = $$('span[data-quote-id]');
	 	if (this.quoteElements.length > 0) {
			// Refresh only once per Minute- nobody uses this anyway
		 	new PeriodicalExecuter(function () {this.refresh();}.bind(this), 60);
			this.refresh();
		}
	},
	refresh: function () {
		new Ajax.Request('/quotes', { method: 'get',
			onSuccess: function(transport) {
					this.quotes = transport.responseText.evalJSON();
					if (this.quotes == null) { return; }
					this.quoteElements.each(function (e) {
						if (e.getAttribute('data-offset')) {
							this._refreshProfit(e);
						} else {
							this._refreshQuote(e);
						}
					}.bind(this));

				}.bind(this)
			});
	},
	_refreshQuote: function(e) {
		var quote = this.quotes["q" + e.getAttribute("data-quote-id")];
		this._updateAndHighlight(e,this._shift(this._buyOrSell(e, quote), quote.decimals));
	},
	_refreshProfit: function(e) {
		var quote = this.quotes["q" + e.getAttribute("data-quote-id")];
		var v = ((this._buyOrSell(e, quote) - e.getAttribute("data-offset")) * 
						(e.getAttribute("data-buy") == "1" ? -1 : 1)).toFixed(1);
		var cl = 'neutral';
		if (v < 0) { cl = 'neg'; } else if (v > 0) { cl = 'pos'; }
		e.removeClassName('em-pos').removeClassName('em-neg').removeClassName('em-neutral');
		e.addClassName('em-' + cl);
		this._updateAndHighlight(e, v > 0 ? "+" + v : v);
	},
	_buyOrSell: function(element, quote) {
		return element.getAttribute('data-buy') == "0" ? quote.buy : quote.sell;
	},
	_shift: function(value, decimals) {
		return (value / Math.pow(10, decimals)).toFixed(decimals);
	},
	_updateAndHighlight: function(element, content) {
		if (element.innerText == content + "") return;
		element.update(content);
		new Effect.Highlight(element);
	}
}

/*	This class provides misc. helper functions to control 
		the interactive behavior of a form. Ie, it can control
		the visibility of several divs based on the selection of
		a listbox.
*/
var FormTools = {
	divSelection: function (element) {
		element.observe('change', function (event) { 
			this._divSelectionUpdate(event.target) }.bind(this));
		this._divSelectionUpdate(element)
	},
	_divSelectionUpdate: function (element) {
		var divs = element.getAttribute('data-div-list').split(",").
								map(function (id) { return $(id) });
		divs.each(function (div) { div.hide(); });
		divs[element.value].show();
	},
	
	divCheckboxToggler: function (element) {
		var div = $(element.getAttribute('data-toggles'));
		div.hide();
		if (element.checked) { div.show(); }
		element.observe('click', function (a) { $(this.getAttribute('data-toggles')).toggle(); });
	},
	
	
	// Highlights the input box green if it matches the desired
	// signature (given as value of data-signature-for attribute)
	signatureChecker: function (element) {
		new Form.Element.Observer(element, 0.25, function (el, value) {
			if (value == element.getAttribute("data-signature-for")) {
				el.addClassName('valid');
			} else {
				el.removeClassName('valid');			
			}
		}.bind(this))		
	}
};


var ContentEditorTab = Class.create({
	element: null,
	initialize: function (element) {
		this.element = element;
		this.element.observe('click', function (event) {
			$$('.lang_tabs').each(function(s) { s.hide(); });
			$('edit_' + this.element.getAttribute('data-edit-locale')).show();
			$$('a[data-edit-locale]').each( function (e) { e.removeClassName('sel'); });
			this.element.addClassName('sel');
			Event.stop(event);
		}.bind(this));	
	}
})

/* Code to run when dom is ready */
document.observe("dom:loaded", function() {
	// setup fields with input-description (data-idesc custom tags)
	$$('input[data-idesc]').each(function (e) { 
		new InputDescription(e, e.getAttribute('data-idesc')); 
	});

	// Add error messages, currently only used in contracts/create
	$$('input[data-error]').each(function (e) {
		Element.replace(e, 
			new Element('div', {'class': 'fieldWithErrors'}).
			insert({ 
					'top' : e.clone(), 
					'bottom' : new Element('div', {'class':'error-bubble'}).
											insert(e.getAttribute('data-error'))
					})
			);
	});


	$$('select[data-div-list]').each(function (e) {
		FormTools.divSelection(e);
	});

	$$('input[data-toggles]').each(function (e) {
		FormTools.divCheckboxToggler(e);
	});

	$$('input[data-signature-for]').each(function (e) {
		FormTools.signatureChecker(e);
	});

	$$('img[data-youtube]').each(function (e) { new VideoLightbox(e) });

	$$('a[data-edit-locale]').each(function (e) { new ContentEditorTab(e); });

	$$('tr[data-ticket-hash]').map(function (e) { return e.getAttribute('data-ticket-hash'); }).
		uniq().each(function (e) { new OrderHighlighter(e) });

	// admins have the real order ids for debugging
	$$('tr[data-order-id]').each(function (e) { new AdminOrderDetails(e); });

	// Radio buttons in quiz form should submit the form upon selection
	$$('input[name="answer"]').each(function (e) { e.observe('click', function (el) { $('answerform').submit(); }); });


	new Ajax.Autocompleter("search", "search-preview", "/search", 
		{ paramName: "q", minChars: 2, indicator: 'search-spin',
		 afterUpdateElement: function(text, li) { window.location.href = '/search/redirect/' + li.id; }
		}
	);

	QuoteRefresher.setup();
});

/* new code for strophe/xmpp */




/* ADMIN-Functions, have to be ausgelagert */



/* ENde bosh-code */

function initApuq(user_id) {

	var apuq = new Apuq('orders', user_id);
	//apuq._debug = true;

	apuq.onError = function(occurred) {
		if (occurred) {
			$('apuq-error').setStyle({ display: 'block' });
		} else {
			$('apuq-error').hide();		
		}
	}
	
	apuq.onEvent = function(event) {
		switch(event.type) {
			case "message":
				addMessage(event.data.from, event.data.text, event.data.time);
				break;
			case "order":
				handleOrder(event.data);
				break;		
		}
	}
	
	apuq.listen();
}


function addMessage(from, content, time) {
	timelineItemCount++;

	var maxItems = 8;

	var darkerStyle = (timelineItemCount % 2 != 0 ? 'background: #ddd;' : '')
	var newEvent = '<div class="update" id="update_' + timelineItemCount + '" style="display: none; ' + darkerStyle + '">' +
	               '<strong>' + from + '</strong> ' + content + '<br /><em>' + time + '</em>' +
	               '</div>';

	Element.insert('timeline', { top: newEvent })

	if (timelineItemCount > maxItems) {
		//Effect.DropOut('update_' + (timelineItemCount - 3));
		Effect.BlindUp('update_' + (timelineItemCount - (maxItems + 1)));
	}
  Effect.BlindDown('update_' + timelineItemCount);
	//new Effect.Highlight('update_' + timelineItemCount);
	
}

var timelineItemCount = 0;


/* Add a warning to all IE6 users */
var $buoop = {} 
$buoop.ol = window.onload; 
window.onload=function(){ 
 if ($buoop.ol) $buoop.ol(); 
 var e = document.createElement("script"); 
 e.setAttribute("type", "text/javascript"); 
 e.setAttribute("src", "/javascripts/ie6warn.js"); 
 document.body.appendChild(e); 
} 

