// ========= Allow multiple onload events
function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 
			func(); 
		};
	} 
}

// ========= External site links open in new window
function externalLinks() {
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
			anchor.getAttribute("rel") == "external") {
				anchor.target = "_blank";
		}
	}
}

// ========= Copyright Date
function copyright() {
	var d = new Date();
	var yr = d.getFullYear();
	document.write(yr);
}

// ========= Load Analytics
function loadGAScript(){
    /*Check browser for Dom compatibility*/
	if (!document.getElementsByTagName) { return false; }
	/*Determines whether the page is using a secure or unsecure protocol*/
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	/*Writes in the script to the document head*/
	var gaScript = document.createElement("script");
	gaScript.setAttribute("src",gaJsHost +"google-analytics.com/ga.js");
	gaScript.setAttribute("type","text/javascript");
	var domHead = document.getElementsByTagName("head")[0];
	domHead.appendChild(gaScript);
}
    loadGAScript();
/*Calls the analytics function*/
function analytics(){   
	var pageTracker = _gat._getTracker("UA-12027045-1"); // ***CUSTOM KEY HERE***
	pageTracker._initData();
	pageTracker._trackPageview();
}

// ==== Scroller
function scroller() {
	var slides, title, originalLink, link, source, current;
	slides = new Array();
	function grab_slide(current){
		$("#scroller #slide img").fadeOut("500");
		if ( slides[current][2] != '' ) {
			$("#scroller #slide").attr("href", slides[current][2]);
		} else {
			$("#scroller #slide").attr("href", originalLink );
		}
		$("#scroller #slide").attr("title", slides[current][0]).html('<img src="'+slides[current][1]+'" alt="'+slides[current][0]+'" />');
		$("#scroller #slide img").load(function () {
			$(this).parent().css("background-image", "none").css("text-indent", "0");
			$(this).fadeIn("500");
		});
	}
	$.ajax({
	        type: "GET",
		url: "/content/scroller/control.xml",
		dataType: "xml",
		success: function(xml) {
			$(xml).find("slide").each(function(){
				current = $(this).attr('id');
				title = $(this).find('title').text();
				source = "/content/scroller/" + $(this).find("image").text();
				link = $(this).find('link').text();
				slides[current] = new Array(title, source, link);
			});
			grab_slide(1);
			current = 1;
			originalLink = $("#scroller #slide").attr("href");
			$("#scroller #slide img").fadeTo("slow", 0.65);
			
			$("#scroller").append('<a href="#" class="nav_lft"><img src="/images/scroll_nav_lft.png" alt="" /></a><a href="#" class="nav_rt"><img src="/images/scroll_nav_rt.png" alt="" /></a>');
			$("#scroller .nav_lft").click(function (event) {
				event.preventDefault();
				current--;
				if (current < 1){
					current = slides.length - 1;
				}
				grab_slide(current);
			});
			$("#scroller .nav_rt").click(function (event) {
				event.preventDefault();
				current++;
				if (current > slides.length - 1){
					current = 1;
				}
				grab_slide(current);
			});
		}
	});
};	
	
