/*
	
	Project Name Global Javascript Functions
	By  - ISITE Design

*/

// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict(); 

// configuration for AddThis social networking widget
var addthis_config = { services_exclude: 'print, email' };

// constant values for callback locations for gallery and front page tabs
// this could be inserted in doc by Sitecore if any of this content needs to be maintained in CMS.
var STRINGS = {
        CALLBACK_LOCATION: {
            gallery: '/Layouts/OFB/Data/PhotoGalleryDriver.ashx?id=',
            home_tabs: '/Layouts/OFB/Data/TabDriver.ashx?tab='
            },
        MESSAGE: {
            ie6_warning: 'Hi! Looks like you are using an old browser. Things may look a little off around here.<br />For a better internet experience, consider <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">upgrading your browser</a> or <a href="http://www.alternativebrowseralliance.com/browsers.html">trying a new one</a>.'
        }
    };

    // jQuery document ready
jQuery(function($) {

  //Map
  
  $('.map-sidebar ul li a').click(function() {
    $(this).parent().toggleClass('open');
  });

  // Enable Slideshow
  $('#slider').nivoSlider({
    effect: 'slideInLeft',
    slides: 0,
    animSpeed:300,
    pauseTime:5000,
    controlNav:true,
    pauseOnHover:true
  });
    
	// JS enabled, add classes to inicate platform/browser.
	$('html').addClass('js').sniff();
	
	if($.browser.msie && jQuery.browser.version < 7) {
		if($('.page-home').length){ $("#primary").append('<div style="clear:left;height:1px;margin-bottom:-30px;"></div>'); }
		$('body').wrapInner('<div id="ie6-wrap"></div>');
		$('<div id="ie6-warn"><div class="content-wrap"><p>'+STRINGS.MESSAGE.ie6_warning+'</p></div></div>').prependTo('body');
		
	}
	
	// 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
	
	$(".search-simple input[type=text]").inputSetter();
	
	$('.page-home #tabs li').each(function(){
		var $this = $(this);
		var tabname = this.id.substr(9);
		var $content = $('#introductions');
		$this.children('a').click(function() { 
			if($this.hasClass('on')) {
				return true;
			} else {
				$('#tabs li.on').removeClass('on');
				$this.addClass('on');
				doReplaceHomepageContent(tabname);
				return false;
			}
		});
	});
	
	if($('.page-news-article').length) {
			$('.page-news-article h1').before('<div class="utility"><div class="addthis_toolbox"><a class="addthis_button_compact" href="http://addthis.com/bookmark.php?v=250&amp;username=xa-4b4b7ba36c9933e9">Share</a></div><span class="print">Print</span><span class="email">Email</span></div>');
			$('.print').click(function(){window.print();});
			$('.email').click(function(){doEmailPage();});
			$.getScript("https://s7.addthis.com/js/250/addthis_widget.js#username=xa-4b4b7ba36c9933e9");
	} else { $.getScript("https://s7.addthis.com/js/250/addthis_widget.js#username=xa-4b4b7ba36c9933e9"); }
	
	if($('#viewer').length){
	
	    $('#viewer').after('<div id="browser"><a href="#" class="prev">Prev</a><a href="#" class="next">Next</a></div>');
	    
		var $next = $('#browser .next'),
		    $prev = $('#browser .prev'),
		    $thumbs = $('.image-nav li');
		
	    
		$thumbs.each(function() { 
		    var $link = $(this).find('a');
		    var linkurl = $link.attr('href');
		    $link.data('hash', linkurl.substr(linkurl.indexOf('#')+1));
			$link.click(function(){ 
			    var $this = $(this);
				var hash = $this.data('hash');
				doReplaceViewerContent(STRINGS.CALLBACK_LOCATION.gallery + hash);
				if(window.location.hash != hash) { window.location.hash = hash; }
				$thumbs.filter('.on').removeClass('on');
				$this.parent('li').addClass('on');
				return false;
			});
		});
		$next.click(function(){
			if ($thumbs.filter(':last').hasClass('on')) {
				$thumbs.filter(':first').find('a').click();
			}
			else {
				$thumbs.filter('.on').next().find('a').click();
			}
			return false;
		});
		$prev.click(function(){
			if ($thumbs.filter(':first').hasClass('on')) {
				$thumbs.filter(':last').find('a').click();
			}
			else {
				$thumbs.filter('.on').prev().find('a').click();
			}
			return false;
		});
		
		if (window.location.hash != '') {
		    var hash =  window.location.hash.substr(1)
		    doReplaceViewerContent(STRINGS.CALLBACK_LOCATION.gallery + hash);
		    $thumbs.filter(function(){return $(this).find('a').data('hash')==hash; }).addClass('on');
		} else {
		    $thumbs.filter(':first').find('a').click();
		}

	}
	
	// lightbox behavior - works only for image urls
	$('.view.album-list li a').lightweightbox();
	
	// faq expand/collapse
	enableExpand("dl.collapsible");


});// document ready

// application logic

// create open/close. receives dl.
var enableExpand = function(el) {	
	$j(el).find("dd").hide();	
	$j(el).find("dt").prepend('<span class="state">+</span> ').wrapInner('<a href="#"></a>').click(function(){
		var textinsert = $j("span.state",this).text() == "+" ? "-" : "+";
		$j(this).next("dd").slideToggle("fast").end().find("span.state").text(textinsert);	
		return false;
	});		
};

// jQuery plugins

