/**
 * Legal Practice Board of Western Australia
 * General Script File
 *
 * @uses jQuery
 * @copyright Legal Practice Board of Western Australia <http://www.lpbwa.org.au>
 * @author Itomic <http://itomic.com.au>
 * @developer Guy Park <guy@itomic.com>
 * @version 1.0
 */
jQuery().ready(function() {
	jQuery.ajaxSetup({ beforeSend: function(xmlreq) { xmlreq.setRequestHeader("Accept", "text/xml"); } });

	// Menu/Navigation Coolness
	jQuery('#nav ul ul').css('opacity', 0.7);
	jQuery('#topNav ul').superfish(LPBWA.opts.superfish);
	
	// Put in a cool fading effect
	/*jQuery('#division-nav a').bind('mouseover', function() { 
		jQuery(this).fadeTo(200, 0.3, function() { 
			jQuery(this).fadeTo(200, 1); 
		});
	});*/
	
	/*jQuery('ul.tabs').localScroll({
		target: 'div.tabs', // could be a selector or a jQuery object too.
		queue:true,
		duration:1000
	});*/
	
	// Make any anchors hashed to the search field box (#searchfield) do this instead
	jQuery('a[href=#searchfield]').bind('click', function() { LPBWA.focusSearchField(); return false; });

	// Give very low divisional nav an expand/collapse feature
	jQuery('.column .nav ul a').each(function() {
		// If this link has no subnav, forget it
		if (!jQuery(this).siblings('ul').length) return;
		
		// If we're here, then we have a sub nav, add a toggle thingy
		var toggler = jQuery('<span class="toggler"><span></span></span>');
		jQuery(this).prepend(toggler);
		toggler.bind('click', function() {
			jQuery(this).parent().siblings('ul').slideToggle();
			jQuery(this).parent().toggleClass('collapse');
			return false;
		});
		
		// Open and levels we have open
		if (jQuery(this).siblings('ul[class="open"]')) jQuery(this).toggleClass('collapse');
	}).siblings('ul[class!="open"]').hide();
	
	// Auto Complete
	jQuery('form.search input#searchfield')
		.autocomplete(jQuery('form.search').get(0).action, jQuery.extend({formatItem: LPBWA.formatSearchItem},LPBWA.opts.autoComplete))
		//.bt(jQuery.extend({}, LPBWA.opts.beautyTip, LPBWA.opts.searchBoxTip))
		.bind('keydown', function() { jQuery(this).btOff(); });
	
	// Auto Complete - Practitioner Search Only
	jQuery('input#practitionersearch').each(function() {
		jQuery(this)
			.autocomplete(jQuery(this).get(0).form.action, jQuery.extend({formatItem: LPBWA.formatSearchItem}, LPBWA.opts.autoComplete, LPBWA.opts.autoCompletePactitioner))
			.bt(jQuery.extend({}, LPBWA.opts.beautyTip, LPBWA.opts.searchBoxTip));
	});
		
	//jQuery('acronym[title]').simpletip({ fixed: false });
	var borderColor = jQuery().cssRule('.tooltip .content','borderColor').split(' rgb')[0];
	var borderRadius = (jQuery().cssRule('.tooltip','MozBorderRadius').replace(/px.*$/,'')*1)
	
	/* Removed for copyright reasons on SimpleTip-2.0
	var contentText = '';
	var splitter = null;
	jQuery('acronym[title]').each(function() {
		contentText = jQuery(this).attr('title');
		var titleText = false;
		if (contentText.match(' :: ')) {
			var splitter = contentText.split(' :: ')[0];
			titleText = { content: splitter };
			contentText = contentText.replace(/^.* :: /, '');
		}
		
		jQuery(this).simpletip(contentText, {
			title: titleText,
			hook: { tooltip: 'bottomMiddle', target: 'topMiddle' }, 
			stem: { corner: 'bottomMiddle', color: borderColor }, 
			//parentClass: 'tooltip-light' ,
			viewport: true, 
			border: { size: 5, radius: borderRadius, color: borderColor }
		}).attr('title','');
	});*/
	jQuery('.contentarea [title]').each(function() {
		// Turn title="Title :: Content" ... into a formatted ... title="<h2>Title</h2>Content";
		var content = jQuery(this).attr('title');
		var title = false;
		if (content.match(' :: ')) {
			title = content.split(' :: ')[0];
			jQuery(this).attr('title', "<h2>"+title+"</h2>" + content.replace(/^.* :: /, ''));
		}
	}).bt(LPBWA.opts.beautyTip);
	
	// Downloadable forms wrap-up (accordion)
	jQuery('div.downloadforms').accordion({
		autoheight: true,
		alwaysOpen: false,
		header: 'h2'
	});
	
	// Activate any tag clouds
	jQuery.tagcloud.defaults.height = 150;
	jQuery('ul.tag-cloud').tagcloud(LPBWA.opts.tagCloud);
	
	// Convert external links to do external stuff, like open in new windows and classed
	jQuery('a[href^=http://]').each(function() {
		if (!jQuery(this).attr('href').match(/^http:\/\/[^\.]+\.lpbwa.org.au/) && !jQuery(this).attr('href').match(/^http:\/\/[^\.]+\.lpbwa.itomicpowered.com/)) {
			jQuery(this).addClass('external');
			jQuery(this).attr('target', '_blank');
		}
	});
});

