
// Original JavaScript by Chris Coyier
// Updated October 2010 by Stewart Heckenberg & Chris Coyier
// Updated May 2011 by Chris Coyier
// Prepared for Anton Schwartz by Wess Willis and Dan Christopher
// Gallery and Slideshow object written by Dan Christopher

// Self-Executing Anonymous Function to avoid more globals
$(function() {

	// HTTPS: INCOMPATIBLE WITH ALLAJAX. FORWARD TO STANDARD HTTP:
	if(location.protocol === 'https:' && (location.pathname !== '/' || location.hash)) {
		location = 'http://' + location.hostname + location.pathname + location.hash;
	}

	$(window).resize(function() {
		bgChanger();
	}).trigger("resize");

    initSlider();

    // Home link isn't dynamic, so default set class name to it to match how dynamic classes work in WordPress
	$(".home li.home").removeClass("home").addClass("current_page_item");

	// Add spinner via JS, cuz would never need it otherwise
	$("#page-wrap").append("<div id='ajax-loader'></div>");

    var $mainContent = $("#main-content"),
        URL = '',
        siteURL = "http://" + top.location.host.toString(),
        $internalLinks = $("a[href^='"+siteURL+"']"),
	    $ajaxSpinner = $("#ajax-loader"),
        $el, $allLinks = $("a");
	
    // Auto-clear search field
    $("#s").focus(function() {
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    });

	$('#searchform').submit(function() {
		var s = $searchInput.val();
		if (s) {
			var query = '/?s=' + s;
			$.address.value(query);
		}
		return false;
	});

	// If odd number of categories, add a fake one
	if ($(".widget_categories li").length%2 != 0) {
		$(".widget_categories ul").append("<li><a>&nbsp;</a></li>");
	}

	// If odd number of tags, add a fake one
	if ($(".widget_tag_cloud a").length%2 != 0) {
		$(".widget_tag_cloud").append("<a>&nbsp;</a>");
	}

	// URL internal is via plugin http://benalman.com/projects/jquery-urlinternal-plugin/
	$('a:urlInternal').live('click', function(e) {
		var exempt = ['/downloads/','/uploads/','/x/','?feed'],
			direct = false;
		// Caching
		$el = $(this);

		// if it's meant to be directly linked to (skip ajax loading)
		for(var i=0; i < exempt.length; i++) {
			if (($el.attr('href').indexOf( exempt[i] ) >= 0)) {
				direct = true;
			}
		}
    	
		if(direct === true) {
			window.location = $el.attr('href');
		// if it's not a reply link
		} else if ((!$el.hasClass("comment-reply-link")) && ($el.attr("id") != 'cancel-comment-reply-link')) {
			var path = $(this).attr('href').replace(base, '');
			$.address.value(path);
			$(".current_page_item").removeClass("current_page_item");
			$allLinks.removeClass("current_link");
			$el.addClass("current_link").parent().addClass("current_page_item");
			return false;
		}

		// Default action (go to link) prevented for comment-related links (which use onclick attributes)
		e.preventDefault();

	});

	// Fancy ALL AJAX Stuff
	$.address.change(function(event) {
		var current = location.protocol + '//' + location.hostname + location.pathname,
			flag = (event.value.indexOf('?') >= 0) ? '&' : '?'; // for appending ajax_request=true to url's
		if (event.value) {
			$ajaxSpinner.fadeIn();
			$mainContent
				.empty()
				.load(base + event.value + flag + 'ajax_request=true #inside', function(response, status, xhr) {
					if (status == "error") {
						$('#main-content').html("<h2 class='notFound'>Page Not Found</h2> <p>Sorry, but we couldn't find that page.<br/>Please use the menu at left to find what you are after...<br/>or <a href='/#/contact'>contact Anton</a> about the error.</p>"); 
					}
					$ajaxSpinner.fadeOut();
					bgChanger();
					$mainContent.fadeIn();
					emailObfuscator(); 
					initSlider();
					slider.init();
					initSuperscroller();
					$('.cdContainer').trigger('loadPlayer');
					validate.load();
					scrollSection();
				});
		}
	});
  
  (function ($) {

    // Log all jQuery AJAX requests to Google Analytics
    $(document).ajaxSend(function(event, xhr, settings){
      if (typeof _gaq !== "undefined" && _gaq !== null) {
        _gaq.push(['_trackPageview', settings.url]);
      }
    });

  })(jQuery);
  
  //Gigpress Ajax Load (similar to above) 
  $('#gigpress_menu').live('change',function(){
	  	var path = $(this).val().replace(base, '');
			$.address.value(path); 
			return false;
		});

  
  //CALENDAR EXPANDER
  $('.gigpress-row').live('click',function(){
    $(this).find('div.gAdditionalInfo').slideToggle('medium');
		$(this).find('.clickNote').html( ($(this).find('.clickNote').html() == 'Show More Info') ? 'Hide More Info' : 'Show More Info' );
		
		//Track in Google Analytics 
		if($(this).find('.clickNote').html() == 'Hide More Info') {
	   	_gaq.push(['_trackEvent', 'Gigs', 'Individual Show', 'Expansion']);
	}
	});

  // ZIP CODE ADDER
   $('#zipList dd').live('click',function(){
		$t = $(this).attr("title");
		$('#input_1_3').val($('#input_1_3').val() + $t + ',');
	});

	//READ MORE EXPANSION
	$('.cdReadMore').live('click',function(){
		$t = $(this);
		$t.next().toggle('medium');
		$t.html( ($t.html() == 'Read More') ? 'Read Less' : 'Read More' );

	  //Track Event in Google Analytics
	  if($t.html() == 'Read Less'){
	    _gaq.push(['_trackEvent', 'CDs', 'Read More Clicked', 'CD Detail']); 
	  }
	});

	$('dl.expand dt').live('click',function() {
		$(this).toggleClass('open');
		var targetHeight = $(this).next().children('.dd_inner').height()+20;
		if($(this).hasClass('open')) {
			$(this).next().animate({
				height: targetHeight+'px'
			},500);
		} else {
			$(this).next().animate({
				height: '1px'
			},500);
		}
	});


});

