$(document).ready(function() {

/*	$('.backlink').click(function() {
		lastpage = document.referrer;
		if (lastpage.search(/jungundwillich/i) != -1)
		{
			if(lastpage.search(document.location.href) != 0)
			{
				document.location.href = lastpage;
				return(false);
			}
		}
		return(true);
	}); */
	

	// callback form

	$('.callback_form #time, .callback_form #dd, .callback_form #mm').hide();
	$('a.callback').click(function() {
		$('.callback_form').slideToggle('normal', function() {switchstyles();});
		try
		{
			_gaq.push(['_trackEvent', 'callbackclick', location.href]);
		}
		catch(err){}

		return(false);
	});
	$('.callback_form #day').change(function() {
		if ($('.callback_form #day option:selected').attr('value') != 'schnellschnell')
		{
			$('.callback_form #time').show();
			if ($('.callback_form #day option:selected').attr('value') == "datum")
			{
				$('.callback_form #dd, .callback_form #mm').show();
			}
		}
		else
		{
			$('.callback_form #time').hide();
		}

		if ($('.callback_form #day option:selected').attr('value') != "datum")
		{
			$('.callback_form #dd, .callback_form #mm').hide();
		}
	});
	
	$('.callback_form input').focusin(function() {
		if (($(this).val() == "Ihr Name") || ($(this).val() == "Ihre Telefonnummer"))
		{
			$(this).data('prev_val', $(this).val());
			$(this).val("");
		}
	});

	$('.callback_form input').focusout(function() {
		if (($(this).val() == ""))
		{
			$(this).val($(this).data('prev_val'));
		}
	});

	// switch style if window width too small

	prev_width = $(window).width();
	switchstyles();
	$(window).resize(function() {switchstyles();});	

	// general forms

	$('input .send').replaceWith('<button id="send" name="send" type="button" value="Absenden">Absenden</button>');
	$('button #send').click(function() {
		$(this).parentsUntil('form').submit();
	});
	
	// nav rewrite

	$('#nav > li > a').each(function(index,element) {
		$(element).attr('href', $(element).parents('li').children('ul').children('li').children('a').attr('href'));
	});

	// images + slideshows

	$('.bgimgwrap > a').each(function(index, element){
		wrapper = $(element).closest('.bgimgwrap');
		contents = $(element).children().detach();
		$(element).after(contents);
		link = $(element).detach();
		$(wrapper).css('cursor', 'pointer').wrap(link);
		$(wrapper).click(function(){ // dämlicher IE7
			$(this).parentsUntil('a').click();
		});
	});

		// set up stacks
	$('.bgimgwrap').each(function(index,element){
		$(element).wrap('<div class="bgimgoutwrap"></div>');
		$(element).data('elecount', -1);
		$(element).data('imgstack', new Array);
		$(element).data('curele', 0);
		$(element).children('img').each(function(imgindex, imgelement) {
			istack = $(element).data('imgstack');
			istack.push(imgelement);
			$(element).data('imgstack', istack);
			$(element).data('elecount', $(element).data('elecount') + 1);
		});
		
		if($('body').hasClass('home') || $('body').hasClass('page-id-2507')) { 
			$(element).append($('<img src="/braunschweig/themes/werbeagentur-braunschweig-jungundwillich/images/shadow-mask-breit.png" class="mask">'));	
		}
		else
		{
			$(element).append($('<img src="/braunschweig/themes/werbeagentur-braunschweig-jungundwillich/images/shadow-mask.png" class="mask">'));
		}
		
		$('.mask').css('z-index', '-1').css('position', 'absolute').css('top', '-24%').css('left', '-11%').css('width', '120%');
		
		if($('body').hasClass('home') || $('body').hasClass('page-id-2507')) {
			$('.mask').css('top', '-36%').css('width', '123%').css('left', '-12%');
		}

		if ($(element).data('elecount') > 0) {
			$(element).append($('<img src="/braunschweig/themes/werbeagentur-braunschweig-jungundwillich/images/slideshow-open.png" class="zoombutton">').css('z-index', '100'));
			$(element).addClass('has_slideshow');
		}
	});

	$('.bgimgoutwrap').each(function(index,element){
		$(element).css('position', 'relative').css('overflow','visible');
	});

	$('.bgimgwrap img:not(:first-child):not(.zoombutton):not(.mask)').css('position', 'absolute').css('top', '0').css('left', '0').css('z-index', '-99').css('width', '100%').css('height', 'auto');
	
	$('.bgimgwrap img:first-child').css('z-index', '-3').css('position', 'relative').css('top', '0').css('left', '0').css('width', '100%').css('height', 'auto');

	startAutoSlideshow();

	$('.zoombutton').click(
		function(e){
			oxwrap = $(this).parents('.bgimgwrap');
			wrapwidth = $(oxwrap).width();
			wrapheight = $(oxwrap).height();
			
			num_elements = $(oxwrap).data('elecount');
			imgstack = $(oxwrap).data('imgstack');
			curele = $(oxwrap).data('curele');
			
			bg = $(imgstack[curele]);
			outwrap = $(oxwrap).parents('.bgimgoutwrap');
			
			if (!$(oxwrap).hasClass('open'))
			{
				rememberdimensions(outwrap);
				$('.moreinfo').css('z-index','-99');

				//set up slider
				
				nextslide = $('<div class="next"></div>').css('z-index', 98);
				prevslide = $('<div class="prev"></div>').css('z-index', 98);
					
				$(nextslide).animate({opacity: 0.2});
				$(prevslide).animate({opacity: 0.2});

				$(nextslide).hover(function() {
					$(this).animate({opacity: 0.8});
				}, function() {
					$(this).animate({opacity: 0.2});
				});
				$(prevslide).hover(function() {
					$(this).animate({opacity: 0.8});
				}, function() {
					$(this).animate({opacity: 0.2});
				});
	
				$(oxwrap).append(nextslide).append(prevslide);
				
				setup_slider(oxwrap);
				
				$(nextslide).click(function() { chgimg(oxwrap, 'next') });
				$(prevslide).click(function() { chgimg(oxwrap, 'prev') });
				
				//resize n stuff
			
				winwidth = getWindowWidth();
				maxallowedwidth = winwidth - 350;

				mywrap = $(oxwrap).clone();
				mybg = $(mywrap).children('img:first');
				
				$(mywrap).css('width', 'auto');
				$(mybg).css('position','absolute').css('width','auto').css('height','auto');

				$('body').prepend(mywrap);

				bgwidth = $(mybg).width();
				bgheight = $(mybg).height();
				
				ratio = bgwidth/bgheight;

				$(bg).css('position','relative').css('width','100%').css('height', 'auto');


				if (bgwidth > maxallowedwidth) {
					$(mywrap).css('width', maxallowedwidth + 'px');
					bgwidth = maxallowedwidth;
					bgheight = maxallowedwidth/ratio;
				}

				$(oxwrap).css('width', wrapwidth).css('position', 'absolute').css('height', '100%');
				$(outwrap).css('height', recallheight(outwrap)).css('width', recallwidth(outwrap));
				$(oxwrap).animate({width : bgwidth}).addClass('open');
				$(outwrap).animate({height: bgwidth/ratio}, function() {
					$(imgstack).each(function (i,e) {
						$(e).css('position', 'absolute').css('top', 0).css('left', 0).css('width', '100%').css('height', 'auto');
					})
				});
				
				$('.zoombutton').attr('src', '/braunschweig/themes/werbeagentur-braunschweig-jungundwillich/images/slideshow-close.png');
				
				$(mywrap).remove();
				try
				{
					_gaq.push(['_trackEvent', 'zoomclick', location.href]);
				}
				catch(err)
				{

				}
			}
			else
			{
				$(bg).css('position', 'relative').css('width', '100%').css('height', 'auto');
				$(oxwrap).children('.next').remove();
				$(oxwrap).children('.prev').remove();
				$(outwrap).animate({height: 220});
				$(oxwrap).animate({width : '100%', height : 220}).removeClass('open');
				$('.moreinfo').css('z-index','1');
				$('.zoombutton').attr('src', '/braunschweig/themes/werbeagentur-braunschweig-jungundwillich/images/slideshow-open.png');
			}
		}
	);
	
	// sorting stuff
	
	$('body:not(.page-template-kunden-overview-php) a.button:not(.is_ie)').click(function(e) {
		try
		{
			_gaq.push(['_trackEvent', 'sortclick', location.href, $(this).attr('href')]);
		}
		catch(err){	}

		$('#respawn').quicksand($($(this).attr('href')).children('div'), {
			attribute: 'title',
			adjustHeight: 'dynamic',
			enhancement: function(e) {
				Cufon.refresh();
				Cufon.now();
    		}
		});
		$('.active').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});


	$('body.page-template-kunden-overview-php a.button, a.button.is_ie').click(function(e) {
		try
		{
			_gaq.push(['_trackEvent', 'sortclick', location.href, $(this).attr('href')]);
		}
		catch(err){	}
		$('#all, #respawn, #newmedia, #crossmedia, #classicmedia').hide();
		$($(this).attr('href')).detach().insertAfter('#respawn').show().effect("highlight", { color: '#ffffff'}, 1000);
		$('.button.active').removeClass('active');
		$(this).addClass('active');
		return(false);
	});

	if($('body.page-template-kontakt-php').length > 0) setupGmap();
	
/*	$('#flash_outer').css('position', 'relative').append($('<img src="/braunschweig/themes/werbeagentur-braunschweig-jungundwillich/images/shadow-mask.png" class="mask">'));
	$('#flash_outer *').css('position', 'absolute').css('z-index', '-5');
	$('#flash_outer .mask').css('position', 'absolute').css('left', '0').css('top', '0').css('z-index', '1').click(function() { $('#flash_outer object').css('z-index', '-99'); $(this).css('z-index', '-1'); }); */
	
	Cufon.refresh();
	
});


