// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 6;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 0;
// the version of javascript supported
var jsVersion = 1.0;

var spielfeld;
// -----------------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////////////////////////////
self.onError=null;

var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

  // *** BROWSER VERSION ***
// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)  && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)  && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;
var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);
var NS = (document.layers) ? 1 : 0;
var IE = (document.all) ? 1: 0;

var is_ie3    = (is_ie && (is_major < 4));
var is_ie4    = (is_ie && (is_major == 4) && (clientPC.indexOf("msie 4")!=-1) );
var is_ie4up  = (is_ie && (is_major >= 4));
var is_ie5    = (is_ie && (is_major == 4) && (clientPC.indexOf("msie 5.0")!=-1) );
var is_ie5_5  = (is_ie && (is_major == 4) && (clientPC.indexOf("msie 5.5") !=-1));
var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_ie6    = (is_ie && (is_major == 4) && (clientPC.indexOf("msie 6.")!=-1) );
var is_ie6up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);



/////////////////////////////////////////////////////////////////////////////////////////////////////////

// JavaScript helper required to detect Flash Player PlugIn version information
function JSGetSwfVer(i){
      // NS/Opera version >= 3 check for Flash plugin in plugin array
      if (navigator.plugins != null && navigator.plugins.length > 0) {
            if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
                  var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
                        var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
                        descArray = flashDescription.split(" ");
                        tempArrayMajor = descArray[2].split(".");
                        versionMajor = tempArrayMajor[0];
                  if ( descArray[3] != "" ) {
                        tempArrayMinor = descArray[3].split("r");
                  } else {
                        tempArrayMinor = descArray[4].split("r");
                  }
                        versionMinor = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
                        flashVer = parseFloat(versionMajor + "." + versionMinor);
            } else {
                  flashVer = -1;
            }
      }
      // MSN/WebTV 2.6 supports Flash 4
      else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
      // WebTV 2.5 supports Flash 3
      else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
      // older WebTV supports Flash 2
      else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
      // Can't detect in all other cases
      else {
            
            flashVer = -1;
      }
      return flashVer;
}
// If called with no parameters this function returns a floating point value 
// which should be the version of the Flash Player or 0.0 
// ex: Flash Player 6r65 returns 6.65
// If called with reqMajorVer, reqMinorVer this function returns true if that version or greater is installed
function DetectFlashVer(reqMajorVer, reqMinorVer) 
{
      reqVer = parseFloat(reqMajorVer + "." + reqMinorVer);
      // loop backwards through the versions until we find the newest version      
      for (i=25;i>0;i--) {      
            if (isIE && isWin && !isOpera) {;
                  versionStr = VBGetSwfVer(i);
            } else {
                  versionStr = JSGetSwfVer(i);
            }
            if (versionStr == -1) {
					return false;
			  } else if (versionStr != 0) {
                  if(isIE && isWin && !isOpera) {
                        tempArray = versionStr.split(" ");
                        tempString = tempArray[1];
                        versionArray = tempString .split(",");
                        
                        versionMajor = versionArray[0];
                        versionMinor   = versionArray[2];
                        
                        versionString = versionMajor + "." + versionMinor;
                        versionNum = parseFloat(versionString);
                  } else {
                         versionNum = versionStr;
                  }
                  return (versionNum >= reqVer ? true : false );            
            }
      }
      
      return (reqVer ? false : 0.0);
}



function changeHeader(type) {
		switch (type){
			case 1: flashProxy_0.call("pictureInterval2", '1');break;
			case 2: flashProxy_0.call("pictureInterval2", '2');break;
			case 3: flashProxy_0.call("pictureInterval2", '3');break;
			case 4: flashProxy_0.call("pictureInterval2", '4');break;
			default: flashProxy_0.call("pictureInterval2", '0');break;
		}

}
  
  
/** **/
var myGlobalHandlers = {
	onCreate: function(){
	//	Element.show('systemWorking');
		new Effect.Appear('systemWorking',{ duration:0.5 });
		//Element.hide(element);
	},
	onComplete: function() {
		if(Ajax.activeRequestCount == 0){
		//	new Ajax.Updater('categories', 'blog/category/cupdate', {asynchronous:true});
		//	Element.hide('systemWorking');
			new Effect.Fade('systemWorking',{ duration:0.5 });
			//Element.show('content-swapper');
			initLightbox();
		}
	}
};
Ajax.Responders.register(myGlobalHandlers);