// SCROLL TO SPECIFIC SECTION
function scrollSection() {
	var queryPos = window.location.hash.indexOf('?'),
        query = '';

	// USE QUERY STRING FOR SCROLLTO
	if(queryPos >= 0) {
		query = window.location.hash.substr(queryPos);
	} else {
		query = null;
	}

	if(query) {
		query = query.substr(query.indexOf('=')+1);
		$(window).scrollTo('#'+query, 500, {offset: {top:-20, left:0}});
		//Track In Google Analytics 
		_gaq.push(['_trackEvent', 'Super-Scroller', 'Subpage Scrolled To', queryPos]);
	}
}

function bgChanger() {
	if (window.location.href == base+"/#" || !window.location.href.match('#'))  {
		$('.subpageBG').fadeOut("slow");
		$('.homeBG').fadeIn("slow");
		var $bg = $(".homeBG");
	} else {
		$('.homepageBG').fadeOut("slow");
		$('.subpageBG').fadeIn("slow");
		var $bg = $(".subpageBG");
	}

	$bg.css('position','fixed');

  // resize bg
	var bgWidth = $bg.width(),
		aspectRatio = bgWidth / $bg.height(),
		adjust = 0,
		windowWidth = $(window).width(),
		windowHeight = $(window).height();

	if ( (windowWidth / windowHeight) < aspectRatio ) {
		$bg.css('width','auto')
		$bg.css('height',windowHeight+'px');
		adjust = Math.ceil((bgWidth-windowWidth)/2)*-1;
	} else {
		$bg.css('width',windowWidth+'px')
		$bg.css('height','auto');
		adjust = '0';
	}

	$bg.css('left',adjust+'px');

}

function emailObfuscator() {
  var user = "anton"; 
  $('.replaceEM').replaceWith('<a href="mai'+'lto:' + user + '@' + 'antonjazz' + '.com">' + user + '@' + 'antonjazz' + '.com</a>'); 
  
}
/*  

  function outputEmail(user){
   document.write(user+"@"+dom+".com")
  }

  function emailLink(user){
   document.write(linkStart);
   outputEmail("user");
   document.write('">');
   outputEmail(user);
   document.write('</a>');
  }
}

*/ 
function initSuperscroller() {
	// INIT SCROLLING LINKS
	$('#subpage_nav a').click(function() {
		var targetID = this.href.substr(this.href.indexOf('#'));
		$(window).scrollTo( targetID, 500, {offset: {top:-20, left:0}});
		// update hash for bookmarking
//		window.setTimeout(function() { window.location.hash = window.location.hash + "?section=" + targetID.replace(/#/,''); }, 500);
		return false;
	});

	$('.toplink').click(function(){
		var targetID = this.href.substr(this.href.indexOf('#'));
		$(window).scrollTo(targetID, 500);
		return false;
	});

}