function rememberdimensions(element)
{
	$(element).data('height', $(element).height());
	$(element).data('width', $(element).width());
}

function recallheight(element)
{
	return($(element).data('height'));
}

function recallwidth(element)
{
	return($(element).data('width'));
}

function setup_slider(theparent)
{
	nextclick = $(theparent).children('div.next');
	prevclick = $(theparent).children('div.prev');	
}

function chgimg(wrap, dir)
{
	imgstack = $(wrap).data('imgstack');
	elecount = $(wrap).data('elecount');
	curele = $(wrap).data('curele');
	
	if (dir == 'next') {
		nextele = curele + 1;
	}
	else
	{
		nextele = curele - 1;
	}

	if (nextele > elecount) { nextele = 0; } else if (nextele < 0) { nextele = elecount }

	$(wrap).css('height', $(wrap).height());

	$(imgstack[nextele]).hide().css('z-index', '-4').fadeIn(1000, function() {
		
	});
	$(imgstack[curele]).css('z-index', '-2').fadeOut(1000);

	$(wrap).data('curele', nextele);
}

function startAutoSlideshow() {
	setTimeout('autoSlideshow()', 5000);
}

function autoSlideshow() {
	$('.bgimgwrap.has_slideshow:not(.open)').each(function(k, ele) {
		chgimg(ele, 'next');
	});
	
	setTimeout('autoSlideshow()', 10000);
}

