/* --------------------------------------------

	CDAA Pty Ltd
	Scripts and Such

-------------------------------------------- */

$(document).ready(function() {


	/* --------------------------------------------
	
	FUNKY SLIDY ARROW THAT DOES STUFF™
	
	-------------------------------------------- */
	
	//figures out if the user is on the homepage, top level page, or sub page
	
	// Check for "work" over-ride
	if ( $("nav").hasClass("work") ) {
		var itemoffset  = $("#dnn_topnav li.nav-Work").position();
		var itemoffsetw = $("#dnn_topnav li.nav-Work").width();
		$(".line").show();
	
	// Top level
	}else if ( $("#dnn_topnav > ul > li.mmSelected").length > 0 ){
		var itemoffset  = $("#dnn_topnav li.mmSelected").position();
		var itemoffsetw = $("#dnn_topnav li.mmSelected").width();
		$(".line").show();
	// Subpage
	}else if ( $("#dnn_topnav > ul > li > ul > li.mmSelected").length > 0 ){
		var itemoffset  = $("#dnn_topnav .mmSelected").parent('ul').parent('li').position();
		var itemoffsetw = $("#dnn_topnav .mmSelected").parent('ul').parent('li').width();	
		$(".mmSelected").parent('ul').parent('li').children('a').addClass('activeParent');
		$(".line").show();
	// Subsubpage
	}else if ( $("#dnn_topnav > ul > li > ul > li > ul > li.mmSelected").length > 0 ){
		var itemoffset  = $("#dnn_topnav .mmSelected").parent('ul').parent('li').parent('ul').parent('li').position();
		var itemoffsetw = $("#dnn_topnav .mmSelected").parent('ul').parent('li').parent('ul').parent('li').width();	
		$("#dnn_topnav li.mmSelected").parent('ul').parent('li').parent('ul').parent('li').children('a').addClass('activeParent');
		$(".line").show();
	// Home
	}else{
		var itemoffset  = $("#dnn_topnav .child-1").position();
		var itemoffsetw = $("#dnn_topnav .child-1").width();	
		$('#dnn_topnav li.mmSelected a').addClass('activeParent');
		
		$(".line").show()
	}
	
	// This offsets the "line" to where it thinks it should be, from above.
	$(".line").css({left:itemoffset.left+10, width:itemoffsetw-20});			
	
	$('#top nav > div > ul > li').hover(function(){
		if ($("ul", this).length > 0){
		//matthew need to make work better....
			$(this).children("ul").show();
			$(".sub_back_ground").show();
		}
		},function(){	
		if ($("ul", this).length > 0){
		//matthew need to make work better....
			$(this).children("ul").hide();	
			$(".sub_back_ground").hide();
		}		
				

	});
	
	$('#top nav > div > ul > li').hover(function(){
		var thisoffset = $(this).position();	
		var thiswidth = $(this).width();
		$(".line").stop().animate({left:thisoffset.left+10, width:thiswidth-20},{queue: false, duration:200});			
	},function(){
		$(".line").animate({left:itemoffset.left+10, width:itemoffsetw-20},{queue: false, duration:200});			
	});
	
	// Removing Titles
	$('#top nav a').removeAttr("title");
	
	// Removing border on last li
	$('#dnn_topnav > ul li:last-child').css({'border-right':'none'});
	
	
	/* --------------------------------------------
	
	MEGA MENUS AND WHATNOT
	
	-------------------------------------------- */
	
	// Capabilities
	$('#dnn_topnav .nav-Capabilities li:nth-child(8n)').css({'border-right':'none'});
	$('#dnn_topnav .nav-Capabilities li:nth-child(1) a').append('<div class="menu_icons brand_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(2) a').append('<div class="menu_icons digital_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(3) a').append('<div class="menu_icons mobile_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(4) a').append('<div class="menu_icons app_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(5) a').append('<div class="menu_icons shop_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(6) a').append('<div class="menu_icons host_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(7) a').append('<div class="menu_icons om_icon"></div>');
	$('#dnn_topnav .nav-Capabilities li:nth-child(8) a').append('<div class="menu_icons optimum_icon"></div>');
	


	// Company
	$('#dnn_topnav .nav-Company li:nth-child(7n)').css({'border-right':'none'});
	$('#dnn_topnav .nav-Company li:nth-child(1) a').append('<div class="menu_icons company_icon"></div>');
	$('#dnn_topnav .nav-Company li:nth-child(2) a').append('<div class="menu_icons people_icon"></div>');
	$('#dnn_topnav .nav-Company li:nth-child(3) a').append('<div class="menu_icons value_icon"></div>');
	$('#dnn_topnav .nav-Company li:nth-child(4) a').append('<div class="menu_icons sustain_icon"></div>');
	$('#dnn_topnav .nav-Company li:nth-child(5) a').append('<div class="menu_icons achieve_icon"></div>');
	$('#dnn_topnav .nav-Company li:nth-child(6) a').append('<div class="menu_icons partners_icon"></div>');
	$('#dnn_topnav .nav-Company li:nth-child(7) a').append('<div class="menu_icons project_icon"></div>');
	
	
	// Career
	$('#dnn_topnav .nav-Career li:nth-child(6n)').css({'border-right':'none'});
	$('#dnn_topnav .nav-Career li:nth-child(1) a').append('<div class="menu_icons career_icon"></div>');
	$('#dnn_topnav .nav-Career li:nth-child(2) a').append('<div class="menu_icons join_icon"></div>');
	$('#dnn_topnav .nav-Career li:nth-child(3) a').append('<span></span>');
	$('#dnn_topnav .nav-Career li:nth-child(4) a').append('<span></span>');
	$('#dnn_topnav .nav-Career li:nth-child(5) a').append('<span></span>');
	$('#dnn_topnav .nav-Career li:nth-child(6) a').append('<span></span>');
	
	
	/* --------------------------------------------
	
	Tab Menus
	
	-------------------------------------------- */
	
	//#sidenav2 li, 
	$('#menu li, #TabMenu').append('<div class="bg"></div>');
	$('#menu li a:not(#SideNavCurrentItem), #sidenav2 a').hover(function(){
		$(this).next('.bg').animate({width:200},{queue: false, duration:200});
	}, function(){
		$(this).next('.bg').animate({width:0},{queue: false, duration:200});
	});
	
	$('.follow').hoverIntent(followOver, followOut);
	function followOver(){
		$(this).animate({left:-12},{queue: false, duration:200});
	};
	function followOut(){
		$(this).animate({left:-77},{queue: false, duration:200});
	};
	
	//slide show scripts for scrolling left and right through modules
	$('span[id*="lblRequired"]').parent('td').parent('tr').hide();
	$('textarea.NormalTextBox').parent('div').parent('td').attr('colspan','4').prev('td').remove();
	
	/*$("#menu #SideNavCurrentItem").parent("ul").parent("li").addClass("show_sub");
	$("#menu .show_sub").children("a").click(function(){return false}).css({"cursor":"default"});
	$("#menu #SideNavCurrentItem").parent("ul#SideNav").children("li").css({"display":"block"}); //if top level item
	$("#menu .show_sub > a").css({'color':'#47C8F5','padding-bottom':'0','margin-bottom':'0'}).wrap("<h1></h1>")*/
	
	
	if ( $("#dnn_tabNav ul").length > 0 ){
	
		if ( $("#dnn_tabNav .mmSelected").parent("ul").parent("li").parent("ul").parent("li").length > 0 ){
			$("#dnn_tabNav .mmSelected").parent("ul").parent("li").parent("ul").parent("li").addClass("show_sub");
			$("#dnn_tabNav .mmSelected").parent("ul").parent("li").addClass("active_item");
			var taboffset  = $("#dnn_tabNav .show_sub > ul > li.active_item").position();
			var taboffsetw = $("#dnn_tabNav .show_sub > ul > li.active_item").width();	
		}else{
			$("#dnn_tabNav .mmSelected").parent("ul").parent("li").addClass("show_sub");
			$("#dnn_tabNav .mmSelected").parent("ul#TabNav").children("li").css({"display":"block"}); //if top level item
			var taboffset  = $("#dnn_tabNav .show_sub > ul > li.mmSelected").position();
			var taboffsetw = $("#dnn_tabNav .show_sub > ul > li.mmSelected").width();	
		}
		
		$("li.show_sub > a:first-child").hide();
				
		// Selected Bubble
		if (taboffset) {
			$("#TabMenu .bg").css({left:taboffset.left, width:taboffsetw},{queue: false, duration:200});
		} else {
			// Suck it
		}
		$('#TabMenu .show_sub > ul > li').hover(function(){
			var thisoffset = $(this).position();	
			var thiswidth = $(this).width();
			$("#TabMenu .bg").stop().animate({left:thisoffset.left, width:thiswidth},{queue: false, duration:200});			
		},function(){	
			$("#TabMenu .bg").animate({left:taboffset.left, width:taboffsetw},{queue: false, duration:200});			
		});
		$('.ie #TabMenu .bg').append('<div class="left"></div><div class="right"></div>');
		
	}
	
	$('.openClose .moduleTitle a').click(function(){
		$(this).parent('.moduleTitle').next('.moduleBody').slideToggle();
		$(this).parent('.moduleTitle').parent('.openClose').toggleClass('open'); 
		return false;
	});
	
	/* --------------------------------------------
	
	Fading Testimoanials
	
	-------------------------------------------- */
	$('.testimonials').cycle({ 
		fx:			'fade', 
		speed:  	250,
		timeout:  	6000,
		pause:   	1 
	});
	
	/* --------------------------------------------
	
	equal height columns on inside pages
	
	-------------------------------------------- */
	
	// Regular columns
	var colLeftH = $('.columnLeft').height();
	var colRightH = $('.columnRight').height();
	if (colLeftH > colRightH){
		$('.columnRight').height(colLeftH);
	}else{
		$('.columnLeft').height(colRightH);
	};
	
	// Tab Columns
	var colLeftH = $('.TabColumnLeft').height();
	var colRightH = $('.columnRightTab').height();
	if (colLeftH > colRightH){
		$('.columnRightTab').height(colLeftH);
	}else{
		$('.TabColumnLeft').height(colRightH);
	};
	
	// blog pages
	var colLeftH = $('.blog .columnLeft').height();
	var colRightH = $('.columnRight').height();
	if (colLeftH > colRightH){
		$('.columnRight').height(colLeftH);
	}else{
		$('.blog .columnLeft').height(colRightH);
	};
	
	// contact
	var colLeftH = $('.contactColumnLeft').height();
	var colRightH = $('.contactColumnRight').height();
	if (colLeftH > colRightH){
		$('.contactColumnRight').height(colLeftH);
	}else{
		$('.contactColumnLeft').height(colRightH);
	};

	/* --------------------------------------------
	
	Re-Tweet Button
	
	-------------------------------------------- */
	/*
	 * Easy Retweet Button
	 * http://ejohn.org/blog/retweet/
	 *   by John Resig (ejohn.org)
	 *
	 * Licensed under the MIT License:
	 * http://www.opensource.org/licenses/mit-license.php
	 */
	
	window.RetweetJS = {
		// Your Bit.ly Username
		bitly_user: "retweetjs",
	
		// Your Bit.ly API Key
		// Found here: http://bit.ly/account
		bitly_key: "R_6287c92ecaf9efc6f39e4f33bdbf80b1",
	
		// The text to replace the links with
		link_text: "Tweet",
	
		// What # to show (Use "clicks" for # of clicks or "none" for nothing)
		count_type: "clicks",
	
		// Tweet Prefix text
		// "RT @jeresig " would result in: "RT @jeresig Link Title http://bit.ly/asdf"
		prefix: "",
	
		// Style information
	styling: "a.retweet { font: 12px Helvetica,Arial; color: #000; text-decoration: none; border: 0px; }" +
			"a.retweet span {   color: #FFFFFF;    font-size: 12px;    position: relative;    top: -8px; }" +
				"a.vert { display: block; text-align: center; font-size: 16px; float: left; margin: 4px; }" +
			"a.retweet strong.vert {  float: left;    left: 5px;    position: relative;    top: -45px;    width: 52px; color:#3a3a3d;}" +
			"a.retweet span.vert {   left: 5px;    position: absolute;    top: 49px;}"
	};
	
	//////////////// No Need to Configure Below Here ////////////////
	
	var loadCount = 1;
	
	// Asynchronously load the Bit.ly JavaScript API
	// If it hasn't been loaded already
	if ( typeof BitlyClient === "undefined" ) {
		var head = document.getElementsByTagName("head")[0] ||
			document.documentElement;
		var script = document.createElement("script");
		script.src = "http://bit.ly/javascript-api.js?version=latest&login=" +
			RetweetJS.bitly_user + "&apiKey=" + RetweetJS.bitly_key;
		script.charSet = "utf-8";
		head.appendChild( script );
	
		var check = setInterval(function(){
			if ( typeof BitlyCB !== "undefined" ) {
				clearInterval( check );
				head.removeChild( script );
				loaded();
			}
		}, 10);
	
		loadCount = 0;
	}
	
	if ( document.addEventListener ) {
		document.addEventListener("DOMContentLoaded", loaded, false);
	
	} else if ( window.attachEvent ) {
		window.attachEvent("onload", loaded);
	}
	
	function loaded(){
		// Need to wait for doc ready and js ready
		if ( ++loadCount < 2 ) {
			return;
		}
	
		var elems = [], urlElem = {}, hashURL = {};
	
		BitlyCB.shortenResponse = function(data) {
			for ( var url in data.results ) {
				var hash = data.results[url].userHash;
				hashURL[hash] = url;
	
				var elems = urlElem[ url ];
	
				for ( var i = 0; i < elems.length; i++ ) {
					elems[i].href += hash;
				}
	
				if ( RetweetJS.count_type === "clicks" ) {
					BitlyClient.stats(hash, 'BitlyCB.statsResponse');
				}
			}
		};
	
		BitlyCB.statsResponse = function(data) {
			var clicks = data.results.clicks, hash = data.results.userHash;
			var url = hashURL[ hash ], elems = urlElem[ url ];
	
			if ( clicks > 0 ) {
				for ( var i = 0; i < elems.length; i++ ) {
					var strong = document.createElement("strong");
					strong.appendChild( document.createTextNode( clicks + " " ) );
					elems[i].insertBefore(strong, elems[i].firstChild);
	
					if ( /(^|\s)vert(\s|$)/.test( elems[i].className ) ) {
						elems[i].firstChild.className = elems[i].lastChild.className = "vert";
					}
				}
			}
	
			hashURL[ hash ] = urlElem[ url ] = null;
		};
	
		if ( document.getElementsByClassName ) {
			elems = document.getElementsByClassName("retweet");
		} else {
			var tmp = document.getElementsByTagName("a");
			for ( var i = 0; i < tmp.length; i++ ) {
				if ( /(^|\s)retweet(\s|$)/.test( tmp[i].className ) ) {
					elems.push( tmp[i] );
				}
			}
		}
	
		if ( elems.length && RetweetJS.styling ) {
			var style = document.createElement("style");
			style.type = "text/css";
	
			try {
				style.appendChild( document.createTextNode( RetweetJS.styling ) );
			} catch (e) {
				if ( style.styleSheet ) {
					style.styleSheet.cssText = RetweetJS.styling;
				}
			}
	
			document.body.appendChild( style );
		}
	
		for ( var i = 0; i < elems.length; i++ ) {
			var elem = elems[i];
	
			if ( /(^|\s)self(\s|$)/.test( elem.className ) ) {
				elem.href = window.location;
				elem.title = document.title;
			}
	
			var origText = elem.title || elem.textContent || elem.innerText,
				href = elem.href;
	
			elem.innerHTML = "<span>" + RetweetJS.link_text + "</span>";
			elem.title = "";
			elem.href = "http://twitter.com/home?status=" +
				encodeURIComponent(RetweetJS.prefix + origText + " http://bit.ly/");
	
			if ( urlElem[ href ] ) {
				urlElem[ href ].push( elem );
			} else {
				urlElem[ href ] = [ elem ];
				BitlyClient.shorten(href, 'BitlyCB.shortenResponse');
			}
		}
	
	}

	/* ---------------------------------------------------
	
	RSS Feeds
	
	--------------------------------------------------- */	
	// Check if CDAA Life module area exists
	if ( $("#dnn_CDAALife").length != 0  ){
		
		// THis module is no longer empty, my friend
		$("#dnn_CDAALife").removeClass("DNNEmptyPane");
		
		// Insert a module div that we prepared earlier
		$("#dnn_CDAALife").html("<div class='module'><div class='ModDNNNewsFeedsC'></div></div>");
		
		// Get the URL for the Feed
		var newsPageUrl ="/Life.aspx";
		
		// AJAX Load the URL and grab the relevant info in to our target module area
		$('#dnn_CDAALife .ModDNNNewsFeedsC').load(newsPageUrl+' .BlogTitle', function(response, status, xhr) {
			
			// If successfully loaded
			if (status == "success"){		
				if ( $('.BlogTitle').length != 0 ) {
					
					$('.BlogTitle:gt(3)', this).hide();
					$('.BlogTitle:lt(3)', this).show();
					
				}else{
					$("#dnn_CDAALife .ModDNNNewsFeedsC").append("<em>Check back regularly for updates</em>");
				}
			}
		})
		
	}
	
	/* ---------------------------------------------------
	
	Twitter Scripts
	
	--------------------------------------------------- */
	
	// Call tweetable on #twitter
	$("#twitter .module").tweetable({username: 'cdaalife', time: false, limit: 8, replies:false});
	
	
	/* --------------------------------------------
	
	DNN6 Logout Button Yo
	
	-------------------------------------------- */
	$("#dnnOtherTools").after("<li id='dnnLogout' class='root'><a href='Logoff.aspx'>Logout</a></li>");
	
	
	/* --------------------------------------------
	
	Colorboxing
	
	-------------------------------------------- */
	$(".cboxPopup").colorbox({width:"312px", height:"470px", iframe:true});

		
	/* ---------------------------------------------------
	
	WORK SECTION SCRIPTS
	
	--------------------------------------------------- */
	
	// LazyLoad
	/* Can't lazyload elements that are fading in 
	$(".workItem img").live("load", function() {

		$(this).lazyload({
			placeholder : "/Portals/0/skins/cdaa/images/work_loading.gif", 
			failurelimit : 5000,
			effect: "fadeIn"
		});
		
	});
	*/
	
	// We have hidden the work container so we won't see it before the JS fires, so now that the JS is firing we'll show it again.
	$(".workPane").show();
	
	// Linkifying the whole article while retaining our technically-semantic code for non-js
	$(".workItem").each(function() {
		// Getting link inside
		newLink = $("a", this).attr("href");
		
		// Adding link around whole box
		$(this).wrapInner("<a href='"+newLink+"' class=''></a>");
		
		// Adding blue hover box
		//$(this).append("<div class='hoverElement'><span>View Project</span></div>");
		
		// Adding link around box to fix IE being IE.
		$(this).append("<a href='"+newLink+"'><div class='hoverElement'><span>View Project</span></div></a>");
		
	});

	// Reusable function to set up the boxes of things
	function setUpWork() {
		
		// Fading in each item for browsers other than IE
		// Don't slide in IE, fading causes the browser to jump back to top.
		if($.browser.msie) {
			$(".workItem").show();
		} else {
			
			var $sequence = $(".workItem").hide(), fade_item = 0; 

			// Calling this inside an anon function
			(function(){ 
			
				// Go through each item in the sequence
				$($sequence[fade_item++])
					// Lazy Loading
					.lazyload({
						placeholder : "/Portals/0/skins/cdaa/images/work_loading.gif", 
						failurelimit : 500
					})
					// Fade'r in
					.fadeIn(100, arguments.callee);
				
				// Fix missing first item ???
				$(".workItem:first").css("opacity",1);
				
			})();
		
		}
		
		// Setting up work section column classes
		$(".workItem").removeClass("col1").removeClass("col2").removeClass("col3");
		$(".workItem:nth-child(3n+1)").addClass("col1");
		$(".workItem:nth-child(3n+2)").addClass("col2");
		$(".workItem:nth-child(3n+3)").addClass("col3");
		
		// Remove HRs
		//$(".workPane hr").remove();
	
		// Adding the line div after each third box
		//$(".workItem.col1").before("<div class='hr'></div>");
	
		// WorkItem Hover States
		// Reset hoverElement for Javering, while still hiding them from no-js users
		$(".hoverElement").css("opacity",0).show();
		// Animate in/out
		$(".workItem").hover(function() {
			$(".hoverElement", this).stop().animate({opacity: 1}, 250);
			$("a", this).addClass("hovered");
		}, function() {
			$(".hoverElement", this).stop().animate({opacity: 0}, 250);
			$("a", this).removeClass("hovered");
		});
		
	}
	
	// Call set up work on load to start the goods by default.
	setUpWork();

		
	/* ---------------------------------------------------
	
	WORK FILTERING
	
	--------------------------------------------------- */

	// Wrap DNN_WorkPane with a non-id selector
	$(".workPane .DNNModuleContent > div").wrapInner("<div class='workPaneContent'/>");

	// get the first collection
	var $workpane = $(".workPaneContent");
	
	// clone applications to get a second collection
	var $results = $workpane.clone();
	
	// Button Press
	$("#workFilter a").click(function(e) {
		
		// Stop right there, criminal scum!
		e.preventDefault();
		
		// Getting the data-id to filter with
		var $filterType = $(this).attr("data-id");
		
		// GoTo WorkFilter
		workFilter($filterType);
		
	});
	
	// Check for # in URL and go to the appropriate area
	if (window.location.hash.substring(1) != "") {
		workFilter(window.location.hash.substring(1));
	};
	
	// Reusable Work Filter function
	function workFilter($filterType) {
		
		// Setting button states
		// Removing all active classes
		$("#workFilter a").removeClass("currentFilter");
		// cehcking data id against the buttons and adding the class to any matches
		$("#workFilter a[data-id="+$filterType+"]").addClass("currentFilter");
		
		// Chucking the clone in to another clone so you can clone while you clone.
		var $sourcePool = $results.clone();
		
		// Check if filterType is all, if so show EVERYTHING.
		if ($filterType === "all") {
			//console.log("allodem");
			var $filteredData = $sourcePool.find(".workItem");
			
		// If it isn't all, check for the filterType against the .workItem's data-id and show those instead.
		} else {
			//console.log($filterType);
			var $filteredData = $sourcePool.find('.workItem[data-id~=' + $filterType + ']');
		}
		
		// Log data for debugging
		//console.log($sourcePool.text());
		//console.log($filteredData.text());
		
		/* Quickstand is super buggy, using replace HTML instead
		// Call Quicksand on WorkPane using $filteredData, then throw a callback to setUpWork to redo stuff.
		$workpane.quicksand($filteredData, {
			duration: 800,
			easing: 'easeInOutQuad'
		}, function() {
			setUpWork();
		});
		*/
	
		// Replace $workpane HTML with $filteredData
		$workpane.html($filteredData);
		
		// Calling setupwork() to re-init hovers, fading and classifying
		setUpWork();
		
	};
	
	/* ---------------------------------------------------
	
	PROJECT SECTION
	
	--------------------------------------------------- */
	
	// Just a simple little animation of padding on hover for the next/prev bars.
	// Called on "live" since this script is run before the slider script, so we need to listen for this element being put in it's place.
	$(".project_container .tab .next").live("mouseover mouseout", function(event) {
		if(event.type == "mouseover") {
			$(this).stop().animate({"padding-left": 20, "padding-right": 20}, 500);
		} else {
			$(this).stop().animate({"padding-left": 10, "padding-right": 10}, 500);	
		}
	});
	$(".project_container .tab .prev").live("mouseover mouseout", function(event) {
		if(event.type == "mouseover") {
			$(this).stop().animate({"padding-left": 20, "padding-right": 20}, 500);
		} else {
			$(this).stop().animate({"padding-left": 10, "padding-right": 10}, 500);	
		}
	});
	
	
	/* ---------------------------------------------------
	
	SOME GENERAL CLEANING UP
	Checking each element exists before cleaning
	
	--------------------------------------------------- */
	if($('#feeds .DNN_News_ItemLink a').length >0) {
		$('#feeds .DNN_News_ItemLink a ').textOverflow('...', true);
	}
	
	if($('.DNN_News_ItemDate').length >0) {
		$('.DNN_News_ItemDate, .recent_date').each(function(){
			var olddate = $(this).text()
			var newdate = olddate.substr(8,4)+olddate.substr(4,3)+olddate.substr(11,5);
			$(this).html(newdate);
		});
	}
	
	
/* End of document.ready */
});
		
		