Effect.Updater = Class.create();
Object.extend(Object.extend(Effect.Updater.prototype,
Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend ({
      duration: 0.001,
      newContent: ''
    }, arguments[1] || {});
    this.start(options);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      Element.update(this.element ,this.options.newContent);
      this.cancel();
      return;
    }
  }
});


function getFormParams(element,returnObj){
	
	postObj = new Object();
	element = $(element);	
	if (element == undefined) element = document;
	
	if (!element.getElementsByTagName){ return; }
	result = '';
	var inputs = element.getElementsByTagName('input');
	// loop through all input  tags
	for (var i=0; i<inputs.length; i++){
		var input = inputs[i];
		if (input.name != 'action' && input.type != 'button') {
			if (input.type != 'radio' && input.type != 'checkbox') {
				result += input.name+'='+encodeURI(input.value)+'&';
				if (!(typeof postObj[input.name] == 'object')) postObj[input.name] = new Array();
				postObj[input.name].push(input.value);
			} else if (input.type == 'checkbox'){
				result += input.name+((input.checked)?'=1&':'=&');
				if (!(typeof postObj[input.name] == 'object' || typeof postObj[input.name] == 'object')) postObj[input.name] = new Array();
				postObj[input.name].push(((input.checked)?'1':'0'));
			} else if (input.type == 'radio' && input.checked){
				result += input.name+'='+encodeURI(input.value)+'&';
				if (!(typeof postObj[input.name] == 'object' || typeof postObj[input.name] == 'object')) postObj[input.name] = new Array();
				postObj[input.name].push(input.value);
			}
		}
	}	
	
	var textAreas = element.getElementsByTagName('textarea');
	// loop through all textarea tags
	for (var i=0; i<textAreas.length; i++){
		var textArea = textAreas[i];
		result += textArea.name+'='+encodeURI(textArea.value)+'&';
		if (!(typeof postObj[textArea.name] == 'object')) postObj[textArea.name] = new Array();
		postObj[textArea.name].push(textArea.value);
	}		
	
	var selects = element.getElementsByTagName('select');
	// loop over all select tags
	for (var i = 0; i < selects.length; i ++) {
		var select = selects[i];
		var twoselect = (select.getAttribute) ? select.getAttribute('rel') == 'twoselect' : false;
		if (twoselect) {
			if (select.options.length <= 0)
				result += select.name + '=&';
		}
		postObj[select.name] = new Array();
		//var o = 0;
		for (var j = 0; j < select.options.length; j ++) {
			var option = select.options[j];
			if (option.selected || twoselect ) {
				result += select.name + '=' + encodeURI(option.value) + '&';
				postObj[select.name].push(option.value);
			} 
		}		
	}
	return (returnObj) ? $H(postObj) : result.substr(0, result.length-1);
}

function getInnerHtmlById(n) {
	typeExpr = new RegExp("<([a-zA-Z]*)[^>]*id=."+n+"[^>]*>");
	if ((n.length == 0) || (this.indexOf(n) == -1) || this.search(typeExpr)  == -1) return this;
	
	
	type = this.match(typeExpr)[1];	
	
	var front = ''
	var end = ''		
	if (type == null || type == undefined) return false;
	startExpression = new RegExp("<"+type+"[^>]*id=."+n+"[^>]*>");	
	startDivExp = new RegExp("<"+type+"[^>]*>");	
	endDivExp =  new RegExp("</"+type+">");
	
	startTag = new String(this.match(startExpression));
	startIndex = this.search(startTag) + startTag.length;

	var txt = new String(this.substr(startIndex)).replace(/<!--.*-->/,'');
	endMatch = txt.match(endDivExp);
	endIndex = 6 + txt.search(endDivExp);
	
	front = txt.substr(0,endIndex);
	end = txt.substr(endIndex);
	var lastIndex = endIndex;
	startMatch = front.split('<'+type);
	frontCount = 0;
	if (startMatch != null){
			startMatch = startMatch.uniq();
			frontCount += startMatch.length-1;
	}
	$secure = 100;
	while (frontCount > 0 && --$secure){
		endMatch = end.match(endDivExp);
		endIndex = 6 + end.search(endDivExp);
		lastIndex += endIndex;
		front = end.substr(0,endIndex);
		end = end.substr(endIndex);
	
		startMatch = front.split('<'+type);
		if (startMatch != null){
			startMatch = startMatch.uniq();
			frontCount += startMatch.length-1;
		}		
		frontCount--;
	}
	result = txt.substr(0,lastIndex-6);
	//alert(result);
	return result;
}

