
// INIT ========================================================================

$(document).ready(function () {
	// on all pages
	InitClientLogin();
	InitSiteOptions();
	MarginParas();
	whatOurClientsSay();

	// bind window resize
	var resizeTimer = null;
	$(window).bind('resize', function () {
		if (resizeTimer) clearTimeout(resizeTimer);
		resizeTimer = setTimeout(HandleResize, 100);
	});

});



// GLOBAL ======================================================================
$.fn.image = function (src, f) {
	return this.each(function () {
		var i = new Image();
		i.src = src;
		i.onload = f;
		this.appendChild(i);
	});
}

function whatOurClientsSay() {
	/*	$('#explain-terabyte > li > ul').each(function () {
	var randomNumber, i = 0;
	while (i == 0) {
	randomNumber = (Math.floor(Math.random() * 3)) + 1;
	$(this).find('li:nth-child(' + randomNumber + ')').show();
	}
	});
	*/
}

//Moves any two-line rendered services to the end of the list (so its move balanced)
function BalanceServicesRenderedList() {
	if ($('.services-list')[0]) {
		$('.services-list li').each(function () {
			if ($(this).height() > 25) {
				$(this).appendTo($(this).parents('ul:first'));
				$(this).removeClass('no-right-margin');
			}
		});
		$('.services-list li:nth-child(even)').each(function () {
			if (!$(this).hasClass('no-right-margin')) {
				$(this).addClass('no-right-margin');
			}
		});
	}
}

// set client login box
function InitClientLogin() {
	$("#login-link").show();
	$("#client-login").hide();
	$("#client-login .close").show();
	$("#login-link").toggle(
		function () {
			$("#client-login").slideDown("fast");
			$(this).html("<span class='slash'>/</span> Close Client Login");
		},
		function () {
			$("#client-login").slideUp("fast");
			$(this).html("<span class='slash'>/</span> Client Login");
		}
	);
	$("#client-login .close").click(
		function () {
			$("#login-link").trigger('click');
		}
	);
}

function InitSiteOptions() {
	// setup box & launch link
	$("#options-link").show();
	$("#site-options").hide();
	$("#site-options .close").show();
	$("#options-link").toggle(
		function () {
			$("#site-options").slideDown("fast");
			$(this).html("<span class='slash'>/</span> Close Site Options");
		},
		function () {
			$("#site-options").slideUp("fast");
			$(this).html("<span class='slash'>/</span> Site Options");
		}
	);
	$("#site-options .close").click(
		function () {
			$("#options-link").trigger('click');
		}
	);
	// append alt stylesheet
	//$("head").append("<link rel='stylesheet' title='Light' type='text/css' href='/Css/light.css' media='screen' />");
	// set links to change stylesheet
	$(".options-list a").each(
		function () {
			$(this).click(
				function () {
					SwitchStyle(this.getAttribute("rel"));
					return false;
				}
			);
		}
	);
	// disable alt stylesheets
	$('link[@title*=Light]').each(
		function () {
			this.disabled = true;
		}
	);
	// check cookie
	var c = readCookie('style');
	//if (c) SwitchStyle(c);
}

function SwitchStyle(styleName) {
	$('link[@media*=screen]').each(function (i) {
		this.disabled = true;
		if (this.getAttribute('title') == styleName) this.disabled = false;
	});
	createCookie('style', styleName, 365);
}

function CheckScreenSize() {
	var dimensions = { width: 0, height: 0 };
	if (document.documentElement) {
		dimensions.width = document.documentElement.offsetWidth;
		dimensions.height = document.documentElement.offsetHeight;
	} else if (window.innerWidth && window.innerHeight) {
		dimensions.width = window.innerWidth;
		dimensions.height = window.innerHeight;
	}
	return dimensions;
}

function MarginParas() {
	//alert( $("h4").prev().val() );
	$("h4").prev("p").each(
		function () {
			$(this).addClass("extra-bottom-margin");
		}
	);
	$("h3").prev("p").each(
		function () {
			$(this).addClass("extra-bottom-margin");
		}
	);
	$("h1").next(".news-date").each(
		function () {
			$(this).addClass("article-news-date");
		}
	);
}

// HOME ========================================================================

function HomepageLayout() {
	var theWidth = CheckScreenSize().width;
	if (theWidth < 1460 && theWidth > 1100) {
		/* 1024 */
		$("#news-col").removeClass("med-col");
		$("#news-col").addClass("lrg-col");
	} else {
		/* 1600 or 800 */
		$("#news-col").removeClass("lrg-col");
		$("#news-col").addClass("med-col");
	}
}

function HandleResize() {
	// if homepage?
	HomepageLayout();
}

