// ew.js - Funktionen fuer Essinger Wohnbau GmbH
// Copyright (c) 2011 Studioo, Brenner
// Erstellt: 2011-06-22
//
// Mischt beim Start die in der HTML deklarierte ew_options mit ew_defaults
// und initialisiert die Colorbox-Links

var ew_options = null;

var ew_defaults = {
	
	// Map-Einstellungen (public)
	mapZoom: 15,
	mapLat: null,
	mapLng: null,
	mapMarkerTitle: null,
	mapInfoWindowHTML: null,
	mapContainerId: null,
	mapMarkerDraggable: false,

	// 
	

	// Default Colorbox-Optionen:
	colorboxMaxWidth:  "90%",
	colorboxMaxHeight: "85%",
	colorboxCurrent:   "Bild {current} von {total}",
	colorboxPrevious:  "zurück",
	colorboxNext:      "weiter",
	colorboxClose:     "schließen",

	// Diverse (privat)
	colorboxDefaultContentId:  'colorboxContent',
	colorboxDefaultContent:    '<div id="colorboxContent" style="width: 100%; height: 100%;">Colorbox Content</div>',
	colorboxDefaultContentSWF: '<div id="colorboxContent" style="width: 100%; height: 100%; overflow: hidden"><div id="ewFlashContent"><p><strong><br />Ihr Browser kann kein Flash oder die Flash-Version ist zu alt.</strong><br />Sie können die aktuelle Version hier downloaden:</p><p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p></div></div>',
	colorboxResizeTimeout: 400
};

var ew_resizeTimeoutRef = null;



// Return: Array-Objekt mit map-Objekt google.maps.Map und dem marker-Objekt google.maps.Marker
function ew_startMap()
{
	// Init Maps

	// elementId = Id eines DIVs indem die Karte platziert wird (default=null)

	if (ew_options.mapContainerId == null)
	{
		ew_options.mapContainerId = ew_options.colorboxDefaultContentId;
	}

	// google maps v3
	//
	// http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/tutorial.html
	// Mobile Standalone-Version:
	// <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	//
	// Bsp.:
	// http://wired.propertylistingsoftware.com/property/gmap/162
	//

	var myLatLng = new google.maps.LatLng(ew_options.mapLat, ew_options.mapLng);
	
	var myOptions = {
		zoom: ew_options.mapZoom,
		center: myLatLng,
		mapTypeControl: true,
		mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
		navigationControl: true,
		mapTypeId: google.maps.MapTypeId.HYBRID
	};
	
	var ewMap = new google.maps.Map( document.getElementById( ew_options.mapContainerId ), myOptions);

	// Add the marker to the map
	var ewMarker = new google.maps.Marker({
		position: myLatLng,
		title: ew_options.mapMarkerTitle,
		map: ewMap,
		draggable: ew_options.mapMarkerDraggable
	});
	ewMarker.setMap(ewMap);  
	
	if (ew_options.mapInfoWindowHTML != null)
	{
		var infowindow = new google.maps.InfoWindow({
			content: ew_options.mapInfoWindowHTML
		});
		// infowindow.open(ewMap, ewMarker); // zeige sofort
	
		google.maps.event.addListener(ewMarker, 'click', function() {
			infowindow.open(ewMap, ewMarker);
		});
	}

	return {map: ewMap, marker: ewMarker};
}

function ew_startFlash( swfUrl )
{

	// SWF aus GET-Parameter 'swfpath' extrahieren
	swfUrl = unescape( swfUrl );
	var REG = /.*swfpath=(.*\.swf)/;
	REG.exec(swfUrl);
	swfUrl = RegExp.$1;//alert('URL: ' + RegExp.$1);

	// und SWF einfuegen
	var myAttributes = {
	   id: 'ewFlashContent',
	   allowFullScreen: 'true',
	   allowScriptAccess: 'sameDomain'
	   // wmode: opaque/* wmode = [window|opaque]
	};

	swfobject.embedSWF(swfUrl, 'ewFlashContent', "100%", "100%", "9.0.28", null, {}, {}, myAttributes);
}

function ew_releaseFlash()
{
	if (document.getElementById('ewFlashContent')) {
		swfobject.removeSWF('ewFlashContent');
	}
}

