/*	Author:		Daniel C. Richmond
	File:		misc.js
	Purpose:	miscellaneous site-wide JavaScript
*/

var imageKeyA;
var imageKeyB;
var imageUrl;

// adding hasAttr() to check if an attribute exists on an element
$.fn.hasAttr = function(name) {  
	return this.attr(name) !== undefined;
};

// extend jQuery functinality
$.extend({
	getUrlVars: function() {
		var vars = [], hash;
		var url 	= window.location.href;
		url 		= (url.indexOf("#") > 0) ? url.substring(0, url.indexOf("#")) : url;
		var hashes	= url.slice(url.indexOf('?') + 1).split('&');
		if (hashes[0].indexOf("=") > 0) {
			for (var i = 0; i < hashes.length; i++) {
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
			}
			return vars;
		}
		return false;
	},
	getUrlVar: function(name) {
		var urlVars		= $.getUrlVars();
		for (var i in urlVars) {
			if (i == name) {
				return urlVars[i];
			}
		}
		return false;
	},
	getUrl: function(from) {
		// pass an anchor link as var from to get its href value
		// if undefined, will return window URL
		var index, url = "", from = (typeof(from) === undefined ? false : from);
		if (from) {
			url		= (from.hasAttr("href") ? from.attr("href") : "");
		} else {
			url		= window.location.href;
		}
		if ((index = url.indexOf("#")) > 0) {
			return url.slice(0, index);
		} else if (url != "") {
			return url;
		}
		return false;
	},
	getHash: function(from) {
		// pass an anchor link as var from to get its hash value
		// if undefined, will return URL hash
		var urlArr, url = "", from = (typeof(from) === undefined ? false : from);
		if (from) {
			url		= (from.hasAttr("href") ? from.attr("href") : "");
		} else {
			url		= window.location.href;
		}
		if (url.indexOf("#") >= 0) {
			urlArr 	= url.split("#");
			return urlArr[1] == "" ? false : urlArr[1];
		}
		return false;
	}
});

function solverGallery() {
	var mainNav		= $("#problem_solver_nav");
	var links, items, active, targeted = $("h4 a[name = " + $.getHash() + "]");
	//
	// if var mainNav actually exists on this page...
	if (mainNav.length >= 1) {
		// ... then we know we're in the solutions area
		// define items as all .solver_block
		items = $("div.solver_block");
		// for each .solver_block...
		items.each(
			function() {
				// ... add .gallery_item
				$(this).addClass("gallery_item");
			}
		)
		//
		if (targeted.length) {
			// the targeted anchor link exists... go to it
			active = targeted.parent().parent().parent().parent();
		} else {
			// if not, then just go to the first link
			active = $(items[0]);
		}
		// add .active to our active .solver_block, and make it visible (this is a new page visit, no animation)
		active
			.addClass("active")
			.css("display", "block");
		/* ------- NAV CONTROLS --------- */
		$("#problem_solver_nav a.right").click(
			function() {
				forward();
				return false;
			}
		);
		$("#problem_solver_nav a.left").click(
			function() {
				back();
				return false;
			}
		);/*----- /NAV CONTROLS ------*/
		
		// for each anchor in #solver_gallery...
		$("#solver_gallery").find("a").each(
			function() {
				var hash;
				// if this anchor has a hash value...
				if (hash = $.getHash($(this))) {
					// .. override default click functionality
					$(this).click(
						function() {
							// if the page URL and anchor URL DO NOT match...
							if ($.getUrl($(this)) != $.getUrl()) {
								// ... then we have an inter-page anchor link, which we'll need to override
								// define target named anchor link using clicked anchor's hash
								targeted	= $("h4 a[name = " + $.getHash($(this)) + "]");
								// its containing div will be our new target
								var _new	= targeted.parent().parent().parent().parent();
								// remove active element's .active and slide it away
								active
									.removeClass("active")
									.slideUp(500);
								// add .active to new element and slide it in
								_new
									.addClass("active")
									.slideDown(500);
								// redefine active
								active		= _new;
								// block default anchor functionality
								return false;
							}
						}
					)
				}					
			}			
		)
	}
	
	function forward() {
		/*
			deactives current item, slides out
			actiate next item
		*/
		var _new = active.next();
		if (_new.length) {
			active
				.removeClass("active")
				.slideUp(500);
			_new
				.addClass("active")
				.slideDown(500);
			active = _new;
		}
	}
	
	function back() {
		/*
			deactives current item, slides out
			actiate last item
		*/
		var _new = active.prev();
		if (_new.length) {
			active
				.removeClass("active")
				.slideUp(500);
			_new
				.addClass("active")
				.slideDown(500);
			active = _new;
		}
	}
}

function dimInputs(inputs){
	/*
		inputs should be a multidimensional array, formatted like:
		inputs(	{id:"an_id", text:"some text"},
				{id:"another_id", text:"more text"});
		//
		this will loop through that array and assign blur and focus handlers to each specified input
	*/
	for(i in inputs){
		// if it exists on this page...
		if($(inputs[i].id).length > 0){
			$(inputs[i].id).val(inputs[i].text);
			// ... add the "active" class to the input box
			$(inputs[i].id).addClass("inactive");
			// assign the following focus event:
			$(inputs[i].id).focus(function() {
				// if the input's value upon focus matches the corresponding text then...
				if($(this).val() == inputs[i].text){
					// ... clear the text out and...
					$(this).val("");
					// ... remove the "inactive" class from the input
					$(this).removeClass("inactive");
				}
			});
			// assign the following blur event:
			$(inputs[i].id).blur(function() {
				// if the input's value upon blur is "" then...
				if($(this).val() == ""){
					// ... assign the corresponding text as the input box's value...
					$(this).val(inputs[i].text);
					// ... add the "active" class to the input box
					$(this).addClass("inactive");
				}
			});
		}
	}
}

