$ = jQuery;
$(function(){
   nav.setup();
   side.setup();
   nct.init();
});

nct = {
	init: function() {
		nct.initComments();
		$('#dsq-sort-select').live('change', function(){setTimeout(nct.processComments, 500)}); 
	},
	showChunks: function(name, on, next){
		setTimeout(function(){ 
			$('.chunkBox').fadeOut().removeClass('chunkBox-active');
			$('#chunksFor-'+next.slug).css('position', 'absolute').fadeIn(function() { $(this).css('position', 'relative');}).addClass('chunkBox-active');
		},100);
	},
	initComments: function(){
		var done = false;
		if (nct.doComments) {
			nct.processComments();
			done = true;
		}
		if ($('#dsq-comments').length > 0) {
			nct.doComments = true;
		}
		else {
			nct.commentTries++;
			if (nct.commentTries > 20) {
				done = true;
			}
		}
		if (!done) {
			setTimeout(nct.initComments, 1500);
		}

	},
	processComments: function() {
		$('.aCommentShell').remove(); 
		$('#commentGap').remove(); 
		var cs = $('#dsq-comments');
		$('#dsq-comments').remove();
		cs.hide().insertAfter('#commentShell');
		$('<div class="clear"></div><div id="commentGap"></div>').insertAfter("#commentShell");
		nct.cmtHtml = $('<div></div>');
		$('.dsq-comment', cs).each( function() {
			var $t = $(this);
			nct.processComment($t);
			
		});                 
		cs.empty();
		$(nct.cmtHtml.html()).insertAfter('#commentGap');
	},
	processComment: function($t) {
		var id = ari($t.attr('id').split('-'), 2);
		$('#comment-'+id).remove();
		$('#dsq-append-post-'+id).remove(); 
		var html = '<div class="row aCommentShell">';
		var commentContent = $('#dsq-comment-body-'+id).clone();
		$('#dsq-comment-body-'+id).remove();
		var auth = $('.dsq-comment-cite', $t); 
		var link = $('a', auth).length ? $('a', auth).attr('href') : false;
		var url = link;
		link = link ? '<li><b>from</b> <a href="'+link+'">'+link+'</a></li>' : '';
		var likes = $('#dsq-like-pts-'+id).length ? ari($('#dsq-like-pts-'+id).html().split('&nbsp;'), 0) * 1 : ''; 
		likes = likes > 0 ? ('<b>liked</b> '+( likes === 1 ? '1 time' : likes+' times' )) : '';
		var time = $('.dsq-comment-header-time', $t).text(); 
		var avatar = $('.dsq-avatar', $t).clone();  
		$('.dsq-avatar', $t).remove();
		var buttons = $('.dsq-comment-buttons', $t).clone();  
		$('.dsq-comment-buttons', $t).remove(); 
		var isReply = $t.hasClass('child') ? true : false;
		if (!isReply) {
			html += ''
			+ '<div class="threecol commentMeta">'
			+ '		<ul class="left-side-head">'
			+ '			<li class="side-head"><h4>'+auth.text()+'</h4></li>'
			+ '			<li class="sub sub-content">'
			+ '			<ul>' + link + '<li><b>posted </b>' + time + '</li><li>' + likes +'</li></ul>'	
			+ '			</li>'
			+ '		</ul>'
			+ '</div>'
			+ '<div id="commentContainer-'+id+'" class="sevencol">'
			+ '			<div id="comment-'+id+'"></div>'
			+ '			<div class="commentContent">' 
			+ '				<div class="avatarShell"></div> '
			+ '  			<div class="commentContentShell"></div>' 
			+ '				<div class="clear"></div><div class="commentButtons"></div><div class="clear"></div>'
			+ '			</div>'
			+ '			<div id="dsq-append-post-'+id+'"></div>' 
			+ '</div><div class="twocol last"></div>';
			html += '</div><div class="clear"></div>';
			html = $(html);
			$('.commentContentShell', html).append(commentContent);
			$('.commentButtons', html).append(buttons);
			$('.avatarShell', html).append(avatar);
			nct.cmtHtml.prepend(html);
		}                  	
		else {
			var pid = false;
			var classes = $t.attr('class').split(' ');
			var html = '';
			$.each(classes, function(i, v){
				if (v.indexOf('parent-is') > -1) {
					pid = ari(v.split('-'), 3);
					return;
				}
			});
			if (pid != undefined && pid) {
				html += ''
					+ '<div id="commentContainer-'+id+'" class="childComment"> '
					+ '		<div class="childCommentHead">'
					+ '			<div class="avatarShell"></div>'
					+ '			<a href="'+url+'">' + auth.text() + '</a>'
					+ '			<span class="right">'+time+' '+likes+'</span>'
					+ '		</div>'
					+ '			<div id="comment-'+id+'"></div>'
					+ '			<div class="commentContent">' 
					+ '  			<div class="commentContentShell"></div>' 
					+ '				<div class="clear"></div><div class="commentButtons"></div><div class="clear"></div>'
					+ '			</div>'
					+ '			<div id="dsq-append-post-'+id+'"></div>' 
					+ '</div>';
				html = $(html);
				$('.commentContentShell', html).append(commentContent);
				$('.commentButtons', html).append(buttons);
				$('.avatarShell', html).append(avatar); 
				$('#commentContainer-'+pid, nct.cmtHtml).append(html);
			}
						

		}
	},
	commentTries: 0,
	doComments: false,
	__end: true
}

