/*global jQuery document window */
/*
	
	The Confederated Tribes of Grand Ronde Javascript Functions
	Auhthor: ISITE Design

*/

// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict(); 

var ix_vars = ix_vars ? ix_vars : {};

ix_vars = {
	flashAssetPath: 'http://' + window.location.host + '/_resources/flash/',
	defaultFlashPlayer: 'videoPlayer.swf',
	defaultFlashPlayerSkin: 'gr_skin.swf',
	defaultFlashPlayerHeight: 340,
	defaultFlashPlayerWidth: 600,
	defaultFlashPlayerControlsHeight: 38,
	defaultGRLat: 45.0754150,
    defaultGRLong: -123.6175420

};


// jQuery document ready
jQuery(function ($) {

	// JS enabled
	$('html').addClass('js');
	
	// Few setups for IE6
	if (document.all) {
		//add class to drop downs and buttons 
	    $('#nav li, button').hover(
			function () { $(this).addClass('over'); },
			function () { $(this).removeClass('over'); }
	    );
	}// if document.all
	
	$('.input-setter').inputSetter();
	
	$('.tabs').IX_tabs();
	$('.list-departments').enableTree();
	$('#gallery').videoGallery();
	
	$('a.media').videoLightbox('lightbox=true');
	
	$('a.movie').swfObjSetup();
	
	$('.main-calendar .event-item a').calendarTips();
	
	$('.aside a').bnsp();
	
	$('.location').buildGoogleMap();
	
	/* development convenience.  append query fed=1 to url to see a layout grid overlayed on page */
	if (window.location.search.match(/fed=1/)) {
		var $g = $('<div id="grid"></div>'),
			$b = $('body');
		$g.height($b.height());
		$b.append($g);
	} else { return false; }

});// document ready


// application logic


// jQuery plugins


