
/*	Shiny JS, Core
	This code is copyright (c) Ernesto Mendez 2010.
	http://der-design.com */

$(document).ready(function() {

	//twitter_user = ''; // dynamically defined

	current_color_theme = get_metavar('shiny_color_theme');

	init_globals();

	initialize();

	twitter_init();

	prettyphoto_init();

	init_portfolio();

	initialize_alt_forms();

	hover_events();

	click_events();

	init_flickr_widgets();

	automatic_image_resizing();
	
});


function init_globals() {

	header_controls_opacity = $('#header ul.controls li').css('opacity');

}

function initialize() {

	// Dropdown Menu Animation

	$('#nav li').hover(function() {

		$(this).find('ul:first').css({visibility: 'visible',display: 'none'}).slideDown(400,'easeOutSine');

	}, function() {

		$(this).find('ul:first').css({visibility: 'hidden'});

	});

	// Post Images reflection (normal)

	$('ul.post-image:not(.single) li img.reflection').reflect({opacity: 0.3, height: 60});

	$('#single ul.post-image li img.reflection').reflect({opacity: 0.24, height: 60});

	// Post Images reflection (full width)

	$('#blog .content-full-width .post .post-image img.reflection').reflect({opacity: 0.3, height: 125});

	// Webkit Fixes

	if ( $.browser.safari ) {

		$('#search-popup p input[type=text]').css('top', '31px');

	}

	// Precache hover images

	$.cacheImage([
		theme_path('icons/more-btn-right-hover.png')
	]);

	// Style Fixes

	$('#nav').css('overflow', 'hidden');

	$('#nav > li').css('marginTop', '10px');

	// Global Keyboard Support

	$(document).keyup(function(e) {

		if ( top_sidebar_active == true ) {

			if ( e.keyCode == 27 ) {$('#top-sidebar-dismiss').click();}

		}

		if ( header_search_active == true ) {

			if ( e.keyCode == 27 ) {$('#header #search-popup .close').click();}

		}

	});

	// Sticky footer, JQuery style

	var window_height = $(window).height();

	var body_height = $('body').height();

	if ( body_height < window_height ) {

		var m = window_height - body_height + 0 + 'px';

		$('#footer-wrap').css('marginTop', m);

	}

	// Enhance WordPress Menus

	$('#header #nav ul.sub-menu, #header #nav ul.children').each(function() {

		$(this).parents('li').addClass('page-parent');

	});

	$('#header #nav li a').removeAttr('title');

	// Remove empty pagination

	var pagination_fix_selector = '#blog-pagination, #portfolio-pagination';

	$(pagination_fix_selector).each(function() {

		if ( $(this).children().length == 0 ) {

			$(this).remove();

		}

	});
	
	// Initialize Pagination on portfolio pages
	
	if ( $('body#portfolio').length ) {
		var nav = $('#portfolio span.pagination-nav');
		var current = $('#portfolio ul.pagination li.current');
		var next = current.next().find('a').attr('href') || '#';
		var prev = current.prev().find('a').attr('href') || '#';
		nav.find('a').eq(0).attr('href', prev); // previous
		nav.find('a').eq(1).attr('href', next); // next
	}
	$('a[href=#]').click(function() { return false; });

}

function automatic_image_resizing() {

	// Automatic Image Resizing for Single Posts (Normal & Full Width)

	var single_post = $('body#single').length;

	var single_post_fullwidth = $('body#blog #content.content-full-width:not(.blog)').length;

	if ( single_post || single_post_fullwidth ) {

		var boundary_width = ( single_post ) ? $('#single .post').width() : $('#blog #content .post .post-content').width();

		var selector = ( single_post ) ? '#single .post .excerpt img, #single .post .excerpt embed' : '#blog #content .post .post-content img, #blog #content .post .post-content embed';

	} else {

		// Automatic Image Resizing for Pages (Normal & Full Width)

		var page = $('#page #content-wrap:not(.content-full-width)').length;

		var page_fullwidth = $('#page #content-wrap.content-full-width').length;

		if ( page || page_fullwidth ) {

			var boundary_width = ( page ) ? $('#page #content .post').width() : $('#page #content-wrap .post').width();

			var selector = ( page ) ? '#page #content .post img, #page #content .post embed' : '#page #content-wrap .post img, #page #content-wrap .post embed';

		}

	}

	// Resize Images / Flash video!

	$(selector).each(function() {

		if ( $(this).parents('.post-image').length == 1 ) {return true;}

		// Proportionally resize Images

		if ( $(this).is('img') ) {

			var w = parseInt( $(this).attr('width') );

			var h = parseInt( $(this).attr('height') );

			if ( w > boundary_width ) {

				$(this).attr('width', boundary_width).removeAttr('height');

			}

			return true;

		}

		// Proportionally resize videos / flash media

		if ( $(this).is('embed') ) {

			var w = $(this).attr('width');

			var h = $(this).attr('height');

			var proportional_height = Math.ceil( ( boundary_width * h )/w );

			$(this).attr('width', boundary_width).attr('height', proportional_height);

			return true;

		}

	});

}

