// global javascript

$(document).ready(
	function(){
		
		//set up header navs 
		$('ul#headerDropdown > li').hover(
				function() {
					$(this).addClass('topLevelHover');
					$(this).children('.menuBox').show(0);
				},
				function() {
					$(this).removeClass('topLevelHover');
					$(this).children('.menuBox').hide(0);	
				}
		);
		
		// blur clicks
		$('a').click(function() {this.blur();});
		$('button').click(function() {this.blur();});

		// setup the drop down functionality on our "extra" buttons
		$('.lnkExtraDropdown').click(
			function(){
				// close any open boxes
				$('.extraDropdownActive').not($(this).next('.extraDropdown')).removeClass('extraDropdownActive');
				
				// now toggle it
				$(this).next('.extraDropdown').css('left',$(this).position().left+1);
				$(this).next('.extraDropdown').toggleClass('extraDropdownActive');
				return false;
			}
		);
		
		// setup the drop down functionality on our "extra" buttons
		$('.lnkExtraDropdown').mouseover(
			function(){
				// close any open boxes
				$('.extraDropdownActive').not($(this).next('.extraDropdown')).removeClass('extraDropdownActive');
				
				// now toggle it
				$(this).next('.extraDropdown').css('left',$(this).position().left+1);
				$(this).next('.extraDropdown').toggleClass('extraDropdownActive');
				return false;
			}
		);		
		
		// make sure a click outside will hide the dropdown
		$('body').click(
			function() { $('.extraDropdownActive').removeClass('extraDropdownActive'); }
		)
		
		// make sure on mouseout will hide the dropdown
		$('.lnkExtraDropdown').mouseout(
			function() {setTimeout('$(\'.extraDropdownActive\').removeClass(\'extraDropdownActive\')',2000); }
		)		

		// clear text inputs on click (or to reset on blur if they didn't enter anything)
		$('.searchBox').each( function(){
				$(this).attr('orgValue',$(this).val());
				$(this).focus( function() {
					if (($(this).val() == $(this).attr('orgValue')) && ($(this).val() == 'Search' || $(this).val() == 'Sign up now!') ){ $(this).val(''); }
 			    });
				$(this).blur( function() {
					if ($(this).val() == ''){ $(this).val($(this).attr('orgValue')); }
 			    });
				
			}
		  );
		
		/* add red arrows to all author_links
		 * AND make sure that there is no line break between the arrow and the link
		 * AND expect random tags (e.g. <i>) inside the links
		 * AND make sure you can handle multi line links
		 */
		authorlinks = $('.author_link')
		for(i = 0; i < authorlinks.length; i++) {
			
			e = authorlinks[i].lastChild.tagName == 'I' ? authorlinks[i].lastChild : authorlinks[i];
			words = e.innerHTML.split(' ')
			
			$(e).empty().append(
				words.slice(0, words.length - 1).join(' ') +
				' <span style="white-space:nowrap">' + words[words.length - 1] + 
				'<img style="float:none;position:relative;top:6px;left:2px" src="/imgs/global/bulletRedRightArrow.gif"/></span>')
		}

		// fix png transparency in IE
		$('img[@src$=.png]').ifixpng();

})

//////////////////////
// FUNCTIONS
/////////////////////

function balanceColumnsWithFooter(balanceList,debug) {
	// by Martin Olson (molson@hugeinc.com)
	// 
	// ARGUMENTS:
	// balanceList - a comma delimited list of CSS IDs to balance
	//
	// WHAT IT DOES:
	// balances columns by adding spave above the last child item for each column,
	// allowing the footer (or just an empty div)to stay at the bottom
	//
	// REQUIRES:
	// jQuery
	// jQuery dimensions plugin
			
	balanceList = balanceList.split(",");	
	var cols = new Array();
	var maxheight = 0;
	
	// get the maximum height and the measurement for each column	
	for (x in balanceList)
	{
	    //SG - added check to see div is available 
	    //otherwise js error was been thrown
	    if ($(balanceList[x])[0])
	    {
		    cols[x] 		= new Array();
		    cols[x].height	= $(balanceList[x]).position().top + $(balanceList[x]).outerHeight();
		    cols[x].id		= balanceList[x];
    		
		    // see if this is the maximum height
		    maxheight = Math.max(cols[x].height,maxheight);
    		
		    if  (debug) {
			    //console.log(maxheight, cols[x].height);	
		    }
		}
	}

	// go through the cols and add spacing above the last child item where required
	for(x in cols) {
		if (cols[x].height < maxheight){
			$(cols[x].id).children(':last-child').not(".clear").css("margin-top",maxheight-cols[x].height);
		}			
	}
}


function truncateCopyToParent(selector,charsPerLine,extraPx) {
		// truncate copy to fit, if needed
		// requires jquery Dimensions plugin
		
		extraPx = (!extraPx) ? 0 : extraPx;
	
		$(selector).each( function() {
			parentHeight	= $(this).parent().parent().height();
			textStart		= $(this).offset({ margin: false }).top - $(this).parent().parent().offset().top;
			visiblePart		= parentHeight - textStart - extraPx ;
			lineHeight		= $(this).css('line-height');
			lineHeight		= lineHeight.replace('px','');
			linesToShow		= Math.floor(visiblePart/lineHeight);
			$(this).truncate(linesToShow*charsPerLine);
		});
}


/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * with another plugin
 * Version 1.9  (27/09/2007)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 
 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
 
(function($) {
	
	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/imgs/global/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var base = $('base').attr('href'); // need to use this in case you are using rewriting urls
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').substring(0,1)!='/') ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().positionFix();
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);