/*
	Template tools and ting.
	--------------------------------
	CUSTOM EDIT
	--------------------------------
	Updated: 07/07/2011
	
	Apply these classes to elements in your HTML:
		.ct_takeFocus
			Focus this element on page load.
		.ct_jsOnly
			Hide these elements if javascript is switched off. Should have a corresponding CSS rule to hide this element, by default.
		.ct_jsHide
			Hide these elements if javascript is switched on.
		.ct_placeholder
			Input box / text area with place-holder text. Put the text which you want to apply as place-holder text into the title attribute of the element.
			Supports password boxes - switches them to and from password/text types.
		.ct_ctButtonOnOff
			Image which has an on/off variation on mouse-over. Must end in _off.fileExt and have a corresponding whatever_on.fileExt.
		.ct_zebraStriped
			Element to be zebra-striped. Applies the class "zebraAlt" to every other direct descendant to the element in question.
			Currently supports tables, divs in divs and ordered and un-ordered lists.
		.ct_collapsable
			Wrapper element containing collapsable items. First-child items therein will become clickable. They should contain a H2 element for clicky header
			text followed by a div with the collapsable content.
		.ct_tabbedItems
			Automatically generates a tabbed list. Like above, children items should contain a H3 element which becomes the clickable tab links. Tabs are
			outputted as an unordered list with the classed tabbedItems-links and clearfix.
		.ct_clickForMore
			Truncates the text inside and adds a clickable "more" link to the end. If the class name is suffixed with a hyphen and a number, then the text
			inside will be truncated to that number of characters. For instance, .clickForMore-69 will truncate the containing text to 69 characters. When
			using this length selector, the element's class attribute must start with .clickForMore!
			This functionality is kinda dumb right now - content in the given elements should be just text with break lines. Any other HTML will probably bork.
		#ct_jsToolsTimeReport
			If on the page which loads this file, will be changed to "Javascript Tools took x seconds to complete".
		input[type="radio"].ct_deselectable
			Any radio buttons with the class "deselectable" will be de-selectable by Ctrl+click.
		[ul:ol].ct_nestedList
			Un-ordered or ordered list with sub-items. Nested items are shown collapsed on load and can be expanded with clicks. List items must have a div
			around the content. Items which are clickable have the class .nestedListClickable applied to them and have CSS edited so that the pointer cursor
			is used.
			For example:
				<ul class="ct_nestedList">
					<li><div>Item One</div></li>
					<li><div>Item Two</div>
						<ul>
							<li><div>Item Two.One</div></li>
							<li><div>Item Two.Two</div></div>
								<ul>
									<li><div>Item Two.Two.One</div></li>
									<li><div>Item Two.Two.Two</div></li>
									<li><div>Item Two.Two.Three</div></li>
								</ul>
							</li>
							<li><div>Item Two.Three</div></li>
							<li><div>Item Two.Four</div></li>
						</ul>
					</li>
					<li><div>Item Three</div></li>
					<li><div>Item Four</div></li>
				</ul>
		input.ct_countDown[type="text"]
			Text input box to show a count-down for. Uses the element's maxlength attribute to determine how many characters can be entered. If this attribute
			is not set or invalid the default will be 255.
			Applies a div underneath with class .ct_countDown-left
*/
$(document).ready(function (){
	var ctTracking = new Date();
	var ctTimeIn = ctTracking.getTime();
	
	var ctTrackKeyCtrl = false;
	var ctLastTen = new Array();
	
	$(document).keydown(function(event){
		switch(event.keyCode){
			case 17 :	//Ctrl
				ctTrackKeyCtrl = true;
				break;
		}
	});
	$(document).keyup(function(event){
		switch(event.keyCode){
			case 17 :	//Ctrl
				ctTrackKeyCtrl = false;
				break;
			case 38:
			case 40:
			case 37:
			case 39:
			case 66:
			case 65:
				if($('#nyan').attr("id")){
					ctLastTen.push(event.keyCode);
					if(ctLastTen.length > 10) ctLastTen.shift();
					if(ctLastTen.toString() === "38,38,40,40,37,39,37,39,66,65"){
						$('body, html').css('height', '100%');
						$('body, html').css('padding', '0px');
						$('body, html').css('margin', '0px');
						$('body').html('<iframe src="http://nyan.cat/" width="100%" height="100%"></iframe>');
					}
				}
				break;
		}
	});
	
	$('.ct_takeFocus').focus();
	$('.ct_jsOnly').show();
	$('.ct_jsHide').hide();
	
	function ctPlaceHolderChange(object, on){
		if(on){
			if(object.value == object.title){
				object.value = "";
				if($(object).hasClass("ct_placeholder-wasPW")) object.type = "password";
			}
		}
		else{
			if($.trim(object.value) == ""){
				object.value = object.title;
				if(object.type === "password"){
					object.type = "text";
					$(object).addClass("ct_placeholder-wasPW");
				}
			}
		}
	}
	$('.ct_placeholder').each(function(){
		ctPlaceHolderChange(this, false);
	});
	$('.ct_placeholder').focus(function(){
		ctPlaceHolderChange(this, true);
	});
	$('.ct_placeholder').blur(function(){
		ctPlaceHolderChange(this, false);
	});
		
	function ctButtonOnOff(object, over){
		var src = new String(object.src);
		var firstPart = src.substring(0, src.lastIndexOf("_"));
		var lastPart = src.substring(src.lastIndexOf("."));
		var onOff = (over) ? "_on" : "_off";
		object.src = firstPart + onOff + lastPart;
	}
	$('.ct_buttonOnOff').mouseenter(function(){
		ctButtonOnOff(this, true);
	});
	$('.ct_buttonOnOff').mouseleave(function(){
		ctButtonOnOff(this, false);
	});
	
	var ctZebraSelector = "table.ct_zebraStriped > tbody > tr:odd";
	ctZebraSelector += ", div.ct_zebraStriped > div:odd";
	ctZebraSelector += ", ul.ct_zebraStriped > li:odd";
	ctZebraSelector += ", ol.ct_zebraStriped > li:odd";
	$(ctZebraSelector).addClass("zebraAlt");
	
	$('.ct_collapsable > div > div').hide();
	$('.ct_collapsable > div > h2').each(function(index){
		$(this).css('cursor', 'pointer');
		$(this).click(function(){
			$('.ct_collapsable > div:nth-child(' + (index+1) + ') > div').slideToggle();
		});
	});
	
	var ctTabListCount = 0;
	$('.ct_tabbedItems').each(function(index){
		ctTabListCount++;
		$(this).addClass("ct_tabbedItems-" + ctTabListCount);
		var tabHtml = '<ul class="ct_tabbedItems-links clearfix">';
		var tabItemCount = 0;
		$(this).children("div").each(function(){
			tabItemCount++;
			$(this).addClass("ct_tabbedItems-" + ctTabListCount + '-' + tabItemCount);
			$(this).children("h3").each(function(){
				tabHtml += '<li class="ct_tabbedItems-' + ctTabListCount + '-' + tabItemCount + '-link" style="cursor:pointer; z-index:' + (666 - tabItemCount) + '; left:' + ((tabItemCount - 1) * 137) + 'px;"><div align="center">' + $(this).html() + '</div></li>';
				$(this).hide();
			});
			if(tabItemCount > 1) $(this).hide();
		});
		tabHtml += '</ul>';
		$(this).html(tabHtml + $(this).html());
		$('.ct_tabbedItems-' + ctTabListCount + '-1-link').addClass("selected");
		for(var i=1; i<=tabItemCount; i++){
			$('.ct_tabbedItems-' + ctTabListCount + '-' + i + '-link').click(function(){
				var classExp = this.className.split("-");
				$('.ct_tabbedItems-' + classExp[1] + ' > div').hide();
				$('.ct_tabbedItems-' + classExp[1] + '-' + classExp[2]).show();
				$('.ct_tabbedItems-' + classExp[1] + ' .ct_tabbedItems-links li').removeClass('selected');
				$('.ct_tabbedItems-' + classExp[1] + '-' + classExp[2] + '-link').addClass('selected');
			});
		}
	});
	
	$('[class|="ct_clickForMore"]').each(function(index){
		var newLength = 100;
		var elClasses = this.className.split(" ");
		for(var i=0; i<elClasses.length; i++){
			elClass = elClasses[i];
			if(elClass.substring(0, 16) === "ct_clickForMore-"){
				var dirtyLength = elClass.substr(16);
				if(!isNaN(dirtyLength)) newLength = dirtyLength;
			}
		}
		var newHtml = this.innerHTML;
		if(newHtml.length > newLength){	
			while(newHtml.search("\n") >= 0) newHtml = newHtml.replace("\n", "");
			while(newHtml.search("\r") >= 0) newHtml = newHtml.replace("\r", "");
			while(newHtml.search("<br>") >= 0) newHtml = newHtml.replace("<br>", "\n");
			var endPoint = newLength - 1;
			var noGoodEnd = Array(".", ",");
			while(newHtml.charAt(endPoint) != " "){
				endPoint--;
				if(endPoint < 0) break;
			}
			for(var i=0; i<noGoodEnd.length; i++){
				while(newHtml.charAt(endPoint-1) == noGoodEnd[i]){
					endPoint--;
					if(endPoint < 0) break;
				}
			}
			newHtml = newHtml.substring(0, endPoint) + '<span id="ct_clickForMoreExpanded-' + index + '" style="display:none;">' + newHtml.substring(endPoint) + '</span> <a href=\"#\" id="ct_clickForMoreLink-' + index + '">more...</a>';
			this.innerHTML = newHtml;
			$('#ct_clickForMoreLink-' + index).click(function(){
				$('#ct_clickForMoreExpanded-' + index).toggle();
				this.innerHTML = (this.innerHTML === "more...") ? "...less" : "more...";
				return false;
			});
		}
	});
	
	$('input[type="radio"].ct_deselectable').click(function(){
		if(ctTrackKeyCtrl) this.checked = false;
	});
	
	$('ul.ct_nestedList li ul').hide();
	$('ul.ct_nestedList li:has(ul) > div:first-child').css('cursor', 'pointer');
	$('ul.ct_nestedList li:has(ul) > div:first-child').addClass('ct_nestedListClickable');
	$('ul.ct_nestedList li:has(ul) > div:first-child').click(function(element){
		$(this).parent().children("ul").toggle();
		$(this).parent().children("li").toggle();
	});
	
	function ctCountDownsUpdate(element, event){
		var charsLeft = element.maxLength - $(element).val().length;
		var ctId = isNaN(event) ? event.data.ctCountDownNum : event;
		var charChars = (charsLeft === 1) ? 'character' : 'characters';
		$('#ct_countDown-' + ctId).html(charsLeft + ' ' + charChars + ' left.');
	}
	var ctCountDowns = 0;
	$('input.ct_countDown[type="text"]').each(function(){
		ctCountDowns++;
		if(isNaN(this.maxLength) || this.maxLength < 1) this.maxLength = 255;
		$(this).after('<div class="ct_countDown-left" id="ct_countDown-' + ctCountDowns + '">&nbsp;</div>');
		$(this).keyup({'ctCountDownNum':ctCountDowns}, function(event){
			ctCountDownsUpdate(this, event);
		});
		ctCountDownsUpdate(this, ctCountDowns);
	});
	
	var ctTracking = new Date();
	var timeOut = (ctTracking.getTime() - ctTimeIn) / 1000;
	$('#ct_jsToolsTimeReport').html('Javascript Tools took ' + timeOut + ' seconds to complete.');
});