function init_portfolio() {

	if ( $('body#portfolio').length == 1 ) {

		// Configure overlay excerpts height

		$('#portfolio-wrap .thumbs-container li .overlay').each(function() {

			var h = $(this).find('h3.item-title').height();

			$(this).find('.excerpt').height(247-h);

		});

		// Hover event for overlays

		current_overlay_hovered = false;

		var t1 = 400;

		var t2 = 300;

		$('#portfolio-wrap .thumbs-container li').hover(function() {
		
			current_overlay_hovered = $(this).find('.overlay');

			current_overlay_hovered.css('visibility', 'visible').stop().animate({opacity: 1}, t1);

		}, function() {

			current_overlay_hovered.stop().animate({opacity: 0}, t2);

		});

		// Hover event for category buttons

		$('#portfolio-categories .center ul li:not(.active) a').hover(function() {

			$(this).find('.center').css('color', '#4b4849');

		}, function() {

			$(this).find('.center').css('color', '#2f2e2e');

		});

		// Set Initial Top Coordinate for Portfolio Categories

		var h = $('#header-outer').height() + 37;

		$('#portfolio-categories').css('top', h + 'px');

		// Click event for Portfolio Plus (+)

		plus_active = false;

		$('#portfolio-plus a').click(function() {

			if ( plus_active ) {return false;}

			plus_active = true;

			$(this).parent().css('zIndex', '101');

			$('#portfolio-overlay').css('visibility', 'visible');

			var top = parseInt( $('#portfolio-categories').css('top').replace('px', '') );

			var initial_pos = top - 30 + 'px';

			if ( NOT_IE ) {
				$('#portfolio-categories').css({top: initial_pos, visibility: 'visible'}).stop().animate({opacity: 1, top: top + 'px'}, 400);
			} else {
				$('#portfolio-categories').css({top: initial_pos, visibility: 'visible'}).stop().animate({top: top + 'px'}, 400);
			}

			return false;

		});

		// Click event for Portfolio Plus (+) Close button

		$('#portfolio-categories-close, #portfolio-overlay, #portfolio-categories-overlay, #portfolio-plus').click(function(evt) {

			var trigger = $(evt.target).attr('id');

			if ( $(this).attr('id') == 'portfolio-categories-close' || trigger == 'portfolio-overlay' || trigger == 'portfolio-categories-overlay' || trigger == 'portfolio-plus') {

				var t = 400;

				if ( NOT_IE ) {
					$('#portfolio-categories').stop().animate({opacity: 0}, t);
				} else {
					$('#portfolio-categories').css('visibility', 'hidden');
				}

				setTimeout(function() {

					plus_active = false;

					$('#portfolio-categories, #portfolio-overlay').css('visibility', 'hidden');

					$('#portfolio-plus').css('zIndex', '1');

				}, t+10);

				return false;

			} else {

				return true;

			}
			
		});

	}

}

function twitter_init() {

	if ( twitter_user == null || $('body#home').length == 0 ) {return false;}

	var twitter_icon_src = $('#twitter .twitter-icon img').attr('src');

	/* Make sure we load twitter icon before proceeding to fetch tweets from twitter.com, since
	 * the twitter section's layout depends on the icon's width. */

	$.cacheImage(twitter_icon_src, {
		complete : function(e) {

			// Complete callback start

			/* After the twitter icon has been cached, now we can proceed to calculate the
			 * layout's dimensions, since we can now use .width(), because the img exists. */

			$('#twitter .tweet').tweets({
				tweets:1,
				username: twitter_user,
				callback: function(tweet) {

					$('#twitter .tweet').html(tweet);

					var h = $('#twitter').height();

					var tw_icon_top = Math.ceil( ( h - $('#twitter .twitter-icon').height() )/2.0 ) + 'px';

					$('#twitter .twitter-icon').css('top', tw_icon_top);

					var btn_top = Math.ceil( ( h - 47 )/2.0 ) + 'px';

					$('#twitter #twitter-follow').css('top', btn_top);

					var p_width = 860 - 30 - $('#twitter .twitter-icon').width() - $('#twitter #twitter-follow').width() + 'px';

					var p_mleft = $('#twitter .twitter-icon').width() + 15 + 'px';

					$('#twitter .tweet').css({
						'paddingLeft': p_mleft,
						'width'		: p_width
					});

				}
			});

			// Complete callback end

		}
	});

}

