
$j().ready(function(){

	// detect support for css3 transitions
	window.transitions = 	document.body.style.transition !== undefined || 
							document.body.style.MozTransition !== undefined || 
							document.body.style.msTransition !== undefined || 
							document.body.style.MsTransition !== undefined || 
							document.body.style.WebkitTransition !== undefined || 
							document.body.style.webkitTransition !== undefined ;

	// handle pseudo form-labels
	$j('input.prefilled').each( function() {
	//$('#callback input, #search input').each( function() {
		$j(this).data('defaultvalue',$j(this).val());
	}).focus( prefilledFocusHandler).blur( prefilledBlurHandler);
	
	// inject neutral background tiles
	$j('#about .tile-group .tile .img').each( function() {
		$j(this).css({ backgroundImage : 'url("' + $j(this).find('img').attr('src').replace('.jpg','-off.jpg') + '")' });
	});
	
	// provide jquery effects if transitions are not supportet
	if(!transitions) {
		$j('#about .tile-group .img').css({height:'100%'}).find('img').css({opacity:1})
		$j('#about .tile-group').mouseenter( function() {
			$j(this).find('.img img').not($j(this).find('.tile:hover .img img')).stop().fadeOut();
		}).mouseleave( function() {
			$j(this).find('.img img').stop().fadeTo(400,1);
		}).find('.tile').mouseenter( function() {
			$j(this).find('.img').animate({height:'99px'}).find('img').stop().fadeTo(400,1);
		}).mouseleave( function() {
			$j(this).find('.img').stop().animate({height:$j(this).innerHeight()}).find('img').stop().fadeOut();
		});
	}
	
	// inject nook's into elements
	$j('blockquote, #products .use-cases').append('<div class="nook"></div>');

	$j('#team .about').mouseenter( function() {
		$j(this).closest('.tile').addClass('detail');
	}).mouseleave( function() {
		$j(this).closest('.tile').removeClass('detail');
	});
	
	if($j('#home #header').length)
		$j('#home #header').after('<ul id="pager"/>').wrapInner('<div/>').children().css({position: 'relative'}).cycle({
			fx:						'fade',
			timeout: 				5 * 1000,
			pager:					'#pager',
			pause:					true,
			pagerAnchorBuilder: 	neutralPaginator
		});
	if($j('#products #header').length) {
		$j('#products #header').after('<ul id="pager"/><button class="prod-nav prev"/><button class="prod-nav next"/>').children('.slide').wrap('<div/>').parent().parent().cycle({
			fx:						'fade',
			timeout:				10 * 1000,
			pause:					true,
			pager:					'#pager',
			before:function(){
				$j(this).find('img.packshot').hide().css({marginLeft:'600px'}).fadeIn().animate({marginLeft:'0px'},'slow','swing');
			},
			pagerAnchorBuilder: 	neutralPaginator
		});
		$j('.prod-nav.prev').click(function() {
			$j('#products #header').cycle('prev');
		});
		$j('.prod-nav.next').click(function() {
			$j('#products #header').cycle('next');
		});
	}
	
	$j('#products .slide').not(':first-child').hide();
	$j('#products .info').tabs();
	
	$j('form#callback').submit(callbackSubmitHandler);

	$j('form#mail').submit(mailSubmitHandler);
	
	if( $j('#home #prices').length) {
		$j('#home #prices #destination').change( function() {
			$j.getJSON( 'services/index.php/rates', {country:$j(this).val()}, function(data,status) { 
				var rates = $j('#home #prices #rates'), prices = [];
				rates.find('option').remove();
				for(var i=0; data[i]; i++) {
					rates.append($j('<option/>').html( data[i].carrier + " " + data[i].price + " " + data[i].currency ));
					prices.push( data[i].price );
				}
				// get top price
				prices.sort(); 
				$j('.tile.left .sticky strong').html(prices.shift());
			});
		});
		$j.getJSON( 'services/index.php/prices', function(data,status) { 
			var destinations = $j('#home #prices #destination');
			for(var iso in data.countries) 
				destinations.append($j('<option/>').attr('value',iso).html(data.countries[iso] + " " + iso.toUpperCase() ));
			$j('#home #prices #destination option[value=de]').attr('selected',true);
			destinations.change();
		});
	}
	
	if( $j('#about').length) 
		anim_about();
	if( $j('#team').length) 
		anim_team();
	if( $j('#messaging').length) 
		anim_messaging();
		
	$j('#change-password').click( function() { 
		if(this.checked) 
			$j('#password-fieldset').fadeIn(); 
		else  {
			$j('#password-fieldset input').attr( 'value', '');
			$j('#password-fieldset').fadeOut(); 
		}
	});
});