var play;
function initSlider() {
	if(play)
		window.clearInterval(play);

	//Set Default State of each portfolio piece
	$(".paging").show();
	$(".paging a:first").addClass("active");

	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".window").width();
	var imageSum = $(".slide").size();
	var imageReelWidth = imageWidth * imageSum;

	//Adjust the image reel to its new size
	$(".image_reel").css({'width' : imageReelWidth});

	//Paging + Slider Function
	rotate = function(){
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".paging a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

		//Slider Animation
		$(".image_reel").animate({
			left: -image_reelPosition
		}, 500 );

	};

	//Rotation + Timing Event
	rotateSwitch = function(){   
	  
	  //Speed at which slides move.  Default is 4000.  Adjust lines below or add classes for differents speeds. 
	  var sliderSpeed = 4000; 
	  
	  if($(".main_view").hasClass('slow')) { 
	    sliderSpeed = 8000; 
	  } else if($(".main_view").hasClass('fast')) {
	    sliderSpeed = 2000; 
	  } 
	   
		play = setTimeout(function(){ //Set timer - this will repeat itself every n seconds
			$active = $('.paging a.active').next();
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $('.paging a:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
			rotateSwitch()
		}, sliderSpeed); //Timer speed in milliseconds (n/1000 seconds)
	};

	rotateSwitch(); //Run function on launch

	//On Hover
	$(".window").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});

	//On Click
	$(".paging a").click(function() {
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearTimeout(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});

};






// OBJECT FOR JQUERY SLIDER NAVIGATION
var slider = {
	pageWidth : 0,

	init : function () {
		var sliders = $(".horizontal_slider");
		if(sliders.length > 0) {
			var _obj = this;

			// ACTIVATE PAGINATION
			sliders.each(function() {

				// calculate page width, show first page
				var firstPage = $(this).find('.page').filter(':first');
				_obj.pageWidth = firstPage.innerWidth() + parseInt(firstPage.css('margin-right').replace('px', '')) - 1;
				_obj.showPage($(this).find('.page_controls'), 1);

				// FOR GALLERY
				if($(this).attr('id') == 'gallery') {
					gallery.init();
				}

				// activate pagination controls
				$('.page_controls').each(function() {
					var pageList = $(this).children('a');
					var pageCount = pageList.length-2;
					var parent = this;
					pageList.unbind();
					pageList.click(function() {
						var hash = $(this).attr('href'),
							pageTo,
							currentPage = $(parent).data('currentPage');
						if(hash == '#prev') {
							pageTo = (currentPage > 1) ? currentPage-1 : pageCount;
						} else if(hash == '#next') {
							pageTo = (currentPage < pageCount) ? currentPage+1 : 1;
						} else {
							pageTo = $(this).attr('rel');
						}

						_obj.showPage(parent,pageTo);
						return false;
					});
				});
			});
		}
	},

	// SLIDE TO PAGE
	showPage : function (selector, pageNumber) {
		if($(selector).attr('class')) {
			$(selector).data('currentPage',parseInt(pageNumber));
			this.selPage(selector,pageNumber);
			var parent = $(selector).parent();
			var pages = parent.find('.page');

			// MOVE SLIDER
			var pos = this.pageWidth*pageNumber - this.pageWidth;
			var container  = $(parent).children('.inner');
			pos = pos*-1;
			$(container).animate({left: pos},500,function() {
				// AFTER SLIDING -- TRIGGER inView EVENTS
				$(pages[pageNumber-1]).trigger('inView');
			});
		}
	},

	// SELECT THE PAGE INDICATOR
	selPage : function (parent,num) {
		$(parent).children('a').each(function() {
			if($(this).attr('rel') == num) {
				$(this).addClass('active');
			} else {
				$(this).removeClass('active');
			}
		});
	}
}



// OBJECT FOR BROWSING AN IMAGE GALLERY
// BROWSE PHOTO GALLERY AND VIDEOS ON THE PHOTOS/VIDEOS PAGE