function ew_doColorboxResize()
{
	//var w = ( parseInt( $(window).width() ) * 0.9 ) + "px"; //ew_options.colorboxMaxWidth
	//var h = ( parseInt( $(window).height() ) * 0.9 ) + "px"; //ew_options.colorboxMaxHeight
	
	ew_resizeTimeoutRef = null;
	jQuery.fn.colorbox.resize({ width: ew_options.colorboxMaxWidth, height: ew_options.colorboxMaxHeight });
}

function ew_onColorboxResize(e)
{
	if (ew_resizeTimeoutRef != null) {
		// clearTimeout(ew_ResizeTimeoutRef);
		// ew_ResizeTimeoutRef = null;
		return;
	}

	ew_resizeTimeoutRef = setTimeout("ew_doColorboxResize()", ew_options.colorboxResizeTimeout);
}

function ew_initColorboxResizer()
{
	// resize binden
	$(window).bind('resize', ew_onColorboxResize );
}

function ew_releaseColorboxResizer()
{
	$(window).unbind('resize');
}

$(document).ready(function(){

	// Overwrite ew_default options 
	// with user provided ones 
	// and merge them into "ew_options". 
	ew_options = $.extend({}, ew_defaults, ew_options);

	// Bilder im Contentbereich
	$("a[rel='colorboxContentBildZoom']").colorbox({
		current:     ew_options.colorboxCurrent,
		previous:    ew_options.colorboxPrevious,
		next:        ew_options.colorboxNext,
		close:       ew_options.colorboxClose,
		maxWidth:    ew_options.colorboxMaxWidth,
		maxHeight:   ew_options.colorboxMaxHeight,
		//slideshow: true,
		scalePhotos: true
	});
	
	// Sonder-Bildergalerie im Contentbereich (15.11.2011 Brenner: fuer Darstellung Ploucquet Auftaktveranstaltung)
	var $sondergalerie = $("a[rel='colorboxSondergallerie']").colorbox({
		current:     ew_options.colorboxCurrent,
		previous:    ew_options.colorboxPrevious,
		next:        ew_options.colorboxNext,
		close:       ew_options.colorboxClose,
		maxWidth:    ew_options.colorboxMaxWidth,
		maxHeight:   ew_options.colorboxMaxHeight,
		//slideshow: true,
		scalePhotos: true,
		onOpen: (typeof(colorboxExt_onopen)!='undefined' ? colorboxExt_onopen : null),
		onLoad: (typeof(colorboxExt_onload)!='undefined' ? colorboxExt_onload: null),
		onCleanup: (typeof(colorboxExt_onclose)!='undefined' ? colorboxExt_onclose: null)
	});

	$('a[rel=colorboxSondergallerieStart]').click(function(e){
		e.preventDefault();
		$sondergalerie.eq(0).click();
	});

	// Init Gallery
	var $gallery = $("a[rel='colorboxGallery']").colorbox({
		current:     ew_options.colorboxCurrent,
		previous:    ew_options.colorboxPrevious,
		next:        ew_options.colorboxNext,
		close:       ew_options.colorboxClose,
		maxWidth:    ew_options.colorboxMaxWidth,
		maxHeight:   ew_options.colorboxMaxHeight,
		//slideshow: true,
		scalePhotos: true,
		onOpen: (typeof(colorboxExt_onopen)!='undefined' ? colorboxExt_onopen : null),
		onLoad: (typeof(colorboxExt_onload)!='undefined' ? colorboxExt_onload: null),
		onCleanup: (typeof(colorboxExt_onclose)!='undefined' ? colorboxExt_onclose: null)
	});
	
	$('a[rel=colorboxGalleryStart]').click(function(e){
		e.preventDefault();
		$gallery.eq(0).click();
	});

	var $grundriss = $("a[rel='colorboxGrundriss']").colorbox({
		current:     ew_options.colorboxCurrent,
		previous:    ew_options.colorboxPrevious,
		next:        ew_options.colorboxNext,
		close:       ew_options.colorboxClose,
		maxWidth:    ew_options.colorboxMaxWidth,
		maxHeight:   ew_options.colorboxMaxHeight,
		//slideshow: true,
		scalePhotos: true
	});

	$('a[rel=colorboxGrundrissStart]').click(function(e){
		e.preventDefault();
		$grundriss.eq(0).click();
	});

	var $kleinlage = $("a[rel='colorboxKleinlage']").colorbox({
		current:     ew_options.colorboxCurrent,
		previous:    ew_options.colorboxPrevious,
		next:        ew_options.colorboxNext,
		close:       ew_options.colorboxClose,
		maxWidth:    ew_options.colorboxMaxWidth,
		maxHeight:   ew_options.colorboxMaxHeight,
		//slideshow: true,
		scalePhotos: true
	});

	$('a[rel=colorboxKleinlageStart]').click(function(e){
		e.preventDefault();
		$kleinlage.eq(0).click();
	}); 

	// Init Map
	$("a[rel=colorboxMap]").colorbox({
		onComplete:  function(){ ew_initColorboxResizer(); ew_startMap(); },
		onCleanup:   function(){ ew_releaseColorboxResizer(); },
		close:       ew_options.colorboxClose,
		width:       ew_options.colorboxMaxWidth,
		height:      ew_options.colorboxMaxHeight,
		html:        ew_options.colorboxDefaultContent
	});
	
	// Init Flash Expose
	$("a[rel=colorboxFlashExpose]").colorbox({
		
		onComplete:  function(){ ew_initColorboxResizer(); var swfUrl = $(this).context.href; ew_startFlash( swfUrl ); },
		onCleanup:   function(){ ew_releaseFlash(); ew_releaseColorboxResizer(); },
		close:       ew_options.colorboxClose,
		width:       ew_options.colorboxMaxWidth,
		height:      ew_options.colorboxMaxHeight,
		html:        ew_options.colorboxDefaultContentSWF
	});
	
	// Init Film
	$("a[rel=ewProjektFilm]").colorbox({
		href: function() { return $(this).attr('href') + ' .video-js-box'; },
		close: ew_options.colorboxClose,
		data: 'callByAjax=1',
		rel: 'nofollow',
		width: 840,
		height: 540
	});
	
	// Init Ajax
	$("a[rel=colorboxAjax]").colorbox({
		href: function() { return $(this).attr('href') + ' #ajaxContainer'; },
		close: ew_options.colorboxClose,
		data: 'callByAjax=1',
		rel: 'nofollow',
		width: ew_options.colorboxMaxWidth,
		maxHeight: ew_options.colorboxMaxHeight
	});
	
	var REG = /iPhone|iPod.* OS \d+_/;
	if (REG.test(navigator.userAgent))
	{
		$("#cboxOverlay").css({'width': '975px', 'height': '20975px'});
	}
	
	// Init Essinger Wohnbau Slider
	$("ul#ewSlider").ewSlider();

});










