// JavaScript Document
var ssTimer;
var origContent="";
$(document).ready(function(){						   
	//preload over images
	$(".btn_over").each(function(){var ext=$(this).attr("src").split(".")[1];var overImg=$(this).attr("src").replace("."+ext,"_f2."+ext);preloadImage(overImg);});
	//make over functionality
	$(".btn_over").hover(function(){var ext=$(this).attr("src").split(".")[1];if($(this).attr("src").match("_f2."+ext)){$(this).attr("src",$(this).attr("src").replace("_f2",""));}else{$(this).attr("src",$(this).attr("src").replace("."+ext,"_f2."+ext));}});
	//close popup window
	$(".closeBtn").click(function(){closePop();});	
	//dropdown menus
	$("ul.dropdown li").hoverIntent({timeout: 200,
									over:function(){$(this).addClass("hover"); $('ul:first',this).css({display:'none',visibility:'visible'}).slideDown();},
									out: function(){$(this).removeClass("hover"); $('ul:first',this).css({visibility:'hidden',display:'none'});}							  
									});    
    $("ul.dropdown li ul li:has(ul)").find("a:first").append('&nbsp;&nbsp;&nbsp;<b>&rsaquo;</b> ');
	
	//initialize history api
	$.history.init(loadContent,{unescape:",/"});	
	
	//make href=/somepage go to href=/#/somepage 
	resetLinks('browser');
	
	//embed intro logo animation
	if (flashInstalled){
		loadFlashInDiv('/inc/flash/logo.swf','logo');
		//$("#logo").click(function(){window.location.hash='#/home';});
		loadFlashInDiv('/inc/flash/audio.swf','audioWrap');
	}else{
		$("#logo").css({display:'none'}).fadeIn(1500,function(){logoDone();});	
	}

});
function logoDone(){
	$("#header .nav").css({display:'none',visibility:'visible'}).fadeIn(1200,function(){											 	
												setupListeners();
												$("#contentWrap").css({display:"none",visibility:"visible"}).fadeIn(2000,function(){																						 	
																							setupDisplayListeners();
																							$("#audioWrap").animate({opacity:'100',filter:'alpha(opacity=100)'}).fadeIn();
																						 });
											 });
		
}

var firstHit='';
function loadContent(hash) {
	if (hash=='' && firstHit!=''){hash=window.location.toString().replace('http://','').split('/')[1];}
	firstHit=hash;
	if(hash!=""){
		if ($(".hoverScrollPane").smoothDivScroll().length>0){
			//leaving a page with a thumbscroll confuses IE, the setInterval keeps humming away...
			$(".hoverScrollPane").smoothDivScroll("disable").smoothDivScroll("destroy").remove();
		}
		$('#contentWrap').fadeOut("fast").load('/index.php?ajax=1&url='+hash.replace(/\s/g,'+'),function(){document.title=$("#ptLoader").html();setupListeners();resetLinks('ajax');$(this).fadeIn("fast",function(){setupDisplayListeners();});});
	}
}

function setupListeners(){
	//background image fade rollovers
	$(".fadeOver").hide();
	$(".fadeLink").hover(
						 function(){if($.browser.msie){$(this).children(".fadeOver").show();}else{$(this).children(".fadeOver").fadeIn("slow");}}, 
						 function(){if($.browser.msie){$(this).children(".fadeOver").hide();}else{$(this).children(".fadeOver").fadeOut("fast");}}
						 );
}

//listeners that depend on the display:block and width/height returning true (ie scrollers)
function setupDisplayListeners(){
	//tabs
	//$(".tabContent").hide();
	$(".tab").click(function(){selTab($(this).attr('id'));});	
	//twitter
	$('#tFeed').twit('CherryAdair');
	//text scrollpane
	$('.scrollPane').jScrollPane({showArrows:1,verticalGutter:20});
	//auto hover scroll pane
	if($(".hoverScrollPane").length>0 && $(".scrollWrapper").length>0){$(".hoverScrollPane").smoothDivScroll({});}
	//click/expand
	$('.clickExpand').unbind('click');
	$('.clickExpand').click(function(){var el=$(this).next('.revealContent:first');if(el.is(':visible')){$(this).removeClass('open');el.slideUp('fast');}else{$(this).addClass('open');el.slideDown('fast');}});	
}

