function shadowBox (a) {
	// 0 = close, 1 = open
	if (a) {
		$('#shadowBox').css({opacity : 0, display : 'block'});
		$('#shadowBox').animate({opacity : 0.8}, 300);
		return true;
	}
	
	$('#shadowBox').animate({opacity : 0}, 300, function() {
		$('#shadowBox').css({display : 'none'});
	});
	
	return true;
}
function shadowResize () {
	var _h = $(document).height();
	var _w = $(document).width();
	$('#shadowBox').height(_h).width(_w);
	return true;
}

Array.prototype.search = function( value, strict )
{
    if( typeof value == "undefined" ) {
        return false;
    }
    var retVal = false;
    if( strict ) {
        for( key in this ) {
            if( this[key] === value ) {
                retVal = key;
                break;
            }
        }
    } else {
        for( key in this ) {
            if( this[key] == value ) {
                retVal = key;
                break;
            }
        }
    }
    return retVal;
}
 


var handleGal = {

	/*
		Var deklaration
	*/
	navArray     : new Array(),
	holeGalArr   : new Array(),
	holeDivArr   : new Array(),
	identifyGal  : new Array(),
	numPics      : -1,
	appendTo     : '#gal_wrapper',
	openedGal    : new Array(),
	galPrefix    : '#s_gal_',
	newGalMargin : 20, // Umbedingt das Bild mitberechnen!
	startMarginTop : 0, // der erste wrapper nach oben
	shuffleIdentify : false,
	shuffledIdentify : false,
	lastzIndex       : false,
	/*
		OpenGal:
		    [id] => array(GalId, lastMargin)   // die richtige Reihenfolge! WIe beim Vorgänger! Wichtig!
	*/
	goShuffleIdent : function () {
		var _newArr = new Array();
		for (var x = 0; x < identifyGal.length;x++) {
			_newArr[x] = '';
		}
		
	
	},
	openGal : function (galId, oldId, a) {
		/*if (handleGal.shuffleIdentify == false) {
			handleGal.shuffleIdentify = true;
			handleGal.goShuffleIdent();
		}*/
		//window.alert(galId);
		// gal ID ist in diesem Fall ein !unique! String
		// -> dieser muss in eine id umgewandelt werden.
		// corrGalId ist der unangetastete String
		/*window.alert(galId);
		handleGal.identifyGal['']
		window.alert(handleGal.identifyGal[""+galId+""]);*/
		//window.alert(galId);
		//window.alert(oldId);
		
		if (a == true) {
			if (typeof handleGal.identifyGal[galId] == 'undefined') {
				window.alert("Fehler beim selektieren der Gallerie. Bitte die export Datei überprüfen.");
				return false;
			} else {
				galId = handleGal.identifyGal[galId];
			}
		}
		
		if (handleGal.searchOpenedGal(galId)) {
			/*
				CSS Befehl hier einbaun!
			*/
			$('#' + oldId).removeClass('openedGal');
			handleGal.closeGal(galId); // Gallerie wird geschlossen!
			return false;
		}
		$('html').animate({scrollTop : 0}, 300);
		/*
			CSS Befehel hier einbaun!
		*/
		
		$('#' + oldId).addClass('openedGal');
		
		// Gallery öffnen
		/*
			Wichtige Daten:
			-> angesrochene Galerie
			-> Letzter MarginTop Wert
			-> Neuer MarginTop Wert
		*/
		//window.alert(galId);
		var _openGal 	   = $(handleGal.galPrefix + galId); // fin
		var _lastMarginTop = 0;
		var _newMarginTop  = handleGal.startMarginTop;
		var _slideMargin = handleGal.holeGalArr[galId]['holeHeight'];
		if (handleGal.openedGal.length > 0) {
			// es gibt einen last Margin!
			/*var _c = handleGal.openedGal.length - 1;
			var _lastId = handleGal.openedGal[_c][0];

			_lastMarginTop = handleGal.openedGal[_c][1];
			_lastHoleHeight = handleGal.holeGalArr[_lastId]["holeHeight"];
			// Einfach alles nach unten sliden lassen!
			// neuen Margin errechnen
			_newMarginTop = _lastHoleHeight + _lastMarginTop + handleGal.newGalMargin; 
			*/
			var _holeNewMargin = _slideMargin + handleGal.newGalMargin;
			$('.image_wrapper').each(function () {
				$(this).animate({
								'marginTop' : '+=' + _holeNewMargin
								},200);
			});
		}
		 //window.alert(handleGal.holeGalArr[galId]['holeHeight']);
		handleGal.openedGal[handleGal.openedGal.length] = new Array();
		handleGal.openedGal[handleGal.openedGal.length -1][0] = galId;
		handleGal.openedGal[handleGal.openedGal.length -1][1] = _newMarginTop;
	
		// GALLERIE EINBLENDEN (Anfang)
		$(handleGal.appendTo).append(handleGal.holeDivArr[galId]);
			/*
				Show effects
			*/
			$(handleGal.galPrefix + galId).css({
												'marginTop' : _newMarginTop 
											 }).show('fast');
		//window.alert($(handleGal.galPrefix + galId).length);
		handleGal.done();
		// \\ Gallerie Eingeblendet (Ende)
		
		//window.alert("oldTop:" + _lastMarginTop);
		//window.alert("newTop:" + _newMarginTop);
		
		
	},
	searchOpenedGal : function (galId) {
		// galerie ausfindig machen

		for (var x = 0;x < handleGal.openedGal.length;x++) {
			if (handleGal.openedGal[x][0] == galId) {
			
				return true;
			}
		}

		return false;
	},
	getOpenedGalId : function (galId) {
		for (var x = 0; x < handleGal.openedGal.length; x++) {
			if (handleGal.openedGal[x][0] == galId) {
				return x;
			}
		}
		window.alert("err: no id found!");
	},
	closeGal : function (galId) {
		/*
			Gal wird geschlossen.
			
				#1 Div wird via opacity verborgen
				#2 hide()
				#3 id's neu mischen
				#4 die anderen DIvTags verschieben
				#5 Höhe anpassen!
		*/
		//$(handleGal.galPrefix + galId).hide('slow');
		// id in openedGal herausfinden
		var _openedId = handleGal.getOpenedGalId(galId);
		handleGal.removeAndSortGal(_openedId, galId);
		// _größe für die Margin Verschiebung sichern
		//window.alert(galId)//
	
		
		
		
		// schauen ob es NICHT der letzte Eintrag ist
			// remove()
			// aus Array entfernen
				// neu mischen u. marginTop ändern
		
	},
	removeAndSortGal : function (id, galId) {
		var _marginDifference = 0;
		var _last = false;
		switch (id) {
			case 0 : 
						/*
							_marginDifference = höhe!
						*/
					_marginDifference = handleGal.holeGalArr[galId]['holeHeight'] + handleGal.newGalMargin;
					break; // Erster Eintrag
			case handleGal.openedGal.length-1 : 
						/*
							_marginDifference = 0
						*/
					_marginDifference = 0;
					_last = true;
					break;// Letzter Eintrag
			default :
						/*
							_marginDifference = Höhe + newRowMargin
						*/
					_marginDifference = handleGal.holeGalArr[galId]['holeHeight'] + handleGal.newGalMargin;
					break;
		}
		var _divId = handleGal.openedGal[id][0];
		$(handleGal.galPrefix + _divId).hide('slow', function () {
			$(this).remove(); // Div Tag ist komplett weg!
		});
		if (_last == true) {
			handleGal.openedGal.pop(); // letztes element wird entfernt
			return true;
		}
		if (handleGal.openedGal.length == 1) {
			handleGal.openedGal.pop(); // letztes element wird entfernt
			return true;
		
		}
	
		
		// Array neu mischen und Größen anpassen
		/*
			Wichtige WErte:
				ID gibt die start ID für die Verschiebung an! Ab id = id wird der margin abgezogen mittels animate!
		*/
		var z = 0;
		var _nArr = new Array();
		for (var x = 0; x < handleGal.openedGal.length;x++) {
			if (x == id) {
				continue;
			}
			if (x > id) {
				// bezugsId
				_bId = x;
				//window.alert(_bId);
				_newContent = handleGal.openedGal[_bId];
			
				_newContent[1] -= _marginDifference; // neuer Margin Wert
				//window.alert(_newContent[1]);
				
				/*
					ANIMATE!!!!!
				*/
				
				//$(handleGal.galPrefix + _newContent[0]).animate({'marginTop' : _newContent[1]}, 1000); // ANIMATE AUF 1.9k MS
				
				// Margin abändern
			} else {
				_newContent = handleGal.openedGal[x];
			}
			_nArr[z] = _newContent;
			z++;
		}
		handleGal.openedGal = _nArr; // neues Array zugewiesen
	//	window.alert(handleGal.openedGal.length + "(Höhe)" + handleGal.openedGal[0][0] + "(ID: 0, ID <- ->)");
		
		
	},
	/*
		+++ importArray+++
		///
			Importiert das von PHP erzeugte Array.
			Achtung: Anzahl der Reihen, gesamte 
			Höhe & gesamte Breite werden von JavaScript
			zusätzlich erzeugt.
			
			Nachtrag: 
					Gesamte Breite ermittelt PHP
													\\\	
	*/
	importArray : function (id, url, info, height, width, ax, owidth, oheight) {
		
		// gesamtanzahl der gallerien sollte angegeben sein, um das Event zu steuern. wenn die gesamtanzahl NICHT vorhanden ist, dann passiert bei Klick's nicht.
		// D.h. das JS Array muss vollständig gefüllt sein, bevor Event's Auswirkungen haben
		// er rechnet direkt aus auf welcher position sich die Bilder innerhalb des GALLERY-Containers befinden -> ACHTUNG: NICHT der komplette Container!
		// -> der jeweilige GALLERY Container richtet sich dann nach dem Container außenrum
		/*window.alert(typeof handleGal.holeGalArr[id]['pictures']); */
		if (typeof handleGal.holeGalArr[id]['pictures'][ax] == 'undefined') {
			handleGal.holeGalArr[id]['pictures'][ax] = new Array();
		}
		
		
		handleGal.holeGalArr[id]['pictures'][ax]['url'] = url;
		handleGal.holeGalArr[id]['pictures'][ax]['info'] = info;
		handleGal.holeGalArr[id]['pictures'][ax]['height'] = height;
		handleGal.holeGalArr[id]['pictures'][ax]['width'] = width;
		handleGal.holeGalArr[id]['pictures'][ax]['oWidth'] = owidth;
		handleGal.holeGalArr[id]['pictures'][ax]['oHeight'] = oheight;
	},
	 done : function () {
		/*
			Hier müssen immer wieder alle Befehle rein!
		*/
		
		$('.thickbox').click(function(){
			var _img = $(this).parent('div').parent('div').children('.oriPic').attr('src');
			//window.alert('Erhöhe auf maximale Größe der Datei: '+ $(this).parent('div').parent('div').children('.oriPic').attr('src'));
			//window.alert($(this).position().top);
			$('#zoomPicture').remove(); // ggf vorhandene entfernen
			//shadowBox(0);
			shadowBox(1);
			$('body').prepend('<div id="zoomPicture"><img src="'+_img+'" alt="" title=""/></div>');
			  $('#zoomPicture').css('top', $(window).scrollTop()); // auf richtige position schieben
				$(window).click(function(){
					$(window).unbind();
					$('#zoomPicture').animate({opacity:0}, 600, function(){
						$('#zoomPicture').remove(); 
						shadowBox(0);
					})
				});
			shadowResize();
			$(window).resize(function(){
				shadowResize();
			});
			return false;
		});
		//// IMG Mouse Over \\\
			// opacity effect
			$('.image_wrapper').hover(
						function () {
							$(this).children('div').stop().animate({opacity : 0.9}, 250);
							$(this).children('.infoText').stop().css("opacity", 0);
							//$('.image_wrapper img').animate({'opacity' : 0.3}, 160);
							//$(this).children('img').stop().css('opacity', 1);
							
						}, 
						function () {
							//$('.image_wrapper img').stop().animate({'opacity' : 1}, 160);
							//$(this).css({'zIndex' : handleGal.lastzIndex});
							$(this).children('div').stop().animate({opacity : 0}, 250);
						}
						
						);
				$('.image_wrapper').click(function () {
					handleGal.lastzIndex += 1;
					$(this).css({'zIndex': handleGal.lastzIndex});
				});
			// show div Tags
				// click info Tag
				$('img.showInfo').click(function () {
					if ($(this).parent('div').parent('div').children('.infoText').css('opacity') == 0) {
						$(this).parent('div').parent('div').children('.infoText').stop().animate({opacity : 0.7}, 250);
					} else {
						$(this).parent('div').parent('div').children('.infoText').stop().animate({opacity : 0}, 250);
					}
				});
				// click close Tag
				$('img.closeImg').click(function () {
					$(this).parent('div').parent('div').stop().animate({opacity : 0}, 500, function () {
						$(this).css({'display':'none'});
						/*
							Wiviel BIlder sind noch über ?
						*/
						var _galId = $(this).parent('div').attr('id');
						 _galId = _galId.split("_");	
						 _galId = _galId[2]; // works fine!
						 // Zählen wieviel auf display : none sind, und wieviel auf display : block sind
						 var _t_block = 0;
						 var _t_none  = 0;
						 $(this).parent('div').children('.image_wrapper').each(function () {
							var _stat = ($(this).css('display') == 'none')?'none':'block';
							if (_stat == 'none') {
								_t_none++;
							} else {
								_t_block++;
							}
						});
						if (_t_block == 0) {
							var _oldId = handleGal.identifyGal.search(_galId); // BSP letter-three rausfiltern
							//window.alert();
							handleGal.openGal(_galId, _oldId, false);
						}
						 
					});
				});
					// check num pic -> ggf. remove
				// click GalleryTag
				$('img.openAllImg').click(function () {
					//window.alert($(this).parent('div').parent('div').parent('div').children('.image_wrapper').length);
					$(this).parent('div').parent('div').parent('div').children('.image_wrapper').each(function () {
						var _stat = $(this).css('display');
						//window.alert(_stat);
						if (_stat == 'none') {
							$(this).css('display', 'block');
							$(this).animate({opacity : 1}, 500);
						} 
					});
				});
				
				
		//// IMG Dragable   [image_wrapper]
		$(".image_wrapper").draggable( {  drag: function() {
				//$(".image_wrapper").css("zIndex", "0");
				//$(this).css("zIndex", "20");
				$(this).css({'zIndex': handleGal.lastzIndex+1});
				}, start: function() {
					$(this).animate( { opacity: 0.75 }, 100);
				}, stop: function() {
					$(this).animate( { opacity: 1 }, 100);
					
		}});
		//// IMG RESIZEABLE [image_wrapper]
	
		$(function() {
			$(".image_wrapper").resizable({aspectRatio: true,  ghost : true});
			$("div").removeClass("ui-resizable");
			$(".image_wrapper div").css("opacity", 0);	
		});
		$('.image_wrapper').dblclick(function () {
			// gal Id herausfinden
				var _wrapperId = $(this).attr('id');
				_wrapperId = _wrapperId.split("-");
				// 0 = gal, 1 = pic
				//window.alert(_wrapperId[1]);
				// orginal höhe&breite herausfinden
				//window.alert(handleGal.holeGalArr[_wrapperId[0]]['pictures'][_wrapperId[1]]['oHeight']);
			
				var _oHeight = handleGal.holeGalArr[_wrapperId[0]]['pictures'][_wrapperId[1]]['oHeight'];
				var _oWidth  = handleGal.holeGalArr[_wrapperId[0]]['pictures'][_wrapperId[1]]['oWidth'];
				var _height  = handleGal.holeGalArr[_wrapperId[0]]['pictures'][_wrapperId[1]]['height'];
				var _width   = handleGal.holeGalArr[_wrapperId[0]]['pictures'][_wrapperId[1]]['width'];
				// wenn diese aktuelle höhe ist: auf thumb verkleinern
				if (parseInt($(this).css("height")) == _oHeight) {
					$(this).animate({
							'height' : _height,
							'width'  : _width
						}, 200);
				} else {
					$(this).animate({
							'height' : _oHeight,
							'width'  : _oWidth
						}, 200);
				}
				// ansonsten auf orginalhöhe
					
		}); 
	 },
}


