/**
 * Common JS for HBF
 */
$(document).ready(function(){

	// Init Hbf.Navigation
	new Hbf.Navigation();

	// Init Hbf.MoreInformation
	new Hbf.MoreInformation();

	// Init Text Resizer
	new Hbf.TextResizer();

	// Hint
	$("li.search form input#keywords").hint();

	// Print
	$('li.print').click(
		function()
		{
			window.print();
		}
	);
	
	// Product Selector Hover
	Hbf.ProductSelectorQuestionOverlay('/include/product_selector_questions.html');

	$('div.modules').equalHeights();

	// Init Hbf.ScrollTo
	new Hbf.ScrollTo();

	// IE table column fixes
	$('table tr > :nth-child(even)').addClass('even');

	// Tag cloud
	$('#cloud').tagcloud({type: 'list', sizemin: 12, sizemax: 24, colormin: '999999', colormax: '333333'});

	// Mix the tag cloud up a bit
	$('#cloud li').each(
		function()
		{
			// Get some random numbers
			var rand1 = Math.floor(Math.random()*4);
			var rand2 = Math.floor(Math.random()*6);

			$(this).css('margin-top', rand1 + 'px').css('margin-left', rand2 + 'px');
		}
	);
	
	// Init Video
	new Hbf.Video();
	
	// Assign the Tooltips
	$('table#coverDetailsTable td[title]').hover(function()
	{
		$(this).css({'cursor': 'pointer'});
	},
	function()
	{
		$(this).css({'cursor': 'auto'});
	});
	
	$('table#coverDetailsTable td[title]').tooltip(
	{
		showURL: false,
		showBody: "-",
		track: true,
		top: -14,
		left: 25
	});
	
	$('#tooltip').append('<div class="arrow"></div>');
  
  /*  Sym - Fix to allow popular links to be clickable anywhere within the blue box*/
    $('div.popularLinks ul li').each(function(){
	 $(this).click(function(){
	 window.open($(this).find("a").attr("href"),$(this).find("a").attr("target"));
	});
});

});

/**
 * HBF Navigation object
 *
 */
Hbf.Navigation = function()
{
	/**
	 * @var object mainNavLi
	 */
	var mainNavLi = $('div#mainNav > ul > li');

	/**
	 * @var int maxItemsPerColumn
	 */
	var maxItemsPerColumn = 10;

	/**
	 * Init
	 */
	function init()
	{
		// Remove nav class from li
		mainNavLi.removeClass('nav');

		// Reposition the secondNav
		// --- disable to prevent drop down menu wrapping --- repositionSecondNav();

		// Restructure the thirdNav into multiple columns
		restructureThirdNav();

		// Bind hover event to the top level nav items
		mainNavLi.hover(
			function()
			{
				var secondNav = $(this).children('.secondNav');

				var origHeight = secondNav.outerHeight();

				if( secondNav.is(':hidden') )
				{
					secondNav.css('height', '0px');
					secondNav.animate({
						height: origHeight
					},{
						step: function()
						{
							secondNav.boxShadow(0, 5, 5, '#BBBBBB');
						},
						complete: function()
						{
							secondNav.boxShadow(0, 5, 5, '#BBBBBB');
						},
						specialEasing:'easeOutExpo',
						duration: 400
					});
				}
			},
			function()
			{
				var secondNav = $(this).children('.secondNav');

				secondNav.stop(true, true).fadeOut(200);
				secondNav.boxShadow('hide');
			}
		);
	}

	/**
	 * Restructure the third navigation to ensure that it is seperated
	 * evenly across 2 columns.
	 * Only if there are more than 'maxItemsPerColumn' items in the list
	 */
	function repositionSecondNav()
	{
		// Reposition all of the secondary nav elements
		mainNavLi.each(function(i, value)
		{
			var secondNav = $(value).children('.secondNav');

			if( secondNav.length > 0 )
			{
				var position = secondNav.position();
				if( position.left + $(value).position().left + secondNav.width() > $('div#top').width() )
				{
					secondNav.css({'left': 'auto', 'right': '-10px'});
				}
			}
		});
	}

	/**
	 * Restructure the third navigation to ensure that it is seperated
	 * evenly across 2 columns.
	 * Only if there are more than 'maxItemsPerColumn' items in the list
	 */
	function restructureThirdNav()
	{
		// Iterate
		mainNavLi.find('div.children ul.thirdNav').each(function(i, value)
		{
			// Get a list of all li's in the current thirdnav
			items = $(value).find('li');

			if( items.length > maxItemsPerColumn )
			{
				// Get the middle point then get the 2nd parent
				// The second parent is the Li that sits directly underneath the thirdnav
				var middlePoint = items.eq(Math.floor(items.length / 2)).parent().parent();

				// Create newNavUl
				var newNavUl = $('<ul class="thirdNav"></ul>');

				// Get a list of all elements after the middle point and append
				newNavUl.append(middlePoint.nextAll());

				// Append to current thirdNav
				$(value).after(newNavUl);
			}

		});
	}

	// Init
	init();
};

