var old_content
var address

   var map;
   var gdir;
   var geocoder = null;
   var addressMarker;

   function load() {
     if (GBrowserIsCompatible()) {
       map = new GMap2(document.getElementById("map_canvas"));
       map.setCenter(new GLatLng(0, 0), 10);
       map.setMapType(G_NORMAL_MAP);

    //map control
       var mapTypeControl = new GMapTypeControl();
       var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
       var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
       map.addControl(mapTypeControl, topRight);
       map.addControl(new GSmallMapControl());

	//target address
	  var geocoder=new GClientGeocoder();
	  geocoder.getLatLng(
	    address,
	    function(point)
	    {
	      if (!point)
	      {
	        alert(address + " not found");
	      }
	      else
	      {
	        map.setCenter(point, 14);
	        var marker = new GMarker(point);
	        map.addOverlay(marker);
	        marker.openInfoWindowHtml(address);
	      }
	    }
	  );

	//routing
       gdir = new GDirections(map, document.getElementById("directions"));
       GEvent.addListener(gdir, "load", onGDirectionsLoad);
       GEvent.addListener(gdir, "error", handleErrors);
     }
   }

   function setDirections(from) {
     gdir.load("from: " + from + " to: " + address,
               { "locale": 'de' });
     $(".printer, #directions").show();
     $("#map_print").text("Karte & Plan drucken").css("margin-left", "30px");
   }

   function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("Fuer die eingegebene Addresse wurde kein geografischer Ort gefunden.\n Die gesuchte Adresse ist moeglichweise noch zu neu oder falsch.\nBitte versuchen Sie es mit 'Strasse Nr, PLZ Ort'.\n\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("Google Maps Fehler\n\nA geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n\n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("Google Maps Fehler\n\nThe HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("Google Maps Fehler\n\nThe geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n\n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("Google Maps Fehler\n\nThe given key is either invalid or does not match the domain for which it was given. \n\n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("Google Maps Fehler\n\nA directions request could not be successfully parsed.\n\n Error code: " + gdir.getStatus().code);

   else alert("Google Maps Fehler\n\nAn unknown error occurred.");

}

function onGDirectionsLoad(){
         // Use this function to access information about the latest load()
         // results.

         // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

//NATIVE FUNCTIONS
var change_background_image=undefined;

var preloadImage=function(src, onload){

	var image=new Image()
	image.src=src;

	if($.browser.msie){
	    function testImg(){
	        if(image.complete != null && image.complete == true){
	                onload();
	                return;
	        }
	        setTimeout(testImg, 500);
	    }
	    setTimeout(testImg, 500);
	}else{
	    image.onload = onload
	}
};

var switch_form_result_to_form=function(id){

	var $form_container=CoreX("#"+id+":not(:visible, :animated)");
	var $form_result_container=CoreX("#"+id+"_result");

	if($form_result_container.parent().find(".image_description").is(":visible"))
	{
		//$form_result_container.slideUp(800);
		$form_container.animate({
					opacity: 0.8,
					filter: 'alpha(opacity=80)',
					height: 'toggle'
					}, 800, "swing");
	}
}

//START ACTIONS

//CONTENT MANIPULATION
CoreX(window).ready(function(){

	//image gallery tooltips
	var ttname="tooltip";
	var ttcount=0;
	Core(".image_gallery a").livequery(function(){

		CoreX(this).hover(function(e){
			if(!CoreX("#tooltip").is(":visible"))
			{
				if(this.title != "")
				{
					CoreX(this).find("img").attr("alt", "");

					this.t = this.title;
					this.title = "";
					CoreX(this).parent().parent().append("<div id='tooltip'>"+ this.t +"</div>");
					CoreX("#tooltip")
						.css("top","41px")
						.css("left", (CoreX(this).position().left + 27)+"px")
						//.css("left",((((CoreX(this).parent().width() - CoreX(this).position().left)) ) - CoreX(this).width() - 8 + 18) + "px")
						.fadeIn("fast");
				}
				else
				{
					this.t="";
				}
			}

		}, function(){
			if(this.t != "")
			{
				this.title = this.t;
				$("#tooltip").remove();
			}
		});

	});

	if($.browser.msie && $.browser.version < 7)
	{
		CoreX(".content_layer, #sub_navigation").each(function(){
			CoreX(this).find(".content_layer_background").height(CoreX(this).outerHeight());
			CoreX(this).find(".content_layer_background").width(CoreX(this).outerWidth());
		});
	}
});

//startanimation
var $logo, $navi, $content, $background, resize_background;
var show_init_background=true;

var start_animation=function(){

	if(show_init_background && window.location.hash.substring(1) == "")
	{
		resize_background();
		$background.show();
	}

	CoreX("#start_loading_layer").fadeOut(800, function(){
		$navi.find("a").hide().end().show();

		$logo.fadeIn(1000, function(){
			//$logo.fadeIn(1000);
			$navi.find("a:eq(0)").fadeIn(1500);
			$navi.find("a:eq(1)").fadeIn(1700, function(){
				$content.fadeIn(800);

				if(CoreX("#navi a.active img[alt='fallstudien']").length>0)
				{
					CoreX("#sub_navigation").fadeIn(1000);
				}
			});
			$navi.find("a:eq(2)").fadeIn(1900);
			//$navi.filter(":eq(3)").fadeIn(2100);
			$navi.find("a:eq(3)").fadeIn(2200);
			//$navi.filter(":eq(5)").fadeIn(2300);
			//$navi.filter(":eq(6)").fadeIn(2400);
			$navi.find("a:eq(4)").fadeIn(2500);
		});
	}).remove();

};

//DOCUMENT MANIPULATION
CoreX(document).ready(function(){

	//startanimation variables
	$logo=CoreX("#logo");
	$navi=Core("#navi_wrap");
	$content=CoreX("#content_area_wrap");
	$background=CoreX("#site_background img");

	//image preload and animation start
	var navi_img_preload_counter=1;

	if ( !($.browser.msie && $.browser.version < 7) )
	{
		CoreX("#sub_navigation").hide();
		$logo.hide();
		$navi.fadeOut(0);
		$content.hide();
		if(show_init_background)
		{
			$background.hide();
		}

		//display load layer
		CoreX("body").append("<div id=\"start_loading_layer\"><img src=\"/client/neun/static/images/loader.gif\" alt=\"\" /></div>")

		//start startanimation
		var src=$background.filter(".fadein").attr("src");

		preloadImage(src, function(){
			navi_img_preload_counter--;

			if(navi_img_preload_counter==0)
			{
				start_animation();
			}
		});
	}
	else if(CoreX("#navi a.active img[alt='fallstudien']").length<=0)
	{
		CoreX("#sub_navigation").hide();
	}

	CoreX("#navi a img").each(function(){
		var src=CoreX(this).attr("src");
		var src_clean=src.replace("_hover", "");
		var src_hover=src_clean.replace(".gif", "_hover.gif");

		navi_img_preload_counter++;
		preloadImage(src_clean, function(){
			navi_img_preload_counter--;

			if(navi_img_preload_counter==0)
			{
				start_animation();
			}
		});

		navi_img_preload_counter++;
		preloadImage(src_hover, function(){
			navi_img_preload_counter--;

			if(navi_img_preload_counter==0)
			{
				start_animation();
			}
		});
	});

	//navigation
	Core("#navi").livequery(function(){
		CoreX("a", this).hover(function(){

			if(CoreX(this).hasClass("active"))
			{
				CoreX("img", this).attr("src", CoreX("img", this).attr("src").replace("_hover", ""));
			}

			CoreX("img", this).attr("src", CoreX("img", this).attr("src").replace(".gif", "_hover.gif"));

		}, function(){

			if(!CoreX(this).hasClass("active"))
			{
				CoreX("img", this).attr("src", CoreX("img", this).attr("src").replace("_hover", ""));
			}

		});
	});

	//extern gallery image link
	if(window.location.hash.substring(1) != "")
	{
		var hash=window.location.hash.substring(1);
		var parameter=hash.replace("image_gallery_click,", "").split(",");

		if(parameter.length==2)
		{
			show_init_background=false;

			CoreX("#site_background").hide();


			$link=CoreX(".image_gallery[id='image_gallery_"+parameter[0]+"'] a[id='gallery_image_"+parameter[1]+"']");
			preloadImage($link.find("img").attr("src"), function(){
				$link.trigger("click");
			});
		}
	}

	//background resizing functions
	var $window=CoreX(window);
	var $gallery_stage=CoreX("#site_background");
	var $gallery_stage_fadein=$gallery_stage.find(".fadein");
	var $gallery_stage_background=$gallery_stage.find(".background");/*
	var $background=CoreX("#site_background");
	var $background_fadein=$background.find(".fadein");
	var $background_background=$background.find(".background");*/

	resize_background=function(){

		var window_width=$window.width();
		var window_height=$window.height();

		//background area hack
		if ( ($.browser.msie && $.browser.version < 7) )
		{
			CoreX(".background_area").attr("style", "width:"+window_width+"px;height:"+window_height+"px;");
		}

		//background
		if(arguments.length!=0 && arguments[0]['type']==undefined)
		{
			for( var i = 0; i < arguments.length; i++ )
			{
				$this=arguments[i];

				if($this.attr("src")!= "" && $this.width() != 0 && $this.height() != 0)
				{
					var image = new Image()
					image.src=$this.attr("src");

					var image_width=image.width;
					var image_height=image.height;

					var width_factor=window_width/image_width;
					var height_factor=window_height/image_height;

					if(width_factor>height_factor)
					{
						var width=width_factor*image_width;
						var height=width_factor*image_height;
					}
					else
					{
						var width=height_factor*image_width;
						var height=height_factor*image_height;
					}

					$this.css("width", width+"px");
					$this.css("height", height+"px");
				}
			}
		}
		else
		{
			CoreX(".background_area img").each(function(){
				$this=CoreX(this);

				if($this.attr("src")!= "" && $this.width() != 0 && $this.height() != 0)
				{
					var image = new Image()
					image.src=$this.attr("src");

					var image_width=image.width;
					var image_height=image.height;

					var width_factor=window_width/image_width;
					var height_factor=window_height/image_height;

					if(width_factor>height_factor)
					{
						var width=width_factor*image_width;
						var height=width_factor*image_height;
					}
					else
					{
						var width=height_factor*image_width;
						var height=height_factor*image_height;
					}

					$this.css("width", width+"px");
					$this.css("height", height+"px");
				}
			});
		}

	}
/*
	var change_site_background_image=function(src, callback){

		if($background.is("not(:visible)"))
		{
			$background.show().find(".background").hide();
		}

		preloadImage(src, function(){

			$background_fadein.hide().attr("src", src);
			resize_background($background_fadein);
			$background_fadein.fadeIn(1000, function(){
				$background_background.attr("src", src).show();
				resize_background($background_background);

				callback();
			});

		});
	}*/

	change_background_image=function(src, callback){

		if($gallery_stage.is(":not(:visible)"))
		{
			$gallery_stage.show();
			$gallery_stage.find(".background").hide();
			$gallery_stage.find(".fadein").hide();
		}

		preloadImage(src, function(){

			$gallery_stage_fadein.hide().attr("src", src);
			resize_background($gallery_stage_fadein);
			$gallery_stage_fadein.fadeIn(1000, function(){
				$gallery_stage_background.attr("src", src).show();
				resize_background($gallery_stage_background);

				callback();
			});

		});
	}

	//IMAGE GALLERY
	CoreX("#content_area .content_layer.image_gallery a").live('click', function(){

		var $this=CoreX(this);
		var $text_container=CoreX("#"+$this.parents(".content_layer").attr("id")+"_description");

		var $form=CoreX("#"+$this.parents(".content_layer").attr("id")+"_description_form");
		$form.find("input[type='text'], textarea").val("");

		var image_url="http://";
		var host=window.location.host;
		var a="";
		var gallery_id=$this.parents(".content_layer").attr("id").replace("image_gallery_", "");
		var image_id=$this.attr("id").replace("gallery_image_", "");

		if(window.location.hash.substring(1) != "" && window.location.hash.indexOf(",")==-1)
		{
			a="/"+window.location.hash.substring(1)
		}
		else
		{
			a=window.location.pathname;
		}

		image_url+=host+a+"#image_gallery_click,"+gallery_id+","+image_id

		$form.find("input[name='gallery_image_link']").attr("value", image_url);
		$form.find("input[name='gallery_image_name']").attr("value", ((document.title!="")?document.title+" - ":"")+$this.find("img").attr("alt"));

		//close in current gallery & open selected
		if($this.is(":not(.active)") && $text_container.is(":visible") && $this.attr("rel")!="")
		{

			//set background
			change_background_image($this.attr("href"), function(){

				//animation out
				CoreX(".image_form_result:visible").slideUp(500);
				CoreX(".image_form:visible").slideUp(500);
				CoreX(".image_description:visible").animate({
						opacity: 0.0,
						filter: 'alpha(opacity=0)'
						}, 0, "swing", function(){
					if($this.attr("rel")!="")
					{
						//description fill
						$text_container.find(".image_description_title").text($this.find("img").attr("alt"));
						$text_container.find(".image_description_text").text($this.attr("rel"));
					}
				});

				//animation in
				if($this.attr("rel")!="")
				{
					//animation
					$text_container.animate({
						opacity: 0.8,
						filter: 'alpha(opacity=80)'
						}, 0, "swing");
				}
			});

			//set/remove link active
			CoreX(".image_gallery a.active").removeClass("active");
			$this.addClass("active");
		}
		//close every & open selected (if its not selected already)
		else
		{
			if($this.is(".active"))
			{
				//do nothing...

				return false;
			}

			//animation out
			if(CoreX(".image_form").is(":visible"))
			{
				CoreX(".image_form_result:visible").slideUp(500);
				CoreX(".image_form:visible").slideUp(500, function(){
					CoreX(".image_description:visible").slideUp(500);
				});
			}
			else
			{
				CoreX(".image_form_result:visible").slideUp(500);
				CoreX(".image_description:visible").slideUp(500);
			}

			//set gallery background image
			change_background_image($this.attr("href"), function(){

				//animation in (if its not selected already)
				if($this.attr("rel")!="")
				{
					//description fill
					$text_container.find(".image_description_title").text($this.find("img").attr("alt"));
					$text_container.find(".image_description_text").text($this.attr("rel"));

					//animation
					$text_container.attr("style", "opacity: 0.0;filter:alpha(opacity=0);").animate({
						opacity: 0.8,
						filter: 'alpha(opacity=80)',
						height: 'toggle'
						}, 500, "swing");
				}
			});

			//set/remove link active
			CoreX(".image_gallery a.active").removeClass("active");
			$this.addClass("active");
		}

		return false;
	});

	//image gallery form
	CoreX(".image_description_link a").live("click", function(){

		var $form_container=CoreX("#"+CoreX(this).parents(".content_layer").attr("id")+"_form");

		if($form_container.is(":visible"))
		{
			$form_container.slideUp(800);
			CoreX("#"+CoreX(this).parents(".content_layer").attr("id")+"_form_result").slideUp(800);
		}
		else
		{
			$form_container.animate({
						opacity: 0.8,
						filter: 'alpha(opacity=80)',
						height: 'toggle'
						}, 800, "swing");
		}

		return false;
	});

	CoreX(".image_form_link a").live("click", function(){
		var $this=Core(this);
		var $form=$this.parents("form");
		var image_form_id=$this.parents(".image_form").attr("id");
		var $form_container=CoreX("#"+image_form_id);
		var $form_result_container=CoreX("#"+image_form_id+"_result");

		var valid_form=true;
		$form.find("input.required, textarea.required").each(function(){
			if(CoreX(this).val()=="")
			{
				valid_form=false;
			}
		});

		if(valid_form)
		{
		    $form.ajaxify({
				target: "#"+image_form_id+"_result",
				link: $form.attr("action"),
				event:false,
				forms: "#"+image_form_id+"_paper",
				loading_fn:function(){},
				onStart: function(){
					$form_result_container.slideUp(300);
				},
				onSuccess: function(options, data){
					if(data=="true")
					{
						$form_result_container.html("<div class=\"image_form_headline green\">Vielen Dank f&uuml;r Ihre Weiterempfehlung.</div>");
					}
					else
					{
						$form_result_container.html("<div class=\"image_form_headline red\">Es ist ein Fehler aufgetaucht. Bitte &uuml;berpr&uuml;fen Sie Ihre Eingabe.</div>");
						setTimeout("switch_form_result_to_form(\""+image_form_id+"\")",5000);
					}

					$form_container.slideUp(500);
					$form_result_container.animate({
								opacity: 0.8,
								filter: 'alpha(opacity=80)',
								height: 'toggle'
								}, 800, "swing");
				}
		    });
		}
		else
		{
			$form_result_container.html("<div class=\"image_form_headline red\">Bitte &uuml;berpr&uuml;fen Sie Ihre Eingabe. Es m&uuml;ssen alle Felder mit einem * ausgef&uuml;llt sein.</div>");
			$form_result_container.filter(":not(:visible)").animate({
						opacity: 0.8,
						filter: 'alpha(opacity=80)',
						height: 'toggle'
						}, 800, "swing");
		}

	    return false;
	});

	//resize background at window resize event
	$window.resize(resize_background);

	if ( ($.browser.msie && $.browser.version < 7) )
	{
		resize_background();
	}

	//anfahrtsplan
	/*var dialog = Core("<div title=\"Anfahrtsplan\"><iframe id=\"modalIframeId\" width=\"100%\" height=\"100%\" marginWidth=\"0\" marginHeight=\"0\" frameBorder=\"0\" scrolling=\"auto\" title=\"Dialog Title\">Your browser does not suppr</iframe></div>").appendTo("body");
  	dialog.dialog({
    	autoOpen: false,
        modal: true,
        height: 370,
        width: 800,
        closeOnEscape: true,
        resizable: false
    });*/
	Core(".anfahrtsplan").attr("href", "#");

	Core(".anfahrtsplan").livequery(function(){
		Core(this).click(function(){

			//old_content=CoreX("#content_area div.content_layer").html();

			CoreX("#content_area div.content_layer:first h1").text("Anfahrtsplan");

			//config layer
			CoreX("#content_area div.content_layer:last").css("padding", "0px").css("width", "518px");

			//set content
			CoreX("#content_area div.content_layer .content_layer_wrap:last").html("<div class=\"headline\" style=\"height:40px;\"><div style=\"float:left;\"><form action=\"#\" onsubmit=\"setDirections(this.from.value); return false\" style=\"margin-bottom: 0px;padding:8px;float:left;\"><label for=\"fromAddress\">Route von: </label><input type=\"text\" size=\"25\" id=\"fromAddress\" name=\"from\" value=\"\"/><input name=\"submit\" type=\"submit\" value=\"Route berechnen\" /></form><a id=\"map_print\" style=\"float:left;font-size:9px;font-weight:bold;line-height:40px;margin-left:50px;text-decoration:none;\" href=\"javascript:this.print();\">Karte drucken</a></div><div class=\"printer\" style=\"float:left;margin-left:120px;padding:10px;\"></div></div><div style=\"\"><div id=\"map_canvas\" style=\"height: 245px;\"></div><div id=\"directions\"></div></div>");


			//set map adress
			address=Core(this).attr("rel");

			//load map
			load();

	       //dialog.dialog("open");
	       //Core("#modalIframeId").attr("src", Core(this).attr("rel"));

			return false;
		});
	});

/*
	//MICRO SITE - SCROLLING
	Core(".scroll").jScrollPane(jscrollpane_settings);


	//MICROSITE - FLASH CONTROL
	var getFlashVersion=function() {
		// ie
		try {
			try {
				// avoid fp6 minor version lookup issues
				// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
				var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
				try { axo.AllowScriptAccess = 'always';	}
				catch(e) { return '6,0,0'; }
			} catch(e) {}
			return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
		// other browsers
		} catch(e) {
			try {
				if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
					return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
				}
			} catch(e) {}
		}
		return '0,0,0';
	};
/*
	//switch flash objects to images alternatives
	if(getFlashVersion()=="0,0,0")
	{
		//flash alternative images
		Core(".flash_alternative_image").livequery(function(){
			CoreX(this).each(function(){
				CoreX(this).show().parent().find("object, embed").hide();
			});
		});

		//video zoom alternative
		Core(".flash_alternative_image_zoom").livequery(function(){
			CoreX(this).each(function(){
				CoreX(this).parent().attr("href", CoreX(this).attr("src"))
			});
		});

		//noaccess site
		var NoAccessURL = document.location.href;
		NoAccessURL= NoAccessURL.split("?");
		if(NoAccessURL[1] != "noaccess")
		{
			window.location=noaccessurl+"?"+document.location.href;
		}
	}
*/
/*
	//MICRO SITE - CONTENT DETAILS - SUPER CLICK
	Core("div.site_layer div.mod_list_navigation_entry_div").livequery(function(){
		CoreX(this).css("cursor", "pointer");

		Core(this).click(function(){
			Core(this).find("a:first").click();
		})
		.hover(function(){
			CoreX(this).addClass("hover");
		}, function(){
			CoreX(this).removeClass("hover");
		});
	});

	Core("a.fancybox").livequery(function(){

		//initiate zoom
		 CoreX(this).fancybox({
			'hideOnContentClick': false,
			'overlayShow': true,
			'overlayOpacity': 0.7,
			'padding': 0,
			'centerOnScroll': false,
			'overlayColor': '#000000',
			'callbackOnClose': function() {
		     	$("#fancy_content").empty();
		     },
			'callbackOnShow': function() {
		     	$("#fancy_div .contact_list_scroll_content").jScrollPane(jscrollpane_settings);

		     	//set right position
		     	var window_width=CoreX(window).width();
		     	var container_width=CoreX("#fancy_outer").width();
		     	var pos_left = (window_width/2) - 486.5

		     	CoreX("#fancy_outer").css("left", pos_left+"px").css("top", "25px");
		     	CoreX("#fancy_title").hide();
		     }
		 });

		 //set close icon
		 CoreX("#fancy_close img").attr("src", "http://www-tmp.thornlight.com/ms_icons/btn_ms_lightbox-close.gif");
	});*/

});

