
// http://jqfundamentals.com/
// http://www.ltg.ed.ac.uk/~richard/utf-8.cgi
// http://www.ajaxload.info/

$.fn.escapeHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    me.html(html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'));
  });
};
 
$.fn.unescapeHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    me.html(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
  });
};


$(document).ready(function() {



	if ( typeof console == "undefined" ) {
		
			var console = { log: function() {} };
			
	}else if( typeof console.log == "undefined" ) {
		
				console.log =  function() {};
	}
	

/*
	$("a").each(function() { 

			if($(this).children().length < 1) 	{

				$(this).addClass("badged-dark")
	
			}
				
			});
*/

	$(function() {

		tmp=$("xml#xmldata document overlay").unescapeHTML().html();
		
		if( tmp != "" )	{
			
			$("#custom").html( tmp );

			layer23.overlay.show( $("#custom"), { align: 'center' } );
			
			layer23.overlay.attachHideClick( $("#custom") );
			
			layer23.overlay.hideAuto( $("#custom") );
		}

	} );


	$("body :input").focus( function()	{
		
						if( $(this).val() != "" )	{

							$(this).removeClass("undefined");
						}
						
						if( $(this).hasClass("mandatory") )	{
						
							$(this).removeClass("mandatory");
							
							$(this).data('is_mandatory', true );
						}
					}
				);

	$("body :input").blur( function() {
		
						if( $(this).data("is_mandatory") === true )	{
						
//							if( $(this).val() == "" ) {
						
								$(this).addClass("mandatory");
//							}
						}
					}
				);
	
	$("body :input").bind('keypress', function(e) {
						
						switch(e.keyCode)	{
							
							case 8:

								if( $(this).val() == "" ) {
									
									$(this).addClass("undefined");
								
									$(this.id + ".undefined").val(1);
								}								

								break;		

							case 9:
							
								break;		
								
							default: 
							
								$(this).removeClass("undefined");

								$(this.id + ".undefined").val(0);

								break;		
						} 
					}
	);

//----------------------------------------------------------------------------------------------------------------------------------------------------------------

	$(':input.autosubmit').click(function() {
		
			// http://stackoverflow.com/questions/1621714/jquery-find-parent-form
		
			var frm=$(this.form);
		
			// console.log(frm);
		
			$(frm + ":input#f\\.c\\.cgi\\.asm" ).val(1);
		
			frm.submit();
	} );

//----------------------------------------------------------------------------------------------------------------------------------------------------------------

	$('form:not(.global):first :input:visible:enabled:first').focus();


//----------------------------------------------------------------------------------------------------------------------------------------------------------------

	$('a[rel=external]').click(function() {
	
			window.open($(this).attr('href'));
			
			return false; 
	} );

	$('img').each(function(index, event){ 
	
		/* manchmal wichtig fuer floating sachen */
	
		// console.log( "image", $(this) );

		var img_dummy = new Image();
		
		var that = this;
		
		$(img_dummy).bind( {
							
				load: function(event){
							
					$(that).css( { 'height': this.height, 'width': this.width } );
				}
		} );
						
		$(img_dummy).attr( "src", $(this).attr("src") );
		
	 } );

	$('.100ph').each(function(index, event){ 
		
			$(this).css( { "height": $(this).parent("div").height() } );
			
	} );

//----------------------------------------------------------------------------------------------------------------------------------------------------------------

	layer23.overlay.canvas( { 'action': 'update' } );

	$(window).resize(function() {

		console.log($(window).width(),$(window).height());
		
		layer23.overlay.canvas( { 'action': 'update' } );
		
	});

	$("#canvas").bind({

		click: function(event){
					
					console.log( "#canvas->click()" );
					layer23.overlay.canvas( { 'action': 'hide' } );
					$('.overlay:visible').each(function(index, event){ layer23.overlay.hide( $(this) ) } );
				},
	});

	$(document).keypress(function(event) { 

	    if (event.keyCode == 27) {

					$("#canvas").trigger("click");
			}
	});



//----------------------------------------------------------------------------------------------------------------------------------------------------------------
// http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html

/*

    if (self.parent.frames.length != 0) 
    self.parent.location=self.location;
*/

	$(function() {

		var display_timeout = 0;
	
		$(".overlay_tooltip_add").bind({
			
			mouseover: function(event){
	 
					if(display_timeout != 0) {
	
						clearTimeout(display_timeout);
					}
	 
					var that = this;
	
					display_timeout = setTimeout(function() {
	
						display_timeout = 0;
	
						layer23.overlay.show( $( $(that).data('selector') ), { align: 'trigger' }, event );
	
					}, 500 );
			},
	
			mouseout: function(event){
		
					if(display_timeout != 0) {
	
						clearTimeout(display_timeout);
					}
		
					layer23.overlay.hide( $( $(this).data('selector') ) );
			},
		});

	});
// 
//----------------------------------------------------------------------------------------------------------------------------------------------------------------

	$(".overlay_memo_add").bind({
		
		click: function(event){

					var selector = $(this).data('selector');

					layer23.overlay.canvas( { 'action': 'show' } );

					layer23.overlay.show( $( selector ), { align: 'trigger' }, event );
					
					$( selector + " :button[name$='_apply']" ).bind({
						
						click: function(event)	{

							event.preventDefault();

							// http://stackoverflow.com/questions/3070400/jquery-button-click-event-is-triggered-twice							
							$(this).unbind( 'click' );
							
							console.log( "#button->click()" );
							
							layer23.overlay.hide( $(selector) );

							layer23.overlay.canvas( { 'action': 'hide' } );
						}
					});
				},
	});



//----------------------------------------------------------------------------------------------------------------------------------------------------------------

	$.ajaxSetup({
		
		url: "/bin/cgi/stg/dispatch",
		
		// dataType: ($.browser.msie) ? "text" : "xml",

		timeout: 5000,

		// accepts: {

		//	xml: "text/xml",
		////	text: "text/xml"
		// },

		type: "GET",

		context: document.body,

		error: function( jqXHR, textStatus, errorThrown ) {
			
			layer23.debug( 0, "ajaxHttpError: " + jqXHR.status + " / " + textStatus );
		},
	});
	
	layer23.initDOM( "document" );

});