/* --------------------------------------------

TzCheckboxes - move to plugins.js

-------------------------------------------- */
(function($){
	$.fn.tzCheckbox = function(options){
		
		// Default On / Off labels:
		
		/*options = $.extend({
			labels : ['ON','OFF']
		},options);*/
		
		return this.each(function(){
			var originalCheckBox = $(this),
				labels = /*[]*/ $(this).next('label').text();

			// Checking for the data-on / data-off HTML5 data attributes:
			/*if(originalCheckBox.data('on')){
				labels[0] = originalCheckBox.data('on');
				labels[1] = originalCheckBox.data('off');
			}
			else labels = options.labels;*/

			// Creating the new checkbox markup:
			var checkBox = $('<span>',{
				className	: 'tzCheckBox '+(this.checked?'checked':''),
				html:	'<span class="tzCBContent">'+labels+
						'</span><span class="tzCBPart"></span>'
			});

			// Inserting the new checkbox, and hiding the original:
			checkBox.insertAfter(originalCheckBox.hide());

			checkBox.click(function(){
				checkBox.toggleClass('checked');
				
				var isChecked = checkBox.hasClass('checked');
				
				// Synchronizing the original checkbox:
				originalCheckBox.attr('checked',isChecked);
				//checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
			});
			
			// Listening for changes on the original and affecting the new one:
			originalCheckBox.bind('change',function(){
				checkBox.click();
			});
		});
	};
	
})(jQuery);