// ============= Portfolio Player
function portfolio(section) {
	var topId, folder, nav, images, title, large, thumbnail, current, currentClass, prevGroup, nextGroup, getImage, groupEnd;
	topId = "#"+section;
	folder = "/content/"+section+"/";
	nav = "nav_"+section;
	images = new Array();
	// == load up image
	function open_image(current){
		$(topId + " .image img").fadeOut("150", function () {
			$(topId + " .image img").attr("src", images[current][1]).attr("alt", images[current][0]);
		});
		$(topId + " .image img").load(function () {
			$(this).fadeIn("150");
		});
	}
	
	// == Load xml data and set in array
	$.ajax({
	        type: "GET",
		url: folder+"control.xml",
		dataType: "xml",
		success: function(xml) {
			$(topId + " .controls li:not(.nav_lft, .nav_rt)").remove();
			$(xml).find("image").each(function(){
				current = $(this).attr('id');
				currentClass = "image"+current;
				title = $(this).find('title').text();
				large = folder + $(this).find("large").text();
				thumbnail = folder + "thumb/" + $(this).find("thumbnail").text();
				images[current] = new Array(title, large, thumbnail, currentClass);
				$(topId + " .controls").append('<li class="thumbnail"><a href="#" class="'+currentClass+'"><img src="'+ thumbnail +'" alt="'+ title +'" /></a></li>');
			});
			$(topId + " .thumbnail:lt(8)").css("opacity","0").css("display", "block").fadeTo("150", "0.65").addClass("showing");
			$(topId + " .thumbnail:gt(7)").addClass("remaining"); 
			open_image(1);
			current = 1;
			$(topId + " .controls li:first").addClass("current");
			$(topId + " .current").fadeTo("150", "1");
			
			// == Create thumb controls
			if (images.length > 8 ) {
				$(topId + " .controls").addClass(nav).append('<li class="nav_lft"><a href="#"><img src="/images/thumb_nav_lft.png" alt="" /></a></li><li class="nav_rt"><a href="#"><img src="/images/thumb_nav_rt.png" alt="" /></a></li>');
				$(topId + " .nav_rt").css("display", "block");
			}
			
			// == click on thumbnail controls
			// go back
			$(topId + " .controls .nav_lft a").click(function (event) {
				event.preventDefault();
				$(topId + " .thumbnail").css("display", "none");
				$(topId + " .showing:first").prevAll(".thumbnail:lt(8)").addClass("showing").css("opacity","0.65").css("display", "block").filter(".current").css("opacity","1");
				$(topId + " .showing:first").nextAll(".showing:gt(6)").removeClass("showing").addClass("remaining");
				if ($(topId + " .showing:first").prev(".thumbnail").length == 0) {
					$(topId + " .controls .nav_lft").css("display", "none");
				}
				$(topId + " .nav_rt").css("display", "block");
			});
			
			// go forward
			$(topId + " .controls .nav_rt a").click(function (event) {
				event.preventDefault();
				nextGroup = $(topId + " .remaining:lt(8)");
				$(topId + " .thumbnail").css("display", "none").removeClass("showing");
				nextGroup.removeClass("remaining").addClass("showing").css("opacity","0.65").css("display", "block").filter(".current").css("opacity","1");
				if ($(topId + " .remaining").length == 0) {
					$(topId + " .controls .nav_rt").css("display", "none");
				}
				$(topId + " .nav_lft").css("display", "block");
			});
			
			// == click on thumbnail
			$(topId + " .controls li.thumbnail a").click(function (event) {
				event.preventDefault();
				$(this).parent().siblings(".current").fadeTo("150", "0.65", function () { $(this).removeClass("current") });
				$(this).parent().addClass("current").css("opacity", "1");
				getImage = $(this).attr("class");
				getImage = getImage.slice(5);
				open_image(getImage);
			});
			
			
			$(".thumbnail:not(.current)").hover(
				function () {
					$(this).stop().fadeTo("150", 1);
				}, 
				function () {
					if ($(this).is(".current")) {
						null;
					} else {
						$(this).stop().fadeTo("150", 0.65);
					}
				}
			);
		}
	});
};

// ========= Jquery Onload Events
$(document).ready(function(){

	// ==== Create exixting function
	jQuery.fn.exists = function(){return jQuery(this).length>0;}

	// ==== Load content box
	if ($("#scroller").exists()) { scroller() }
	if ($("#design").exists()) { portfolio("design") }
	if ($("#illustration").exists()) { portfolio("illustration") }
	
	// ==== Load content box
	if ($("#upcoming").exists()) { $("#upcoming .text").load("/content/upcoming.txt") }
	
	// ==== Fade Images
	$("#scroller, #place").hover(
		function () {
			$("img:first", this).stop().fadeTo("150", 1);
		}, 
		function () {
			$("img:first", this).stop().fadeTo("150", 0.65);
		}
	);
	
	// ==== Load Image
	if ($("#place").exists()) {
		$(function () {
			var img = new Image();
        			$(img).load(function () {
           				 //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
            				$(this).hide();
           				 $("#place .block").removeClass('loading').html(this);
           				 $(this).show().fadeTo("150", 0.65);
       				 }).error(function () {
           			 // notify the user that the image could not be loaded
       			 }).attr('src', '/content/image.jpg');
		
	/*	
			// ==== Create pre-loader
			var img = new Image();
			$(img).attr("src", "/content/image.jpg").hide();
			$("#place .block").html(img);
			$(img).load(function () {
				$("#place .block").css("background","none");
				$("#place .block img").show().fadeTo("150", 0.65);
			})
*/		});
	}
	
	// ==== Create mailto
	$(function () {
		var name, domain, mail;
		name = "hilljacquard@";
		domain = "gmail.com";
		mail = "mailto:"+name+domain;
		$(".contact").attr("href", mail);
	});	
});

// ========= Execute all the other onload Events
addLoadEvent(externalLinks); 
addLoadEvent(analytics);