/**
 * @author binary1
 */

	var map;
	var markers = new Array();
	var infoWindows = new Array();
	var stepDisplay;
	
	var directionDisplay;
	var directionsService;
	
	var johannesburg;
	var coffeebay;
	var queenstown;
	
	function ini_map(map_canvas) {
		directionsDisplay = new google.maps.DirectionsRenderer();
	    var myOptions = {
	      zoom: 7,
	      center: johannesburg,
	      mapTypeId: google.maps.MapTypeId.HYBRID
	    }
	    map = new google.maps.Map(document.getElementById(map_canvas), myOptions);
	   	directionsDisplay.setMap(map);
		
		var rendererOptions = {
			map: map
		}
		directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)

		showTrip();
		
	}
	
		
	function showTrip() 
	{
		var waypts = [];
		
		waypts[0] = 
		{
			location: coffeebay,
			stopover: true
		};
		
		waypts[1] = 
		{
			location: queenstown,
			stopover: true
		};
		
		waypts[2] = 
		{
			location: johannesburg,
			stopover: false
		};
		
		var request = {
			origin:johannesburg, 
			destination:johannesburg,
			 waypoints: waypts,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		
		//alert(start + ' > ' + end);	
		// start end;
		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			} else {
				alert('failed to pull Google map data, sowwy');	
			}
		});
	}

	
	var tweetMarker = null;
	var tweetInfoWindow = null;
	
	function addTweetMarker(coord, label){
		tweetMarker = new google.maps.Marker({
	        position: coord, 
	        map: map,
	        title: label
	    }); 
				
		/*tweetInfoWindow = new google.maps.InfoWindow({
	        content: html
	    });*/
		
		map.setZoom(16);
		map.setCenter(coord);	      
		//tweetInfoWindow.open(map,tweetMarker);
		
	}
	
	function withZero(n){
		if (n>0 && n<10){
			return '0' + n;	
		}
		return n;
	}
	
	function _external_internal_links()
	{
		// links;
		
		$$("a").each(function(n) {
			if ((n.protocol=='http:' || n.protocol=='https:') && window.location.host!=n.hostname){
				n.target = '_blank';
				/*n.observe('click', function (e){
					//window.open(n.href);
					alert(n.hostname + ' ? ' + window.location.host);
					e.stop();
				});
				//e.stop();*/
				
			}	
		});
	}
	
	var gettingFoto = null;
	
	function _changeTotalAndTitle(total_obj, current_image_count)
	{
		// total
		total_html = withZero(current_image_count) + ' | ' + withZero(fotos_total);
		total_obj.update(total_html);
	// title
			new_title =  document.title.sub(/\d+\s\|/, withZero(current_image_count) + ' |'); 
			document.title = new_title;
			// hashed URL;
				window.location.hash = withZero(current_image_count);
	}
	
	function _changeShownImage(image_holder, current_image_count, tar_img)
	{
					
		
		image_holder.title = current_image_count;
		
		//image_holder.width = tar_img.details[0];
		//image_holder.height = tar_img.details[1];
		
		pre_img = new Image();
		pre_img.src = tar_img.url; //"http://massappeal.co.za" + 
		pre_img.title = current_image_count;
		
		pre_img.onload = function(){
			image_holder.src = pre_img.src;
			image_holder.width = tar_img.details[0];
			image_holder.height = tar_img.details[1];
			image_holder.appear({ duration: 1});
			//alert(pre_img.src);	
		}
	}
	
	function _changeTraversal(obj, current_image_count, total, fotos)
	{
		// next
			if (current_image_count>=total){
				obj.down('.next').addClassName('hidden');
			} else {
				obj.down('.next').removeClassName('hidden');	
				obj.down('.next').down('a').href = fotos[current_image_count+1].link;//data.pagination.next;
			}
			
		// prev
			if (current_image_count<=1){
				obj.down('.prev').addClassName('hidden');
			} else {
				obj.down('.prev').removeClassName('hidden');	
				obj.down('.prev').down('a').href = fotos[current_image_count-1].link
			}
	}
	
	function _prepareChange(n)
	{
		image_holder = n.up('.fotos').down('.foto').down('img');
		
		
		//image_holder.setOpacity(0.1);
		
		ht = image_holder.height;
		wt = image_holder.width;
		
		image_holder.src = 'http://dev.map.build/views/limits/images/ui/blank.png';
		image_holder.setOpacity(0.1);
		
		return image_holder;
	}
	
	
	function _changePictureOnHash(obj, image_number, fotos, total)
	{
		image_holder = _prepareChange(obj);
		if (tar_img = fotos[image_number]){
			_changeTraversal(obj, image_number, fotos_total, fotos);
			_changeTotalAndTitle(obj.down('.total'), image_number);
			_changeShownImage(image_holder, image_number, tar_img);
			cue_fotos(image_holder);
		}
	}
		
	function fotoTraverse(n, url)
	{
		//$('body').scrollTo();
		
		var image_holder = _prepareChange(n); //n.up('.fotos').down('.foto').down('img');
		var current_image_count = eval(image_holder.title);
		
		
		
		// get target_image;
			tar_img = null;//_getTargetImage(n, json_fotos, current_image_count, fotos_total);
			
			if (n.up('.point').hasClassName('next')){ //
			
				tar_img = json_fotos[current_image_count+1];
				if (current_image_count + 1<=fotos_total) {
					tar_img = json_fotos[current_image_count+1];
					current_image_count++;
				};			
			} else {
				if (current_image_count - 1>=0){
					tar_img = json_fotos[current_image_count-1];
					current_image_count--;
				}
			}

		if (tar_img){
		
		// change traversal;
			_changeTraversal(n.up('.traverse'), current_image_count, fotos_total, json_fotos);
				
		// change title + total
			_changeTotalAndTitle(n.up('.traverse').down('.total'), current_image_count);
						
		// change picture;
			_changeShownImage(image_holder, current_image_count, tar_img);
			
		//cue fotos;
			cue_fotos(image_holder);
		}
	}
	
	
	
	function debug(msg)
	{
		$('debug').insert({
		  top: msg
		});

	}
	
	function makeImage(img)
	{
		n_img = new Image();
		n_img.src = img.src;
		n_img.height = img.height;
		n_img.width = img.width;
		
		return n_img;
		
	}
	
	function json_Img(json_img)
	{
		
		new_img = new Image();
		new_img.src = json_img.url;
		new_img.width = json_img.details[0];
		new_img.height = json_img.details[1];
		
		//alert(new_img.src);	
		
		return new_img;
	}
	
	function cue_fotos(img)
	{
	
		foto_num = eval(img.title);
		
		// forward;
		
			if (foto_num + 1<=fotos_total) { fotos[foto_num + 1] = json_Img(json_fotos[foto_num + 1]); };
					
		// back;
			if (foto_num - 1>0) { fotos[foto_num - 1] = json_Img(json_fotos[foto_num - 1]); };
		
		//alert(fotos_total + ' : ' + foto_num); 
	}
	
	var fotos = new Array();
	var fotos_json = null;
	var fotos_total =null;
			
	document.observe("dom:loaded", function()
	{	
		// external links
		_external_internal_links();
		//map
		
		if ($('map_canvas')){
			
			directionsService = new google.maps.DirectionsService();
			johannesburg = new google.maps.LatLng(-26.16611, 28.04906); 
			coffeebay = new google.maps.LatLng(-31.984049, 29.148667);
			queenstown = new google.maps.LatLng(-31.896, 26.87099);// -31.896, 26.87099
			
			ini_map("map_canvas");/**/
		}
		
		// timeline
		
		$$('.timeline').each(function(ob){
			
			// day opener;
			var days_day = ob.select('.days .day');
			var days_tweets = ob.select('.days_tweets .day_tweets');
			
			var day_tweets_to_open_ob = $('day_' + ob.down('.days .selected').id.sub(/\D+/, '') + '_tweets');
			
			days_day.each
			(
				function (p)
				{
					p.down('a').observe
					(
						'click', 
						function(e)
						{
							//unselect the rest
							days_day.invoke('removeClassName', 'selected');
							days_day.invoke('removeClassName', 'yellow');
								// apply to days tweets;
								days_tweets.invoke('removeClassName', 'selected');
							
							// select
							p.addClassName('selected');
							p.addClassName('yellow');
								// apply to selected day tweet;
								day_tweets_to_open_ob = $('day_' + p.id.sub(/\D+/, '') + '_tweets');
								day_tweets_to_open_ob.addClassName('selected');
								
							e.stop();															   
						}
					);
				}
			);
			
			// tweet scroll;	
			
			var traverse = ob.select('.traverse .point');
			//var all_tweets = day_tweets_to_open_ob.select('.tweet');
			
			traverse.each
			(
				function(t)
				{
					//var origin_loc = 
					t.observe
					(
					 	'click',
						function (e)
						{
							skroll = day_tweets_to_open_ob.down('.tweet_scroller');					
							distance = 160;
							
							up_or_down = (t.hasClassName('up')) ? -distance : distance;
							
							pos = skroll.viewportOffset();
								
							// alert(Math.abs(pos[1]) + ' | ' + skroll.getHeight() + ' < ' + distance);
								
							if (skroll.getHeight() > distance){
								new Effect.Move(skroll, { x: 0, y: up_or_down });
							}
							
							e.stop();
						}
					);
				}
			);
			
			// map view
			var tweet_actions = ob.select('.actions a');
			
			tweet_actions.each
			(
				function (a)
				{
					a.observe
					(
					 	'click',
						function (e)
						{
							if (a.hasClassName('pin_icon'))
							{ 
								// map;	
								ob.down('.foto_viewer').addClassName('hidden');
								ob.down('.map_viewer').removeClassName('hidden');
								
								
								point = a.title.split(',');
								
								_html = '';
								
								addTweetMarker(new google.maps.LatLng(point[0], point[1]), 'Tweet Location', _html);
					
								
							} else if (a.hasClassName('picture_icon'))
								{ 
									// picture;
									ob.down('.foto_viewer').removeClassName('hidden');
									ob.down('.map_viewer').addClassName('hidden');
									
									img_html = '<a href="' + a.title + '"><img src="' + a.href + '" /></a>';
									ob.down('.foto_viewer').update(img_html);
									
								}
							e.stop();
							
						}
					);
				}
			);
		});
		
		// .fotos traversing;
		
		$$('.fotos .traverse').each(function(n) {
			
			// pre-load;
				var path = "/coffeebay";
				// get current foto;
				var img = n.up('.fotos').down('.foto').down('img');
					//fotos[img.title] = makeImage(img);// Image();
					
				if (window.location.hash){ // stop stretching
					//img.src = 'http://dev.map.build/views/limits/images/ui/blank.png';	
				}
				
				new Ajax.Request(path + '/fotos.json', {
				  method:'get',
				  requestHeaders: {Accept: 'application/json'},
				  onComplete: function(transport){
					json = transport.responseText.evalJSON(true);
					json_fotos = json.idea.fotos;
					fotos_total = json.pagination.total;
					//cue_fotos(img);
					
					// adjusting according to #foto-tag;
						if (window.location.hash){
							_changePictureOnHash(n, eval(window.location.hash.sub(/\D+/, '')), json_fotos, fotos_total);
						} else {
							cue_fotos(img);
				  		}
				  }
				});

			
			// foto traversing with key stroke;
			
			Event.observe(document, 'keyup', function(e){
				// 
				p = null;
				
				if (e.keyCode == 37){
					p = n.down('.prev').down('a');
				} else if (e.keyCode == 39){
					p = n.down('.next').down('a');
				}
				
				if (p){
					url = p.href + '.json';
					fotoTraverse(p, url);
				}
			});
			
		});
		$$('.fotos .traverse .point a').each(function(n) {	
			n.observe('click', function(e) {
				url = n.href + '.json';
				fotoTraverse(n, url);
				e.stop();
			});
		});
	});
	
	
	
	
	
// eof