nav = {
	setup : function()
	{
		$(window).scroll(function()
		{
		   var y = $(window).scrollTop();
		   if(y > 129){
			   $('#masthead').css('position', 'fixed').css('top', '-130px').css('margin-bottom', '130px');
			   $('#top-fade').show();
			   nav.stay();
		   }
		   else{
			   $('#masthead').attr('style', '');
			   $('#top-fade').hide();
			   nav.release();
		   }
		});
	}, 
	event: function(onStay, onRelease) {
		var tStay = nav.stay();
		var tRel = nav.release();
		nav.stay = function(){
			tStay();
			onStay();
		}
		nav.release = function(){
			tRel();
			onRelease();
		}
		nav.stay = onStay;
		nav.release = onRelease;
	},
	stay : function(){},
	release : function(){},
	__end : true
}

side = {
	setup : function()
	{
		//Create JSON for each rotating head
		//and its subheads
		var areHeads = false;
		$('.rotating-head').each(function(){
			var rotName = $(this).idData();
			var pages = [];
			$('li', $(this)).each(function(){
				pages.push({
				    slug : $(this).children().first().idData(),
					text : $(this).children().first().text()
				});
			});
			side.rots[rotName] = {
				pages : pages,
				on : false,
				onPage : 0,
				wait : 11000,
				lastElm : $('<li id="sub-'+pages[0].slug+'" class="sub"><a href="#" id="'+rotName+'-'+pages[0].slug+'">'+pages[0].text+'</span></li>')
			};
			areHeads = true;
		});
		if (areHeads){
		  side.start('catlist', nct.showChunks);    
		}
		$('a', '.left-side-head').live('click', side.clickTo);
		side.checkHeadSize();
	},
	start : function(name, fnc)
	{    
		side.rots[name].timeout = setTimeout(function(){
            side.rots[name].on = true;
			side.next(name, fnc);
		}, side.rots[name].wait);
	},
	next: function(name, fnc) {
		side.go(false, name, fnc);
	},
	go : function(index, name, fnc)
	{
		var rot = side.rots[name];
		var onPage = rot.pages[rot.onPage];
		var onIndex = side.pageId(name, onPage);
		var nextIndex = (rot.onPage < rot.pages.length-1) ? rot.onPage + 1 : 0;
		var toIndex = nextIndex;
		if (index !== false){
			toIndex = side.pageId(name, index);
			clearTimeout(side.rots[name].timeout);
		}
		var nextPage = rot.pages[nextIndex]; 
		var toPage = rot.pages[toIndex];
		var options = $('li', '#rotating-'+name);
		var moveNum = options.index($('#sub-'+toPage.slug));
		var moveDir = (moveNum * 27) + 0;

		//Trigger External Actions
		fnc(name, onPage, nextPage);

		var newSubs = [rot.lastElm];
		var existingSubs = [];
        var c = 0;  

		//Animate sub shift
		$('.sub', '#rotating-'+name).each(function(){
			opacity = 1;
			var $this = $(this);
			if (c < moveNum) {
				var opacity = 0;
				if ($this.idData() != toPage.slug) {
					newSubs.push($this.clone().hide()); 
				}
				else{
					side.rots[name].lastElm = $this.clone(); 
				}
			}
			else{
				existingSubs.push($this.clone());
			}
			$(this)
				.animate({
				top: '-='+moveDir,
				opacity: opacity,
			}, 345, function(){
				existingSubs = existingSubs.concat(newSubs);
				$('.sub', '#rotating-'+name).remove();
				$.each(existingSubs, function(i, v){
					v = $(v);
					$('#rotating-'+name).append(v);
					if (v.is(':hidden')) {
						v.fadeIn();
					}
				});         
			});
			if (c < moveNum) {
				setTimeout(function() {
					$this.html('<span style="height:17px; display:block; width:2px"></span>');
				}, 100);
			}
			c++;
		});

		//Change left-head
		setTimeout(function(){
			$('#catlist-'+onPage.slug).fadeOut(function() {$(this).remove()});
			var $head = $('<h4 id="catlist-'+toPage.slug+'">'+toPage.text+'</h4>').css('display', 'none !important');
			$('.side-head', '#rotating-'+name).append($head);
			setTimeout($head.fadeIn(),1000);
			side.rots[name].onPage = toIndex;
		}, 160);

		//Make sure the headsize fits
		setTimeout(side.checkHeadSize, 300);

		//Rotate in rot.wait seconds
		if (index == undefined) {
			side.rots[name].timeout = setTimeout(function(){
				side.next(name, fnc);
			}, rot.wait); 
		}
	   
	},
	clickTo: function() {
		var sideid = $(this).closest('.rotating-head').idData();
		var headid = $(this).idData();
		side.go(headid, sideid, nct.showChunks);
		return false;
	},
	pageId: function(sideid, slug) {
		var id = false;
		$.each(side.rots[sideid].pages, function(i, v) {
			if (v.slug == slug){
				id = i;
			}
		});
		return id;
	},
	checkHeadSize : function(elm)
	{
		if (elm != undefined) {
			elm = $(elm);
		}
		else {
			elm = $('h4', '.side-head');
		}
		elm.each(function() {
			$this = $(this);
			while($this.width() > 230) {
				$this.css('font-size', px(parseInt($this.css('font-size')) - 1));
			}
			var top = ($this.parent().innerHeight() / 2 - $(this).outerHeight() / 2) - 4;
			$this.css('top', px(top));
		});
	},
	rots : {}      
}