(function($)
{
	$.fn.ewSlider = function(variables) 
	{

		var defaults = 
		{
			slides: 'li',			// the element inside the container which serve as slide
			animationSpeed: 1000,		// animation duration
			autorotationSpeed: 5		// duration between autorotation in Seconds
			
		};

		var options = $.extend(defaults, variables);

		return this.each(function()
		{
			var slideContainer = $(this);	// container element
			var slides         = slideContainer.find(options.slides);
			var images         = slideContainer.find('img');
			var imagesToLoad   = images.length;
			var currentSlideNumber  = 0;
			var nextSlideNumber  = 0;
			var timeoutReference = null;
			
			slideContainer.methods = {

				init: function()
				{
					images.each( function(i, event)
					{
						var image = $(this);
						
						if (event.complete == true)
						{	
							//alert('loaded already');
							slideContainer.methods.imageLoaded(image);
						}
						else
						{	
							//alert('have to load');
							image.bind('error load', { loadedImage: image }, slideContainer.methods.imageLoaded );
						}
					});
				},
				
				imageLoaded: function(image)
				{
					imagesToLoad --;

					if( typeof( image.data.loadedImage ) != 'undefined' )
					{
						var image = image.data.loadedImage;
						image.unbind();
					}
					
					if (imagesToLoad == 0)
					{
						//alert('everything has been loaded');
						
						slideContainer.methods.prepareNextSlide();
					}
				},
				
				
				
				toggleSlide: function( slideNumber )
				{
					if( typeof( slideNumber.data) != 'undefined' && typeof( slideNumber.data.slideNumber ) != 'undefined' )
					{
						slideNumber = slideNumber.data.slideNumber;
					}
					else
					{
						//alert('no slideNumber received by toggleSlide('+slideNumber+')');
						//return;
					}
					nextSlideNumber = slideNumber;

					slides.each( function(i)
					{
						var slide = $(this);
						
						slide.stop();
						
						if (i == nextSlideNumber)
						{
							slide.css({ 'opacity': 0.0,  'display': 'block' , 'z-index': 3});
							slide.animate(
									{ opacity: 1.0 },
									options.animationSpeed,
									slideContainer.methods.toggleSlideReady
								);
						}
						else
						{
							slide.css( { 'z-index': 2 } );
						}
					});
					
					
					
				},
				
				toggleSlideReady: function()
				{
					//alert('callback');
					slides.each( function(i)
					{
						if (i != nextSlideNumber)
						{
							var slide = $(this);
							slide.css({ 'opacity': 0.0 } );
						}
					});
					currentSlideNumber = nextSlideNumber;
					slideContainer.methods.prepareNextSlide();
				},
				
				prepareNextSlide: function()
				{
					if (timeoutReference != null)
					{
						window.clearTimeout( timeoutReference );
						timeoutReference = null;
					}
					timeoutReference = window.setTimeout(
						function() {
							var nr = currentSlideNumber + 1;
							if (nr >= slides.length)
							{
								nr = 0;
							}
							slideContainer.methods.toggleSlide( nr );
						},
						parseInt(options.autorotationSpeed) * 1000
						);
				}
				
			};
			
			slideContainer.methods.init();
		});
		
	};
}) (jQuery);