function HomePageEqualise() {
	//The RHS container may be equliased with the LHS, but its children are'nt
	//Therefore, find the amount of extra padding we need to give the last children of the RHS box.
	var mainWrapperHeight = $("#home-main-wrapper").outerHeight();
	var whatwedo = $(".what-we-do").outerHeight()
	var newsbox = $(".news-box").outerHeight();
	var contactTweetsMax = Math.max($(".news-box").outerHeight(), $(".tweets-box").outerHeight());
	//Calc extraPaddingToAdd, integer at end (e.g 40), is the sum of the bottom margins in RHS children pods
	var extraPaddingToAdd = (mainWrapperHeight - (whatwedo + newsbox + contactTweetsMax)) - 20;
	if (extraPaddingToAdd >= 0) {
		$(".contact-box, .tweets-box").height($(".contact-box").height() + extraPaddingToAdd);
	} else {
		$("#home-main-wrapper").height($("#home-main-wrapper").outerHeight() + (extraPaddingToAdd * -1));
	}
}

// setup flash image rotator
function InitFlash(Context) {

	// if we're on the project detail page, grab the first image/caption & reinsert it above the flash holder. 
	// Is hidden via Css, & revealed in Print stylesheet. This is so when printing a project page user still gets some 
	// visual content (which would be hidden along with the flash otherwise).
	if (Context == "port") {
		$(".home-site-promo").before("<div class='hide-for-print'>" + $("#project-rotator li:first").html() + "</div>");
	}

	var so = new SWFObject("/Flash/navImgRotator.swf", "imgRotator", "640", "360", "8", "#000000");
	so.addVariable("theData", BuildProjectXML());
	so.addVariable("Context", Context);
	so.addParam("wmode", "transparent");
	so.write("flash-container");

	if ($("#flash-container #project-rotator").length == 0) {
		$("#flash-container").addClass("contains-flash");
	}

	window.imgRotator = document.getElementById('imgRotator');
	$(window.imgRotator).width("64em");
	$(window.imgRotator).height("36em");
	$(".project-abstract").css({ display: "none" });
	InitVideo();


	var tempHolder = '<div id="temp-holder" style="display:none;"></div>';
	$('body').append(tempHolder);
}

// build XML to pass to flash from DOM
function BuildProjectXML() {
	var theXML = "<projects>";
	$("#project-rotator li").each(
		function () {
			var theTitle = $(this).find(".project-quote .source").text(); //$(this).children("h4").text();
			var theImg = $(this).children("a").children("img").attr("src");
			var theAbstract = $(this).find(".project-quote .quote").text(); //$(this).children("p").text();
			var theUrl = $(this).children("a").attr("href");
			//theXML += "<project title='"+theTitle+"' img='"+theImg+"' abstract='"+theAbstract+"' url='"+theUrl+"' />";
			theXML += "<project><title><![CDATA[" + theTitle + "]]></title><img>" + escape(theImg) + "</img><abstract><![CDATA[" + theAbstract + "]]></abstract><url>" + escape(theUrl) + "</url></project>";
		}
	);
	theXML += "</projects>";
	return theXML;
}

// called from flash, displays abstract for rotated project on page
function ShowAbstract(theAbstract) {
	var holder = $('#temp-holder');
	holder.html(theAbstract);
	//console.log('[' + theAbstract + '] : [' + holder.html() + ']');
	var format = '<div class="project-quote"><blockquote><p>[QUOTE]<span class="source">&ndash; [SOURCE]</span></p></blockquote></div>';
	var source = holder.find('h4').text();
	var quote = holder.find('p');
	quote.find('a').remove();
	quote = quote.text();
	quote = quote.replace(source, '');

	//console.log('['+source + '] [' + quote+'] [' + format + ']');

	if (quote.length > 10) {
		format = format.replace('[QUOTE]', quote);
		format = format.replace('[SOURCE]', source);
		$(".project-abstract").html(format);
		$(".project-abstract").fadeIn("slow");
		//console.log(format);
	} else {
		/*
		var link = $(theAbstract).find('a');
		var html = '<p><a href="' + link.attr('href') + '">' + link.text() + '</a></p>';
		$(".project-abstract").fadeIn("slow");
		$(".project-abstract").html(html);
		*/
		$(".project-abstract").hide();
	}
}

function InitVideo() {
	$(".video-holder").show();
	$(".video-link").click(function () {
		flashMovie = document.getElementById("imgRotator");
		var theTitle = $(this).parents("li").children("h5").children("a").text();
		var theAbstract = $(this).parents("li").children("p").text();
		flashMovie.LaunchVideo($(this).attr("href"), theTitle, theAbstract);
		return false;
	});
}