function imageSwap( e ) {
	var big				= $( "#big_image" );
	var small			= $( "#small_image" );
	var bigCaption		= $( "#big_image" ).parent().find( ".swap" ).text();
	var smallCaption		= $( "#small_image" ).parent().find( ".swap" ).text();
	//
	if( !big.hasClass( "disabled" ) || !small.hasClass( "disabled" ) ) {
		//
		switch( $( e.currentTarget ).attr( "id" ) ) {
			case "small_image":
				var imgBig = big.find( "img" );
				var currentBigKey	= big.attr( "rel" );
				var currentSmallKey	= small.attr( "rel" );
				var imgSmall = small.find( "img" );
				
				big
					.addClass( "disabled" )
					.css( "background-image", "url('../images/graphics/loading.gif')" )
					.find( "img" )
						.replaceWith( "<img />" )
						.end()
					.find( ".swap" )
						.text( "" );
				small
					.addClass( "disabled" )
					.css( "background-image", "url('../images/graphics/loading.gif')" )
					.find( "img" )
						.replaceWith( "<img />" )
						.end()
					.parent()
					.find( ".swap" )
						.text( "" );
					
				
				$( imgBig )
					.load( function () {
						$( big )
							.append( "<div class = \"shader\" />" )
							.find( ".shader" )
								.fadeOut( "slow", function() {
									$( this ).remove();
								} )
								.end()
							.css( "background-image", "url('" + $( imgBig ).attr( "src" ) + "')" )
							.removeClass( "disabled" )
							.attr( "rel", currentSmallKey )
							.parent()
							.find( ".swap")
								.text( smallCaption );
					} )
					.error(function () {
						// notify the user that the image could not be loaded
						// console.log( "small error" );
					} )
					.attr( "src", imageUrlGenerator( currentSmallKey,"L" ) );
					
				$( imgSmall )
					.load( function () {
						$( small )
							.append( "<div class = \"shader\" />" )
							.find( ".shader" )
								.fadeOut( "slow", function() {
									$( this ).remove();
								} )
								.end()
							.css( "background-image", "url('" + $( imgSmall ).attr( "src" ) + "')" )
							.removeClass( "disabled" )
							.attr( "rel", currentBigKey )
							.parent()
							.find( ".swap")
								.text( bigCaption );
					} )
					.error(function () {
						// notify the user that the image could not be loaded
						// console.log( "small error" );
					} )
					.attr( "src", imageUrlGenerator( currentBigKey,"M" ) );
					
					//.attr( "background-image", "url('images/graphics/loading.gif')" );
				
				
				
			case "big_image":
				// big image click does NOTHING.
				break;
		}
	}
	return false;
}
function imageUrlGenerator( key, size ) {
	return imageUrl.replace( /(.+)(res=)[a-zA-Z](.+)/, "$1$2" + size + "$3" + key );
}
$(document).ready(function() {
	// pass dimInputs an array of input box IDs you want dimmed when not in use as well as their
	// "dim state" text
	dimInputs([
		{id:"#sign_up_form input.sign_up", text:"email address"},
		{id:"#sign_up_sub input.sign_up", text:"email address"}
	]);
	solverGallery();
	//
	/* if( $( "#job_site_sort" ).length > 0 ) {
		$("#job_site_sort select").change( function() {
			$( "#job_site_sort" ).submit();
		});
	} */
	if( $( "#preview_612" ).length > 0 && window.supersleight ) {
		//$( "#preview_612" ).supersleight();
		supersleight.init();
	}
	
	if( $( "#small_image" ).length && $( "#big_image" ).length ) {
		// define image keys for small and large images
		imageKeyA		= $( "#small_image img" ).attr( "src" ).replace( /(.+)(key=)([a-zA-Z]+)/, "$3" );
		$( "#small_image" ).attr( "rel", imageKeyA );
		imageKeyB		= $( "#big_image img" ).attr( "src" ).replace( /(.+)(key=)([a-zA-Z]+)/, "$3" );
		$( "#big_image" ).attr( "rel", imageKeyB );
		imageUrl		= $( "#small_image img" ).attr( "src" ).replace( /(.+)(key=)([a-zA-Z]+)/, "$1$2" );
		//
		$( "#big_image, #small_image" ).click( imageSwap );
	}
	
	if( $( ".close-popup" ).length ) {
		$( ".close-popup" ).bind( "click", function() {
			parent.removeModal();
			return false;
		} );
	}
	
	if( $( "#job-site-search" ).length ) {
		$( "#job-site-search select" ).change( function() {
			document.getElementById( "job_site_search_box" ).readOnly = true;
			$( "#job-site-search" ).submit();
		} );
	}
	
	if( $( ".temp-hide" ).length ) {
		$( ".temp-hide" ).removeClass( "temp-hide" );
	}
	/* if( $( "h1, h2, h3" ).length ) {
		$( "h1, h2, h3" ).each( function() {
			$( this ).html( $( this ).html().replace(/&reg;/g, "<sup>&reg</sup>") );
		} );
	} */
});