function about_fireCircles() {
	var delay = 0.6, circles = 4;
	for(var i=0; i<circles; i++)
		window.setTimeout( about_fireSingleCircle, i * delay * 1000);
}

function about_fireSingleCircle() {
	var circle = r.circle(640.5, 65.5, 2);

	circle.attr({
		opacity: 0.15,
		'stroke-width': 1
	}).animate({
		opacity: 0,
		r: 200,
		easing: 'easeIn',
		callback: function() { this.remove(); }
	}, 	10*1000);

}

function anim_about() {
	$j('#header').append('<div id="animation"/>');
	var r = Raphael("animation", $j('#header').width(), $j('#header').height());
	window.r = r;
	
	window.setInterval( about_fireCircles,6*1000);
	about_fireCircles();



}

function coord(x,y) {
	this.x = x;
	this.y = y;
	return this;
}

/*function c(x,y) {
	return new coord(x,y);
}*/

var messaging_ranges = [
	{ x1: 598, y1: 171, x2: 603, y2: 249 }
];

function anim_messaging() {
	$j('#header').append('<div id="animation"/>');
	var r = Raphael("animation", $j('#header').width(), $j('#header').height());
	window.r = r;
	
	
	
	window.setInterval( function(){
		var areas  = [
			{
				min : 	{ x1: 598, y1: 171, x2: 611, y2: 170 },
				max :	{ x1: 603, y1: 249, x2: 616, y2: 248 }
			},
			{
				min : 	{ x1: 622, y1: 169, x2: 648, y2: 168 },
				max :	{ x1: 628, y1: 248, x2: 654, y2: 246 }
			},
			{
				min : 	{ x1: 786, y1: 138, x2: 954, y2: 136 },
				max :	{ x1: 790, y1: 231, x2: 954, y2: 237 },
				cut : 	true
			}/**/
		];
		var a /*area*/   = areas[ Math.floor( Math.random() * areas.length) ];
		var f /*factor*/ = Math.random();
		var c /*coords*/ = { 
			x1: a.min.x1 + f * ( a.max.x1 - a.min.x1 ) , 
			x2: a.min.x2 + f * ( a.max.x2 - a.min.x2 ) , 
			y1: a.min.y1 + f * ( a.max.y1 - a.min.y1 ), 
			y2: a.min.y2 + f * ( a.max.y2 - a.min.y2 ), 
		};
		if(a.cut) {
			var f1 = Math.random(), f2 = Math.random();
			c = { 
				x1: c.x1 + f1 * ( c.x2 - c.x1 ),
				y1: c.y1 + f1 * ( c.y2 - c.y1 ),
				x2: c.x1 + f2 * ( c.x2 - c.x1 ),
				y2: c.y1 + f2 * ( c.y2 - c.y1 )
			};
		}
		p = r.path("M"+c.x1+" "+c.y1+"L"+c.x2+" "+c.y2+"");
		p.attr({
			stroke: '#fff',
			'stroke-width': 2,
			opacity: 0
		}).animate({
			opacity: .6,
	//		r: 200,
	//		easing: 'easeIn',
			callback: function() { this.animate({
			opacity: 0,
	//		r: 200,
	//		easing: 'easeIn',
			callback: function() { this.remove(); }
		}, 	.3*1000); }
		}, 	.1*1000);
		
		
	},.02*1000);
	//about_fireCircles();


}

function anim_team() {
	$j('#header').append('<div id="animation"/>');
	setInterval(anim_team_single,.03*1000);
	anim_team_single();
}