// CONTACT =====================================================================

function InitContactPage() {
	currentRoute = "";
	ShowHideDirections("#southern-directions", "#from-southern", "", "", "slide");
	ShowHideDirections("#northern-directions", "#from-northern", "", "", "slide");
	ShowHideDirections("#newmarket-directions", "#from-newmarket", "", "", "slide");
	ShowHideDirections("#strand-directions", "#from-strand", "", "", "slide");
	setRouteLinks();

	//Use js to insert map link for xhtml validation
	$("#gMap p").html("<a href=\"http://maps.google.co.nz/maps?f=q&hl=en&geocode=&q=terabyte&sll=-41.244772,172.617188&sspn=27.267014,55.195313&ie=UTF8&ll=-36.852565,174.777954&spn=0.0142,0.026951&z=16&iwloc=A\" rel=\"external\">Click here to find us on Google Maps</a>");
}

// sets the show / hide on directions
function ShowHideDirections(theTarget, theLauncher, openText, closedText, showType) {

	$(theTarget).hide();

	$(theLauncher).toggle(
		function () {
			$(".directions-link").each(function () {
				if (this.isOpen) {
					$(this).trigger("click");
					//alert("go");
				}
			});
			$(theTarget).slideDown(200);
			$(".route-text").hide();
			$(this).parent().next(".route-text").show();
			this.isOpen = true;
			return false;
		},
		function () {
			$(theTarget).slideUp(200);
			$(this).parent().next(".route-text").hide();
			this.isOpen = false;
			return false;
		}
	);

}

// loader for Google Map on contact page
function loadGMap() {

	$("#gMap").height("40em");
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("gMap"));
		//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		map.addControl(new GLargeMapControl());
		var geocoder = new GClientGeocoder();

		var address = "16 York Street, Parnell, Auckland, New Zealand";

		geocoder.getLatLng(
			address,
			function (point) {
				if (!point) {
					alert(address + " not found");
				} else {
					map.setCenter(point, 17);

					baseIcon = new GIcon();
					baseIcon.iconSize = new GSize(37, 43);
					baseIcon.iconAnchor = new GPoint(18, 43);
					baseIcon.infoWindowAnchor = new GPoint(9, 2);
					baseIcon.infoShadowAnchor = new GPoint(18, 25);
					baseIcon.image = "/Images/Global/map_icon.png";

					var marker = new GMarker(point, baseIcon);
					map.addOverlay(marker);

					//marker.openInfoWindowHtml(address);
				}
			}
		);

	}

}

function showRouteOnMap(route, launcher) {

	if (currentRoute != "") { map.removeOverlay(currentRoute); }

	switch (route) {

		case 1: /* from northern & southern motorways */
			var polyline = new GPolyline([
			new GLatLng(-36.85273712538665, 174.77346897125244),
			new GLatLng(-36.85088274365454, 174.77527141571045),
			new GLatLng(-36.851226151072794, 174.77630138397217),
			new GLatLng(-36.85048782321647, 174.77709531784058),
			new GLatLng(-36.84986968278299, 174.77827548980713),
			new GLatLng(-36.85089991406209, 174.77887630462646)
		], "#b31111", 5);
			break;
		case 2: /* from newmarket */
			var polyline = new GPolyline([
			new GLatLng(-36.86456633509247, 174.7791337966919),
			new GLatLng(-36.86218003818444, 174.78177309036255),
			new GLatLng(-36.86046323172769, 174.78276014328003),
			new GLatLng(-36.85891807293982, 174.78293180465698),
			new GLatLng(-36.85764758564406, 174.78185892105103),
			new GLatLng(-36.85199881212365, 174.778254032135),
			new GLatLng(-36.851226151072794, 174.77630138397217),
			new GLatLng(-36.85048782321647, 174.77709531784058),
			new GLatLng(-36.84986968278299, 174.77827548980713),
			new GLatLng(-36.85089991406209, 174.77887630462646)
		], "#b31111", 5);
			break;
		case 3: /* from strand */
			var polyline = new GPolyline([
			new GLatLng(-36.8494060741779, 174.78248119354248),
			new GLatLng(-36.84997270653566, 174.78185892105103),
			new GLatLng(-36.848890950208286, 174.77954149246216),
			new GLatLng(-36.84950909855533, 174.77750301361084),
			new GLatLng(-36.850298947503184, 174.77647304534912),
			new GLatLng(-36.851123129009295, 174.77591514587402),
			new GLatLng(-36.851226151072794, 174.77630138397217),
			new GLatLng(-36.85048782321647, 174.77709531784058),
			new GLatLng(-36.84986968278299, 174.77827548980713),
			new GLatLng(-36.85089991406209, 174.77887630462646)
		], "#b31111", 5);
			break;

	}

	map.addOverlay(polyline);
	map.setZoom(16);
	currentRoute = polyline;

}