function prettyphoto_init() {

	// Global prettyphoto settings

	prettyphoto_settings = {};

	// Slideshow Video Lightbox settings

	$("#slideshow-video-trigger, a[rel^='lightbox']").prettyPhoto({
			animationSpeed: 'normal', /* fast/slow/normal */
			opacity: 1, /* Value between 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
			default_width: 500,
			default_height: 344,
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'facebook', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			wmode: 'opaque', /* Set the flash wmode attribute */
			autoplay: true, /* Automatically start videos: True/False */
			modal: false, /* If set to true, only the close button will close the window */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){

				// If slideshow loop enabled and video has been triggered, continue the slideshow loop

				if ( triggered_video && slideshow_loop_enabled ) {

					triggered_video = false;

					slideshow_loop();

				}

			} /* Called when prettyPhoto is closed */
		});

}

function hover_events() {

	// Header Controls

	controls_locked = false;

	$('#header ul.controls li').hover(function() {

		if ( controls_locked || IE ) {return false;}

		$(this).stop().animate({'opacity': 1}, 200);

	}, function() {

		if ( controls_locked || IE ) {return false;}

		$(this).stop().animate({'opacity': header_controls_opacity}, 200);

	});

	// Slideshow Controls

	if ( NOT_IE ) {

		$('#slideshow #slideshow-left, #slideshow #slideshow-right').hover(function() {

			$(this).children('a').stop().animate({opacity: 1},400);

		}, function() {

			$(this).children('a').stop().animate({opacity: 0},300);

		});

	} else {

		$('#slideshow #slideshow-left, #slideshow #slideshow-right').hover(function() {

			$(this).css('cursor', 'pointer');

			$(this).children('a').css('visibility', 'visible');

		}, function() {

			$(this).css('cursor', 'default');

			$(this).children('a').css('visibility', 'hidden');

		});

	}

	// Gray rounded button

	gray_btn_hovers = {
		'default'	:	'#8bbfff',
		'dark'		:	'#8bbfff',
		'red'		:	'#ff8b8b',
		'green'		:	'#558556',
		'blue'		:	'#8bbfff',
		'orange'	:	'#ffd58b'
	}

	$('ul.gray-btn').hover(function() {

		$(this).find('a').css('text-shadow', '0 0 10px ' +  gray_btn_hovers[current_color_theme]);

	}, function() {

		$(this).find('a').css('text-shadow', '0 0 6px #000');

	});

	// Gray rounded button

	$('ul.more-btn li a').hover(function() {

		$(this).parents('ul').find('li:last-child a').css('background-image', 'url(' + theme_path('icons/more-btn-right-hover.png') + ')');

	}, function() {

		$(this).parents('ul').find('li:last-child a').css('background-image', 'url(' + theme_path('icons/more-btn-right.png') + ')');

	});

	// Sidebar links hover

	hover_grab = false;

	$('.widget ul li a, .excerpt a, .der-flickr a').hover(function() {
		
		if ( $(this).find('img').length == 0 ) {

			/*
			 * A global variable of hover_grab is used because it's more
			 * efficient than making the children check when hovering out.
			 *
			 * Instead of checking if there's an <img> child, we just check
			 * the variable, which takes up less memory, as opposed to re-checking
			 * for children.
			 */

			hover_grab = true;

			$(this).css('textDecoration', 'underline');

		}

 	}, function() {

		if ( hover_grab ) {

			$(this).css('textDecoration', 'none');

			hover_grab = false;

		}

	});

	// Nav Hover Fix

	$('#nav').hover(function() {

		$(this).css('overflow', 'visible');

		if ( $.browser.safari ) {$('html').css('overflow-x', 'hidden');}

	}, function() {

		$(this).css('overflow', 'hidden');

		if ( $.browser.safari ) {$('html').css('overflow-x', 'visible');}

	});

}