var gallery = {
	loader : '#ajax-loader',
	overlay : '#image_overlay',
	imageList : new Array(),
	loaded : new Array(),

	init : function() {
		//activate lightbox
		$('#gallery a.thumb').lightBox();

		var _obj = this;

		// fire showBoxes() if page comes into view
		$('#gallery .page').live('inView',function() { _obj.showBoxes(this); });

		_obj.showBoxes($("#web-page-1"));

		// ACTIVATE PAGE DETAIL
		$(".gallery a.thumb").click(function(event){
			_obj.showImageDetail(this);
			return false;
		});
		$("#image_overlay").click(function() {
			_obj.hideImageDetail();
		});

	},

	// animate display of thumbnails
	showBoxes : function (page) {
		var boxes = $(page).children('a.thumb'),
			delay = 0,
			increment = 25;
		$(boxes).each(function() {
			var img = $(this).children("img:first");
			if(!$(img).attr('src')) {
				$(img).attr('src', $(this).attr('data-source')).load(function() {
					var _this = this;
					window.setTimeout(function() {
						$(_this).parent().css('visibility','visible').css('opacity','0.0').fadeTo(600,1);
						}, delay);
					delay +=  increment;
				});
			}
		});
	},

	showGallery : function (gallery) {
		$(gallery).addClass('selected');
		var id = $(gallery).attr('href');
		$(id).fadeIn();
		this.imageList = $(id+' .thumb');
	},

	// SHOW LIGHTBOX IMAGE
	showImageDetail : function (el) {
/*		_obj = this;
		var imgSrc = $(el).attr('href');
		if(imgSrc) {
			imgSrc = imgSrc.substr((imgSrc.indexOf('#')+1));

			// image detail
			var img = $(this.overlay + ' img.primary');
			if (!$(this.overlay).is(':visible')) {
				img.parent().hide();
				$(this.overlay).fadeIn('slow');
			}

			$(this.loader).fadeIn('fast');

			// calculate next/prev
			var i = 0,
				list = this.imageList;
			for (var i=0; i < list.length; i++) {
				if(el == list[i]) {
					var prev = (i > 0) ? list[i-1] : list[list.length-1];
					var next = (i < list.length-1) ? list[i+1] : list[0];
					break;
				}
			}

			img.unbind();
			img.attr('src', imgSrc).load(function() {
				$(_obj.loader).fadeOut('fast');
				$(this).parent().fadeIn();
				$(this).parent().css('width', $(this).width());

				// activate next/prev
				var siblings = $(this).siblings('a');
					siblings.css('height',this.clientHeight);
					siblings.unbind();
					siblings.click(function(event){
						img.parent().fadeOut();
						if ($(this).attr('rel') == 'next') {
							window.setTimeout(function(){_obj.showImageDetail(next)},400);
						} else {
							window.setTimeout(function(){_obj.showImageDetail(prev)},400);
						}
						event.stopPropagation();
						return false;
					});

			}).click(function(event) {
				event.stopPropagation();
			});

		} else {
			this.hideImageDetail();
		}*/
	},

	hideImageDetail : function () {
		$(this.loader).fadeOut();
		$(this.overlay).fadeOut('slow');
	}
}


/* FORM VALIDATION */
var validate = {
	required : [],
	form : {},

	load : function() {
		var obj = this;
		if(document.forms.length >= 1) {
			this.required = $('.gfield_contains_required input');
			if(this.required.length >= 1) {
				$('form').submit(function(e) {
					obj.form = this;
					validate.doValidate(e);
				});
			}
		}
	},

	doValidate : function(e) {
		var obj = this,
			error = false;

		this.required.each(function() {
			this.error = null;
			if(this.value.length == 0) {
				this.error = 'blank';
			} else if (this.type == 'email' || this.parentNode.parentNode.className.match(/email/)) {
				this.error = obj.validEmail(this);
			}
			if(this.error) {
				error = true;
			}
		});

		if(error === true) {
			this.formatError();
			return false;
		} else {
			this.form.submit();
			this.confirm();
		}
	},

	validEmail : function(el) {
		if(el.value.match(/^\w+(['\.\-\+]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/) == null) {
		  	return 'invalid';
		} else {
			return null;
		}
	},

	formatError : function() {
		var errorCount = 0,
			msg = '';

		this.required.each(function() {
			var el = this,
				label = '';
			if(this.error) {
				$(this).parent().siblings('label').each(function() {
					label = this.firstChild.nodeValue;
					if(label.toLowerCase() === 'name') {
						msg += '   * Please enter your name' + "\n";
					} else if(label.toLowerCase() === 'email') {
						msg += '   * Please enter a valid email address' + "\n";
					}
				});
				errorCount++;
			}
		});
		alert('Please fix the following ' + errorCount + ' ' + txt.pluralize(errorCount,'error') + ':' + "\n\n" + msg);
	},
	
	confirm : function() {
		this.form.style.display = 'none';
		$('#confirmation').html('<h1>Message Received</h1><h2>We will get back to you as soon as possible.</h2>');
	}
};


var txt = {
	pluralize : function(count,txt) {
		if(count == 1)
			return txt;
		else
			return txt + 's';
	}
}