function setRouteLinks() {
	$("#from-southern").click(function () { showRouteOnMap(1) });
	$("#from-northern").click(function () { showRouteOnMap(1) });
	$("#from-newmarket").click(function () { showRouteOnMap(2) });
	$("#from-strand").click(function () { showRouteOnMap(3) });
}

// PORTFOLIO ===================================================================

function InitPortfolio(actionType) {
	/*$("#portfolio-list").removeClass("image-listing");
	$("#portfolio-list").addClass("thumbnail-list");*/
	Equalise($(".thumbnail-list li span.title"));
	InitFilters(actionType);
	InitViews();
	InitOurClients();
	SetBiggerClick();

}

function InitClientColapse() {

	$('.client-portfolio-list > h2').each(function () {
		var text = $(this).text();
		$(this).html('<a href="#">' + text + '</a>');
		$(this).addClass('closed');
	});

	$('.client-portfolio-list > h2 > a').toggle(
		function () {
			var wrapper = $(this).parents('.client-portfolio-list');
			wrapper.find('ul').slideDown('fast');
			wrapper.children('h2').removeClass('closed').addClass('open');
		}, function () {
			var wrapper = $(this).parents('.client-portfolio-list');
			wrapper.find('ul').slideUp('fast');
			wrapper.children('h2').removeClass('open').addClass('closed');
		}
	);
}

function InitFilters(actionType) {
	State = "thumbs-view";
	//var action = "stack"; // or "stack"
	var action = actionType;

	//Setup Event handlers for changing the filter type (fade or stack) (Only accesible to Terabyte Admins)
	$("#filter-with-stack").click(function () {
		$(".filter-list li a").unbind('click'); //Remove Fade event handler
		InitFilters("stack");
		return false;
	});
	$("#filter-with-fade").click(function () {
		$(".filter-list li a").unbind('click'); //Remove Stack event handler
		InitFilters("fade");
		return false;
	});



	$('#region-select').change(function () {
		var $this = $(this);
		var filterBy = $(".filter-list li a.selected");
		var filterClasses = '';

		filterClasses += ($this.val().length > 0 ? '.' + $this.val() : '');
		if (filterBy.attr('rel') !== 'All') {
			filterClasses += '.' + filterBy.attr('rel');
		}

		if (filterClasses === '') {
			$('#portfolio-list li').addClass('visable');
		} else {
			if (action == "fade") {
				$("#portfolio-list li:not(" + filterClasses + ")").fadeTo("fast", 0.20);
			} else {
				$("#portfolio-list li" + filterClasses).addClass('visable');
				$("#portfolio-list li:not(" + filterClasses + ')').hide().removeClass('visable');
			}
		}
		if (State == "thumbs-view") {
			$("#portfolio-list li.visable").each(function () {
				$(this).removeClass("no-right-margin");
			});
			SetListClass("#portfolio-list li.visable", "no-right-margin", "5");
			$("#portfolio-list li.visable").fadeIn(800);
		}
	});

	if (!window.location.search) { // only do fade filtering if they're on the straight port page, not if they've ocome in on query string filtering

		$(".filter-list li a").click(
			function () {
				$(".filter-list li a").removeClass("selected");
				$(this).addClass("selected");
				var filterBy = $(this).attr("rel");
				var filterTitle = $(this).text();
				filterTitle = filterTitle.replace('/', '<span>/</span>');
				$("#portfolio-list li").each(
					function () {
						var classes = '.' + filterBy;
						if (filterBy == "All") classes = '';
						if ($('#region-select').val().length > 0) {
							classes += '.' + $('#region-select').val();
						}
						if ($(this).is(classes) || (filterBy == "All" && $('#region-select').val().length === 0)) {
							if (State == "thumbs-view") {
								if (action == "fade") {
									$(this).fadeTo("fast", 1);
								} else {
									$(this).hide();
									$(this).addClass("visable");
								}
							} else {
								$(this).show();
							}
						} else {
							if (State == "thumbs-view") {
								if (action == "fade") {
									$(this).fadeTo("fast", 0.20);
								} else {
									$(this).hide();
									$(this).removeClass("visable");
								}
							} else {
								$(this).hide();
							}
						}
					}
				);
				if (State == "thumbs-view") {
					// **** setup stack view *****//
					$("#portfolio-list li.visable").each(function () {
						$(this).removeClass("no-right-margin");
					});
					SetListClass("#portfolio-list li.visable", "no-right-margin", "5");
					$("#portfolio-list li.visable").fadeIn(800);
				}
				if (filterBy == "All") {
					$("#portfolio-list-head").html("<span>/</span> All Projects");
				} else {
					$("#portfolio-list-head").html(filterTitle);
				}
				return false;
			}
		);

	}
}