chk = {
	setup : function()
	{

	},
	next : function()
	{

	}
}

/**
 * Very, very commonly used functions
 */
function isset(variable){
	return ( !(variable === undefined) );
}
function d(msg){
	if(console != undefined){
		console.info(msg);
	}
}
function ari(ar, i){
	return ar[i];
}
function px (str) {
	return str + 'px';
}

/**
 * JQuery Plugins
 */
(function($) {
  $.fn.caret = function(pos) {
    var target = this[0];
    if (arguments.length == 0) { //get
      if (target.selectionStart) { //DOM
        var pos = target.selectionStart;
        return pos > 0 ? pos : 0;
      }
      else if (target.createTextRange) { //IE
		target.focus();
		var range = document.selection.createRange();
		if (range == null)
			return '0';
		var re = target.createTextRange();
		var rc = re.duplicate();
		re.moveToBookmark(range.getBookmark());
		rc.setEndPoint('EndToStart', re);
		return rc.text.length;
      }
      else return 0;
    } //set
    if (target.setSelectionRange) //DOM
      target.setSelectionRange(pos, pos);
    else if (target.createTextRange) { //IE
      var range = target.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
})(jQuery);

(function($) {
	$.fn.idData = function(delim){
		if(!isset(delim)){
			delim = '-';
		}
		return ari($(this).attr('id').split(delim), 1);
	}
})(jQuery);

(function($) {
  $.fn.labeledInput = function(val, opts){
	if(opts == undefined){
		opts = {};
	}
	var obj = this;
	if(obj.val() == ''){
		obj
		.val(val);
		obj.addClass('labeledInput-clear');
		if(opts.init != undefined){
				opts.init();
		}
	}
	obj
	.focus(function(){
		if(obj.val() == val){
			obj.val('');
			obj.removeClass('labeledInput-clear');
			obj.addClass('labeledInput-active');
			if(opts.activated != undefined){
				opts.activated();
			}
		}
	})
	.blur(function(){
		if(obj.val() == ''){
			obj.val(val);
			obj.addClass('labeledInput-clear');
			obj.removeClass('labeledInput-active');
			if(opts.cleared != undefined){
				opts.cleared();
			}
		}
	});
	return this;
  }
})(jQuery);

(function($) {
  $.fn.tagName = function(){
	return this.get(0).tagName;
  }
})(jQuery);