window.directions = [ 
	[568,320,  602,290,  660,280, 660,269 ], 
	[799,280,  799,288,  886,319 ], 
	[784,283,  784,292,  858,319 ], 
	[572,235,  572,242,  525,250,  489,275,  514,290,  464,315 ], 
	[499,295,  474,280,  516,251,  568,242,  568,235 ],
	[587,319,  613,295,  670,282,  671,282,  674,271   ],
	[941,319,  827,282,  826,275,  826,273 ],
	[955,287,  891,269,  891,262],
	[569,272,  628,265,  629,258,  632,256],
	[790,319,  799,317,  754,299,  754,290,  751,288],
	[649,319,  660,306,  707,295,  708,288,  712,285],
	[590,285,  648,273,  650,266,  651,264],
	[434,263,  444,257,  559,240,  560,234,  562,233],
	[885,319,  799,289,  799,281,  797,279],
	[981,277,  892,269,  891,262,  890,260],
	[441,252,  471,237,  531,229,  513,233,  543,222],
	[935,294,  867,274,  866,266,  865,263],
	// hinteren Punkte
	[730,178,  736,166],
	[ 506,203,  493,198,  481,199,  434,183,  389,182],
	[511,202,  505,199,  405,200],
	[836,187,  843,185,  844,175,  850,171,  924,162,  920,157],
	[734,178,  736,165,  756,162],
	[586,193,  508,170,  513,167,  549,167,  703,156,  725,156,  736,158],  
	[698,181,  704,166,  735,160],
];


function anim_team_single() {

	var item = $j('<div/>').html('•').addClass('flare');
	var d = directions[ Math.floor( Math.random() * directions.length) ].slice();
//	var duration = .5*1000;
	var speed = 400;
	var path = [];
	pos = prev = new coord(d.shift(),d.shift());
	path.push(pos);
	var pathlength = 0;
	while(d.length) {
		c = new coord(d.shift(),d.shift());
		pathlength += Math.sqrt( Math.pow(c.x-prev.x,2) + Math.pow(c.y-prev.y,2)  );
		path.push(c);
		prev = c;
	}
//	console.log(pathlength);
	if(Math.round(Math.random()))
		path.reverse();
	pos = path[0];
	item.css({left:pos.x,top:pos.y});
	while(path.length) {
		to = path.shift();
		segmentlength = Math.sqrt( Math.pow(to.x-pos.x,2) + Math.pow(to.y-pos.y,2)  );
		//item.animate( {left: to.x, top: to.y}, parseInt( duration / pathlength * segmentlength ), 'linear');
		item.animate( {left: to.x, top: to.y}, parseInt( segmentlength / speed * 1000 ), 'linear');
		pos = to;
	}
	item.animate({left:0},0,'linear',function(){$j(this).remove()});
	$j('#animation').append(item);

}


function prefilledFocusHandler() {
	$j(this).removeClass('prefilled');
	if( $j(this).val() == $j(this).data('defaultvalue') )
		$j(this).val("");
}

function prefilledBlurHandler() {
	if( !$j(this).val())
		$j(this).val($j(this).data('defaultvalue'));
	if( $j(this).val() == $(this).data('defaultvalue') )
		$j(this).addClass('prefilled');
}

function neutralPaginator(idx, slide) { 
	return '<li id="p'+idx+'"><a href="#"></a></li>'; 
} 

function mailSubmitHandler() {
	console.log('mailSubmitHandler');
	if($j(this).valid()) {
		console.log('form validated, sending using ajaxSubmit');
		$j(this).ajaxSubmit( {
			success:	mailAjaxHandler,
			dataType:	"json"
		});
	}
	return false;
}

function callbackSubmitHandler() {
	console.log('callbackSubmitHandler');
	$j(this).find('input.prefilled').each(prefilledFocusHandler);
	if($j(this).valid()) {
		console.log('form validated, sending using ajaxSubmit');
		$j(this).ajaxSubmit( {
			success:	callbackAjaxHandler,
			dataType:	"json"
		});
	}
	$j(this).find('input.prefilled').each(prefilledBlurHandler);
	return false;
}

function mailAjaxHandler(response) {
	console.log('mailAjaxHandler');
	$j('form#mail').before('<p>'+response.msg+'</p>').remove();
}

function callbackAjaxHandler(response) {
	console.log('mailAjaxHandler');
	$j('form#callback fieldset').before('<fieldset>'+response.msg+'</fieldset>').remove();
}

if(!window.console) {
	window.console = { log: function(){} };
}