/* --------------------------------------------

Legacy Scripts, move to plugins.js?

-------------------------------------------- */

/* 
 * Cross-browser event handling, by Scott Andrew
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}

/* 
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

/* 
 * Safari doesn't support canceling events in the standard way, so we must
 * hard-code a return of false for it to work.
 */
function cancelEventSafari() {
    return false;        
}

/* 
 * Cross-browser style extraction, from the JavaScript & DHTML Cookbook
 * <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>
 */
function getElementStyle(elementID, CssStyleProperty) {
    var element = document.getElementById(elementID);
    if (element.currentStyle) {
        return element.currentStyle[toCamelCase(CssStyleProperty)];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(element, '');
        return compStyle.getPropertyValue(CssStyleProperty);
    } else {
        return '';
    }
}

/* 
 * CamelCases CSS property names. Useful in conjunction with 'getElementStyle()'
 * From <http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp>
 */
function toCamelCase(CssProperty) {
    var stringArray = CssProperty.toLowerCase().split('-');
    if (stringArray.length == 1) {
        return stringArray[0];
    }
    var ret = (CssProperty.indexOf("-") == 0)
              ? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1)
              : stringArray[0];
    for (var i = 1; i < stringArray.length; i++) {
        var s = stringArray[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1);
    }
    return ret;
}