function InitViews() {
	$(".switch-view").show();
	$("#portfolio-list li p").hide();
	/*
	$("#portfolio-list li").addClass("clickable");
	$(".view-list li a").click(
	function(){
	$(".view-list li a").each(function(){
	$(this).removeClass("selected");
	});
	$(this).addClass("selected");
	var theView = $(this).attr("rel");
	switch(theView){
	case("thumbs-view"):
	$("#view-all").trigger("click");
	$("#portfolio-list").addClass("thumbnail-list");
	$("#portfolio-list").removeClass("image-listing");
	$("#portfolio-list li p").hide();
	$("#portfolio-list li").show();
	State = "thumbs-view";
	break;
	case("img-list-view"):
	$("#view-all").trigger("click");
	$("#portfolio-list").removeClass("thumbnail-list");
	$("#portfolio-list").addClass("image-listing");
	$("#portfolio-list li p").show();
	State = "list-view";
	break;
	default:
	// oops
	break;
	}
	return false;
	}
	);
	*/
}
// Our Clients =================================================================

function InitClients() {

	$(".client_container").hide();
	$(".show-client").addClass("cursor");
	$(".show-client").each(function () { var text = $(this).text(); $(this).html('<a class="client-expand closed" href="#"></a>'); });


	if (location.hash != '') {
		var clientUrl = location.hash;
		var clientDiv = $('#portfolio-holder').find(clientUrl);

		$(clientDiv).parent().find(".client_container").slideDown("fast");
		$(clientDiv).parent().find(".client_container").removeClass('closed').addClass('open');
	}



	//for click action on + button
	$(".show-client a").click(
		function () {

			if ($(this).hasClass('closed')) {
				$(this).parent().next().next().next().next(".client_container").slideDown("fast");

				//$(this).addClass("selected-service");
				$(this).removeClass('closed').addClass('open');

				//$('.abstracttext').hide();
				this.isSelected = true;
				return false;
			}

			if ($(this).hasClass('open')) {
				$(this).parent().next().next().next().next(".client_container").slideUp("fast");
				//$(this).removeClass("selected-service");
				$(this).removeClass('open').addClass('closed');
				$('.abstracttext').show();
				this.isSelected = false;
				return false;
			}
		});
		//for click action on client heading to manipulate the + icon
		$(".client-heading").click(
		function () {

			if ($(this).parent().parent().find(".client-expand").hasClass('closed')) {


				$(this).parent().next().next(".client_container").slideDown("fast");

				//$(this).addClass("selected-service");
				$(this).parent().parent().find(".client-expand").removeClass('closed').addClass('open');

				//$('.abstracttext').hide();
				this.isSelected = true;
				return false;
			}

			if ($(this).parent().parent().find(".client-expand").hasClass('open')) {

				$(this).parent().next().next(".client_container").slideUp("fast");
				//$(this).removeClass("selected-service");
				$(this).parent().parent().find(".client-expand").removeClass('open').addClass('closed');
				$('.abstracttext').show();
				this.isSelected = false;
				return false;
			}


		});
		$(".client-logo").click(
		function () {

			if ($(this).parent().find(".client-expand").hasClass('closed')) {


				$(this).parent().find(".client_container").slideDown("fast");

				//$(this).addClass("selected-service");
				$(this).parent().find(".client-expand").removeClass('closed').addClass('open');

				//$('.abstracttext').hide();
				this.isSelected = true;
				return false;
			}

			if ($(this).parent().find(".client-expand").hasClass('open')) {

				$(this).parent().find(".client_container").slideUp("fast");
				//$(this).removeClass("selected-service");
				$(this).parent().find(".client-expand").removeClass('open').addClass('closed');
				$('.abstracttext').show();
				this.isSelected = false;
				return false;
			}


		});


	// auto open & scroll to service if directly linked to
	if (location.hash) {
		$(location.hash + ' a').trigger("click");
		var pos = $(location.hash).offset();
		$("html").animate({ scrollTop: pos.top + "px" }, { duration: 500 });
	}



}
// JOBS ========================================================================
function InitJobs() {
	// set inputs type 'file'
	if (jQuery.browser.mozilla) {
		$(".file-input").attr("size", 45);
	}
	if ($(".contact-form").is('.hide')) {
		$(".contact-form").hide();
	}
	else if ($(".contact-form").is('.show')) {
		$(".apply-for-job").text("Close this form");
	}
	$(".apply-for-job").css({ "display": "inline-block" }).addClass("closed");
	$(".job-contact-form").css({ "margin": "0em 0 3em 0" });
	$(".apply-for-job").toggle(
		function () {
			//$(this).parent().next(".contact-form").slideDown("fast");
			$(this).next(".contact-form").slideDown("fast");
			$(this).text("Close this form");
			$(this).removeClass("closed").addClass("open");
			return false;
		},
		function () {
			//$(this).parent().next(".contact-form").slideUp("fast");
			$(this).next(".contact-form").slideUp("fast");
			$(this).text("Apply for this job");
			$(this).removeClass("open").addClass("closed");
			return false;
		}
	);
}