function resetLinks(state){
	var selector=state=='browser' ? 'a' : '#contentWrap a';
	selector=state=='pop' ? '#fade a' : selector;
	//modify links for ajax loads
	$(selector).click(function(){
							var url = $(this).attr('href');
							if (url && !url.match('http://') && !url.match('booklist') && !url.match('/userFiles')){
								closePop();
	                    		url = url.replace(/^.*#/, '');
								$.history.load(url);
        	            		return false;
						   }else{
								return true;					
							}
						  });
}
//auto clear a text field when clicked
function clickclear(thisfield, defaulttext){if (thisfield.value == defaulttext) {thisfield.value = "";}}
//preload images
var cache = [];
function preloadImage(img){$("#debug").html(img);var cacheImage = document.createElement('img');cacheImage.src = img;	cache.push(cacheImage);	}
//load flash in a div after page is loaded
function loadFlashInDiv(flash,theDiv){
	//if (flashInstalled){
		var flash_width="100%";	var flash_height="100%";var version='8,0,24,0';
		var str='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+version+'" width="'+flash_width+'" height="'+flash_height+'">';
		str+='<param name="movie" value="'+flash+'"><param name="quality" value="high"><param name="wmode" value="transparent"><param name="SCALE" value="noborder">';
		str+='<embed src="'+flash+'" width="'+flash_width+'" height="'+flash_height+'" wmode="transparent" scale="noborder" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></object>';
		var theTarg=document.getElementById(theDiv);
		theTarg.innerHTML=str;
	//}
}
//change selected content (tabs)
function selTab(sel){
	$(".tab").each(function(){$(this).removeClass('selected');});
	$('#'+sel).addClass('selected');
	$(".tabContent").hide().removeClass('selected');	
	$('#'+sel+'c').css({display:'block',visibility:'hidden'});	
	$('#'+sel+'c').css({display:'none',visibility:'visible'}).fadeIn("fast",function(){$('#'+sel+'c .tabScroll').jScrollPane({showArrows:1,verticalGutter:20});});
}
//book detail page media
function showPics(id){
	$("#xContent").html('').hide();
	mTop=($(window).height()-500)/2;
	$("#pop").css({width:780,height:440,marginTop:mTop});
	$("#popContent").css({width:780,height:440});
	$(".closeBtn").css({marginRight:40});
	$('body').addClass('popOpen');
	$("#fade").fadeIn();
	$("#picpop").fadeIn();
	if (flashInstalled){
		$.ajax({
		  url: '/index.php?ajax=1&url=slideshow/'+id,
		  success: function(retPage){		 
			 $("#popContent").html(retPage).show("slow");		
		  }
		});	
	}else{
		$("#popContent").html(installFlashMessage.replace('{noun}','photos')).fadeIn("slow");
	}
}
//
function showVid(vid){
	pauseAudio();
	$("#xContent").html('').hide();
	mTop=($(window).height()-500)/2;
	$("#pop").css({width:780,height:440,marginTop:mTop});
	$("#popContent").css({width:780,height:440});
	$(".closeBtn").css({marginRight:40});
	$('body').addClass('popOpen');
	$("#fade").fadeIn();
	$("#picpop").fadeIn();
	if (flashInstalled){
		var vidFrame='<div class="faderWrap"><iframe src="/cms/get/flash/pro/video.php?u=2&width=460&height=320&video=/userFiles/videos/'+vid+'" width="460" height="320" style="background-color:#000;" frameborder="0" scrolling="no"></iframe></div>';
 		$("#popContent").html(vidFrame).show("fast");
	}else{
		$("#popContent").html(installFlashMessage.replace('{noun}','videos')).fadeIn("slow");
	}	
}
function showMan(){
	$("#popContent").html('').hide();
	mTop=($(window).height()-750)/2;
	$(".closeBtn").css({marginRight:-60});
	$("#pop").css({width:950,height:630,marginTop:-50});
	$('body').addClass('popOpen');
	$("#fade").fadeIn();
	$("#xContent").css({width:950,height:630,display:'block',visibility:'hidden'}).html($("#popMan").html());
	$("#xContent .rightBox").addClass("scrollPane");
	$("#xContent .scrollPane").jScrollPane({showArrows:1,verticalGutter:20});
	$("#xContent").css({display:'none',visibility:'visible'}).fadeIn("slow");
	resetLinks('pop');
}
function readExcerpt(id){
	$("#popContent").html('').hide();
	mTop=($(window).height()-460)/2;
	$(".closeBtn").css({marginRight:-40});
	$("#pop").css({width:600,height:400,marginTop:mTop});
	$("#xContent").css({width:600,height:400});
	$('body').addClass('popOpen');
	$("#fade").fadeIn();
	if (flashInstalled){
		loadFlashInDiv('/inc/flash/excerpt.swf?xmlFile=/excerptconfigs/'+id,'xContent');
		$("#xContent").fadeIn();
	}else{
		$("#xContent").html(installFlashMessage.replace('{noun}','book excerpt')).fadeIn("slow");
	}		
}

function closePop(){
	//$(".closeBtn").hide();
	resumeAudio();
	$("#fade").fadeOut("slow",function(){$(".closeBtn").show();});
	$("#popContent").html('').hide();
	clearInterval(ssTimer);
	$("#picpop").hide();
	$("#xContent").html('').hide();
	$('body').removeClass('popOpen');
}
function clearMedia(){
	//doesn't do anything right now.	
}

function checkVideoOverlay(){
	$(document).ready(function(){	
		//check video Overlay for book pages
		if ($("#vo").length>0){			
			var ov=$("#vo").html();
			if(ov!=''){
				$("#vo").html('').show();
				loadFlashInDiv('/userFiles/bookGraphics/videoOverlays/'+ov,'vo');			
			}
		}
	});
}
var playAudio=1;
function stopAudio(){//from flash
	$("#audioWrap").html('<a onclick="startAudio();"><img src="/images/siteAssets/btn/btn_playAudio.png" alt=""></a>');
	playAudio=0;
}
function startAudio(){
	playAudio=1;
	loadFlashInDiv('/inc/flash/audio.swf','audioWrap');
}
function pauseAudio(){//from flash
	$("#audioWrap").html('');
}
function resumeAudio(){
	if ($("#audioWrap").html()==''){
		if (playAudio==1){
			loadFlashInDiv('/inc/flash/audio.swf','audioWrap');
		}
		if (playAudio==0){
			$("#audioWrap").html('<a onclick="startAudio();"><img src="/images/siteAssets/btn/btn_playAudio.png" alt=""></a>');
		}
	}
}
//load tweet dynamically
(function(jQuery){var _i=0;jQuery.fn.twit=function(user,options){if(typeof user!='string')return this;var
opts=jQuery.extend({},jQuery.fn.twit.defaults,options),c=jQuery.isFunction(opts.callback)?opts.callback:_callback,url='http://twitter.com/statuses/user_timeline/'+user+'.json',params={};opts.user=user;params.count=opts.count;return this.each(function(i,e){var $e=$(e);if(!$e.hasClass('twit'))$e.addClass('twit');jQuery.ajax({url:url,data:params,dataType:'jsonp',contentType:'application/jsonp; charset=utf-8',success:function(o){c.apply(this,[(o.results)?o.results:o,e,opts]);}});});};jQuery.fn.twit.defaults={user:null,callback:null,icon:true,username:true,text:true,count:200,limit:10,label:'Twitter',title:''};var _callback=function(o,e,opts){var $this=$(e);if(!o||o.length==0||$this.length==0)return false;$this.data('_inc',1);_i++;var username=o[0].user.screen_name,icon=o[0].user.profile_image_url;var h='<div class="twitHeader">'+' <span class="twitLabel">'+opts.label+'</span>  '+' <span class="twitTitle">'+opts.title+'</span>'+'</div>';if(opts.icon||opts.username){h+='<div class="twitUser">';if(opts.icon)
h+='<a href="http://twitter.com/'+username+'/">'+'<img src="'+icon+'" alt="'+username+'" title="'+username+'" style="vertical-align:middle;">'+'</a>';if(opts.username)
h+='  <a href="http://twitter.com/'+username+'/">Follow '+username+'</a>';h+='</div>';}
h+='<ul class="twitBody" id="twitList'+_i+'">'+_build(o,$this,opts)+'</ul>';$this.html(h);$('a.twitEntryShow','#twitList'+_i).live('click',function(e){e.preventDefault();var $t=$(this);$t.parent().fadeOut(400,function(){var i=$this.data('_inc');i++;$this.data('_inc',i);if($t.hasClass('twitEntryAll')){$t.die('click');var start=(i*opts.limit)-opts.limit;$(this).after(_build(o,$this,opts,start,o.length)).remove();}else{$(this).after(_build(o,$this,opts)).remove();}});});};var _build=function(o,$t,opts,s,e){var
h='',inc=$t.data('_inc'),start=s||(inc*opts.limit)-opts.limit,end=e||((o.length>start+opts.limit)?start+opts.limit:o.length);for(var i=start;i<end;i++){var
t=o[i],username=t.user.screen_name,icon=t.user.profile_image_url;h+='<li class="twitEntry">';if(opts.text){var text=t.text.replace(/(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/,function(u){var shortUrl=(u.length>30)?u.substr(0,30)+'...':u;return'<a href="'+u+'">'+shortUrl+'</a>';}).replace(/@([a-zA-Z0-9_]+)/g,'@<a href="http://twitter.com/$1">$1</a>').replace(/(?:^|\s)#([^\s\.\+:!]+)/g,function(a,u){return' <a href="http://twitter.com/search?q='+encodeURIComponent(u)+'">#'+u+'</a>';});h+=' <span>'+text+'</span>';}
h+='</li>';}
return h;};})(jQuery);
//detect flash
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";
//embedded flash blinks when FlashDetect is called, save to local var
var flashInstalled=FlashDetect.installed;
var installFlashMessage='<div class="installFlash">You need the Flash player installed to view {noun}.<br><a href="http://get.adobe.com/flashplayer/" target="_blank">Install plugin ></a></div>';
