/* Portfolio Theme jQuery
 *
 * @package WordPress
 * @subpackage - Portfolio Theme by Creative Glo
 * vThe Portfolio Theme is Copyright 2009, 2010, 2011 Creative Glo Limited, and is distributed under the terms of the GNU General Public License (Version 3).
 * 
 * This file is part of Portfolio Theme.
 * 
 * Portfolio Theme is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * Portfolio Theme is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with the Portfolio Theme.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 
 * 1 - Global
 * 2 - Masthead
 * 3 - Home page
 * 4 - Links and menus
 * 5 - Sliding panels
 * 6 - General copy
 *		a - Clear paragraph after image
 *		b - jQuery lightbox
 *		c - Parent area clickable
 *		d - Equal height columns
 * 7 - Sidebar
 * 8 - Gallery at foot of article
 * 9 - Blog home page
 * 10 - Forms
 *		a - Input hints
 *		b - Text box hints
 *		c - Comments form
 *		d - Contact form
 * 11 - Image swap gallery
 * 12 - Tabbed panels
 * 13 - Page footer
 * 14 - Variable width stuff
 *		a - Change styles depending on width
 *		b - Count columns
 *		c - Find last column in row
 *		d - Shrink blog images
 */

/**
 * console.log(this); // show events in firebug's console log
 * var $this = $(this); // set $this to speed things up
 *
 * When the document loads do everything inside here ...
 */