// SERVICES ====================================================================
function InitServices() {
	$(".service-container").hide();
	$(".show-service").addClass("cursor");
	$(".show-service").each(function () { var text = $(this).text(); $(this).html('<a href="#" class="closed">' + text + '</a>'); });
	$(".click-below").show();
	/*$(".show-service").hover(
	function(){
	if(!this.isSelected){
	$(this).addClass("selected-service");
	}
	},
	function(){
	if(!this.isSelected){
	$(this).removeClass("selected-service");
	}
	}
	);*/
	$(".show-service a").toggle(
		function () {
			$(this).parent().next(".service-container").slideDown("fast");
			//$(this).addClass("selected-service");
			$(this).removeClass('closed').addClass('open');
			this.isSelected = true;
			return false;
		},
		function () {
			$(this).parent().next(".service-container").slideUp("fast");
			//$(this).removeClass("selected-service");
			$(this).removeClass('open').addClass('closed');
			this.isSelected = false
			return false;
		}
	);
	// auto open & scroll to service if directly linked to
	if (location.hash) {
		$(location.hash + ' a').trigger("click");
		var pos = $(location.hash).offset();
		$("html").animate({ scrollTop: pos.top + "px" }, { duration: 500 });
	}

}

// UTILS =======================================================================

// COOKIES =====================================================================
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name, "", -1);
}


function getTwits() {
	$.getJSON('http://search.twitter.com/search.json?q=TerabyteNZ&callback=?', function (data) {
		if (data != null) {
			$.each(data, function (i, tweets) {
				if (tweets.length != undefined) {
					if (tweets[0] != undefined) {
						if (tweets[0].created_at != undefined) {
							for (var i = 0; i < tweets.length && i < 3; i++) {
								/*var extraInfo = '<br /> <span class="date-time">' + timeAgo(tweets[i].created_at) + 
								'</span>';
								$("<p>" + tweets[i].text + extraInfo + "</p>").tweetify().appendTo(".twitter-pod");*/
								var extraInfo = '<br /> <span class="date-time">' + timeAgo(tweets[i].created_at) +
								', From: ' + tweets[i].from_user + '</span>';
								$("<p>" + tweets[i].text + extraInfo + "</p>").tweetify().appendTo(".twitter-pod");
							}
						}
					}
				}
			});
			$("<a href=\"http://twitter.com/TerabyteNZ\" class=\"find-or-follow follow-tweets floatLeft clear\">Follow us</a>").appendTo(".twitter-pod");
			Equalise($(".short"));
		} else {

		}
	});
}