jQuery.fn.videoGallery = function () {
	var context = jQuery(this),
		thumbnails = jQuery('#gallery-thumbnails a:not(.action)', this),
		buttons = jQuery('#gallery-thumbnails a.action', this),
		gallerywrapper = jQuery(jQuery.fn.videoGallery.templates.wrapper),
		scrollstop, thumbstrip, scrollstep;
		
	if (typeof gallerydata == 'object' && (gallerydata.length === thumbnails.length)) {
		context.addClass('video-gallery');

		/* build the item list */
		for (i=0;i<gallerydata.length;i++) {
			var currentitemhtml = jQuery.fn.videoGallery.templates.item,
			currentitem = jQuery(currentitemhtml.replace(/<#title#>/g, gallerydata[i].title).replace(/<#text#>/g, gallerydata[i].text).replace(/<#url#>/g, thumbnails.eq(i).attr('href')).replace(/<#buttontext#>/g, buttons.eq(i).text()));
			
			if (i!==0) { currentitem.css('display', 'none'); }
			gallerywrapper.append(currentitem);
		}
		/* get the thumbnails ready - bind click behavior and scrolling behavior */
		thumbnails.each(function (index) {
			jQuery(this).bind('click', function (e) {
				e.preventDefault(); 
				
				jQuery('li:visible', gallerywrapper).fadeOut('fast', function () { jQuery('li', gallerywrapper).eq(index).hide().fadeIn('fast'); }); 
				thumbnails.removeClass('on');
				jQuery(this).addClass('on');
			});
		});
		
		// set up the thumbnails as a scroller
		jQuery('#gallery-thumbnails').removeAttr('id').wrap('<div id="gallery-thumbnails"><div class="inner"></div></div>');
		jQuery('#gallery-thumbnails').prepend('<span class="prev">prev</span>').append('<span class="next">next</span>');
		jQuery('#gallery-thumbnails .inner').width((parseInt(thumbnails.outerWidth()) + 6) * 8);
		 
		thumbstrip = jQuery('#gallery-thumbnails ul');
		thumbstrip.width((thumbnails.outerWidth() + 6) * thumbnails.length);
		scrollstop = (thumbnails.length % 8 === 0) ? -1 * ((thumbnails.outerWidth() + 6) * (thumbnails.length - 8)) : -1 * ((thumbnails.outerWidth() + 6) * (thumbnails.length - thumbnails.length % 8));
		scrollstep = (thumbnails.outerWidth() + 6) * 8;
		
		jQuery('#gallery-thumbnails .prev').bind('click', function(){
			if (thumbstrip.is(':animated') || parseInt(thumbstrip.css('left')) === 0) { return false; }
			thumbstrip.animate({left: (scrollstep + parseInt(thumbstrip.css('left')))}, 500);
		});
		jQuery('#gallery-thumbnails .next').bind('click', function(){
			if (thumbstrip.is(':animated') || parseInt(thumbstrip.css('left')) === scrollstop) { return false; }
			thumbstrip.animate({left: (-1 * scrollstep + parseInt(thumbstrip.css('left')))}, 500);
		});
		
		context.prepend(gallerywrapper);
		jQuery('img', gallerywrapper).each(function (index) {
			this.src = gallerydata[index].imgsrc;
		});
		
	}
};

jQuery.fn.videoGallery.templates = {
	wrapper: '<ul id="gallery-items"></ul>',
	item: '<li><div class="description"><h2><#title#></h2><p><#text#></p><a href="<#url#>" class="button media"><#buttontext#></a></div><div class="display"><a href="<#url#>" class="media"><img src="<#imgsrc#>" /></a></div></li>'
};

jQuery.fn.swfObjSetup = function() { 
	return this.each(function () {
		var replacelink = jQuery(this),
			url = replacelink.attr('href'),
			swfWrap = jQuery('<div class="flash-player">You need to install the Adobe Flash Plugin to view this content</div>'),
			settings = {
				height:ix_vars.defaultFlashPlayerHeight + ix_vars.defaultFlashPlayerControlsHeight,
				width: ix_vars.defaultFlashPlayerWidth,
				swf: ix_vars.flashAssetPath + ix_vars.defaultFlashPlayer,
				bgcolor: '#000000',
				allowfullscreen: 'true',
				quality: 'high',
				flashvars: {
					skin: ix_vars.flashAssetPath + ix_vars.defaultFlashPlayerSkin,
					height: ix_vars.defaultFlashPlayerHeight,
					width: ix_vars.defaultFlashPlayerWidth
				}
			},
			query = [],
			pair;
		swfWrap.height(settings.height).width(settings.width);
		if (url.match(/\?/)) {
			settings.swf = (url.split('?')[0] === ix_vars.flashAssetPath + ix_vars.defaultFlashPlayer) ?  ix_vars.flashAssetPath + ix_vars.defaultFlashPlayer : url.split('?')[0];
			query = url.split('?')[1];
			query = query.split('&');
			for (var i = 0; i < query.length; i++) {
				pair = query[i].split('=');
				switch(pair[0]) {
					case 'content':
					case 'serverURL':
					case 'skin':
						settings.flashvars[pair[0]] = pair[1];
						break;
					case 'width':
						settings.flashvars[pair[0]] = pair[1];
						settings[pair[0]] = pair[1];
						break;
					case 'height':
						settings.flashvars[pair[0]] = pair[1];
						settings[pair[0]] = pair[1] + ix_vars.defaultFlashPlayerControlsHeight;
						break;
					default:
						settings[pair[0]] = pair[1];
				}
			}
			if (settings.width !== 600) {
				var ratio =  600 / settings.flashvars.width;
				settings.width = 600;
				settings.flashvars.width = 600;
				settings.height = settings.flashvars.height * ratio + ix_vars.defaultFlashPlayerControlsHeight;
				settings.flashvars.height = settings.flashvars.height * ratio;
			}
		} else {
			settings.flashvars[content] = url;
		}
		replacelink.after(swfWrap).remove();
		swfWrap.flash(settings);
	});
};

// wrapper to bind colorbox function on video links
jQuery.fn.videoLightbox = function(queryString){
	var canrun = jQuery.fn.colorbox || false;
	if (canrun) {
		queryString = queryString || 'lightbox=true';
		this.each(function () {
			this.href += this.href.match(/\?/) ?'&' + queryString : '?' + queryString;
		});
		return jQuery(this).colorbox({
			opacity: 0.75,
			transition:'none',
			onOpen: function () {
				var url = this.href.substring(0, this.href.indexOf('?'));
				jQuery('#colorbox').data('shareUrl', url);
			},
			onComplete: function () {
				jQuery('a.movie').swfObjSetup();
				jQuery.colorbox.resize();
			}
		});
	} else {
		return false;
	}
};

jQuery.fn.buildGoogleMap = function(map) {
	if (typeof (google) !== 'undefined' && typeof(google) !== null) {
		return this.each(function (map) {
				
			var $this = jQuery(this),
				locationdata = {
					orgname: jQuery('.organization-name', this).text(),
					orgunit:  jQuery('.organization-unit', this).text(),
					streetaddress: jQuery('.street-address', this).text(),
					locality: jQuery('.locality', this).text(),
					region: jQuery('.region', this).text(),
					postalcode: jQuery('.postal-code', this).text()
				},
				geo = new google.maps.Geocoder(),
				defaultaddress = '9615 Grand Ronde Road, Grand Ronde, OR, 97347',
				address, infocontent, locationurl; 
			
			map = map || jQuery('.map-wrap', this);
			
			jQuery.each(locationdata, function (index, val) {
				if (typeof(val) !== 'string') {
					locationdata[index] = '';
				}
				locationdata[index] = jQuery.trim(val);
			});
			
			
			if (locationdata.streetaddress === '') { 
				address = defaultaddress; 
			} else {
				address =  locationdata.streetaddress + ', ';
				address += (locationdata.locality !== '') ? locationdata.locality + ', ' : '';
				address += (locationdata.region !== '') ? locationdata.region + ', ' : '';
				address += locationdata.postalcode;

			}

			locationurl = address.replace(/\s/g, '+');
			infocontent = '<div style="margin-right:16px;"><h4>'+locationdata.orgname+'</h4><h5>'+locationdata.orgunit+'</h5><div>'+locationdata.streetaddress+'<br />'+locationdata.locality+', '+locationdata.region+'&nbsp;&nbsp;'+locationdata.postalcode+'</div><a href="http://maps.google.com/maps?q='+locationurl+'" target="_blank">View on Google Maps site</a></div>';
			

			if (map.length) {
				map.html('<div class="map"></div>');
				map = new google.maps.Map(map.children('.map')[0], {
					center						: new google.maps.LatLng(ix_vars.defaultGRLat, ix_vars.defaultGRLong),
					scrollwheel 				: false,
					zoom 						: 15,
					mapTypeId 					: 'roadmap',
					mapTypeControl				: true,
					navigationControl 			: true,
					navigationControlOptions	: {	style : google.maps.NavigationControlStyle.SMALL },
					streetViewControl			: false
				});
				
				geo.geocode({'address':address}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) { 
						map.setCenter(results[0].geometry.location);
						var marker = new google.maps.Marker({
								map: map, 
								position: results[0].geometry.location
							}),
							infowindow = new google.maps.InfoWindow({
								content: infocontent
							});
						google.maps.event.addListener(marker, 'click', function() {
						  infowindow.open(map,marker);
						});
					}
				});
			}
			jQuery('.nav a', this).each(function () {
				var $this = jQuery(this),
					searchtype = ($this.text().match('Get Directions')) ? 'daddr' : 'q';
				
				$this.attr('href', 'http://maps.google.com/maps?'+searchtype+'='+locationurl).attr('target', '_blank');
			});

		});
	}
};