// Brenner 18.11.2011: Erweiterung colorbox um Preview-Icons

function colorboxExt_onopen(ev)
{

	var $element = $.colorbox.element();
	var relation = $element.attr('rel');

	var nr = 0;
	var ext_html = '';
	$('a[rel='+relation+']').each(function(index) {
		ext_html += '<a href="#" onclick="$.colorbox.oo_loadindex('+nr+');return false" style="margin-right: 3px">' +
		            '<img src="'+$(this).attr('href')+'" height="40" style="border: 1px solid silver;" />' +
		            '</a>';
		nr ++;
	});
	if (nr > 1)
	{
		$('body').append('<div class="cboxthumbnailbar" style="display: none; position: absolute; z-index: 9999; left: 0; top: 0; height: 40px; width: 100%; text-align: center">'+ext_html+'</div>');
	}

}

function colorboxExt_onload(ev)
{
	setTimeout( function() {
		var vpos = parseInt( $('#colorbox').css('top') ) + parseInt( $('#colorbox').height() ) + 60;
		$('div.cboxthumbnailbar').css('top', vpos);
		$('.cboxthumbnailbar').show();
		}, 20 );
}

function colorboxExt_onclose(ev)
{
	$('div.cboxthumbnailbar').detach();
}




// Brenner 7.12.2011: Erweiterung Newsticker

(function($)
{
	$.fn.ewTicker = function(variables) 
	{

		var defaults = 
		{
			contentElement: 'p',			// the element inside the container which serve as slide
			overlayClass:   'ewTickerOverlay',	// an overlay may registered at runtime (css class)
			animationSpeed: 3800,			// animation duration per 100px
		};

		var options = $.extend(defaults, variables);

		return this.each(function()
		{
			var tickerContainer  = $(this);	// container element
			var contentElement   = tickerContainer.find( options.contentElement );
			var overlayElement   = null;
			var timeoutReference = null;
			
			tickerContainer.methods = {

				init: function()
				{
					tickerContainer.append('<div class="' + options.overlayClass + '"></div>');
					overlayElement = tickerContainer.find( '.' + options.overlayClass );
					overlayElement.width( tickerContainer.width() );
					overlayElement.height( tickerContainer.height() );
					tickerContainer.methods.restart();
				},
				
				restart: function()
				{
					var speed = Math.round( options.animationSpeed / 100 * contentElement.width() );
					contentElement.css('left', tickerContainer.width() );
					contentElement.animate({
						left: '-' + contentElement.width()
					}, speed, "linear", function() {
						tickerContainer.methods.restart();
					});
				}
				
			};

			tickerContainer.methods.init();
		});
		
	};
}) (jQuery);