var LPBWA = {
	formatSearchItem: function(data, i, total) {
		var content = data.firstChild.textContent;;
		
		var link = data.getElementsByTagName('link');
		var icon = data.getElementsByTagName('media:thumbnail');
		var desc = data.getElementsByTagName('description');
		var iconURL = '';
		
		if (link.length) {
			content = '<a href="' + link[0].textContent + '" onclick="window.location.href = this.href" title="click here to go to this page...">' + content + "</a>";
		}
		if (icon[0].getAttribute('url') != '') {
			iconURL = icon[0].getAttribute('url');
			//content = '<img src="'+icon[0].getAttribute('url')+'" width="16" height="16" /> '+content;
		}
		if (desc.length) {
			content += '<br /><p>'+ desc[0].textContent +'</p>';
		}
		
		return '<div class="item" style="background-image: url('+iconURL+')">'+content+"</div>";
	},
	
	/**
	 * This will focus on the search field
	 * @return boolean
	 */
	focusSearchField: function() {
		jQuery().scrollTo(jQuery('#searchfield'), 1000, {
			offset:-50,
			onAfter: function() {
				// TODO :: Update the animage to use the animateToClass, as this will remove the need for presentation in 
				//			js, and leave it to the CSS file... cleaner
				
				//var oldColor = jQuery('#searchfield').style.backgroundColor;
				//var 
				//jQuery('#searchfield').animateToClass('focused', 500).animateToClass('',500);
				jQuery('#searchfield').focus().select().animate({backgroundColor:'#efff7a'}, 500, function() {
					jQuery(this).animate({backgroundColor: '#ffffff'},500);
				});
			}
		});
		return true;
	},
	
	opts: {
		superfish: {
			animation:   {opacity:'show',height:'show'},
			'autoArrows':false
		},
		beautyTip: {
			fill: jQuery().cssRule('.bt-content-style','backgroundColor').replace(/\)$/im, ', 0.95)').replace(/^rgb/im,'rgba'),
			strokeStyle: jQuery().cssRule('.bt-content-style','borderColor').split(' rgb')[0],
			spikeLength: 10, 
			spikeGirth: 10,
			strokeWidth: 3,
			distance: 10,
			interval: 300,
			padding: 10,
			distance: 0,
			animate: true,
			shadow: true,
		    shadowOffsetX: 0,
		    shadowOffsetY: 0,
		    shadowBlur: 8,
		    shadowColor: 'rgba(0,0,0,.9)',
		    shadowOverlap: false,
		    noShadowOpts: {strokeStyle: '#999', strokeWidth: 2},
		    trigger: ['focus', 'blur']
		},
		searchBoxTip: {
			trigger: 'click', 
			positions: ['bottom'], 
			timeout: 300,
			interval: 300
		},
		autoComplete: {
			minChars: 3,
			cacheLength: 10,
			matchContains: true,
			extraParams: { 'ajax': true },
			/*formatResult: function(data, i, total) { alert(data); },*/
			highlight: false,
			width: 300
		},
		autoCompletePactitioner: {  // Cannot merge for some reason
			extraParams: { 'ajax': true, 'type': 'practitioner' }
		},
		tagCloud: {type:"sphere",sizemin:8,sizemax:14,power:.3}
		/*tagCloud: {type:"list",sizemin:8}*/
	}
}
