/*
 *  Scripts for Mark Schueler's website
 *
 *  Created by Eli Van Zoeren unless otherwise noted
 *  http://elivz.com
 *
 */

jQuery(document).ready(function($) {
	
	// Start homepage slideshow
	$('#slideshow').innerfade({
		speed: 1000,
		timeout: 6000,
		containerheight: 540
	});

	// Automatically clear the comment form
	$('#comment-form input[type=text]').autoClear();
	
	// Setup image pop-ups
	$('.gallery a, a[rel*="attachment"]').vzSlideshow('#single-image');
	

	// Show captions on the gallery thumbnails on hover
	$('.gallery-item').hoverIntent({   
		interval: 200,
		over: function() { $('.gallery-caption', this).fadeIn(700); },
		timeout: 200,
		out: function() { $('.gallery-caption', this).fadeOut(700); }
	}).children('.gallery-caption').hide();
	
});


//
// AutoClear plugin
// Clears an input box when it is entered and returns the original text if nothing is entered
//
(function($) {

	$.fn.autoClear = function() {
		
		// iterate each matched element
		return this.each(function() {
			obj = $(this);
			
			obj.focus(function() {
				if( this.value == this.defaultValue ) {
					this.value = "";
				}
			})
			.blur(function() {
				if( !this.value.length ) {
					this.value = this.defaultValue;
				}
			});
		});
	};
	
})(jQuery);


//
// Tabbify plugin
//
(function($) {

	$.fn.tabbify = function(tabContainer) {
		$(tabContainer).css('position', 'relative').css('height', '80px').children().css('position', 'absolute');
		
		// iterate each matched element
		return this.each(function() {
			tabSet = $(this);
			
			tabs = $('.tab', tabContainer).hide();
			
			$('a', tabSet).click(function() {
			
				// Hide all the tabs
				tabs.fadeOut(400).removeClass('active');
			
				// Show the current one
				$(this.hash).fadeIn(400).addClass('active');
			
				return false;
				
			});
			$('a:first', tabSet).click();
		});
	};
	
})(jQuery);


/*
 * vzSlideshow
 * By Eli Van Zoeren (http://elivz.com)
 *
 * Based on Thickbox by Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
	
	$(document).ready(function() {
		imgLoader = new Image(); // preload loading image
		imgLoader.src = "http://markschuelerphoto.com/wp-content/themes/schueler/images/loader.gif";
	});
	
	$.fn.vzSlideshow = function(domChunk) {
		return this.each(function() {
			$(this).click(function(){
				$.vzSlideshow(this.href, domChunk);
				this.blur();
				return false;
			});
		});
	};

		
	$.vzSlideshow = function(url, domChunk) {	
		
		if (typeof document.body.style.maxHeight === "undefined") { //if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) { //iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		} else { //all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if (tb_detectMacXFF()) {
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
		} else {
			$("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
		}
		
		// Add loader to the page
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");
		$('#TB_load').show();
		

		// Show the overlay, if it is not already up	
		if ($("#TB_window").css("display") != "block") {
			$("#TB_window").append("<div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton'>&times;</a></div><div id='TB_ajaxContent' style='width:100%;height:800px'></div>");
		}
							
		$("#TB_closeWindowButton").click(tb_remove);
		
		$("#TB_ajaxContent").load(url + ' ' + domChunk, function() {
			$('#single-image img').load(function() { vz_ResizePhoto(domChunk) });
			$("#TB_load").remove();
			$(domChunk).click(function(event) { if (event.target == this) { tb_remove(); } });
			$('#info-tabs').tabbify('#tabContainer');
			$("#TB_ajaxContent #pagination a").vzSlideshow('#single-image');
			$("#TB_window").css({display:"block"});
		});
		
		document.onkeyup = function(e){ 	
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			if (keycode == 27) { // close
				tb_remove();
			}	
		};
						
	}
	
	// Helper functions below
	
	function vz_ResizePhoto(wrapper) {
		var image = $('#single-image img').css('opacity', '0.01');	

		var imageWidth = image.attr('width');
		var imageHeight = image.attr('height');
		var imageAspect = imageWidth / imageHeight;
		
		var windowSize = tb_getPageSize();
		
		if (imageAspect > 1) { // Landscape orientation
			var windowWidth = windowSize[0] - 140;
			var windowHeight = windowSize[1] - 200; // Leave room for the caption
			$(wrapper).addClass('horizontal');
		} else { // Portrait orientation
			var windowWidth = windowSize[0] - 410; // Leave room for the caption
			var windowHeight = windowSize[1] - 80;
			$(wrapper).addClass('vertical');
		}
		
		if (imageWidth > windowWidth) {
			imageHeight = imageHeight * (windowWidth / imageWidth); 
			imageWidth = windowWidth; 
		}
		if (imageHeight > windowHeight) { 
			imageWidth = imageWidth * (windowHeight / imageHeight); 
			imageHeight = windowHeight; 
		}
		
		image.css({'width': imageWidth, 'height': imageHeight});
		
		var wrapperWidth = (imageAspect > 1) ? imageWidth : imageWidth + 270;
		$('#image-wrapper').css({'width': wrapperWidth});
		image.css('opacity', '1');	

	}
	
	
	function tb_getPageSize(){
	  var de = document.documentElement;
	  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	  arrayPageSize = [w,h];
	  return arrayPageSize;
	}
	
	function tb_remove() {
	 	$("#TB_imageOff").unbind("click");
		$("#TB_closeWindowButton").unbind("click");
		$("#TB_window,#TB_overlay").fadeOut(500,function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
		$("#TB_load").remove();
		if (typeof document.body.style.maxHeight == "undefined") { //if IE 6
			$("body","html").css({height: "auto", width: "auto"});
			$("html").css("overflow","");
		}
		document.onkeydown = "";
		document.onkeyup = "";
		return false;
	}
	
	
	function tb_detectMacXFF() {
		var userAgent = navigator.userAgent.toLowerCase();
		if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
    	var ffversion = new Number(RegExp.$1);
    	if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
      		return true;
    	}
  }
	}

})(jQuery);


/* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);