$(document).ready(function () {
                      // $('body').append(handleGal.holeDivArr[0]);
	var gal_wrapper = $('#gal_wrapper');
/*
	Galery Klick
*/
  // startWrapper click
  $('#startWrapper img').click(function(){
    var _galId = $(this).attr('gal');
		var _oldId = $(this).attr('gal');
		_galId = _galId.replace(" ","-");
		_galId = _galId.toLowerCase();
		$('#startWrapper').remove();
		handleGal.openGal(_galId, _oldId, true);  
  });
	$('a.galleryLink').click(function () {
	  // entferne startwrapper
	  $('#startWrapper').remove();
		var _galId = $(this).attr('id');
		var _oldId = $(this).attr('id');
		_galId = _galId.replace(" ","-");
		_galId = _galId.toLowerCase();
		//window.alert(handleGal.navArray[0]);
		handleGal.openGal(_galId, _oldId, true);	
	});
	$('#contact').click(function() {
		shadowBox(1);
			var _mL = $(window).width()-357;
			_mL = _mL/2;
			$('#contactUs').css({display:'block', opacity : 0, marginLeft : _mL});
			$('#contactUs').animate({opacity:1}, 600, function(){
			$(window).click(function(){
				$(window).unbind();
				$('#contactUs').animate({opacity:0}, 600, function(){
					$('#contactUs').css('display', 'none'); 
					shadowBox(0);
				})
					
			});
			});
			
		shadowResize();
		$(window).resize(function(){
			shadowResize();
		});
	});
	function writeNav() {
		//window.alert("Aufgerufen");
		for (var x=0;x<handleGal.navArray.length;x++) {
			$('#navigation').append(handleGal.navArray[x]);
			continue;
		}
	}
	
/*
	Galery MouseOver
*/
/*
	$('img').hover(
					function () {
						$('img').animate({'opacity' : 0.6}, 60);
						$(this).stop().css('opacity', 1);
					}, 
					function () {
						$('img').stop().css('opacity', 1);
					}
					
					);
	
	// Testarea*/

	
  // resize
	    /*
	    S
	    */
	     
	    /*
	    */
});




