// load google ajax libraries

google.load("feeds", "1");
google.load("maps", "3.x", {"other_params":"sensor=false"});
google.load("jquery", "1.7.1");
google.load("jqueryui", "1.8.16");

// global variables

var AuthorID, DisqusID, TwitName, FlickrID, AnyWhere, GoogleUA, FilesURL;
var addthis_config, tracker;
var _gaq = _gaq || [];

// now get busy

google.setOnLoadCallback(function() {
	$(function() {

		// read meta parameters

		AuthorID = $("meta[name='text:AuthorID']").attr("content");
		DisqusID = $("meta[name='text:DisqusID']").attr("content");
		TwitName = $("meta[name='text:TwitName']").attr("content");
		FlickrID = $("meta[name='text:FlickrID']").attr("content");
		AnyWhere = $("meta[name='text:AnyWhere']").attr("content");
		GoogleUA = $("meta[name='text:GoogleUA']").attr("content");
		FilesURL = $("meta[name='text:FilesURL']").attr("content");

		// load google map

		var latlng   = new google.maps.LatLng(47.143284, 7.24879);
		var geocoder = new google.maps.Geocoder();

		var ocmMapType = new google.maps.ImageMapType({
			getTileUrl: function(coord, zoom) {return "http://tile.opencyclemap.org/cycle/" + zoom + "/" + coord.x + "/" + coord.y + ".png";},
			tileSize: new google.maps.Size(256, 256),
			isPng: true,
			alt: "Show OpenCycleMap",
			name: "Bike",
			maxZoom: 19
		});

		var mapOptions = {
			zoom: 15,
			center: latlng,
			mapTypeId: "OCM",
			mapTypeControlOptions: {
				mapTypeIds: ["OCM", google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN],
				style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
			}
		};

		var map = new google.maps.Map(document.getElementById("map"), mapOptions);
		map.mapTypes.set("OCM",ocmMapType);
		map.setMapTypeId("OCM");

		if(window.loadTracks) loadTracks();

		// dynamically set various element options

		$("iframe[src*='assets.tumblr.com/iframe']").css("position","fixed");
		$("object").add("<param name='wmode' value='transparent' \/>");

		// set image opacity and animation

		$("article:has(div.container) img").css("opacity","0.5").hover(
			function () {$(this).stop().animate({opacity: 1.0}, "slow");},
			function () {$(this).stop().animate({opacity: 0.5}, "slow");}
		);

		// layout adjustments for blog.collideous.com

		$("article:has(div.container)").each(function() {
			$("figure h3", this).prependTo($("div.post", this));
			pageTag = $("a.permalink", this).attr("rel");
			if (pageTag) $("div.tags a:contains("+pageTag+")", this).css("color","#000");
		});

		// layout adjustments for 29in.ch

		$("article:not(:has(div.container))").each(function() {
			$("div.text h3:first", this).prependTo($("header a.permalink:contains('Today\'s')", this).empty());
			pageTag = $("nav", this).attr("rel");
			if (pageTag) $("nav a:contains("+pageTag+")", this).css("color","#fff");
			if ($("time", this).length==0) {
				$("div.wrapper", this).css("border-radius","30px");
			}
		});

		// attach onclick event to tweetbox (show/hide)

		$("#open").click(function() {
			$("#tweetbox").slideToggle('slow');
			$("#open").text($('#open').text() == 'minimize' ? 'maximize' : 'minimize');
			return false;
		});

		// attach fancybox to various anchor types

		$.getScript(FilesURL+"/fancybox/fancybox.js", function() {
			$(".wrap>a,.wrap>.slider>a,a.fancybox").fancybox({
				'closeClick' : true
			});
			$("a.iframe,a[href$='iframe']").fancybox({
				'height'    : '100%',
				'width'     : '100%',
				'scrolling' : 'no'
			});
			$("a[href*='youtube.com/watch'], a[href*='vimeo.com/']").click(function() {
				switch (this.hostname) {
					case "www.youtube.com":
  						video = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/');
  						break;
					case "www.vimeo.com":
  						video = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1');
  						break;
					default:
						video = this.href;
				}
				$.fancybox({
					'height'    : 495,
					'width'     : 680,
					'href'      : video,
					'type'      : 'swf',
					'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
				});
				return false;
			});
			$("a.question").fancybox({
				'height' : 150,
				'href'   : 'http://www.tumblr.com/ask_form/blog.collideous.com',
				'type'   : 'iframe'
			});
			$("a.comment").fancybox({
				'height' : 380,
				'href'   : 'http://www.tumblr.com/submit_form/blog.collideous.com',
				'type'   : 'iframe'
			});
			$("a[href*='maps.google.com/maps']").click(function() {
				address = this.search.replace(/\+/g, ' ').substring(3);
				geoOBJ  = $(this).parents("div.post").find("a[href*='mapOnly.do']");
				$.fancybox({
					'href'          : '#map',
					'scrolling'     : 'no',
					'title'         : '<a href="http://maps.google.com/">Google<\/a> mapping '+address,
					'afterLoad'    : geocoder.geocode(
						{'address': address},
						function(results, status) {
							if (status == google.maps.GeocoderStatus.OK) {
								map.setCenter(results[0].geometry.location);
								marker = new google.maps.Marker({position: results[0].geometry.location});
								marker.setMap(map); 
								if (geoOBJ.length) {
									geoURL = geoOBJ.attr("href").replace("mapOnly.do", "download.do")+"&filetype=kml";
									geoXML = new google.maps.KmlLayer(geoURL, {preserveViewport: true});
									geoXML.setMap(map);
									if (geoOBJ.attr("rel")) {
										imgURL = encodeURI("http://api.flickr.com/services/feeds/geo/?id="+FlickrID+"&format=rss_200&tags="+geoOBJ.attr("rel"));
										imgXML = new google.maps.KmlLayer(imgURL, {preserveViewport: true});
										imgXML.setMap(map);
									}
								}
							}
						}
					)
				});
				return false;
			});
		});

		// load twitter anywhere

		$.getScript("http://platform.twitter.com/anywhere.js?id="+AnyWhere, function(){
			twttr.anywhere(function (T) {
				T("#tweetbox").tweetBox({
					height: 50,
					width: 490,
					label: false,
					defaultContent: '@'+TwitName+' '
				});
				T(".twitter-name").hovercards({
					username: function(node) {return node.title;}
				});
				T(".twitter-user, .notes .action a.tumblelog").hovercards({
					username: function(node) {return $(node).text();}
				});
				T("section.main").hovercards();
			});
		});

		// create flickr thumbnail page

		if($("#flickrthumbs").length) {
			$.getScript(FilesURL+"/jflickrfeed.js", function(){
				flickrtags = location.hash.length ? location.hash.substring(1) : '';
					if (location.hash.length) {
					$("#flickrthumbs").parents("div.container").find("h3").append(" tagged &quot;"+flickrtags+"&quot;");
				}
				$("#flickrthumbs").jflickrfeed({
					limit: 25,
					qstrings: {
						id   : FlickrID,
						tags : flickrtags
					},
					itemTemplate:
						'<li>' +
							'<a class="wrap" rel="FancyFlickr" href="{{-image_b-}}" title="{{-title-}}">' +
								'<img src="{{-image_s-}}" alt="{{-title-}}" />' +
							'</a>' +
						'</li>'
				}, function(data) {
					$("#flickrthumbs a").fancybox({
						'closeClick' : true
					});
				});
			});
		}

		// create instagram slideshow on static page

		if($("#instagram").length) {
			$.getScript(FilesURL+"/jflickrfeed.js", function(){
				$("#instagram").jflickrfeed({
					limit: 25,
					qstrings: {
						id: FlickrID,
						tags : $("#instagram").attr("title")
					},
					itemTemplate: '<a href="{{-link-}}" title="{{-title-}}"><img title="{{-title-}}" src="{{-image-}}" /></a>'
				}, function(data) {
					$.getScript(FilesURL+"/nivoslider/nivo.slider.js", function(){
						$("#instagram").nivoSlider();
					});
				});
			});
		}

		// load nivo jquery slider

		if($(".slider").length) {
			$(".slider a").each(function () {
				$("img", this).attr("title", $(this).attr("title"));
			});
			$.getScript(FilesURL+"/nivoslider/nivo.slider.js", function(){
				$(".slider").nivoSlider();
			});
		}

		// track visits with google analytics

		$.getScript("http://www.google-analytics.com/ga.js", function(){
			_gaq.push(["_setAccount", GoogleUA]);
			_gaq.push(["_trackPageview"]);
			_gaq.push(["_trackPageLoadTime"]);
		});

		// insert addthis widget

		$.getScript("http://s7.addthis.com/js/250/addthis_widget.js", function(){
			addthis_config = {
				username             : TwitName,
				//data_ga_tracker      : tracker,
				data_track_clickback : true,
				ui_delay             : 300,
				ui_language          : 'en',
				ui_offset_top        : 20,
				services_compact     : 'print,email,favorites,facebook,twitter,tumblr,gmail,google,evernote,more'
			};
			$("a.addthis").bind({
				mouseover : function(){
					title  = $(this).parents("article").find("div.post h3").html();
					return addthis_open(this, "", this.rel, title);
				},
				mouseout  : function(){addthis_close();},
				click     : function(){return addthis_sendto();}
			});
		});

		// get number of disqus comments and insert disqus threads

		$.getScript(FilesURL+"/jdisqus.js", function(){
			$("#disqus_thread").disqus({domain : DisqusID});
			$("a.disqus").disqusLink(DisqusID);
		});

		// change the standard disqus text "x comments and x reactions"

		var disqus_separator = (DisqusID == AuthorID) ? " &bull; " : " <b>&#9733;</b> ";
		var check_disqus = setInterval(function() {
			if ($("footer a.disqus:last:contains(' and ')").length) {
				clearInterval(check_disqus);
				$("footer a.disqus").each(function () {
					$(this).html($(this).html().replace(" and ", disqus_separator));
				});
			}
		}, 100);

	});
});