// http://docs.jquery.com/FAQ#Why_do_my_events_stop_working_after_an_AJAX_request.3F

//----------------------------------------------------------------------------------------------------------------------------------------------------------------

function layer23(){

	this.initDOM = function(root) {

		console.log( "inititalizing DOM for ", root );
		// todo root prefixen
//----------------------------------------------------------------------------------------------------------------------------------------------------------------

		$(':input.sanity').bind({
			
			keyup:	function(event){ 
	
				console.log("HALLLLLLLO");
	
		    	if (event.keyCode == 13) {
	
						return false;
				}
	
				// layer23.ajax.suggest('test', this, $(this).val() );
				layer23.ajax.sanity('doc-id', this );
			}
	
		} );

//----------------------------------------------------------------------------------------------------------------------------------------------------------------

		$(".overlay_tooltip_add, .overlay_memo_add, .overlay_cinematic_add").each( function() {
		// todo read http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-_2F00_-EcmaScript.aspx
		// http://www.bloggingdeveloper.com/post/JavaScript-null-vs-undefined-The-Difference-between-null-and-undefined.aspx
			if( $(this).data('selector') === undefined )	{
				// wg. mehrern Dom-Inits sonst ist title = null
				$(this).data( { 'selector': 'div#' + $(this).attr('title') } );
	
				$(this).removeAttr('title');
			}
		} )

//----------------------------------------------------------------------------------------------------------------------------------------------------------------
	
		$(".overlay_cinematic_add").bind({
			
			click: function(event){
	
						event.preventDefault();
	
						var selector = $(this).data('selector');
	console.log("blahhhh", $(this).data() );
						$("#cinematic").html( $(selector).unescapeHTML().html() );

						if( $("#cinematic img").length == 1 )	{


							layer23.overlay.show( $("#patience"), { 'align': 'center'} );
							
							var img = $("#cinematic img")[0];
							
							console.log( "#cinemtic contains an image " + img );	
	
							var img_dummy = new Image();
							
							var event_inh = event;
							
							var timeout;
							
							$(img_dummy).bind( {
								
								load: function(event){
								
									clearTimeout(timeout);
								
									$("#cinemtic").css( { 'height': this.height, 'width': this.width } );
	
									layer23.overlay.hide( $("#patience") );
	
									layer23.overlay.show( $("#cinematic"), { align: 'center' } );
				
									layer23.overlay.attachHideClick( $("#cinematic") );
								}
							} );
							
						//	$(img_dummy).attr( "src", "eoeoemoemoe" );
							$(img_dummy).attr( "src", $(img).attr("src") );
	
							$(img_dummy).bind("error", function(){
								
								clearTimeout(timeout);
	
								layer23.overlay.canvas( { 'action': 'hide' } );
								
								layer23.overlay.hide( $("#patience") );
								
								layer23.debug(0, "error while loading image '" + $(img).attr("src") );
							});
	
	
	
							timeout = setTimeout(function(){
	
								$(img_dummy).unbind("load");
	
								layer23.overlay.canvas( { 'action': 'hide' } );
								
								layer23.overlay.hide( $("#patience") );
								
								layer23.debug(0, "loading of image '" + $(img).attr("src") + "' timed out" );
	
							}, 4000);
	
						
							// layer23.debug(0,"image '" + $(img).attr("src") + "' could not be loaded" );
						
						}else{
							
							layer23.overlay.show( $("#cinematic"), { align: 'center' } );
				
							layer23.overlay.attachHideClick( $("#cinematic") );
						}
						
						layer23.overlay.canvas( { 'action': 'show' } );
				
						return false;
				
					},
		});

//----------------------------------------------------------------------------------------------------------------------------------------------------------------

		$(function() {
	
	
	// http://stackoverflow.com/questions/169506/obtain-form-input-fields-using-jquery
	// http://webcloud.se/log/Form-validation-with-jQuery-from-scratch/
	
	// Todo auseinanderdröseln patienence, lock, mandatory
	
			$('form').submit(function(event) { 
				
						//	var selector = "#message"; var stay;
	
							console.log("HALLLLLLLLLLLLLO");
	
							$(this).find( ':input.mandatory').each( function() {
	
								if( $(this).val() == "" )	{
	
									event.preventDefault();
	
									console.log( this, "is mandatory" );
	
									layer23.overlay.canvas( { 'action': 'show' } );
	
									layer23.overlay.message( 0, "Formular nicht richtig ausgefuellt,<br>mehr Muehe bitte geben und so!" );
			
									return false;
								}
								
							} );
						
							// if( stay === true )	{ return false; }
						
							// handler(event, this) 
	
						} );
	
			// todo kombination aus mandatory und patience lösen
	
			var handler=function(event, element)	{
				
				$('button[type=submit], input[type=submit]').attr('disabled','disabled' );
				
				layer23.overlay.canvas( { 'action': 'show' } );
				layer23.overlay.show( $("#patience"), { 'align': 'center'} );
			}
	
			$('form.XXXpatience').submit(function(event) { 
	
							handler(event, this) 
							
						} );
	
			$('a.XXpatience:not(.overlay_cinematic)').click(function(event) {
				
							handler(event, this) 
							
						} );
	
	
		} );

//----------------------------------------------------------------------------------------------------------------------------------------------------------------
// http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
		$(function() {
		
			$( ".calendar" ).datepicker( {
				
					firstDay: 1,
					showAnim: "fade",
					dateFormat: "dd.mm.yy",
					dayNames:		['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
					dayNamesShort:	['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
					dayNamesMin:	['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
					monthNames:		['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
					monthNamesShort:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
			} );
		
		});		

	}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------


	this.debug = function(priority, message) {

		var element = "#debug";

		var tmp;

		line=$('<div/>', { text: message } );

		line.css( { 'background-image' : priority == true ? 'url(\'/cdn/img/icons/16x16/arrow_right_1.png\')' : 'url(\'/cdn/img/icons/16x16/closed.png\')' } );

		line.appendTo( $(element) );

		layer23.overlay.show( $(element) );

		clearTimeout( $(element).data("timeout") );
			
		tmp = setTimeout(function() {

			layer23.overlay.hide( $(element) );
					
			$( element + " div").delay(layer23.overlay.fadeSpeed).queue(function() { $(this).remove() } );

		}, 3000);

		$(element).data( { "timeout": tmp } );
	}

	this.sleep = function (milliseconds) {
		var start = new Date().getTime();
		for (var i = 0; i < 1e7; i++) {
			if ((new Date().getTime() - start) > milliseconds){
				break;
			}
		}
	}

	this.uuid = function() {

		var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), uuid = new Array(36), rnd=0, r;

		for (var i = 0; i < 36; i++) {

			if (i==8 || i==13 ||  i==18 || i==23) {

				uuid[i] = '-';

			}else if (i==14) {

				uuid[i] = '4';

			}else{

				if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
				r = rnd & 0xf;
				rnd = rnd >> 4;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}

		return uuid.join('');
	}

	this.ajax = function() {

		// http://api.jquery.com/jQuery.ajax/
		this.main = function( name, param, style, callback_1, callback_0 ) {

			if( style != null )	{
				console.log("with ajax css");
				$("link#ajax").attr("href", "/cdn/css/xyz/" + style + ".css" );
			}

			param['b.path'] = "core/http/ajax/" + name ;
			param['g.ses'] = $("xml#xmldata session param[name='hash']").attr('value');
			// für evtl. neue Sessions ???
			// param['g.cpt'] = $("xml#xmldata session param[name='chapter.name']").attr('value');

			$.ajax( {
				
				data: param,
				
				success: callback_1,
				error: callback_0,
				
			} );
		};

		this.sanity = function( name, element ) {
			
			this.main('sanity', { 'b.name': name, 'p.s': $(element).val() }, null,
				
				function(data, textStatus, jqXHR )	{

						console.log(data);
		
						$(element).removeClass( "isok iserr" );
		
						$(element).addClass( Math.random() > 0.5 ? "isok" : "iserr" );
		
						// $(element).attr("value", data );
		
						layer23.debug( 1, "ajax.suggest resp: " + jqXHR.status + '; ' + data.length + ' bytes' );
				}
			 );
			
		};

		this.suggest = function( name, element ) {
			
			this.main('suggest', { 'b.name': name, 'p.s': $(element).val() }, null,
				
				function(data, textStatus, jqXHR )	{

						console.log(data);
		
						// $(element).attr("value", data );
		
						layer23.debug( 1, "ajax.suggest resp: " + jqXHR.status + '; ' + data.length + ' bytes' );
				}
			 );
			
		};

// http://tobia.github.com/CrossSlide/
		// http://stackoverflow.com/questions/2970544/jquery-cant-access-elements-loaded-through-ajax
		this.realm = function( hash, style, reload_ms ) {

			layer23.debug( 1, "loading realm " + hash );

	
			var canvas=$('div#realm_' + hash + ' > div.realm_canvas');

			// dass man den Kuller sieht, wenn CSS keine Box Dimension vorgibt
			canvas.css( { "min-height": "64px", "min-width": "64px" } );

			layer23.overlay.show( canvas );

			//canvas.fadeTo( layer23.overlay.fadeSpeed, 0.8 );

			this.main('realm', { 'b.hash': hash }, style,
				
				function(data, textStatus, jqXHR )	{

					var element='div#realm_' + hash + ' div.realm_main';

					$(element).html( data );	

					layer23.initDOM( $(element) );

					layer23.overlay.hide( canvas );
		
					//layer23.debug( 1, "ajax.realm resp: " + jqXHR.status + '; ' + data.length + ' bytes' );
				},
				
				function(jqXHR, textStatus, errorThrown) {

					layer23.overlay.hide( canvas );

					layer23.debug( 0, "[realm]ajaxHttpError: " + jqXHR.status + " / " + textStatus );
				}
			
			 );

			 if( reload_ms != null ) 	{

				// return 1;

				var that = this;
	
				var interval;

				var fn_vary = function(value) {
					
					var vary = 50;
					
					return Math.floor( value / 100 * ( 100 + ( Math.random() * vary * 2 ) - vary ) );
				}
				var fn_reload = function() {

					that.realm( hash, style );

					clearInterval( interval );
					interval = setInterval(fn_reload, fn_vary( reload_ms ) );
				}

			 	interval = setInterval(fn_reload, fn_vary( reload_ms ) );
			 }
	 
		};
	};
	
	this.overlay = function() {
		
		this.fadeSpeed = 300;
		
		var pnt = this;
		
		this.message = function( priority, body ) {
			
			var element=$("#custom");
			
			var template_e=$( priority == true ? "div#t_message_1" : "div#t_message_0" ).clone();
			
			var template_u=template_e.unescapeHTML();

			element.html( template_u.html() );
			
			element.find(".message_group_l0 div").html( body );

			layer23.overlay.show( element, { align: 'center' } );

			layer23.overlay.attachHideClick( element );
			
			layer23.overlay.hideAuto( element );
		}
		
		this.show = function(element, param, event ) {

			var param = $.extend( {}, { 'blah': 'hallo' }, param )
			// Todo wenn param.align object von event ist dann das nehmen, anstatt 3. parameter (event)
			//Get the screen height and width
			var windowX = $(window).width();
			var windowY = $(window).height();
		 
		 	// element.show();element.hide();
		 
			var sizeX=element.width(); var sizeY=element.height();
			
			var shift = 16; 
			
			// param.align = "center";
			
			if( param.align != null )	{
			
				if( param.align == "trigger" )	{ // && event
				
					if( event.pageX + ( sizeX + shift ) > windowX )	{
						
						offsetX = - ( sizeX + shift ) ;
					
					}else{
					
						offsetX = shift;	
					}
					
					if( event.pageY - ( sizeY + shift ) < 0 )	{
					
						offsetY = shift;
					
					}else{
					
						offsetY = - (sizeY + shift);
					}
					
					posX=event.pageX + offsetX; posY=event.pageY + offsetY;
	
				}else if( param.align == "center" )	{
	
					posX=windowX / 2 - sizeX / 2; posY=windowY / 2 - sizeY / 2;
	
				}else{
	
					posX=0; posY=0;
				}

				// console.log(event.pageX, event.pageY );
				console.log( "size of", element, sizeX, sizeY );
				
				element.css( { 'left': posX, 'top': posY,  } );
			}

			element.fadeIn(pnt.fadeSpeed);
		}

		this.attachHideClick = function( element) {

			var that = this;
		
			element.bind({
									
				click: function()	{
										
						$(this).unbind( 'click' );
									
						that.hide( $(this) );
			
						that.canvas( { 'action': 'hide' } );
				}
			} )
		}

		this.hideAuto = function( element ) {

			var that = this;

			var display_timeout;
/*
			if(display_timeout != 0) {
	
				clearTimeout(display_timeout);
			}
*/
			display_timeout = setTimeout(function() {
	
				//		display_timeout = 0;
	
						that.hide( element );

						that.canvas( { 'action': 'hide' } );
	
					}, 5000 );
		}

		this.hide = function( element) {

			console.log("hide() for ", element, pnt.fadeSpeed );

			element.fadeOut(pnt.fadeSpeed);
		}

		this.canvas = function( param )	{

				console.log("canvas("+param.action+")" );
			
				var selector="#canvas";
			
				if( param.action == "show" )	{
					
						$(selector).fadeTo( pnt.fadeSpeed, 0.2 );

				}else if( param.action == "hide" )	{

						$(selector).fadeOut(pnt.fadeSpeed);

				}else if( param.action == "update" )	{
		
						$(selector).css({'width':$(window).width() + $(window).scrollLeft(),'height':$(window).height() + $(window).scrollTop() });

						console.log("canvas css", $(selector).css('width'), $(selector).css('height') );
				}
		}
	}	
}

layer23 = new layer23();

layer23.overlay = new layer23.overlay();
layer23.ajax = new layer23.ajax();

//----------------------------------------------------------------------------------------------------------------------------------------------------------------