/*
 * Disables all 'test' links, that point to the href '#', by Ross Shannon
 */
function disableTestLinks() {
  var pageLinks = document.getElementsByTagName('a');
  for (var i=0; i<pageLinks.length; i++) {
    if (pageLinks[i].href.match(/[^#]#$/)) {
      addEvent(pageLinks[i], 'click', knackerEvent, false);
    }
  }
}

/* 
 * Cookie functions
 */
function createCookie(name, value, days) {
    var expires = '';
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
    var cookieCrumbs = document.cookie.split(';');
    var nameToFind = name + '=';
    for (var i = 0; i < cookieCrumbs.length; i++) {
        var crumb = cookieCrumbs[i];
        while (crumb.charAt(0) == ' ') {
            crumb = crumb.substring(1, crumb.length); /* delete spaces */
        }
        if (crumb.indexOf(nameToFind) == 0) {
            return crumb.substring(nameToFind.length, crumb.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, '', -1);
}



/*clear*/

/*
 * Clear Default Text: functions for clearing and replacing default text in
 * <input> elements.
 *
 * by Ross Shannon, http://www.yourhtmlsource.com/
 */

addEvent(window, 'load', init, false);



function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && theInput.className.match(/\bcontact_item\b/)) {  
            /* Add event handlers */          
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
            
            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
}

function clearDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == target.defaultText) {
        target.value = '';
    }
}

function replaceDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == '' && target.defaultText) {
        target.value = target.defaultText;
    }
}