// Input setter - pulls label sets as default value on related input.  If no label, looks for default value.
jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this),
			$label = jQuery("label[for='"+$input.attr("id")+"']"),
			hideLabel = true,
			labelText, defaultText;
		if (($label.length && !this.value) || (this.value === $label.text())){
			labelText =  jQuery.trim($label.text());
		} else {
			hideLabel = true;
			labelText = this.value ? this.value : false;
		}
		if (labelText) {
			defaultText = lower && lower==1 ? labelText.toLowerCase() : labelText;
			if (hideLabel) { $label.hide(); }
			$input.is('input') ? $input.val(defaultText).addClass('settered') : $input.text(defaultText).addClass('settered');
			$input.focus(function() { if (this.value == defaultText) { this.value = ""; } })
				  .blur(function() { if (!this.value.length) { this.value = defaultText; } });
		} 
	});
};


// regular tabs - these appear on home page
// generic tab builder
jQuery.fn.IX_tabs = function(tab) {	
	return this.each(function() {
		var $container = jQuery(this), 
			$tabs = jQuery("a", this),
	 		panes = new Array();

		$tabs.each(function () {
			var $this = jQuery(this);

			// using the href to make the collection of panes			
			var pane = $this.attr('href');
			if (pane.indexOf("#") != 0) {
				return true;
			}
		 	panes.push(pane);

			$this.bind("click", function(){
				//build the jq selector. cheap.
				jQuery(panes.join(",")).hide();

				//do some class switching
				$container.find('.active').removeClass('active');
				$this.parent("li").addClass("active");

				jQuery(pane).show();
				return false;
			});
		});
		
		// set which tab to show
		// if .default is available, get its index and set it. else, check for a tab index passed in or set to 0
		var show = jQuery('a.default',$container).length ? $tabs.index(jQuery('a.default')) : tab || 0;
		
		$tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
	});
};