function click_events() {

	// Slideshow Video frame click event

	/* The click event must be bound to the <map> not to the <img> itself, since the image is connected to
	 * an area map, the click event is registered at the <map>, not at the <img>. */

	 triggered_video = false;	// Global var that will determine if the slideshow video has been triggered

	$('#slideshow map').click(function() {

		/* Forward click() event from the map to the link, which triggers the lightbox, an <img> element can't
		 * trigger the lightbox, even if it it's connected to an area map */

		if ( slideshow_loop_enabled ) {

			triggered_video = true;  // Set to true, so the lightbox knows that the video has been triggered

			clearInterval(slideshow_loop_interval);	 // Stop the slideshow loop, until the lightbox has been closed

		}

		$('#slideshow-video-trigger').click(); // Previously configured by prettyphoto

		return false;

	});

	// Header Controls: Search Button

	header_controls_opacity = $('#header ul.controls li').css('opacity');

	header_search_active = false;

	$('#header #search-control').click(function() {

		header_search_active = true;

		if ( controls_locked ) {return false;}

		controls_locked = true;

		if ( NOT_IE ) {
			
			$(this).parent().css('opacity', 1);

			$('#search-popup').css({top: '15px', visibility: 'visible'})
			.stop().animate({opacity: 1, top: '25px'}, 300);
			
		} else {

			$('#search-popup').css({top: '15px', visibility: 'visible'})
			.stop().animate({top: '25px'}, 300);

		}



		$('#search-popup input[type=text]').focus();

		return false;

	});

	// Header Controls: Search Button > Close

	$('#header #search-popup .close').click(function() {

		controls_locked = false;

		var t = ( NOT_IE ) ? 180 : 0;

		if ( NOT_IE ) {

			$('#header #search-control').parent().stop().animate({opacity: header_controls_opacity}, t);

			$('#header #search-popup').stop().animate({opacity: 0}, t);

		}

		setTimeout(function() {

			$('#search-popup').css('visibility', 'hidden');

			header_search_active = false;

		}, t);

		return false;

	});


	// Header Controls: RSS Button

	$('#header #rss-button').click(function() {

		if ( controls_locked ) {return false;}

		return true; // Go to the link's destination

	});

	// Header Controls: Top Sidebar Control

	top_sidebar_active = false;

	$('#header #top-sidebar-control').click(function() {

		if ( controls_locked ) {return false;}

		controls_locked = true;

		top_sidebar_active = true;

		var h = '-' + $('#top-sidebar-wrap').height() + 'px';

		$('#top-sidebar-wrap').css('top', h);

		$('#top-sidebar, #top-sidebar-foot, #top-sidebar-overlay').css('visibility', 'visible');

		$('#top-sidebar-wrap').stop().animate({top: 0}, 300, 'easeOutSine');

		return false;

	});

	// Top Sidebar Dismiss button

	$('#top-sidebar-dismiss, #top-sidebar-overlay').click(function(evt) {

		top_sidebar_active = false;

		var trigger = $(evt.target).attr('id');

		if ( $(this).attr('id') == 'top-sidebar-dismiss' || trigger == 'top-sidebar-wrap' || trigger == 'top-sidebar-overlay' ) {

			// Dismiss the top sidebar if either the dismiss button is clicked, or by clicking on the overlay

			var h = '-' + $('#top-sidebar-wrap').height() + 'px';

			$('#top-sidebar-wrap').stop().animate({top: h}, 300, 'easeInQuad');

			setTimeout(function() {

				$('#top-sidebar-overlay').css({
					visibility: 'hidden'
				});

				if ( NOT_IE ) {

					$('#header #top-sidebar-control').parent().css('opacity', header_controls_opacity);

				}

				controls_locked = false;

			}, 310);

			return false;

		} else {

			// Process click event as normal

			return true;

		}

	});

}

function initialize_alt_forms() {

	// Initialization code

	$('form.alt input[type=text]').each(function() {

		if ( $(this).val() != '' ) {

			$(this).siblings('label').hide();

		}

	});

	// Hover Events

	$('form.alt .alt-submit').hover(function() {

		$(this).find('input').css('text-shadow', '0px 0px 8px rgba(255,255,255,1)');

	}, function() {

		$(this).find('input').css('text-shadow', '0px 0px 10px rgba(0,0,0,1)');

	});

	// Focus Events

	var t = ( NOT_IE ) ? 200: 0;

	$('form.alt input[type=text]').focus(function() {

		if ( $(this).val() == '' )  {

			if ( NOT_IE ) {
				$(this).siblings('label:not(.error)').stop().fadeOut(t);
			} else {
				$(this).siblings('label:not(.error)').hide();
			}

		}

		$(this).siblings('small').stop().fadeIn(t);

	}).blur(function() {

		if ( $(this).val() == '' ) {

			if ( NOT_IE ) {
				$(this).siblings('label:not(.error)').stop().fadeIn(t);
			} else {
				$(this).siblings('label:not(.error)').show();
			}

		}

		$(this).siblings('small').stop().fadeOut(t);

	});

	// Click Events

	$('form.alt .alt-submit a').click(function() {

		$(this).parents('form').submit();

		return false;
	});

}
