/* 
 * JS/jQuery Functions for
 * www.glennxavier.com
 * written by Glenn Xavier, 2009
 * MIT X11 Licensed
 *
 * Core Dependencies:	jQuery 1.3.2, jQuery Color Animations 1.0
 * 
 * External Function Calls:
 *
 *  jQuery Validate 1.5.1		| used in form validation	| contact(), commentPost()
 *  Google Syntax Highlighter 2.1.364	| loads brushes when needed	| codeHighlight()
 *  SlimBox2 v2.03 core			| executes on loaded pages	| rebind()
 *  ---branched SlimBox2 by GX		| opens contact form in SlimBox	| contact(), navLinks()
 *
 */


jQuery(document).ready(function($) {

	var HoverVars = {}, BoxVars = {}, Public = {}, box = {}, loading;

	Public.base = $("link[rel='index']").attr('href');   //set Base url for easy hash link filtering
	Public.templatedir = $("link[rel='templatedir']").attr('href');  //url for WP template dir

	checkforHistory();

	$('#boxcontainer div.box').css('opacity','0');	
	
	if (document.URL.search(/admin/) == -1) { setInterval(function(){checkforHistory()},500) };

	if (jQuery.browser.msie === true) {
		Public.ie = true;
		pageNotice('ie');
		$('#loading').hide();
	} else {
		Public.ie = false;
	  	$('#loading').css('opacity','0');
	}

	navLinks();
	commentPost();
	codeHighlight();

	$("#loading").ajaxStart(function(){
		loading = true;
		if (Public.ie == false) { $(this).animate({opacity : '.6'}, 400);
		} else { $(this).show() };
	});

	$("#loading").ajaxStop(function(){
		loading = false;
		if (Public.ie == false) { $(this).animate({opacity : '0'}, 400);
		} else { $(this).hide() };
	});


function checkforHistory(string) {	
	
	if (Public.currenthash == undefined) { rebind(); Public.currenthash = ''; }

	if (string == undefined) { 
		if( (location.hash != Public.currenthash) && (location.hash != '#') ) { 		
			var historylink = location.hash.replace( '#' , '' );
			loader(historylink);
		};

	} else { 
		var link = string.replace( Public.base , '' );
		loader(link);
	};

};


function PositionDiv (obj, margin, col, left, top) {
	
	BoxVars.objects = obj;
	BoxVars.margin = margin;  		
	BoxVars.col = col; 			

	BoxVars.offleft = left || 0;		
	BoxVars.offtop = top || 0;					

	BoxVars.pos = BoxVars.objects.eq(0).position();
	BoxVars.outerW = (BoxVars.objects.eq(0).outerWidth(true)) + BoxVars.margin;
	BoxVars.outerH = (BoxVars.objects.eq(0).outerHeight(true)) + BoxVars.margin;
	BoxVars.width = (BoxVars.objects.eq(0).width());
	BoxVars.height = (BoxVars.objects.eq(0).height());

	BoxVars.objects.each(function (i){		
						
		BoxVars.row = parseInt(i / BoxVars.col);
		BoxVars.column = ((BoxVars.row * 3) - i) + 2;

		BoxVars.steppedrow = BoxVars.column + (BoxVars.row) - 1;
		BoxVars.steppedcol = ((BoxVars.column * -1) + 2);
		
	
		if (i <= 1) {
			BoxVars.top = BoxVars.outerH * i;
			BoxVars.left = 0;
		}

		else if (i == 2) {
			BoxVars.top = 0
			BoxVars.left = BoxVars.outerW;

		} else {		
			BoxVars.top = BoxVars.outerH * BoxVars.steppedrow;
			BoxVars.left = BoxVars.outerW * BoxVars.steppedcol;	

		};

		$(this).css({top:BoxVars.top, left:BoxVars.left});

	}); //end each
}; //end Positioning


function IntroAnim (obj){

	boxid = $('#boxcontainer div.box');
	boxid.css('opacity','0');
	box.size = boxid.size();
	arrbox = $.makeArray(boxid);
	divisible = parseInt(box.size/3);
	groupnum = divisible
	remainder = box.size%3;
	box.finalset = [];
	box.counter = 0;

	if (remainder) {
		box.remainder = arrbox.splice(-(remainder), remainder);
		box.remainder.reverse();
		$.merge(box.finalset, box.remainder);
	};

	while (groupnum >= 0) {		
		currentSet = box['set' + groupnum];
		currentSet = arrbox.splice(-3, 3);		
		if (groupnum%2) { currentSet.reverse(); }		
		$.merge(box.finalset, currentSet);	
		groupnum--;
	};

   	setTimeout(function() {

		$.each(box.finalset, function(i,val) {
			if ((box.finalset[i] == undefined) || (loading == true)) { return; }

			setTimeout(function() {	
				if ((box.finalset[i] == undefined) || (loading == true)) { return; }
				id = box.finalset[i].id;
				id = $("#" + id);
				id.animate({opacity: 1}, 500, function(){
					box.counter++;
					if (box.counter >= box.size) {
						
						HoverActions(boxid) };
				});
			}, i * 250); //end iterated timeout
		}); //end Each
   	}, 500);  //end first TimeOut

}; //end Animation


function addLinks (obj) {
	
  	obj.each(function (i){

		linkString = $(this).find('span.entry-thumbnails a.thumblink').attr('href');
		$(this).wrap('<a href="' + linkString + '"></a>');	

		$(this).click(function(e) {				
			boxid.unbind();
			e.preventDefault();
			linkString = $(this).parent().attr('href');	   		

			$(this).children('div.slider').animate({
				marginTop: '0',
				backgroundColor : '#999999'
				}, 800);

			boxid.not($(this)).animate({opacity: '0'}, 800);

			$(this).animate({
				backgroundColor : '#999999',
				borderTopColor : '#999999',
				borderLeftColor : '#999999',
				borderRightColor : '#999999',
				borderBottomColor : '#999999'
					}, 800)
				.animate({top : BoxVars.outerH}, 400)
				.animate({left : BoxVars.outerW}, 400)
				.animate({opacity : '0'}, 400)
				.queue(function () { checkforHistory(linkString); });
		
		}); //end click
	}); //end each
}; //end function


function rebind () {

	if ($('#boxcontainer div.box').length) {
		boxid = $('#boxcontainer div.box'); 
  		boxid.css('opacity','0');
		if (Public.ie == false) { boxid.children('div.dropshadow').css('opacity','.55') };
		PositionDiv(boxid, 4, 3);
		addLinks(boxid);
		$(window).load(IntroAnim());
	}

	commentPost();
	$('.ngg-gallery-thumbnail-box a').slimbox();
	codeHighlight();

};


function codeHighlight() {

	if ($('pre.brush\\:').length) { 

		var languagescripts = {};

		languagescripts.js = 'shBrushJScript.js';
		languagescripts.css = 'shBrushCss.js';
		languagescripts.php = 'shBrushPhp.js';
		languagescripts.plain = 'shBrushPlain.js';
		languagescripts.as3 = 'shBrushAS3.js';
		languagescripts.c = 'shBrushCpp.js';
		languagescripts.java = 'shBrushJava.js';
		languagescripts.perl = 'shBrushPerl.js';
		languagescripts.python = 'shBrushPython.js';
		languagescripts.ruby = 'shBrushRuby.js';
		languagescripts.sql = 'shBrushSql.js';
		languagescripts.xml = 'shBrushXml.js'; 
		
		var jspath = Public.templatedir + '/syntax/scripts/';

		$.getScript(jspath + 'shCore.js', function(){ 
			var pres = $('pre');
			size = pres.size();
			$.each(pres, function(i, val) {				
				preclass = $(this).attr('class').replace('brush: ', ''); 
				if (languagescripts[preclass] != undefined) {
					script = jspath + languagescripts[preclass];
					$.getScript(script);
					delete languagescripts[preclass]
				}
				if (i+1 == size) loadChecker(preclass)
			});


			function loadChecker(last){
				bs = SyntaxHighlighter.utils.findBrush(last,false);
				if ((bs == undefined) | (bs == null) | (loading == true)) {
					SyntaxHighlighter.vars.discoveredBrushes = null; 
					setTimeout(function() { loadChecker(last) }, 200)
				} else {
					SyntaxHighlighter.vars.discoveredBrushes = null;
					SyntaxHighlighter.defaults['light'] = true;
					SyntaxHighlighter.defaults['wrap-lines'] = false;
					SyntaxHighlighter.highlight();
					codeHover()
				};
			}

			function codeHover() {
				$('div.syntaxhighlighter').each(function() {
					var widest = null;
					$(this).find('td.content').each(function() {
						if (widest == null) widest = $(this);
						else
						if ($(this).width() > widest.width()) widest = $(this)
					});
					widest = widest.width();
					if (widest > $(this).width()) {
						$(this).addClass('needsExpansion');
						$(this).attr({greatestWidth: widest});
						$(this).append('<div class="right-shadow"></div>');
						$(this).children('.right-shadow')
							.css({ 'height' : $(this).height(),
								'opacity' : '.80' } )			
					}
				});

				$('div.syntaxhighlighter.needsExpansion').hover(function () {
					targetwidth = parseInt($(this).attr('greatestWidth'));
					$(this).stop().animate({'width' : targetwidth + 15 },  200);
					if (Public.ie == false) {
						$(this).children('.right-shadow').stop()
						.fadeOut(200);
					} else { $(this).children('.right-shadow').css('z-index','-10') }
								
				   } , function() {		
					$(this).stop().animate({'width' : '99%'}, 200);
					if (Public.ie == false) {
						$(this).children('.right-shadow').stop()
						.fadeIn(200);
					} else { $(this).children('.right-shadow').css('z-index','10') }		
				}) 
			}
		}) //end getScript		
	} //end if brushes
}; //end function



function contact() {

	var contactform = $('form[action$=mailer.php]');

	contactform.prepend('<div id="contactstatus" ></div>');
	var infodiv=$('#contactstatus');
	contactform.validate({
		submitHandler: function(form){
			var formdata=contactform.serialize();
			infodiv.html('<p>Processing...</p>');
			var formurl=contactform.attr('action');
			var formurl=Public.templatedir + '/contact/' + formurl;
			$.ajax({
				type: 'post',
				url: formurl,
				data: formdata,
				error: function(XMLHttpRequest, textStatus, errorThrown){ 
					infodiv.html('<p class="error">Post to server failed!</p>')},
	
				success: function(data, textStatus){
				    if(data == "mailsent") {
					infodiv.html('<p class="success">Email Successful! Closing Window...</p>');
					setTimeout(function(){
						$.slimbox('close');
					}, 3000);
							
				    } else { 
					infodiv.html('<p class="error" >Email was rejected...' + data + '</p>') };

				} //end success
			}); //end ajax
		} //end submithandler
	}); //end validate
}; //end contact


function navLinks () {
				
	$('#nav-content .menu li a').not('a[title="Contact"]').each(function (i){

		var linkString = $(this).attr('href');
		
		$(this).click(function(e) { 
			e.preventDefault();
			checkforHistory(linkString);
		});
	});


	$('#nav-content .menu li a[title="Contact"]').click(function(e) { 
			e.preventDefault();			
			form = Public.templatedir + '/contact/contact.php';
			$.slimbox(form, '', {inline: true});
			setTimeout(function() {     //needed a delay before traversing loaded page
				contact();
			}, 1000); 
	});
};


function loader(link) {

	var container = $('#container');
	Public.currenthash = '#' + link;
	location.hash = link;

	if (Public.currenthash == '#') Public.currenthash = '';
	if (Public.ie == true) { container.hide() }; 

	container.animate({opacity : '0'}, 400, function() {

		if (Public.ie == true) { this.style.removeAttribute('filter'); };
		$('#content').remove();
		var string = (Public.base + link + ' #content');

		container.load(string, function(responseText, textStatus, XMLHttpRequest){

			title = $(responseText).find('h1.entry-title,h2.entry-title,h1.feed-title').text();
			if ( title.length ) {
				document.title = 'Glenn Xavier | ' + title; 
			} else { 
				document.title = 'Glenn Xavier | Online Portfolio' };

			
			if (XMLHttpRequest.status == '404') {
				$(responseText).find('#content').appendTo(container);
			}		

			$('#signature').css('z-index','-15');
			if (Public.ie == true) { container.show(); rebind(); } else { 
			container.animate({opacity : '1'}, 400, function(){ rebind(); } ); }


			
		}); //end load	
	}); //end animate callback
}; //end function


function HoverActions (obj){

    boxid.hover(function () {
		
		$(this).stop().animate({
				borderLeftColor : '#F5F5F5',
				borderRightColor : '#F5F5F5',
				borderBottomColor : '#F5F5F5'				
			}, 500);

		if (Public.ie == false) {
			$(this).children('div.dropshadow').stop().animate({
					opacity : '1'
				}, 300);
			};

		$(this).children('div.slider').stop()
			.animate({ backgroundColor : '#F5F5F5' }, { queue:false, duration:500 })
			.animate({ marginTop: '-103' }, 250);

	  } , function() {
		
		$(this).siblings().andSelf().stop().animate({
				borderLeftColor : '#999999',
				borderRightColor : '#999999',
				borderBottomColor : '#999999'
			}, 800);

		$(this).children('div.slider').stop().animate({
				marginTop: '0',
				backgroundColor : '#999999'
			}, 800);

		if (Public.ie == false) {		
			$(this).children('div.dropshadow').stop().animate({
					opacity : '.55'
				}, 800);
		};
    }); //end Event Hover
}; //end function


function commentPost() {

	var commentform=$('form[action$=wp-comments-post.php]');
	commentform.prepend('<div id="commentstatus" ></div>');
	var infodiv=$('#commentstatus');
	commentform.validate({
		submitHandler: function(form){
			var formdata=commentform.serialize();
			infodiv.html('<p>Processing...</p>');
			var formurl=commentform.attr('action');
			$.ajax({
				type: 'post',
				url: formurl,
				data: formdata,
				error: function(XMLHttpRequest, textStatus, errorThrown){ 
					infodiv.html('<p class="error">Comment Refused. Maybe a duplicate?</p>')},
	
				success: function(data, textStatus){
				    if(data=="success") {
					infodiv.html('<p class="commentsuccess">Post successful: You should see your comment soon.</p>');
					commentform.find('textarea[name=comment]').val('');	
					$('#ajaxlist').css('opacity', '0');
			
					var url = window.location.href;
					var url = url.replace('#','');
					var string = url + ' #commentcount';
					
					$('#commentcount').load(string, function(){
						var string = url + ' #commentlist li:last-child';				
						$('#ajaxlist').load(string, function(){
							$(this).animate({opacity:'1'}, 400);
						})			
					}); //end count load 
	
				    } else { infodiv.html('<p class="error" >Something screwy happened...try again</p>') };
				} //end success
			}); //end ajax
		} //end submithandler
	}); //end validate
}; //end commentpost


function pageNotice(notice){

	$('body').prepend('<div id="topnotice1"></div><div id="topnotice2"></div><div id="bottomnotice"></div>');
	var notices = $('#topnotice1, #topnotice2, #bottomnotice');
	var top = $('#topnotice1');
	var top2 = $('#topnotice2');
	var bottom = $('#bottomnotice');

	switch(notice) {
		case "ie":
 	
			top.html('this site was designed primarily for <a href="http://www.mozilla.com" title="FireFox 3.5" target="_blank">gecko</a>, <a href="http://www.google.com/chrome/" title="Google Chrome" target="_blank">webkit</a>, and <a href="http://www.opera.com" title="Opera 10.1" target="_blank">presto</a> engines.');

			top2.html('the trident <a href="http://en.wikipedia.org/wiki/Comparison_of_web_browsers#JavaScript_support" title="Comparison of Javascript Support in Web Browsers" title="_blank">layout engine</a>, powering your internet explorer, will have <a href="http://acid3.acidtests.org/" target="_blank" title="Acid3 Test">difficulty rendering appropriately</a>.');

			break;
	}; //switch

	$.each(notices, function() {
		$(this).html( $(this).html().replace(/(gecko|presto|webkit|internet explorer|trident|difficulty)/g, '<span class="keywords">$1</span>') );
	}); //end each

}; //end pageNotice

function diagnostic(obj){

	$('#diagnosticblock').show('fast');
	//setInterval(function(){$('#diagnostics').val(window.location)}, 500);
	//setInterval(function(){$('#diagnostics2').val(window.location.pathname)}, 500);
	//setInterval(function(){$('#diagnostics3').val(Public.currenthash)}, 500);
	//setInterval(function(){$('#diagnostics4').val(location.hash)}, 500);
	//setInterval(function(){$('#diagnostics5').val(location.hostname)}, 500);
	//setInterval(function(){$('#diagnostics6').val(Public.base + '/' + location.hash)}, 500);
	//setInterval(function(){$('#diagnostics6').val(obj)}, 10);
	var diagnostictext = $('#diagnostictext').val();
	var newvalue = (obj);
	$('#diagnostictext').val(diagnostictext + '\n' + newvalue);

};


}); // End jQuery