/*

	12.19.08 - pdf
	
	@inputSetter
	Input Setter
	pull label and insert as field. clear with click.	
	optional lower param if == 1, string toLowerCase	

	ex: $("#sitesearch input").inputSetter(1); // makes default text lowercase
		$("#sitesearch input").inputSetter(); // no lowercasing

*/

jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this);
		var $label = (jQuery("label[for='"+$input.attr("id")+"']").length) ? jQuery("label[for='"+$input.attr("id")+"']") : jQuery("label[for='"+$input.attr("name")+"']");
		var labeltext = lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();	
		$input.val(labeltext);		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; }	})
			  .blur(function() { var o=this; setTimeout(function(){if (!o.value.length) { o.value = labeltext; } console.log(o); }, 200); } );		
	});
};

// end inputSetter

// lightweightbox - light box style pop over div for images only
jQuery.fn.lightweightbox = function(){ //attach a call to lightweightbox.open to all elements in collection
	if(!jQuery('#lwb').length) { lwb.init(); }
	return this.each(function(){
		jQuery(this).bind('click', {uri : this.href}, lwb.trigger);
	});
}

// lightweightbox functions
var lwb = {
	$lwb_overlay : jQuery('<div id="lwb-overlay"></div>'),
	$lwb : jQuery('<div id="lwb"></div>'),
	$lwb_content : jQuery('<div id="lwb-content"></div>'),
	$lwb_image : jQuery('<img id="lwb-image" />'),
	$lwb_close : jQuery('<div class="lwb-close"><span class="lwb-close-control">Close</span></div>'),
	
	init : function(){
	    lwb.$lwb_overlay.css({height:jQuery(document).height() + 'px', width:jQuery(document).width() + 'px'});
		lwb.$lwb_overlay.bind('click', lwb.close)
		lwb.$lwb.append(lwb.$lwb_content);
		lwb.$lwb_image.bind('load', lwb.open);
		lwb.$lwb_content.append(lwb.$lwb_image);
		jQuery('body').append(lwb.$lwb_overlay).append(lwb.$lwb);
		lwb.$lwb_close.find('.lwb-close-control').click(lwb.close);
		lwb.$lwb.append(lwb.$lwb_close);
	},
	trigger : function(event){
		lwb.$lwb_overlay.css('display', 'block');
		lwb.loadImage(event);	
		return false;
	},
	loadImage : function(event){
		lwb.$lwb_image.attr('src', event.data.uri);
	},
	open : function() {
		lwb.utility.setPosition(lwb.$lwb);
		lwb.$lwb.show(400);
	},
	close : function(event){ 
		lwb.$lwb.hide(400, function(){ lwb.$lwb_overlay.css('display', 'none'); });
	},
	utility : {
		setPosition : function($el){
			var $w = jQuery(window);
			$el.css({	top : (($w.height() - $el.outerHeight())/2 + $w.scrollTop()) + 'px',
						left : (($w.width() - $el.outerWidth())/2 + $w.scrollLeft()) + 'px'
			});
		}
	}
};

jQuery.fn.sniff = function(s) {

	// placeholders for complete class
	var snuff,
		platform,
		v = function(s){
			var ua = navigator.userAgent.toLowerCase();
			ua = ua.substring(ua.indexOf(s+'/') +(s.length + 1));
			return ua.substring(0,1);				
		};
	
	// enable chrome sniffing
	jQuery.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

	// ie
	if (jQuery.browser.msie) {
        snuff = "ie ie" + jQuery.browser.version.substring(0,1);
    }

    // mozilla
    else if (jQuery.browser.mozilla) {

        // firefox
        if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1){  
			// firefox 3-5 has significant improvements over 3. check for it by detecting video element 
            var temp = v("firefox") == 3 && !!document.createElement('video').canPlayType ? "3-5" : v("firefox");
			snuff = "ff ff" + temp;
        }
        // other mozilla
        else {
            snuff = "mz";
        }
    }

	// chrome
    else if (jQuery.browser.chrome) {		
		snuff = "ch ch" + v("chrome");
        // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
        jQuery.browser.safari = false;
    }

	// safari
	else if (jQuery.browser.safari) {
        snuff = "sf sf" + v("version");
    }

    // opera
    else if (jQuery.browser.opera) {
    	snuff = "op";
    }
	
	// platform
	if (navigator.platform.indexOf("Win")!=-1) {
		platform = "windows";
	}			
	else if (navigator.platform.indexOf("Mac")!=-1) {
		platform = "mac";
	}
	else if (navigator.platform.indexOf("Linux")!=-1) {
		platform = "linux";
	}
	// return
	return this.each(function() {
		jQuery(this).addClass(platform + " " + snuff);
	});			
	
};	


// etc

 function theRotator() {
  	//Set the opacity of all images to 0
  	jQuery('div#rotator ul li').css({opacity: 0.0});

  	//Get the first image and display it (gets set to full opacity)
  	jQuery('div#rotator ul li:first').css({opacity: 1.0});

  	//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
  	setInterval('rotate()',4000);

  }
  

  function rotate() {	
  	//Get the first image
    var current = (jQuery('div#rotator ul li.show') ? jQuery('div#rotator ul li.show') : jQuery('div#rotator ul li:first'));
  	
  	//Get next image, when it reaches the end, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? jQuery('div#rotator ul li:first') :current.next()) : jQuery('div#rotator ul li:first'));

    //Hide the current image
    current.animate({ opacity: 0.0 }, 400)
  	.removeClass('show');
    
  	//Set the fade in effect for the next image, the show class has higher z-index
  	next.css({opacity: 0.0})
  	.addClass('show')
  	.animate({opacity: 1.0}, 400);

  	

  };



// 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) {}