jQuery.fn.enableTree = function() {
	return this.each(function () {
		var context = jQuery(this),
			lists = jQuery('.tree', this);
	
		lists.each(function (i) {

			var obj = jQuery(this),
				viewText = "View Page";
			
			if (obj.attr('class').match(/\sdepartments/)) {
				viewText = "View Dept Page";
			}
			
			// hide children and set up css
			obj.addClass("nav expander").find("li ul").hide();
				
			// insert the button to open/close and attach click event
			jQuery("li",obj).each(function(){                                                                                                       
				if(jQuery("li",this).length) {
					var $t = jQuery(this),
						$l = $t.find('a.title').eq(0);
					
					$t.prepend('<a class="btn" href="#"></a>');
					
					if ($l.length) {
						$l.after('<a href="' + $l.attr('href') + '">' + viewText + '</a>')
						.replaceWith('<span class="title">' + $l.text() + ' - </span>');
					}
					jQuery("a.btn",this).click(function() {                                             
						jQuery(this).parent("li").toggleClass("open").find("ul:first").slideToggle("fast");
						return false;                                       
					});
				}              
			});
			if (i === 0) { obj.css('margin-left', 0); }
			obj.css('position', 'static');
		});
		
		context.css('height', 'auto');
	});	
};

jQuery.fn.calendarTips = function () {
	return this.each(function () {
		var $this = jQuery(this),
			text =  $this.next('.description').length ?  $this.next('.description').html() : 'No description available. Please click to the event to see more details.';
		$this.attr('title', $this.text()).attr('alt',text).next('.description').remove();
		$this.parents('td').removeAttr('title');
		$this.tooltip({
			smart: true,
			href: 'x'
		});
	});

};

jQuery.fn.bnsp = function(options) {	
	// if array of characters, use it. else use default set.
	var c = options || ["@","/"];	
	// set bnsp entity based on browser support
	var b = jQuery.browser.msie && jQuery.browser.version < 7 ? "<wbr>" : "&#8203;";	
	// loop and return
	return this.each(function() {		
		var $this = jQuery(this); // store $(this) for use inside another function		
		// loop through each item in character array
		jQuery.each(c, function() {
			var rx = new RegExp(this,'g'); // create new regex object with current character
			$this.html($this.html().replace(rx,this+b)); // replace character with itself + nbsp entity
		}); // end array loop		
	});// end return
}; // end bnsp


// etc

// callbacks from Telerik library AJAX
fedAjaxCallbacks = function(sender, args) {
	jQuery('.main-calendar .event-item a').calendarTips();
}

// clean console.log
function cl(){ if(window.console&&window.console.firebug) { var args = [].splice.call(arguments,0); console.log(args.join(" ")); } }//cl()
// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");


// IE6 fixes
// make sure IE has the abbr and acronym tag
if(document.all){
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}