$.fn.tweetify = function () {
	this.each(function () {
		$(this).html(
			$(this).html()
				.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1">$1</a>')
				.replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
				.replace(/(^|\s)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
		);
	});
	return $(this);
}

function timeAgo(dateString) {
	var rightNow = new Date();
	var then = new Date(dateString);
	if ($.browser.msie) {
		// IE can't parse these crazy Ruby dates
		then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
	}
	var diff = rightNow - then;
	var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7;
	if (isNaN(diff) || diff < 0) {
		return ""; // return blank string if unknown
	}

	if (diff < second * 7) {
		// within 7 seconds
		return "right now";
	}

	if (diff < minute) {
		return Math.floor(diff / second) + " seconds ago";
	}

	if (diff < minute * 2) {
		return "about 1 minute ago";
	}

	if (diff < hour) {
		return Math.floor(diff / minute) + " minutes ago";
	}

	if (diff < hour * 2) {
		return "about 1 hour ago";
	}

	if (diff < day) {
		return Math.floor(diff / hour) + " hours ago";
	}

	if (diff > day && diff < day * 2) {
		return "yesterday";
	}

	if (diff < day * 365) {
		return Math.floor(diff / day) + " days ago";
	}

	else {
		return "over a year ago";
	}
}

function Initsignup() {

	if ($('.news-letter-pod .signup-succsess').length == 0) {

		var newsHeight = $('.latest-news-cont').height();
		var formHeight = $('.signup-newsletter ul').height();

		$('.show-newsletter').click(function (event) {
			event.preventDefault();
			var height = $('.contact-us').height();
			$('.contact-us').css("height", height + "px");
			$('div.pod-inner#get-in-touch').hide();
			$('fieldset.signup-newsletter').show();
			$('.contact-box, .contact-us').find('h3').text("Subscribe");
			return false;
		});
		$('.signup-newsletter .find-or-follow').click(function () {
			$('fieldset.signup-newsletter').hide();
			$('div.pod-inner#get-in-touch').show();
			$('.contact-box, .contact-us').find('h3').text("Contact Us");
			return false;
		});
	}

}

function newsletterSuccess() {
	if ($('.signup-succsess').length > 0) {
		var height = $('.contact-us').height();
		$('.contact-us').css("height", height + "px");
		$('div.pod-inner#get-in-touch').hide();
		$('fieldset.signup-newsletter').show();
		$('.contact-box, .contact-us').find('h3').text("Subscribe");
		setTimeout(function () {
			$('.contact-box h3, .contact-us h3, #get-in-touch, .news-letter-pod').animate({
				"opacity": 0
			}, 500, function () {
				$('.contact-box, .contact-us').find('h3').text("Contact Us");
				$('#get-in-touch').css("display", "block")
				$('#get-in-touch, .contact-box h3, .contact-us h3').animate({
					"opacity": 1
				}, 500, function () {
					if (jQuery.browser.msie) {
						this.style.removeAttribute('filter');
					}
				});
			});
		}, 4000);
	}
}

var Twitter = {

	WrapUrls: function (text) {
		var urlPattern = /(http:\/\/[A-Za-z0-9\.\-\/]+)/g;
		var urlsAdded = text.replace(urlPattern, '<a rel="external" href="$1">$1</a>');
		var usernames = /(@[A-Za-z0-9_]{1,15})/g;
		var usernamesAdded = urlsAdded.replace(usernames, '<a rel="external" href="http://www.twitter.com/$1">$1</a>');
		return usernamesAdded;
	},

	InitTwitterFeed: function (numberOfTweets, accountName) {

		//Tweet/Retweets Feed: http://search.twitter.com/search.json?q=from%3Aterabytenz
		//Mentions Feed (i.e. #UltimateHikes): http://search.twitter.com/search.json?q=%23terabytenz&callback=?
		//consider favourites feed: http://twitter.com/favorites/Username.json?callback=TWTR.Widget.receiveCallback_1&clientsource=TWITTERINC_WIDGET
		// User timeline: http://api.twitter.com/1/statuses/user_timeline.json?screen_name=terabytenz
		$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + accountName + '&count=' + numberOfTweets + '&include_rts=true&callback=?',
				function (data) {
					var tweets = '';
					$.each(data, function (i, tweet) {
						//In some cases if you ask twitter for 2 tweets it only gives you back 1, hence we request more than we need and filter out the rest
						if (i < numberOfTweets) {
							var extraInfo = '<br /> <span class="date-time">' + timeAgo(tweet.created_at) +
										', From: ' + Twitter.WrapUrls("@" + tweet.user.screen_name) + '</span>';
							tweets += "<p>" + Twitter.WrapUrls(tweet.text) + extraInfo + "</p>";
						}
					});
					//Remove non-breaking space and then insert tweets
					$('.twitter-pod').empty().append(tweets + "<a href=\"http://twitter.com/" + accountName + "\" class=\"find-or-follow follow-tweets \">Follow us</a>");
					$('.twitter-pod p a').click(function (event) {
						window.open(this.href);
						event.preventDefault();
					});

					Equalise($(".short"));
					HomePageEqualise();
				}
			);
	}
}

var Blog = (function () {
	function Init() {
		AddReadMore();
	}
	function AddReadMore() {
		$('<a href="' + $('.headline a').attr("href") + '" title="Read More" class="read-more" target="_blank">Read More</a>').appendTo('.blog li div');
	}
	return {
		Init: Init
	}
})();

