// FireBug Protection
try { console.log('init console...'); } catch(e) { console = { log: function() {} } }

jQuery(document).ready(function() {
	
	if($('.page-home').length > 0) {
		//init_showcase_slider();
		init_feature_slideshow();
	}
	if($('.page-logbook').length > 0) {
		init_comment_helpers();
	}
	if($('#comment_form').length > 0) {
		comment_form_fix();
	}
	if($('#comment-preview').length > 0) {
		$.scrollTo('#comment-preview');
	}
	init_newsletter_signup_toggle();
	init_clocks();
	init_attention_spans(5);
	/*
	
	init_ethos();
	
	init_external_links();
	*/
	$('.showcase-item.soon').each( function () {
		
		$(this).css('opacity', .4)
		
	})
});

/* ***************************************************************************************************************************
	SIFR
*/

function init_sifr () {
		if(typeof sIFR == "function"){
		    var template = named({sFlashSrc : "/flash/font_gotham_light.swf", sColor : "#d4a037", sCase : "title", sWmode: "transparent"});
		    sIFR.replaceElement(".feature-copy-text h3", template);
		};
}

function init_sifr3() {
	
	var gotham_thin 	= {	src: '/flash/font_gotham_thin_sifr3.swf' 		};
	var gotham_light 	= { src: '/flash/font_gotham_light_sifr3.swf' 	};
	var gotham_medium = {	src: '/flash/font_gotham_medium_sifr3.swf' 	};

  sIFR.activate(gotham_thin, gotham_light, gotham_medium);

  sIFR.replace(gotham_light, {
    selector	: 	'.feature-copy-text h3',
    css				: 	[ '.sIFR-root { color: #d4a037; }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_light, {
    selector	: 	'.showcase-item h3',
    css				: 	[ '.sIFR-root { color: #888; }', 'a {color: #888; text-decoration: none;}', 'a:hover {color: #888; text-decoration: underline;}' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_medium, {
    selector	: 	'.home-bottom h2',
    css				: 	[ '.sIFR-root { color: #242424; text-transform: uppercase }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_light, {
    selector	: 	'.showcase-overview-title',
    css				: 	[ '.sIFR-root { color: #242424; }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_thin, {
    selector	: 	'.page-head h2',
    css				: 	[ '.sIFR-root { color: #8c8a89; }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_light, {
    selector	: 	'.side-head h3',
    css				: 	[ '.sIFR-root { color: #242424; }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_light, {
    selector	: 	'.page-information h3',
    css				: 	[ '.sIFR-root { color: #242424; }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_light, {
    selector	: 	'.side-h3 h3',
    css				: 	[ '.sIFR-root { color: #242424; }' ],
		wmode 		:		'transparent'
	});
	
	sIFR.replace(gotham_medium, {
    selector	: 	'.comments h3',
    css				: 	[ '.sIFR-root { color: #242424; text-transform: uppercase }' ],
		wmode 		:		'transparent'
	});
}
// sIFR has it's own internal DOM loading handlers. 
// It bugs out when being called within jQuery's (document).ready();
init_sifr3();

/*
function init_feature_cycle() {
	
$('.feature-items').cycle({ 
		fx						: 'fade', 
		speed					: 500, 
		timeout 			: 0,     
		//timeout 		: 4000, 
		next					: '#feature-next', 
		prev					: '#feature-prev', 
		cleartypeNoBg	: true,
		after					: function() { init_sifr3(); }
	});
}
*/
/* ***************************************************************************************************************************
	Clock
*/

function init_clocks() {
	var params = 		{ menu: 'false', allowscriptaccess: 'always', allowfullscreen: 'true', wmode: 'transparent' };
	var attributes = 	{  };
	var flashvars = 	{  };
	swfobject.embedSWF("/flash/timers.swf", "timer-flash", "228", "83", "8.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
}

/* ***************************************************************************************************************************
	Ethos Cycle
*/

function init_ethos() {
	
 	var $old = $("#ethos-cycle").html(); 

	$("#ethos-cycle").load('/home/ajax_snippets/',function(){    
    $(this).prepend($old);
		init_ethos_cycle();
	});     
	
}

function init_ethos_cycle() {
	$('#ethos-cycle').cycle({ 
		fx				: 'fade', 
		cleartypeNoBg	: true,
		after			: onAfter,
		sync     	: 0
	});
	
	function onAfter() { 
		$('#ethos-cycle').cycle('pause');
	}	
}

function getFlashMovie(movieName) {   
	var isIE = navigator.appName.indexOf("Microsoft") != -1;   
	return (isIE) ? window[movieName] : document[movieName];
}  
function formSend() {   
	var text = document.htmlForm.sendField.value;   
	getFlashMovie("ExternalInterfaceExample").sendTextToFlash(text);
}
function cycle10secs(str) { 
	$('#ethos-cycle').cycle('next');
}

/* ***************************************************************************************************************************
	Attention Span
*/
var total_count57;
var count57 = 0;
function init_attention_spans(num) {
	
	total_count57 = num;
	
	var $old = $("#attention-span").html(); 

	$("#attention-span").load('/home/ajax_attention_spans/'+num+'/',function(){    
    $(this).prepend($old);
		init_attention_span_cycle(num);
	});	
}
function init_attention_span_cycle(num) {
	$('#attention-span').cycle({ 
		fx				: 'fade', 
		cleartypeNoBg	: true,
		after			: onAfter,
		sync     	: 0
	});
	
	function onAfter() { 
		$('#attention-span').effect("pulsate", { times: 4 }, 500);
		$('#attention-span').cycle('pause');
	}	
}
function cycle57secs(str) { 
	if (count57 < total_count57) {
		$('#attention-span').cycle('next');
		count57++;
	}
}

/* ***************************************************************************************************************************
	Feature Slideshow
*/
function init_feature_slideshow() {
	
	
	
	$('.feature-items')
	.before('<div id="feature-nav">')
	.cycle({ 
	    fx:     'scrollLeft', 
	    speed:  450, 
	    timeout: 4000, 
	    pager:  '#feature-nav' 
	});
	
	/*
	var featClass = $('#feature-cycle').attr('className');
	
	var index = featClass.substring(featClass.indexOf('feature-count'), featClass.length).split('-')[2];
	
	$('#feature-cycle').ajaxcycle({ 
			total	: index,
			next	: $('#feature-next'),
			prev	: $('#feature-prev'),
			loader : $('#feature-loader'),
			queryUrl : '/home/ajax_feature_panel'
	});
	*/
	
}




/* ***************************************************************************************************************************
	Showcase Slider
*/
function init_showcase_slider() {
	
	var speed = 600;
	var elementHeight = 230;
	var countElements = $('.showcase-items .showcase-item');
	var numberElements = countElements.length;
	var totalHeight = numberElements * elementHeight;
	var containerHeight = $('.showcase-items').height();
	var currentPlace = elementHeight * 3;
	var currentDifference = 0;
	
	$('#showcase-up').addClass('disabled'); // default
	
	$('#showcase-down').click(function(event) {
		$('#showcase-down').addClass('disabled');
		$('#showcase-up').removeClass('disabled');
		event.preventDefault();
		
		if (currentPlace >= totalHeight) { 
		} else {
			currentPlace += elementHeight;
			currentDifference += elementHeight; 
			$("#showcase-items-move").animate({ top: 0-containerHeight + 'px'}, speed );
		}	
	});

	$('#showcase-up').click(function(event) {
		$('#showcase-down').removeClass('disabled');
		$('#showcase-up').addClass('disabled');
		event.preventDefault();

		if (currentPlace <= containerHeight) { 
		} else { // Ellers, continue!
			currentPlace -= elementHeight;
			currentDifference -= elementHeight; 
			$("#showcase-items-move").animate({ top: 0 + 'px'}, speed );
		}	
	});
}
/* ***************************************************************************************************************************
	Comment Helpers
*/
function init_comment_helpers() {
	
	$('#insert-link').click(function(event) {
		addPTag(document.getElementById('comment-textarea'),'[' , '](http://www.zhc.com.au/)', 'link text');
		return false;
	});
	
	$('#insert-em').click(function(event) {
		addPTag(document.getElementById('comment-textarea'),'*' , '*', 'emphasised text');
		return false;
	});
	
	$('#insert-strong').click(function(event) {
		addPTag(document.getElementById('comment-textarea'),'**', '**', 'bold text');
		return false;
	});
}

function getSelection(ta)
  { var bits = [ta.value,'','','']; 
    if(document.selection)
      { var vs = '#$%^%$#';
        var tr=document.selection.createRange()
        if(tr.parentElement()!=ta) return null;
        bits[2] = tr.text;
        tr.text = vs;
        fb = ta.value.split(vs);
        tr.moveStart('character',-vs.length);
        tr.text = bits[2];
        bits[1] = fb[0];
        bits[3] = fb[1];
      }
    else
      { if(ta.selectionStart == ta.selectionEnd) return null;
        bits=(new RegExp('([\x00-\xff]{'+ta.selectionStart+'})([\x00-\xff]{'+(ta.selectionEnd - ta.selectionStart)+'})([\x00-\xff]*)')).exec(ta.value);
      }
     return bits;
  }

function matchPTags(str)
  { str = ' ' + str + ' ';
    ot = str.split(/\[[B|U|I].*?\]/i);
    ct = str.split(/\[\/[B|U|I].*?\]/i);
    return ot.length==ct.length;
  }

function addPTag(ta, openTag, closeTag, str) { 
		bits = getSelection(ta);
    if(bits) { 
			if(!matchPTags(bits[2])) { 
					alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
      }
      ta.value = bits[1] + openTag + bits[2] + closeTag + bits[3];
		} else {
			$(ta).val($(ta).val() + ' ' + openTag + str + closeTag);
		}
		ta.focus();
}
/* ***************************************************************************************************************************
	Vimeos
*/
function init_vimeos() {
	var params = 		{ menu: 'false', allowscriptaccess: 'always', allowfullscreen: 'true', wmode: 'transparent' };
	var attributes = 	{  };
	var flashvars = 	{  };
	swfobject.embedSWF("/flash/timers.swf", "timer-flash", "108", "100", "8.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
}

/* ***************************************************************************************************************************
	Comment Form IE 6 fix
*/
function comment_form_fix () {
	//el = document.getElementById('comment_form')
	//el.setAttribute('name', 'comment_form');
}

/* ***************************************************************************************************************************
	Newsletter Signup Toggle
*/
function init_newsletter_signup_toggle() {
	
	$('#in-the-fold-toggle').click(function(event) {
		if ($("#in-the-fold:visible").length > 0) {
			$("#in-the-fold").slideUp();
		} else {
			$("#in-the-fold").slideDown();
		}
		return false;
	});
	
}

/* ***************************************************************************************************************************
	Fix External Links
*/
function init_external_links() {
	// Creating custom :external selector
	$.expr[':'].external = function(obj){
	    return !obj.href.match(/^http:\/\/\:/) && (obj.hostname != location.hostname);
	};

	// Add 'external' CSS class to all external links
	$('a:external').addClass('external');
}