jQuery(document).ready(function($){


/** ==========================================================================
 * 1 - Global
 * ===========================================================================
 */

$("#content").each(function(){
	if ( $(this).hasClass("fullWidth") ) {
		$(this).addClass("w12 column clearfix");
		} else {
			$(this).addClass("col8 column clearfix");
	}
});

$(".withIntro").each(function(){

	/**
	 * Target first paragraph of blog posts and
	 * Intros on full width pages while ignoring first
	 * article in article listings
	 * @since Portfolio Theme 3
	 */

	var firstParagraph = $(".withIntro p:first");

	if ( $( firstParagraph ).parent("header").length < 1 ) {
		$( firstParagraph ).addClass("first");
	}
});

$("#pageBody").addClass("clearfix");
$("#pageBody .column:last-child").addClass("lastCol");


/** ==========================================================================
 * 2 - Masthead
 * ===========================================================================
 */

/** ==========================================================================
 * 3 - Home page
 * ===========================================================================
 */
	
	$.fn.homeLeaderHeight = function() {

		/**
		 * Set height of homeLeader to match that of the next <li> to the right
		 * if width is 767 or more.
		 * @since Portfolio Theme 3
		 */

		var homeLeader = $(this);

		$.fn.setMyHeight = function() {
			var pageWidth = $(window).width();
	
			if ( pageWidth > 767 ) {
				var setHeight = $(homeLeader).next().height();
				$(homeLeader).height(setHeight)
			}
		}

		$(homeLeader).setMyHeight();

		$(window).resize(function() {

			/**
			 * Do things when the browser window is resized
			 * If width is less that 767 and height has been set, remove it
			 * Else if width is more than 767 & a height has not yet been
			 * set, set one.
			 */

			var pageWidth = $(window).width();
			var attr = $(homeLeader).attr("style");
			//console.log(attr, pageWidth);
			if ( ( pageWidth < 767 ) && (attr !== 'undefined') ) {
				$(homeLeader).removeAttr("style");
				} else if ( ( pageWidth > 767 ) && (attr = 'undefined') ) {
					$(homeLeader).setMyHeight();
			}

		}); // window resize function

	};

	$("li#homeLeader").homeLeaderHeight();


/** ==========================================================================
 * 4 - Links and menus
 * ===========================================================================
 */

	$("a.skip").addClass("linkStyle1");
	$("h1 a").each(function(){

		var parentId = $(this).parents("div").attr("class");

		if( parentId !== "infoPanel") {
			$(this).addClass("linkStyle2");
		}
	});
	$("#homeContent a, #navHeaderPage ul a, #navFooterPage ul a, .siteMap a, a.forward, a.back").addClass("linkStyle2");
	$(".moreLink li:last-child").addClass("last");
	$(".moreLink li:last-child A").addClass("forward linkAsButton");

	$("ul.postNavigation li a").addClass("linkAsButton linkStyle2");
	$("ul.postNavigation li#previous a").addClass("first back");

	/**
	 * #previous and #next are coded into inc/incNavigation.php
	 * Styles are applied like this because of the way the the native
	 * WordPress function uses %link to build the <a> tag
	 * There might be a way to manipulate that functionality.
	 *
	 * @since Portfolio Theme 2.6
	 *
	 */

	$("ul.postNavigation li#next a").addClass("last forward");
	$("ul.moreLink li.last a").addClass("forward linkAsButton linkStyle2");
	$(".vMenu li a img").parents("li").addClass("clearfix");
	$(".vMenu li a img").parent("li").addClass("thumb");
	$(".vMenu li:first-child").addClass("first");
	$("ul.discreet li:last-child").addClass("last");

/** ==========================================================================
 * 5 - Sliding panels
 * ===========================================================================
 *
 * Used for home page slider and gallery page thumbnails
 * IOS specific stuff added @since Portfolio Theme 3.0.2
 */
 
	$.fn.infoContainerFunction = function(options) {
		var defaults = { finishTop: 90, startTop: 184 };
		var options = $.extend(defaults, options);

		$(this).each(function(){
			if ( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) ) {
				$(this).bind('touchstart', function(){
					//console.log("touch started");
					$(this).parents("ul").find("div.infoPanel").removeAttr("style");
					$(this).find(".infoPanel").stop().animate({top: options.finishTop , opacity: "0.8"} , {queue:false,duration:300});
				}); /* /IOS function */

				} else {
					$(this).hover(function(){
						$(this).find(".infoPanel").stop().animate({top: options.finishTop , opacity: "0.8"} , {queue:false,duration:300});
						}, function() {
							$(this).find(".infoPanel").stop().animate({top: options.startTop , opacity: "0"} , {queue:false,duration:300});
				}); /* /hover function */
			} /* /if IOS/else */
		}); /* /each function */
	} /* /infoContainerFunction */

	$("ul.galleryList .infoContainer").infoContainerFunction();

	$("#firstGalleryPost .infoContainer").infoContainerFunction({finishTop: 170 , startTop: 300 });

/** ==========================================================================
 * 6 - General copy
 * ===========================================================================
 */

	$("table").addClass("w8");
	$("tr").each(function(){

		$("td:first-child").addClass("w6");

	});
	$("table").each(function(){

		$("tr:last-child").addClass("last");

	});
	$(".articleMeta dd:last-child").addClass("last");
	$("#content ul#tags a").addClass("linkStyle2");

	$("ul.vMenu").each( function() {

		/**
		 * Add link style to links in vMenus that do not have the ID tweetList
		 * @since Portfolio Theme 3
		 */

		var menu = $(this);
		var parentId = $(this).attr("id");

		if ( parentId !== "tweetList" ) {
			$( menu ).find("li a").addClass("linkStyle2 clearfix");
		}

		$("#tweetList a.linkAsButton").addClass("clearfix");

	});

	$("ul#content li").each( function() {

		/**
		 * Add link style to links in vMenus that do not have the ID tweetList
		 */

		var menu = $(this).parent();
		var parentId = $(this).parents().attr("id");

		if ( parentId !== "articleMena" ) {
			$( menu ).find("li").addClass("clearfix");
		}

	});
	
	$("article.summary img :not(ul.vMenu img)").addClass("imgLeft");
	$("#articleDescription").addClass("column clearfix");
	$("#articleDescription #floatContainer, #asideWorkPost").addClass("col5 column clearfix");
	$("#articleInfo").addClass("col3 column clearfix");
	$("#blogSummaries .panelList li, #articleList li article header, #headerPage, section#articleDescription aside").addClass("clearfix");
	$("#articleInfo dd:last-child, #articleInfo dt:last-child").addClass("last");
	$("#articleInfo dl, #content ul#tags").addClass("clearfix");
	$("ul#tags").addClass("hMenu discreet");


/**
 * 6a - Clear paragraph after image
 * ---------------------------------------------------------------------------
 */

	$("p:has(img)").each(function() {

		$(this).next("p").addClass("clearLeft");

	});


/**
 * 6b - jQuery lightbox
 * ---------------------------------------------------------------------------
 */


	$(".wp-caption a").each(function(){
		var lightboxClass = $(this).attr("rel");
		
		if ( lightboxClass == "lightbox") {
			$(this).addClass("lightbox");
			$(this).children("img").removeAttr("class");
		}

	});

	$("a.lightbox").lightBox();


/**
 * 6c - Parent area clickable
 * ---------------------------------------------------------------------------
 */


	$.fn.clickable = function() {
		
		return this.each(function() { 
			var theUrl = $(this).find('a').attr('href');
			$(this).hover(function(){
				$(this).css("cursor","pointer");
			});

			$(this).click(function(){
				location.href = theUrl;
			});
		});
	 };

$("#articleList li article header, #homeListings li article, .moreLink li.last, #latest").clickable();


/**
 * 6d - Equal height columns
 * ---------------------------------------------------------------------------
 */

	$.fn.equalHeight = function() {
		var myElem = $(this);
		var max_height = 0;
		$(myElem).each(function(){
			if ($(this).height() > max_height) { max_height = $(this).height(); }

		});
			$(this).height(max_height);
		};

	//	$("#imageGallery li").equalHeight();


/** ==========================================================================
 * 7 - Sidebar
 * ===========================================================================
 */

	$("#navCategory").addClass("col4 column clearfix lastCol");

/** ==========================================================================
 * 8 - Gallery at foot of article
 * ===========================================================================
 */

	$("#imageGallery").addClass("clearfix");
	$("#imageGallery li").addClass("col4 column clearfix");
	$("#imageGallery li:odd").addClass("last");


/** ==========================================================================
 * 9 - Blog home page
 * ===========================================================================
 */

	$("#blogSummaries").addClass("clearfix");

/** ==========================================================================
 * 10 - Forms
 * ===========================================================================
 */

	$("#commentform").addClass("neatForm");
	$(".neatForm fieldset, .neatForm legend").addClass("w8");
	$(".neatForm button, .neatForm label, .neatForm li span:nth-child(3)").addClass("w2");
	$(".neatForm textarea").addClass("w6p");
	
	// for chrome
	$(".neatForm input[type='email'], .neatForm input[type='url']").addClass("w2");
	

/**
 * 10a - Input hints
 * ---------------------------------------------------------------------------
 */

	$.fn.hint = function (blurClass) {
		if (!blurClass) { 
			blurClass = 'blur';
		}

		return this.each(function () {
			// get jQuery version of 'this'
			var $input = $(this),
			// capture the rest of the variable to allow for reuse
			title = $input.attr('title'),
			$form = $(this.form),
			$win = $(window);

			function remove() {
				if ($input.val() === title && $input.hasClass(blurClass)) {
					$input.val('').removeClass(blurClass);
				}
			}

			// only apply logic if the element has the attribute

			if (title) { 
				// on blur, set value to title attr if text is blank
				$input.blur(function () {
					if (this.value === '') {
						$input.val(title).addClass(blurClass);
					}

			}).focus(remove).blur(); // now change all inputs to title

			// clear the pre-defined text when form is submitted
			$form.submit(remove);
			$win.unload(remove); // handles Firefox's autocomplete
			}
		});
	};

	$("input:text, textarea").hint();

	
/** ==========================================================================
 * 10b - Text box hints
 * ===========================================================================
 */

	$.fn.textboxhint = function(userOptions) {
		var options = $.extend({}, $.fn.textboxhint.defaults, userOptions);
		var $this = $(this);
		return $this.filter(':text,textarea').each(function(){
			if ($this.val() == '') {
				$this.focus(function(){
					if ($this.attr('typedValue') == '') {
						$this.removeClass(options.classname).val('');
					}
				}).blur(function(){
					$this.attr('typedValue', $(this).val());
					if ($this.val() == '') {
						$this.addClass(options.classname).val(options.hint);
					}
				}).blur();
			}
		});
	};

	$.fn.textboxhint.defaults = {
		// hint: 'Please enter a value',
		classname: 'hint'
	};

	$(".neatForm label:contains('Your comment')").next("textarea").textboxhint({
		hint: 'Your comment'
	});


/** ==========================================================================
 * 10c - Comments form
 * ===========================================================================
 */

	$("header#commentsHeader nav a").addClass("linkAsButton linkStyle2 comment");
	$("ol#commentList .reply a").addClass("linkAsButton linkStyle2 reply");
	$("section#comments ol:first-child li").each(function(){

		// fetch the class of the parent ol of the comment
		var parentId = $(this).parent("ol").attr("class");

		// if comment is not a child add the following classes to the comment header
		if( parentId != "children") {
			$(this).find("article:first header:first").addClass("col2 firstCol clearfix");
		}
	});

	$("section#comments ol li article div").each(function(){

		// fetch the class of the parent ol of the comment
		var parentId = $(this).parents("ol").attr("class");

		// if comment is not a child add the following classes to the comment body containing div
		if( parentId != "children") {
			$(this).addClass("col6 column clearfix");
		}
	});

	$("section#comments li, .children li, .children ul li ul li, .children header, #commentsHeader nav ").addClass("clearfix");
	$(".comment-author img").addClass("imgLeft");
	$("#commentform #submit").addClass("btn");

/** ==========================================================================
 * 10d - Contact form
 * ===========================================================================
 * For Select Simple Contact Form Revisited Widget
 * If removing, also remove:
 * forms.css 3 - Contact form plug-in
 * headerFunctions.php add_action( 'wp_print_styles...
 */
 
	//$("form.contactform").addClass("neatForm").attr("id" , "contactForm").removeClass("contactform");
	
	$("form.neatForm p").each(function(){
		$(this).find('label').addClass("w2");
		//$(this).find('textarea').removeAttr("cols").removeAttr("rows").removeClass("textarea").addClass("w6p");
		$(this).find('input[value="Submit"]').attr("id" , "submit").addClass("btn");
	});

/** ==========================================================================
 * 11 - Image swap gallery
 * ===========================================================================
 */

	$("#galleryContainer img:first").show();
	
	$("#articleGallery ul li a").click(function (e) {
		e.preventDefault();	
		var content_show = $(this).attr("id");
		$("#galleryContainer img").hide();
		$("#galleryContainer").find("#"+content_show).show();
	});
	

	$("#gallerySlider").addClass("clearfix");


/** ==========================================================================
 * 12 - Tabbed panels
 * ===========================================================================
 *
 * Very neat tutorial to follow http://webcloud.se/article/Building_jQuery_plugins/
 * Tabify source http://www.jquerylabs.com/index.php/tabify-tabbed-content-with-ease.html
 */

	$("#navGallery ul").tabify(); /* Requires jQuery tabify */

	// set this class like this otherwise it's scattered about in multliple places
	$(".panelGallery").find("header:first").addClass("panelHeader");

	$("#navGallery ul li a").each(function(){
		var $this = $(this);
		var parentId = $this.parent("li").attr("class");
		if( parentId == "active") {
			$this.addClass("linkStyle2");
			} else {
				$this.addClass("linkStyle1");
		}
	});
	
	/**
	 * When a link is clicked change class of parent list item
	 */

	$("#navGallery ul li a").click(function () {
		// switch all tabs off
		$(".active a").removeClass("linkStyle2").addClass("linkStyle1");

		// switch this tab on
		$(this).removeClass("linkStyle1").addClass("linkStyle2");
	});

	/**
	 * Function create IDs with incremental values
	 */

	$.fn.menuId = function(options) {
		var defaults = { classname: 'tab' };
		var options = $.extend(defaults, options); 

		// traverse all nodes
		this.each(function(i) {
			i = i+1;
			$(this).attr("id" , options.classname + i);
		});

		// allow jQuery chaining
		return this;
	};
	
	$("#galleryContainer img").menuId();
	
	$("#articleGallery ul li a").menuId();

	$("#navGallery ul li:first-child").addClass("active");


/** ==========================================================================
 * 13 - Page footer
 * ===========================================================================
 */

	$("#navFooterPage ul li:last-child").addClass("last");
	$("#footerMenu #searchform").addClass("w3");
	$("#footerPage, #navFooterPage, #navFooterPage ul").addClass("clearfix");


/** ==========================================================================
 * 14 - Variable width stuff
 * ===========================================================================
 */

/**
 * 14a - Change styles depending on width
 * ---------------------------------------------------------------------------
 * @since Portfolio Theme 3
 */


$.fn.variableWidth = function(options) {

	var defaults = { className: 'nothing' };
	// Set up default options

	var options = $.extend({}, defaults, options);
	// Overwrite defaults with options, or combine them
	
	var $this = $(this);

	return this.each(function() {
	
		$.fn.changeClasses = function() {
			var pageWidth = $(window).width();

			if ( pageWidth < 768 ) {
				$(this).addClass(options.className);
			};
		
		}; // changeClasses
			
		$(this).changeClasses();

		$(window).resize(function() {
			// Do things if the browser window is resized

			$($this).removeClass(options.className);
			// Remove all the classes

			$($this).changeClasses();
			// Add classes again in the correct locations

		}); // window resize function

	});  // each

}; // variableWidth

$("#navHeaderPage ul").variableWidth({className: 'hMenu tabbed'});


/**
 * 14b - Count columns
 * ---------------------------------------------------------------------------
 * For the moment there is are large amounts of commented out code which were
 * used to debug this code in IE 7. Can be safely removed at some point.
 * @since Portfolio Theme 3
 */

	$.fn.activateCcf = function(options) {

		/**
		 * 1 - Count the columns
		 * 2 - Set a function which looks for 'x'n+1 or similar
		 */

		var defaults = { childContainer: 'li', className: 'last', firstInRow: 'first' };
		// Set up default options

		var options = $.extend({}, defaults, options);
		// Overwrite defaults with options, or combine them
		
		var container = (this);
		
		return this.each(function() {

			$.fn.columnCountFunction = function() {
			
			//$(container).prepend("<p>Container: " + container + " -</p>");

				// 1 - Count the columns
				
				var colWrap = $(container).width();
				// Find the width of the parent container
		
				var childWidth = $(container).find(options.childContainer).width();
				// Find the width of the children
				
								//$(container).prepend("<p>colWrap: " + colWrap + " ChildWidth: " + childWidth + " -</p>");
		
				var cols = Math.floor(colWrap / childWidth);
				// See how many columns there are

				var nthMany = ( cols + "n+" + cols);
				// Set the value of nth-child based upon the number of columns
				
				childContainer = options.childContainer;
				// Seemed to not work without this step
		
				// 2 - Set a function which looks for 'x'n+1 or similar

				$(container).children("" + childContainer + ":nth-child(" + nthMany +")").each(function(){
					$(this).addClass(options.className);
				});
				
				/**
				 * To support browsers other than Firefox it's necessary to 
				 * apply a class to the first in row
				 */

				var colsPlusOne = ( cols + 1);
				var nextNthMany =  ( cols + "n+" + colsPlusOne);
				
				//$(container).prepend("<p>Child container: " + childContainer + " Cols: " + cols + " nthMany: " + nthMany  + " colsPlusOne: " + colsPlusOne + " NextNthMany: " + nextNthMany + " -</p>");

				$(container).children("" + childContainer + ":nth-child(" + nextNthMany +")").each(function(){
					$(this).addClass(options.firstInRow);
				});
				
			} // columnCountFunction
			
			$(container).columnCountFunction();
			
			$(window).resize(function() {

				/**
				 * Do things if the browser window is resized
				 */
				
				$(container).find(options.childContainer).removeClass(options.className).removeClass(options.firstInRow);
				// Remove all the classes

				$(container).columnCountFunction();
				// Add classes again in the correct locations

			}); // window resize function
		}) // each function
	}; // activateCcf

	/**
	 * In order for this to function as intended the parent should contain ONLY children
	 * of the type to be targeted
	 */

	$("ul.galleryList").each( function() {

		/**
		 * Currently unable to get this to play nicely on category-work.php
		 * So filtering out those ULs.
		 * Using function below this to do the work there.
		 */

		var parentContainer = $(this).parents();
			//console.log(parentContainer);
		var parentId = $(this).parents("div").attr("id");
			//console.log(parentId);

		if ( parentId !== "tabGallery" ) {

			$(".galleryList").activateCcf({childContainer: 'li', className: 'lastCol'});
		}

	});
	
	$("#articleList, #homeListings, #servicesColumns").activateCcf({childContainer: 'li', className: 'lastCol', firstInRow: 'firstInRow'});

	$("#servicesColumns").activateCcf({childContainer: 'div', className: 'lastCol', firstInRow: 'firstInRow'});
	
	$("div.countColumns").each( function() {

		/**
		 * The child container varies, so this finds it & makes it the
		 * varible 'myChild'
		 */

		var myChild = $(this).children();
		$("div.countColumns").activateCcf({childContainer: myChild, className: 'lastCol', firstInRow: 'firstInRow'});
	});
	

/**
 * 14c - Find last column in row
 * ---------------------------------------------------------------------------
 * Currently used for #tabGallery ul.galleryList only.
 * Test before using on anything else.
 * @since Portfolio Theme 3
 */

	$.fn.lastInGallery = function(options) {

	var defaults = { childContainer: 'li', className: 'nothing' };
	// Set up default options

	var options = $.extend({}, defaults, options);
	// Overwrite defaults with options, or combine them

	return this.each(function() {
	
		$.fn.lastClass = function() {
			var container = (this);

			$(container).each(function() {
				var pageWidth = $(window).width();
				var thisID = $(container).attr("id");

				/**
				 * If it's the category-work.php sticky posts loop
				 */
	
				if ( thisID == "latestProject" ) {
					if ( pageWidth > 1023 ) {
						var lastCol = $(this).find("li:nth-child(3n+4)");
						} else if ( pageWidth > 767 ) {
							var lastCol = $(this).find("li:nth-child(2n+3)");
					} //if
				} // if

				/**
				 * For all the other occurences of .galleryList in the category-work.php template
				 * Annoying to have to refresh 'thisID'
				 */

				var thisID = $(container).attr("id");

				if ( thisID == null ) {
					if ( pageWidth > 1023 ) {
						var lastCol = $(this).find("li:nth-child(3n+3)");
						} else if ( pageWidth > 767 ) {
							var lastCol = $(this).find("li:nth-child(2n+2)");
					} // if
				} // if (null)

				/**
				 * Apply the values set above
				 */

				$(lastCol).each(function() {
					$(this).addClass(options.className);
				});
			}); // container each
		}; // lastClass

		/**
		 * Run the above function
		 */

		var container = (this);
		$(container).lastClass();

		$(window).resize(function() {

			/**
			 * Do things when the browser window is resized
			 */

			$(container).find("li").removeClass(options.className);
			// Remove all the classes

			$(container).lastClass();
			// Add classes again in the correct locations

		}); // window resize function

	});  // each

}; // lastInGallery

	$("#tabGallery ul.galleryList").lastInGallery({childContainer: 'li', className: 'lastCol'});

/**
 * 14d - Shrink blog images
 * ---------------------------------------------------------------------------
 * Images placed directly into content currently get a fixed width, for
 * example http://creativeglo.dev/blog/email-design/outlook-unwanted-paragraph-break-bug/
 * This removed the dimensions for tablet size and below.
 * A style is then used to set the width to 100%
 * @since Portfolio Theme 3
 */

$("img").each( function() {
	if ( $(this).hasClass("size-full") ) {
		var pageWidth = $(window).width();
	
		if ( pageWidth < 1024 ) {
			$(this).removeAttr("height").removeAttr("width");
		}
	
		$(window).resize(function() {
			if ( pageWidth < 768 ) {
				$(this).removeAttr("height").removeAttr("width");
			}
		});
	}
});

//	close document ready function

});
