var imageSlide = false;
// Debugging-Function. Only active in Browser who support it
function pr() {
	if (!window.console) {
		return;
	}
	if (typeof window.console !== 'undefined' && typeof window.console.log === 'function') {
		console.log(pr.arguments);
	}
}

if (location.hash) {
	location.href = location.hash.replace('#', '');
	try { GUnload() } catch(e)
	{} 
}

(function($) {
	// Produces correct URLs relative to Router::url('/)
	$.url = function(url) {
	  return $('meta[name=identifier-url]').attr('content')+url.substr(1);
	}

	$(function() {
		// Generate a Page-Object to bind events on
		window.Page = $('body');
		
		//Take care about the non-js fallback-version of the site 
		$('body').addClass('js').removeClass('no-js');
		 
		// Make external links open in a new window
		$('a[rel=external],a[rel=upload]').live('click', function() {
			window.open(this.href);
			return false;
		});

		// Fix Alpha-PNG's for IE6
		if ($.browser.msie && $.browser.version < 7) {
			$.ifixpng($.url('/js/jquery/ifixpng/pixel.gif'));
			$('img[src$=.png], h1 a, #footer .content').ifixpng();
		}

		$('#menu-main a, #logo a, .content a, .news a').filter('[rel!=external],[rel!=upload]').live('click', function() {
			window.location.hash = $(this).attr('href');
			return false;
		} );

		$(window).history(function( e, ui ){
			if (!ui) {
				return false;
			}
			if (!ui.value) {
				ui.value = window.location.pathname;
			}
			var $that = $('a[href='+ui.value+']:first');
			var href = $that.attr('href');
			if (!href) {
				href = ui.value;
			}
			// Set Menu
			if ($that.closest('#menu-main').length) {
				$('#menu-main li').removeClass('active');
				$that.closest('li').addClass('active');
			}
			$('#content-inner').load(href, function() {
				if ($('#content').find('#gmap').length > 0) {
					gMapInitialize();
				}
				$.prepareAjaxForm();
			});
		});

		// Image controls
		$('.gallery a#prev,.gallery a#next, .index ul li a').live('click', function(){
			if (imageSlide) {
				return false;
			}
			imageSlide = true;
			$('ul.image li, .index ul.controls li a').removeClass('show');
			var direction = $(this).attr('id');
			if (direction.length == 0) {
				direction = $(this).semantic('img');
				var $that = $(this);
			}
			var $imageList = $('ul.image');
			var imageCount = $('ul.image li').size();
			var imageWidth = 540;

			var cLeft = $imageList.css('left');
			var currentLeft = Math.abs(parseInt(cLeft.substr(0, cLeft.length -1)));

			if (currentLeft == 0) {
				var currentCount = 1;
			} else {
				var currentCount = currentLeft / imageWidth +1;
			}

			if (direction == 'next') {
				var move = currentLeft + imageWidth;
				if (currentCount - imageCount == 0) {
					move = 0;
					currentCount = 1;
				} else {
					currentCount++;
				}
			} else if (direction == 'prev') {
				var move = currentLeft - imageWidth;
				if (currentCount == 1) {
					move = (imageCount-1) * imageWidth;
					currentCount = imageCount;
				} else {
					currentCount--;
				}
			} else {
				var move = (direction-1) * imageWidth;
				currentCount = direction;
			}
			$imageList.animate({"left": - move}, 1100, function(){
				$('.index ul li a.img-'+currentCount).addClass('show');
				imageSlide = false;
			});
			$('ul.descriptions li.show').fadeOut(500, function(){
				$(this).removeClass('show');
				$('ul.descriptions li.img-'+currentCount).fadeIn(500, function(){
					$(this).addClass('show');
				});
			});
			return false;
		});
		$('#contact-form input,#contact-form textarea').each(function(){
			var content = $(this).attr('value');
			if (content == 'Nachricht' || content == 'E-Mail' || content == 'Name') {
				$(this).data('text', content);
			}
		});
		$('#contact-form .text input,#contact-form textarea').bind('focus', function(){
			if ($(this).data('text') == $(this).attr('value')) {
				$(this).attr('value', '');
			}
		}).bind('blur', function(){
			$('#contact-form .text input,#contact-form textarea').each(function(){
				if ($(this).attr('value').length < 1) {
					$(this).attr('value', $(this).data('text'));
				}
			});
		});
	});

	$.prepareAjaxForm = function(){
		var options = { 
			success: function(responseText){
				$('#content-inner').html(responseText);
				$.prepareAjaxForm();
				if ($('#content').find('#gmap').length > 0) {
					gMapInitialize();
				}
			}
		};
		if ($.browser.msie && $.browser.version < 7) {
			$('#contact-form').submit(function() {
				$('#contact-form').ajaxSubmit(options);
			});
		} else {
			$('#contact-form').ajaxForm(options);
		}
	};

	$.fn.field = function(field, val, accessor, map) {
		var r = [], one = (this.length == 1), get = true, fields = field, customAccessor = !!accessor, customMap = map;
		var multi = (field.constructor == Array)
			? 'get'
			: (typeof fields == 'object')
				? 'set'
				: false;
		if (multi == 'get') {
			fields = {};
			$.each(field, function() {
				fields[this] = undefined;
			});
		} else if (multi == false) {
			fields = {}
			fields[field] = val;
		}
		this.each(function(i) {
			map = customMap || $.data(this, 'fields');
			var $this = $(this), self = this;
			for (var f in fields) {
				var v = fields[f];
				accessor = accessor || {
					get: function(f) {return map[f].get.call(this);},
					set: function(f, v) {map[f].set.call(this, v)}
				};
				if (get = get && (typeof v == 'undefined')) {
					if (multi == 'get') {
						r[i] = r[i] || {};
						r[i][f] = accessor.get.call($this, f);
					} else {
						r.push(accessor.get.call($this, f));
					}
				} else {
					accessor.set.call($this, f, v);
					if (!customAccessor && 'Page' in window) {
						Page.trigger('changeField', [$this, f, v]);
					}
				}
			}
		});
		return (!get)
			? this
			: (one)
				? r[0]
				: r;
	};

	$.fn.semantic = function(options, key, val) {
		if (typeof options == 'string') {
			val = key;
			key = options;
			options = undefined;
		}

		arguments.callee.helpers = arguments.callee.helpers || {
			get: function(key, options) {
				var m = (this.attr(options.attr) || "").match(options.regex);
				return (m)
					? m[1]
					: false;
			},
			set: function(key, val, options) {
				var attrVal = this.attr(options.attr) || "", newAttrVal;
				if ((newAttrVal = attrVal.replace(options.regex, key+'-'+val)) == attrVal && !options.regex.test(attrVal)) {
					newAttrVal = (attrVal)
						? attrVal+' '+key+'-'+val
						: key+'-'+val;
				}
				this.attr(options.attr, newAttrVal);
			}
		};
		options = $.extend({
			attr: 'class',
			get: arguments.callee.helpers.get,
			set: arguments.callee.helpers.set,
			regex: new RegExp(key+'-([^\\s]+)')
		}, options || {});

		return this.field(key, val, {
			get: function(k) {return options.get.call(this, k, options);},
			set: function(k, v) {options.set.call(this, k, v, options);}
		}, {});
	};

	window.gMapInitialize = function() {
		if($('#gmap').length < 1) {
			return false;
		}
		var el = document.getElementById('gmap');
		var map = new GMap2(el);
		var point = new GLatLng(47.711073, 7.581694);

		// shows new 3D controls
		var customUI = map.getDefaultUI();
		map.setUI(customUI);

		// Set map type
		map.setMapType(G_HYBRID_MAP);

		var marker = new GMarker(point);
		map.setCenter(point, 15);
		marker.myhtml = '<h2>Hofgut Kaltenherberge</h2><p>An der B3<br/>79400 Kandern</p>';
		map.addOverlay(marker);

		GEvent.addListener(map, 'click', function(overlay, point) {
			if (overlay) {
				// we now need a check here in case the overlay is the info window
				// only our markers will have a .myhtml property
				if (overlay.myhtml) {
					overlay.openInfoWindowHtml(overlay.myhtml);
				}
			} else if (point) {
				//whatever you want to happen if you don't click on an overlay.
			}
		});
	};

})(jQuery);

if (typeof google != "undefined") {
	google.load("maps", "2.x");
	google.setOnLoadCallback(gMapInitialize);
}