var javarotator = {
	timeOutID: "", //Gets Set my setInterval
	init: function () {
		$('.java-rotator li:not(.loaded)').each(function () {
			var path = $(this).find('span').text();
			var link = $(this).find('a');
			var item = $(this);
			$(this).image(path, function () {
				if (link.length > 0) {
					item.html('<a href="' + link.attr('href') + '" title="' + link.attr('title') + '"><img src="' + path + '" alt="' + link.attr('title') + '" /></a>');
				} else {
					item.html('<img src="' + path + '" alt="' + link.attr('title') + '" />');
				}
				item.addClass('loaded');
				javarotator.checkstatus(item);
			});
		});
		javarotator.timeOutID = setInterval("javarotator.movenext($(\".java-rotator\"))", 8000);
	},
	checkstatus: function (item) {
		item = item.parent();

		if (item.find('li').length == item.find('.loaded').length) {
			item.find('.loaded').addClass('item').removeClass('loaded');

			item.append('<li class="control prev"><a title="previous item" href="#" class="prev"></a></li><li class="control next"><a title="next item" href="#" class="next"></a></li>');

			item.find('a.next').click(function () {
				clearTimeout(javarotator.timeOutID); //clear the automatic timer
				javarotator.movenext(item);
				return false;
			});

			item.find('a.prev').click(function () {
				clearTimeout(javarotator.timeOutID); //clear the automatic timer
				javarotator.moveprev(item);
				return false;
			});

			//Bind event for next and previous arrows to move through images
			$('html').keydown(function (event) {
				if (event.which === 37) {
					clearTimeout(javarotator.timeOutID); //clear the automatic timer
					javarotator.moveprev(item);
				}
				else if (event.which === 39) {
					clearTimeout(javarotator.timeOutID); //clear the automatic timer
					javarotator.movenext(item);
				}
			});

			$('.java-rotator .item a').each(function () {
				var title = $(this).attr('title');
				//$(this).append('<span class="overlay">View the ' + title + ' project</span>');
				//var titleOverlay = $(this).find('.overlay');
				//titleOverlay.css({ 'opacity': '0', 'display': 'block' });
			});
			$('.java-rotator .item a').hover(
				function () {
					var titleOverlay = $(this).find('.overlay');
					var titleHeight = titleOverlay.height();
					var padding = (360 - titleHeight) / 2;
					titleOverlay.css({ 'padding-top': padding + 'px', 'padding-bottom': padding + 'px', 'height': titleHeight + 'px' });
					$(this).find('.overlay').show().fadeTo('fast', .75);
				}, function () {
					$(this).find('.overlay').fadeTo('fast', 0);
				}
			);
		}
	},
	movenext: function (item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i < (noOfImgs - 1)) {
				next = item.find('.item').eq(i + 1);
				//console.log(item.find('.item').eq(i).hasClass('.current') + ' index[' + i + ']');
				break;
			} else {
				next = item.find('.item').eq(0);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	},
	moveprev: function (item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i > 0) {
				next = item.find('.item').eq(i - 1);
				break;
			} else {
				next = item.find('.item').eq(noOfImgs - 1);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	}
}

var clientrotator = {
	init: function () {
		var highest = 0;
		for (var i = 0; i < $('.client-rotator li').length; i++) {
			highest = Math.max(highest, $('.client-rotator li').eq(i).height());
		}
		$('.client-rotator').height(highest);
		$('.client-rotator').append('<li class="controls"><a class="prev" title="Show previous quote" href="#"><span>Show Previous Quote</span></a><a class="next" title="Show next quote" href="#"><span>Show Next Quote</span></a></li>');

		$('.client-rotator a.prev').click(function () {
			clientrotator.moveprev($(this).parent().parent());
			return false;
		});
		$('.client-rotator a.next').click(function () {
			clientrotator.movenext($(this).parent().parent());
			return false;
		});
	},
	movenext: function (item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i < (noOfImgs - 1)) {
				next = item.find('.item').eq(i + 1);
				//console.log(item.find('.item').eq(i).hasClass('.current') + ' index[' + i + ']');
				break;
			} else {
				next = item.find('.item').eq(0);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	},
	moveprev: function (item) {
		var pauseTime = 0;
		var noOfImgs = item.find('.item').length;
		var current = item.find('.current');
		var next;
		for (var i = 0; i < noOfImgs; i++) {
			if (item.find('.item').eq(i).is('.current') && i > 0) {
				next = item.find('.item').eq(i - 1);
				break;
			} else {
				next = item.find('.item').eq(noOfImgs - 1);
			}
		}

		next.addClass('current').hide().fadeIn(500);
		current.removeClass('current').show().fadeOut(350);
	}
}

var terabyte = {
	javarotator: javarotator,
	clientrotator: clientrotator
}

$(document).ready(function () {
	Initsignup();
	newsletterSuccess();
	if ($('signup-newsletter:visible').length > 0) {
		$('.hide-newsletter').trigger("click"); //Fixes Chrome initially showing the Subscribe 
	}
});

(function () {
	var head = document.getElementsByTagName("head")[0];
	if (head) {
		var scriptStyles = document.createElement("link");
		scriptStyles.rel = "stylesheet";
		scriptStyles.type = "text/css";
		scriptStyles.href = "/css/javascript.css";
		scriptStyles.media = "screen,print";
		head.appendChild(scriptStyles);
	}
})()