/**
 * HBF ScrollTo object
 *
 */
Hbf.ScrollTo = function()
{
	// Find all the links on the page that have anchors
	$('a[href^=#]').each(function(i, value){

		var link = $(value);
		var href = link.attr('href');

		if( '#' != href )
		{
			link.click(function(event){

				$.scrollTo(href, 500);

				event.preventDefault();
			});
		}

	});
}

/**
 * HBF Text resizer object
 *
 */
Hbf.TextResizer = function()
{
	// Definition of the three sizes
	var fontSize = {
		small: "0.75em",
		medium: "1em",
		large: "1.15em"
	};

	// Font resizer
	function resizeText( fontSize )
	{
		//$('body').css('font-size', fontSize);
		$('#mainContent, div#header, div#footer div.siteLinks, div#footer div.articles, div#footer div.popular h6, div#footer div.deep, div#footer p.top, div#sidebar div.module, div.rightBar, div.navBoxes, div.imageLinks, div.lowerBox, div.footerContainer').css('font-size', fontSize);
		$.cookie('fontSize', fontSize, { expires: 7 });
	}

	function init()
	{
		if($.cookie('fontSize'))
		{
			resizeText($.cookie('fontSize'));
		}
		
		// Text sizing
		$('.textSize span.normal').click(function() { resizeText(fontSize.small); });
		$('.textSize span.larger').click(function() { resizeText(fontSize.medium); });
		$('.textSize span.largest').click(function() { resizeText(fontSize.large); });
	}

	init();
}

/**
 * HBF IE6 object
 *
 */
Hbf.IE6 = function()
{
	// Add first class to deep links
	$('div.deep li:first-child').addClass('first');

}

/**
 * ------------------------------------
 * Onload Functions
 * ------------------------------------
 *
 */

/*
 * Nice helper javascript to enable you to make some javascript commands any where
 * in your script and call them once the page has loaded. To use, simply call
 * onLoad.push() to add a function as an event:
 *
 * Pass in a function to be run
 * onLoad.push(my_onload_function);
 *
 * Note that onLoad.push() is called with the function itself, not the result of
 * calling the function!
 *
 * You also pass a string to be evaluated if your function requires parameters:
 * onLoad.push("function_call('one', 2)");
 *
 * but consider using an anonymous function instead, as this will give you more
 * immediate feedback on syntax errors:
 * onLoad.push(function() { function_call('one', 2); });
 *
*/

/* GCT - Re- introduced to get Mu Ad banners served */

function OnloadRunner()
{
	this.push = function( item )
	{
		var fun = this.wrapFunction(item);

		if( typeof window.addEventListener != 'undefined' )
		{
			// standards compliant browsers
			window.addEventListener('load', fun, false);
		}
		else if( typeof document.addEventListener != 'undefined' )
		{
			// opera 7
			document.addEventListener('load', fun, false);
		}
		else if( typeof window.attachEvent != 'undefined' )
		{
			// win/ie
			window.attachEvent('onload', fun);
		}
		else
		{
			//.. mac/ie5 and anything else that gets this far
			if( typeof window.onload == 'function' )
			{
				var existing = window.onload;

				window.onload = function()
				{
					existing();

					fun();
				}
			}
			else
			{
				window.onload = fun;
			}
		}
	}

	/*
	 * Wrap a function (or string to be evaluated) in a try/catch.
	 */
	this.wrapFunction = function( func_or_string )
	{
		return function()
		{
			try
			{
				if( typeof func_or_string == 'function' )
				{
					func_or_string();
				}
				else
				{
					eval(func_or_string);
				}
			}
			catch( ex )
			{
				alert("nload Failed: " + func_or_string + "\nError Message:" + ex.message + "\non line " + ex.lineNumber + " in file " + ex.fileName);
			}
		}
	}
}



function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";

  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}
  

function checkCookie() {  

  var x = readCookie('hbfSurveyCookie');

  if (x) {

    return true;
  } else {


    return false;
  }
}


var onLoad = new OnloadRunner();

window.onunload = unloadPage;
 
function unloadPage()
{

   // range from 0 to 99, so 5 percent of the random number
   if (Math.floor(Math.random()*100) < 5) {

     if (checkCookie() == false) {

       // create a survey cookie that will be expired in 6 months (30 x 6)
       createCookie('hbfSurveyCookie','hbfSurvey', 180)


       var answer = confirm("Please help us make HBF.com better and rate this site by clicking OK or selecting Cancel to continue.");
       if (answer) {         
         window.open("http://survey.marketresearch.com.au/hbf_customer_experienceh/hbf_customer_experienceh.htm");
       }

     }
   }

}