function build_img_stack(wrap)
{
	curele = 0;
	$(wrap).children('img:not(".zoombutton")').each(function(index, element)
	{
		imgstack[curele] = element;
		if (curele != 0) { $(element).css('z-index', -99); }
		curele++;
	});
	elecount = curele;
	curele = 0;
}

function getWindowWidth() {
	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	}
	else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
};

/* function constructMarker(staedte)
{
	var point = new GLatLng(staedte[i][1], staedte[i][2]);
	var markermon = new GMarker(point);
	var myHtml = '<a href="' + staedte[i][3] + '">' + staedte[i][0] + '</a>';
	GEvent.addListener(markermon, "click", function() {
		map.openInfoWindowHtml(point, myHtml);
	});
	return markermon;
} */

function setupGmap() {
    var latlng = new google.maps.LatLng(52.266715, 10.503590);
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    
    var marker = new google.maps.Marker({
      position: latlng, 
      map: map
    });
    
    $('#map_canvas').css('height', '200px');

/*	try {
		if (GBrowserIsCompatible())
		{
			$('#gmap').css('position', 'relative').css('height', 201).css('margin-bottom', '2em');
			var map = new GMap2(document.getElementById("gmap"));
			map.addControl(new GSmallZoomControl()); 
			map.setCenter(new GLatLng(52.27593621332223, 10.531172007322311), 15);
	//		map.setMapType(G_HYBRID_MAP);
	
			staedte = new Array(1);
			
			for (i = 0; i < staedte.length; i++) {
				staedte[i] = new Array(4);
			}
	
			staedte[0][0] = "Jung & Willich";
			staedte[0][1] = "52.27593621332223";
			staedte[0][2] = "10.531172007322311";
			staedte[0][3] = "http://jungundwillich.de";
					
			for (i = 0; i < staedte.length ; i++) {
				map.addOverlay(constructMarker(staedte));
			}
		}
	}
	catch(err)
	{
		return(false);
	} */
}

/* switch a couple of styles depending on window width */
function switchstyles()
{
	if ($(window).width() < 1131)
	{
		$('.callback_form #time').css('width', 'auto');
		$('#content').height('auto');
		$('body').addClass('narrow').removeClass('wide');
		if ($(window).width() < 1048)
		{
			$('body').addClass('ultranarrow');
		}
		else
		{
			$('body').removeClass('ultranarrow');
		}
	}
	else
	{
		$('body').addClass('wide').removeClass('narrow').removeClass('ultranarrow');
		$('.callback_form #time').css('width', '100%');

		if ($('.moreinfo').height() > $('#content').height())
		{
			$('#content').height($('body .moreinfo').height() + 60);
		}
	}
}

(function($) {
    var userAgent = navigator.userAgent.toLowerCase();

    $.browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
    };

})(jQuery);

function strpos (haystack, needle, offset) {
    // Finds position of first occurrence of a string within another  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/strpos    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);    // *     returns 1: 14
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