String.prototype.getInnerHtmlById = getInnerHtmlById

function request(options){
	var url 	= (options && options.url)?options.url : '/index.php';
	var action 	= (options && options.action)? $H({ action: options.action}) : $H({});
	var id  	= (options && options.id )?options.id : 'main-content';
	var params  = (options && options.params )?options.params : null;
	var collect = (options && options.collect )?options.collect : false;
	var attach  = (options && options.attach )?options.attach : false;
	var fade  	= (options && options.fade )?options.fade : false;
	var blind  	= (options && options.blind )?options.blind : false;
	var update 	= (options && options.update )?options.update : true;
	var success_extra = (options && options.onComplete )?options.onComplete : '';
	var show_error_id = (options && options.errorId )?options.errorId : 'global_error_stack_output';
	var show_error_container_id = (options && options.errorContainerId )?options.errorContainerId : 'global_error_stack_output_container';
	var element = $(id);
	
	show_error_element = (show_error_id == undefined || show_error_id.length <= 0 || !show_error_id || $(show_error_id) == null)?false:$(show_error_id);
	show_error_element_container = (show_error_container_id == undefined || show_error_container_id.length <= 0 || !show_error_container_id || $(show_error_container_id) == null)?false:$(show_error_container_id);

	var formParams = (collect)?getFormParams($(collect),true):'';	
	var post = (formParams != '') ? formParams:'';
	
	if (params != '' && params != undefined && params != null){
		if (typeof post == 'object' || typeof params == 'object'){
			if (typeof post != 'object') post = new Object();
			if (typeof params == 'string') params = params.toQueryParams();
			Object.extend(post,params);
		} else {
			post += (post != '')?'&':'';
			post += (params);
		}
	}

	post = $H(post).merge(action);
	
	if (typeof post == 'object' ) post = (post.toQueryString)?post.toQueryString():$H(post).toQueryString() ;
	
	var opt = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: post,	
		// Encoding
		encoding: 'ISO-8859-1',	
		 // Handle successful response
		onSuccess: function(t) {
			var new_content = unescape(t.responseText);
			// *#*#*#*#*#*#* ersetzen...
			if (new_content.search(/\*#\*#\*#\*#\*#\*#\*/g) >= 0){
				new_content = new_content.replace(/\*#\*#\*#\*#\*#\*#\*/g, '\\');
			} else {
				new_content = new_content;
			}
			
			// Error Handling...
			if (show_error_element != false && new_content.indexOf('error;') == 0){
				var errormessage = new_content.replace(/error;/,'');
				
				Element.update(show_error_element,errormessage);
				new Effect.Appear(show_error_element_container,{queue:'end'});
	//			new Effect.Opacity(show_error_element,{ duration: 0.5,transition: Effect.Transitions.linear,from: 0.001, to: 1.0 ,queue:'end'});
				new Effect.Fade(show_error_element_container,{queue:'end',delay:10});
	//			new Effect.Opacity(show_error_element,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.001 ,queue:'end',delay:5});
			} else {
				
				if (update){
					
					if (new_content != 'kb_error' && (element != null || id == '')){
						if (id != ''){
							new_content = (attach)? element.innerHTML + new_content : new_content;
							Element.update(element,new_content.getInnerHtmlById(id));
						}
						if (success_extra != undefined && success_extra.length > 0 && new_content.indexOf('error;') != 0){
							eval(success_extra);
						}
						
					} else {
						if (element == null) alert('Das Element mit der id '+id+' existiert nicht !!!');
						if (new_content == 'kb_error') alert('interner Fehler !!!');
						
					}
					if (blind && element != null && (!element.visible() || element.style.opacity <= 0.5))  new Effect.BlindDown(id,{ duration: 0.3, queue: 'end' });
					if ((!is_ie6) && fade && element != null && (!element.visible() || element.style.opacity <= 0.1))  new Effect.Opacity(id,{ duration: 1.0,transition: Effect.Transitions.linear,from: 0.01, to: 1.0, queue: 'end' });
				} else {
					if (success_extra != undefined && success_extra.length > 0){
						eval(success_extra);
					}
				}
				
			}
		},
		// Handle 404
		on404: function(t) {
			alert('Error 404: location "' + t.statusText + '" was not found.');
		},		

		// Handle other errors
		onFailure: function(t) {
			alert('Error ' + t.status + ' -- ' + t.statusText);
		}
	}

	if (update){
		if (blind && element != null && (element.visible() || element.style.opacity > 0.5))  new Effect.BlindUp(id,{ duration: 1.0});
		if ((!is_ie6) && fade && element != null && (element.visible() || element.style.opacity > 0.5))  new Effect.Opacity(id,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.01 });
	}
	new Ajax.Request(url, opt);
}


 function clearFormParams(element){
	element = $(element);
	if (element == undefined) element = document;
	if (!element.getElementsByTagName){ return; }
	var inputs = element.getElementsByTagName('input');
	// loop through all input  tags
	for (var i=0; i<inputs.length; i++){
		var input = inputs[i];
		if (input.getAttribute && input.getAttribute('type') != 'hidden' && input.getAttribute('type') != 'button'){
			input.value='';
		}
	}	
	var textAreas = element.getElementsByTagName('textarea');
	// loop through all input  tags
	for (var i=0; i<textAreas.length; i++){
		var textArea = textAreas[i];
		textArea.value='';
	}
}


