$(document).ready(function() {
	
	// -------------------------------------------------------
	// set error handler for AJAX calls via jquery -----------
	// -------------------------------------------------------
	$.ajaxSetup({
		error:function(x,e){
			if(x.status==0){
				alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
				alert('Requested URL not found.');
			}else if(x.status==500){
				alert('Internel Server Error.');
			}else if(e=='parsererror'){
				alert('Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
				alert('Request Time out.');
			}else {
				alert('Unknow Error.\n'+x.responseText);
			}
		}
	});

	// -------------------------------------------------------
	// block code definitions --------------------------------
	// -------------------------------------------------------
	var slide_fadeTime = 1000/2;
	var slide_pauseTime = 5000/2 ;  	
	var slide_startOffset = 400;

	var loadedImages = new Array();
	
	var displayed_entry = new Array(1,1,1); // max three blocks
	
	var start_width_pause = true;
	if (block_headers[0] == '../media/himmel_header.jpg') { // simple workaround for haz - no pause
		start_width_pause = false;
	}
	var now = new Date(); // workaround (you just have to love the caching of the ajax calls in IE...)
	var transitionsComplete = 0; 
	
	var crossSlidesSum = 0;
	var crossSlidesCount = 0;
	var crossSlidesSingleImage = 0;
	var loadingCircleActive = false;
	
	buildBlockElements (block_images.length);

	// -------------------------------------------------------
	// block code (+check: flash / images) ---------------------
	// -------------------------------------------------------
	function buildBlockElements (buildCount) {
		crossSlidesSum = buildCount;
		loadingCircleActive = true;
		
		for (var i = 1 ; i <= crossSlidesSum ; i++) {
			// add handler (to load new block entry) where it is needed 
			// jquery or php navigation check
			// if an column_type has more than one entries a php script will generate a 'previous','next' button in the sub_navigation
			// if, however, all entries of this column_tpye contain only ONE image the php navigation will be replaced by a jquery navigation
			// this is, because in the case of the php navigation not only the single block but all of the page will be reloaded
			// causing the other block images to fadein again
			if (block_entries[i-1] != 'single') {
				set_sub_navigation(i, false, true);
			}
			
			loadedImages.push ({ images: new Array(), url: new Array(), count: 0, slidShowcounter: 0});
			$('#block_holder' + i).showLoading();
			loadImagesNames(i, 1);
		}
		
		/*
		 * flash check:
		 * if a swf is to be displayed in the block the empty.gif image will still be loaded in the image container (set in loadImagesNames)
		 * as there are no transitions for single images it will simple remain and the flash file diplayed over it 
		 * (only one swf can be displayed in each block)
		 */
		for (var i = 1 ; i <= crossSlidesSum ; i++) {
			if (block_types[i-1] == 'flash') {
				preloadFlash(i);
			}
		}
	} 
	

	// -------------------------------------------------------
	// load different column entry -----.---------------------
	// -------------------------------------------------------
	function set_sub_navigation (target, hasprevious, hasnext) {
		$('#block_holder' + target).parent().children('.block_sub_navigation').children('.prev').html('&nbsp;');
		$('#block_holder' + target).parent().children('.block_sub_navigation').children('.next').html('&nbsp;');
		
		if (hasprevious) {
			$('#block_holder' + target).parent().children('.block_sub_navigation').children('.prev').html('<a href="#"><</a>');
			$('#block_holder' + target).parent().children('.block_sub_navigation').children('.prev').children('a').click(function (event) { 
			     event.preventDefault();
			     load_new_block_entry ($(this).parent().parent().parent().children('.block_holder').attr('id'), 'prev');
			});
		}
		if (hasnext) {
			$('#block_holder' + target).parent().children('.block_sub_navigation').children('.next').html('&nbsp;<a href="#">></a>');
			$('#block_holder' + target).parent().children('.block_sub_navigation').children('.next').children('a').click(function (event) { 
			     event.preventDefault();
			     load_new_block_entry ($(this).parent().parent().parent().children('.block_holder').attr('id'), 'next');
			});
		}
	}
	
	function load_new_block_entry (blocknr, direction) {
		$.post(
				main_path + "scripts/block/scripts/load_block_entry.php?t=" + now.getTime(),
		    {
		    	block_column_type:block_column_types[$('#' + blocknr).attr('columnid')-1],
		    	displayed_entry:displayed_entry[$('#' + blocknr).attr('columnid')-1],
		    	direction:direction,
		    	snippet: 's_n' + '_i_p'
		    },  
		    function(data){
		    	//	returns:
		    	//		data.error (invaliddata / loaderror)
		    	//		data.text
		    	//		data.hasprevious
		    	//		data.hasnext
		    	//		data.newid
		    	//		data.newimage
				
		    	if (data.error == 'invaliddata' || data.error == 'loaderror') {
		    		//alert(data.error); 
		    	} else {
		    		$('#' + blocknr).parent().children('.block_text').fadeOut(200, function () {
		    			$(this).html(data.text);
		    			$(this).fadeIn(200);
		    		});
		    		displayed_entry[$('#' + blocknr).attr('columnid')-1] = data.newid;
		    		set_sub_navigation ($('#' + blocknr).attr('columnid'), (data.hasprevious == 'true' ? true : false), (data.hasnext == 'true' ? true : false));
		    		
		    		if (data.newimage.length > 4) {
		    			$('#' + blocknr).children('.block_image').css('background-image', 'url("' + main_path + 'media/' + data.newimage + '")');
		    		} else {
		    			$('#' + blocknr).children('.block_image').css('background-image', 'url("' + empty_file + '")');
		    		}
		    	}
		    },
		    "json"
		);
	}

	
	// -------------------------------------------------------
	// flash code ----------------------------------------
	// -------------------------------------------------------
	function preloadFlash(targetID) {
		// TODO:
		// $.flash.hasVersion(9.1) // returns true if at least Flash 9.1 or greater is detected
		// return $.flash.available; // returns true or false if flash player is available
		$.flash.expressInstaller = 'scripts/expressInstall.swf';
		$('#block_holder' + targetID).append('<a style="display:none" href="' + block_images[targetID-1][0][0] + '"></a>');
		$('#block_holder' + targetID).append('<a href="' + block_images[targetID-1][0][0] + '"></a>');
		var targetSWF = $('#block_holder' + targetID + ' a').attr('href');
		
		
		onFlashLoaded(targetSWF, targetID); // workaround - JSON parse bug of IE		
		//$('#block_holder' + targetID + ' a').load( targetSWF, onFlashLoaded(targetSWF, targetID));
	}
	
	function onFlashLoaded(targetSWF, targetID) {
		$('#block_holder' + targetID).hideLoading();
		
		$('#block_holder' + targetID + ' .block_flash').css('display', 'none');
		$('#block_holder' + targetID + ' .block_flash').flash(
			{
				swf: targetSWF,
				height:214,
				width:285
			}
		);
		$('#block_holder' + targetID + ' .block_flash').delay(slide_startOffset*(targetID-1)).fadeIn(slide_fadeTime);
		$('#block_holder' + targetID + ' a').remove();

	}
	
	// -------------------------------------------------------
	// slideshow code ----------------------------------------
	// -------------------------------------------------------
	function loadImagesNames(imageType, callNr) {
		var block_number_of_calls = block_images[imageType-1].length;
		
		var block_overall_images = 0;
		for (var i = 0 ; i < block_images[imageType-1].length ; i++) {
			block_overall_images += block_images[imageType-1][i].length;
		}
		
		// display empty.gif if swf will be diplayed in top container else use defined images
		if (block_types[imageType-1] == 'flash') {
			var imageArray_temp = new Array(empty_file);
		} else {
			var imageArray_temp = block_images[imageType-1][callNr-1];
		}
		
		loadedImages[imageType-1].count = block_overall_images;
		preloadImages (imageArray_temp, imageType, 0, block_number_of_calls, callNr);
	}
	
	function preloadImages(imageArray, imageType, counter, numberOfCalls, callNr) {
		if (imageArray.length > counter) {
			preloadSingleImage (imageArray, imageType, counter, numberOfCalls, callNr);
		} else {
			if (callNr == 1) { // first load completed - inform handler
				onReady();
			}
			
			if (callNr < numberOfCalls) { // there is more to load
				callNr++;
				loadImagesNames (imageType, callNr);
			} else { // loading completed
				// supi...
			}			 
		}
	}

	function preloadSingleImage(imageArray, imageType, counter, numberOfCalls, callNr) {
		var loadedImage = $('<img />')
			.attr('src', imageArray[counter]+ '?random=' + (new Date()).getTime()) // IE 'super' caching workaround
			.load(function(){
				loadedImages[imageType-1].images.push ($(this));
				loadedImages[imageType-1].url.push (imageArray[counter]);
				counter++;
				preloadImages (imageArray, imageType, counter, numberOfCalls, callNr);
			});
	}

	function onReady() {
		crossSlidesCount++;
		if (crossSlidesCount == crossSlidesSum) {
			if (loadingCircleActive) {
				loadingCircleActive = false;

				for (var i = 1 ; i <= crossSlidesSum ; i++) {
					// if the image is just an empty background and a swf will be be displayed let the flash function handle the hideLoading
					if (block_types[i-1] != 'flash') {
						$('#block_holder'+i).hideLoading();
					}
						
					// check on first init if all crossslides have only one image to avoid empty loop
					if (loadedImages[(i-1)].count == 1) {
						crossSlidesSingleImage++;
					}
				}
			} else {
				transitionsComplete++;
			}
			
			crossSlidesCount = 0;

			if (transitionsComplete == 0) {
				startTransition(); 
				addPauseFunction(); // after (!) transition start
			} else {
				setTimeout(startTransition, slide_pauseTime); 
			}
		}
	}
	
	function startTransition() {
		for (var i = 1 ; i <= crossSlidesSum ; i++) {
			displaySlide(i);
		}
	}
	
	function addPauseFunction() {
		for (var i = 1 ; i <= crossSlidesSum ; i++) {
			if (start_width_pause) {
				$('#block_holder' + i).addClass('pause'); // PAUSE AT START
			}

			if (block_types[i-1] != 'flash' && loadedImages[i-1].count > 1) {
				
				// hover handler to display / hide pause-play div
				$('#block_holder' + i).hover(
					function () {
						$(this).children('.playpause').fadeIn(200);
					}, 
					function () {
						$(this).children('.playpause').fadeOut(200);
					}
				);
				
				// click handler to halt / continue the slideshow
				$('#block_holder' + i).click(function() {
					if ($(this).hasClass('pause')) {
						$(this).removeClass('pause');
					} else {
						$(this).addClass('pause');
					}
				});
			}
		}
	}

	function displaySlide(imageType) {
		if ($('#block_holder' + imageType).hasClass('pause')) {
			onReady();
		} else if (block_types[imageType-1] == 'flash') {
			// block displayes actually an swf leave setting like in style.css (display: none)
			onReady();
		} else if (crossSlidesSingleImage == crossSlidesSum && loadedImages[imageType-1].slidShowcounter == 1) {
			// every element has only one image and that is already displayed - no further calls necessary
		} else if (loadedImages[imageType-1].count == 1 && loadedImages[imageType-1].slidShowcounter == 1) {
			// there is just one image but other crossslides display more - do not initiate further transitions for this one
			onReady();
		} else {
			var upperHolder = $('#block_holder' + imageType + ' .block_image_2');
			var lowerHolder = $('#block_holder' + imageType + ' .block_image_1');
			
			if (loadedImages[imageType-1].slidShowcounter == loadedImages[imageType-1].url.length) { // if max or not yet loaded
				if (loadedImages[imageType-1].slidShowcounter % 2 == 1) {
					// slideShow has end at targetMode = 0 (switch display states to keep flow)
					lowerHolder.css('background-image', 'url(' + loadedImages[imageType-1].url[loadedImages[imageType-1].slidShowcounter-1] + ')');
					upperHolder.css('display', 'none');
				}
				loadedImages[imageType-1].slidShowcounter = 0;
			} 
			
			var targetMode = loadedImages[imageType-1].slidShowcounter % 2;
			
			if (targetMode == 0) {
				upperHolder.css('background-image', 'url(' + loadedImages[imageType-1].url[loadedImages[imageType-1].slidShowcounter] + ')');
				upperHolder.delay(slide_startOffset*(imageType-1)).fadeIn(slide_fadeTime).queue(function() {
					//alert('pause complete.');
					if (loadedImages[imageType-1].slidShowcounter == 0) {
						lowerHolder.css('display', 'inline');
					}
					loadedImages[imageType-1].slidShowcounter++;
					onReady();
					$(this).dequeue();
				});
			} else {
				lowerHolder.css('background-image', 'url(' + loadedImages[imageType-1].url[loadedImages[imageType-1].slidShowcounter] + ')');
				upperHolder.delay(slide_startOffset*(imageType-1)).fadeOut(slide_fadeTime).queue(function() {
					//alert('pause complete.');
					loadedImages[imageType-1].slidShowcounter++;
					onReady();
					$(this).dequeue();
				});
			}
		}
	}
});	
