/*
Javascript for HenryTapia.com (using Wordpress theme henrytapia2010)

Uses jQuery 1.3.2
*/

$(function(){
	ht.init();
});

var ht = {

	init : function() {
	
		/*
		Global settings
		============================================================ 
		*/
		var settings = {
			extraShortDelay		: "500",
			shortDelay				: "1000",
			mediumDelay				: "3000",
			flickrThumbs			: "#footer #flickr li a img"
		};

		/*
		// do this on DOMReady:
		============================================================ 
		*/

		// Tweet.js
		$.getScript( wp_templatePath + "/javascript/jquery.tweet.js", function(){
			$("#twitter .inner").tweet({
	            username: 					"henrytapia",
	            join_text: 					"",
	            avatar_size: 				48,
	            count: 						6,
	            auto_join_text_default: 	"I said,",
	            auto_join_text_ed: 			"I",
	            auto_join_text_ing: 		"I was",
	            auto_join_text_reply: 		"I replied to",
	            auto_join_text_url: 		"I am checking out",
	            loading_text: 				"Getting latest tweet...",
				outro_text: 				"<span class='arrow'></span><span class='shitbird'></span>",
				template: 					"{avatar}{join}{text}{time}{follow_me}"
	        });
			$(".home #twitter").slideDown();
		});

		// Show cufon elements then call Cufon - these lines correspond with the items hidden (using visibility: hidden) near the end of style.css
		$("#container .sidebar ul h3, h2.entry-title, .home .headlines h2, .headlines h3, .home #twitter h2, .home .post .entry-date, .single .post .entry-date, .single #comments h3, .single #respond h3, h2.page-title, .page-template-archives-php #monthly-archives h3, .page-template-archives-php #category-archives h3, #footer h3.widgettitle, .special-type").css("visibility","visible");
		Cufon.replace('#container .sidebar ul h3, h2.entry-title:not(.nocufon), .home .headlines h2, .headlines h3, .home #twitter h2, .home .post .entry-date, .single .post .entry-date, .single #comments h3, .single #respond h3, h2.page-title, .page-template-archives-php #monthly-archives h3, .page-template-archives-php #category-archives h3, #footer h3.widgettitle, .special-type');

		// Init hover button behaviour
		initFadingHovers("#header .rss a", .6);
		initFadingHovers(".single .entry-content .sharing a, #footer #social_networks li a", .75);

		// Init flickr image rollovers
		initThumbnails(settings.flickrThumbs);

		// Init logo tooltip
		createLogoTooltip('#blog-title a');
		
		// Add spans to ampersands
		dressUpAmpersands();

		// Create mobile style switcher elements as follows:
		/*
		<li class="mobile-style-switcher">
			<p class="to-full">Viewing mobile site. Switch to <a href="#">full site</a></p>
			<p class="to-mobile">Viewing full site. Switch to <a href="#">mobile site</a></p>
		</li>
		*/
		var mobileStyleSwitcher = $('<li class="mobile-style-switcher"></li>');
		var switchToMobile = $('<p class="to-full">Viewing mobile site. Switch to <a href="#">full site</a></p>');
		var switchToFull = $('<p class="to-mobile">Viewing full site. Switch to <a href="#">mobile site</a></p>');
		switchToMobile.appendTo(mobileStyleSwitcher);
		switchToFull.appendTo(mobileStyleSwitcher);
		mobileStyleSwitcher.insertAfter('li#social_networks');

		// Init mobile style switcher cookie
		/*var mobileStylesheet = $('head link.mobile');
		//var appleMeta = $('head meta.apple'); */
		var postStylesheet = $('head link.post-style');

		if (!$.cookie('isMobile')) { 				// check if cookie is already present. If it isn't, create it.
			$.cookie('isMobile', 'true', { path: '/', domain: 'henrytapia.com', expires: 90 });
		} else {														// otherwise check if isMobile is true, and if not, remove mobile stylesheet (switch to full site)
			if ($.cookie('isMobile') == 'false') {
				postStylesheet.attr('media', 'screen');
				$('.mobile-style-switcher').show();
				$('.mobile-style-switcher .to-full').hide();
				$('.mobile-style-switcher .to-mobile').show();
			}
		}

		// Init mobile style switcher behaviours
		$('.mobile-style-switcher a').click(function() {
			if ($.cookie('isMobile') == 'true') {		// switch to full site
				$.cookie('isMobile', 'false', { path: '/', domain: 'henrytapia.com', expires: 90 });
				window.location.reload();
			} else {																// switch to mobile site
				$.cookie('isMobile', 'true', { path: '/', domain: 'henrytapia.com', expires: 90 });
				window.location.reload()
			}
			return false;
		});

		// Add "new" bubble to nav	(COMMENTED OUT: not new any more)
		// $('<span class="new"</span>').appendTo('#menu .page-item-214');		/* live */
		// $('<span class="new"</span>').appendTo('#menu .page-item-295');		/* local */

		// init lightbox gallery overlay
		if ($('#footer #flickr li a').length) {	// only where required

			// change flickr links to point directly to photos instead of flickr page
			$('#footer #flickr li a').each(function(){
				$(this).data('flickrURL', $(this).attr('href'));
				var flickrImgUrl = $('img', this).attr('src');
				if (flickrImgUrl.indexOf("_s.jpg") != -1) {
					$(this).attr('href', flickrImgUrl.replace("_s.jpg", "_z.jpg"));
				} else {
					$(this).attr('href', flickrImgUrl.replace("_m.jpg", "_z.jpg"));
				}
			});

			// create overlay content elements
			createGalleryOverlay("flickrGallery");

			// create overlay instances
			$('#footer #flickr li a')
				.overlay({
					target: '#flickrGallery',
					expose: {
						color: '#000',
						opacity: .9
					}
				}).gallery({
					autohide: false,
					speed: 800,
					template:	"<strong><a href='${link}' target='_blank' title='View this photo at Flickr'>${title}</a></strong> <span>Image ${index} of ${total}</span>"
				});

		}

		$('.thumbnail-grid').each(function() {

			// create overlay content elements
			createGalleryOverlay("gallery");

			$('a', this).overlay({
				target: '#gallery', 
				expose: {
					color: '#000',
					opacity: .9
				}
			}).gallery({
				autohide: false,
				speed: 800 
			});

		});

		$('a[rel=lightbox]').each(function() {

			// create overlay content elements
			createGalleryOverlay("lightbox");

			$(this).overlay({
				target: '#gallery', 
				expose: {
					color: '#000',
					opacity: .9
				}
			}).gallery({
				autohide: false,
				speed: 800 
			});

		});

		// add speech bubble arrows to comments and validation errors
		$('.single #comments .comments li.comment .comment-content, .page div.wpcf7 .wpcf7-not-valid-tip-no-ajax, .tooltip-logo').append('<span class="arrow"></span>');

		/* ---- Work/portfolio scripts ---- */

		// Create slideshow and thumbnail "more info" hovers
		$('.page-template-work-php .slideshow .gallery li a, .page-template-work-php .thumbnails li a').append('<span class="info"></span>');	

		// Make thumbnail captions clickable
		$('.page-template-work-php .thumbnails li')
			.css('cursor', 'pointer')
			.click(function() {
				window.location = $('a', this).attr('href');
			});

		// Show info icon on hover
		if (!$.browser.msie){
			$('.page-template-work-php .thumbnails li').hover(function(){
				$('span.info', this).fadeIn();
			}, function(){
				$('span.info', this).fadeOut('fast');
			});
		}

		// init scrollable slideshow
		$('.page-template-work-php .slideshow .gallery').each(function() {	// do the following only for the work/portfolio section

			// create carousel navigation elements as follows:
			/*
			<div class="nav clearfix">
				<p><a class="prev">Prev</a></p>
				<ul class="clearfix">
				</ul>
				<p><a class="next">Next</a></p>
			</div>
			*/
			var prev = $('<p><a class="prev">Prev</a></p>');
			var next = $('<p><a class="next">Next</a></p>');
			var navi = $('<ul class="clearfix"></ul>');
			var nav = $('<div class="nav clearfix"></div>');
			$(nav).append(prev, navi, next);
			$(this).after(nav);

			// init scrollable with navigator and autoscroll plugins
			slideshow = $(this).scrollable({
				items: 'ul',
				circular: true
			})
			.navigator({
				navi: '.nav ul',
				naviItem: 'li',
				activeClass: 'current'
			})
			.autoscroll(5000);

			// show info icon on hover
			if (!$.browser.msie){
				$('li a', this).hover(function(){
					$('span.info', this).fadeIn();
				}, function(){
					$('span.info', this).fadeOut('fast');
				});
			}

		});

		/*
		// functions
		============================================================ 
		*/

		function initThumbnails(thumbnails) {
			var thumbs = $(thumbnails);
			if (!$.browser.msie){
				thumbs.hover(function() {
					$(this).parent().parent().siblings().fadeTo(settings.extraShortDelay, .35);
					$(this).parent().parent().fadeTo(settings.extraShortDelay, 1);
				}, function(){ });
				thumbs.parent().parent().parent().hover(function() {
				}, function() {
					$(this).children("li").fadeTo(settings.shortDelay, 1);
				});
			}
		}

		// fading hover button behaviour
		function initFadingHovers(fadingElement, fadeOpacity) {
			$(fadingElement)
				.css("opacity", fadeOpacity)
				.hover(function(){
						$(this).fadeTo("fast", 1);
					}, function() {
						$(this).fadeTo("fast", fadeOpacity);
					});
		}

		// create overlay elements - photo gallery overlays
		function createGalleryOverlay(overlayId) {
			var galleryOverlay = $('<div class="overlay" id=' + overlayId + '></div>');
			var galleryPrev = $('<a class="prev">Previous</a>');
			var galleryNext = $('<a class="next">Next</a>');
			var galleryInfo = $('<div class="info"></div>');
			var galleryProgress = $('<img class="progress" />');

			galleryPrev.appendTo(galleryOverlay);
			galleryNext.appendTo(galleryOverlay);
			galleryInfo.appendTo(galleryOverlay);
			galleryProgress
				.attr('src', wp_templatePath + '/images/ajax-loader.gif')
				.appendTo(galleryOverlay);
			galleryOverlay.insertAfter('#wrapper');
		}
		
		// create custom logo tooltip
		function createLogoTooltip(textSource) {
			var tooltip = $('<div class="tooltip-logo"></div>');
			tooltip.text($(textSource).html().replace(String.fromCharCode(8211),""));
			
			$(textSource)
				.attr('title','')
				.hover(function() {
					tooltip.fadeIn('fast');
				}, function() {
					tooltip.fadeOut('fast');
				});
			
			tooltip.appendTo('#header .inner');
		}
		
		function dressUpAmpersands() {
		    $("h1,h2,h3,p:contains('&amp')", document.body).each(function() {
		        $(this).html( $(this).html().replace( /&amp;/g, "<span class='amp'>&amp;</span>" ) );
		    });
		}

	}
}