switchImage = function(num) {
	var show;
	var hide;
	var currentDiv = null;
	var pics = $('preview-image').getElementsByTagName('div');
	for (var i=0; i<pics.length; i++){
		if ($(pics[i]).visible()) currentDiv = $(pics[i]);
	}
	if (!currentDiv){
		show = $('preview'+num);
		hide = $('preview1');
	} else {
		show = $('preview'+num);
		hide = $(currentDiv);
	}
	
	Element.cleanWhitespace(show);
	Element.cleanWhitespace(hide);
	//show.firstChild.src = "/images/pics/room" + num + ".png";
	
	if (show.id != hide.id){
		for (var i=0; i<pics.length; i++){
			if ($(pics[i]).visible()) currentDiv = $(pics[i]);
			if (Element.visible(currentDiv)){
				new Effect.Fade(currentDiv, { duration:0.3});
			}
		}
		
		if (!Element.visible(show)) new Effect.Appear(show, { duration:0.3, queue: 'end'});
	}
	//new Effect.Opacity(hide,{ duration: 0.5,transition: Effect.Transitions.linear,from: 1.0, to: 0.01 });
	//new Effect.Opacity(hide,{ duration: 0.5,transition: Effect.Transitions.linear,from: 0.01, to: 1.0 , queue:'end'});
	currentDiv = !currentDiv;
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function markSubMenu(element,root){
	root = $(root);
	element = $(element);
	if (!root || !element) return;
	var links = root.getElementsByTagName('a');
	for (var i=0; i<links.length; i++){
		link = $(links[i]);
		if (link != element){
			link.setStyle({color: '#000000'});
		} else {
			link.setStyle({color: '#9a0a1e'});
		}
	}
}

function switchImageNew(element,index) {
	var show;
	var hide;
	var images = element.childElements();
	var current = images.find(function(e){	return e.visible();	}) || element.childElements().first();
	var next = (index && images.size() > index)? element.childElements()[index] : current;
	if ($(current) && $(next) && current != next && Effect.Queue.effects.size() == 0){
		current.absolutize();
		new Effect.Parallel([
			new Effect.Fade(current, { sync: true }), 
			new Effect.Appear(next, { sync: true }) 
		], { 
			duration: 0.6
		});

	}
	
	
}
