/*! Respond.js v1.0.1pre: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
(function(e,h){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=h;if(h){return}var u=e.document,r=u.documentElement,i=[],k=[],p=[],o={},g=30,f=u.getElementsByTagName("head")[0]||r,b=f.getElementsByTagName("link"),d=[],a=function(){var B=b,w=B.length,z=0,y,x,A,v;for(;z<w;z++){y=B[z],x=y.href,A=y.media,v=y.rel&&y.rel.toLowerCase()==="stylesheet";if(!!x&&v&&!o[x]){if(y.styleSheet&&y.styleSheet.rawCssText){m(y.styleSheet.rawCssText,x,A);o[x]=true}else{if(!/^([a-zA-Z]+?:(\/\/)?)/.test(x)||x.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:x,media:A})}}}}t()},t=function(){if(d.length){var v=d.shift();n(v.href,function(w){m(w,v.href,v.media);o[v.href]=true;t()})}},m=function(G,v,x){var E=G.match(/@media[^\{]+\{([^\{\}]+\{[^\}\{]+\})+/gi),H=E&&E.length||0,v=v.substring(0,v.lastIndexOf("/")),w=function(I){return I.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+v+"$2$3")},y=!H&&x,B=0,A,C,D,z,F;if(v.length){v+="/"}if(y){H=1}for(;B<H;B++){A=0;if(y){C=x;k.push(w(G))}else{C=E[B].match(/@media ([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&w(RegExp.$2))}z=C.split(",");F=z.length;for(;A<F;A++){D=z[A];i.push({media:D.match(/(only\s+)?([a-zA-Z]+)(\sand)?/)&&RegExp.$2,rules:k.length-1,minw:D.match(/\(min\-width:[\s]*([\s]*[0-9]+)px[\s]*\)/)&&parseFloat(RegExp.$1),maxw:D.match(/\(max\-width:[\s]*([\s]*[0-9]+)px[\s]*\)/)&&parseFloat(RegExp.$1)})}}j()},l,q,j=function(E){var v="clientWidth",x=r[v],D=u.compatMode==="CSS1Compat"&&x||u.body[v]||x,z={},C=u.createDocumentFragment(),B=b[b.length-1],w=(new Date()).getTime();if(E&&l&&w-l<g){clearTimeout(q);q=setTimeout(j,g);return}else{l=w}for(var y in i){var F=i[y];if(!F.minw&&!F.maxw||(!F.minw||F.minw&&D>=F.minw)&&(!F.maxw||F.maxw&&D<=F.maxw)){if(!z[F.media]){z[F.media]=[]}z[F.media].push(k[F.rules])}}for(var y in p){if(p[y]&&p[y].parentNode===f){f.removeChild(p[y])}}for(var y in z){var G=u.createElement("style"),A=z[y].join("\n");G.type="text/css";G.media=y;if(G.styleSheet){G.styleSheet.cssText=A}else{G.appendChild(u.createTextNode(A))}C.appendChild(G);p.push(G)}f.insertBefore(C,B.nextSibling)},n=function(v,x){var w=c();if(!w){return}w.open("GET",v,true);w.onreadystatechange=function(){if(w.readyState!=4||w.status!=200&&w.status!=304){return}x(w.responseText)};if(w.readyState==4){return}w.send(null)},c=(function(){var v=false;try{v=new XMLHttpRequest()}catch(w){v=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return v}})();a();respond.update=a;function s(){j(true)}if(e.addEventListener){e.addEventListener("resize",s,false)}else{if(e.attachEvent){e.attachEvent("onresize",s)}}})(this,(function(f){if(f.matchMedia){return true}var e,i=document,c=i.documentElement,g=c.firstElementChild||c.firstChild,h=!i.body,d=i.body||i.createElement("body"),b=i.createElement("div"),a="only all";b.id="mq-test-1";b.style.cssText="position:absolute;top:-99em";d.appendChild(b);b.innerHTML='_<style media="'+a+'"> #mq-test-1 { width: 9px; }</style>';if(h){c.insertBefore(d,g)}b.removeChild(b.firstChild);e=b.offsetWidth==9;if(h){c.removeChild(d)}else{d.removeChild(b)}return e})(this));

/** FILE SEPARATOR **/

$('HTML').addClass('JS');
	
$(document).ready(function() {
	var Arrow = '  <span class="nav_arrow"><a href="#">&#9660;</a></span>';
	var gameMenu;
	var huntingMenu;
	var megaDisplay = 'off';
	var showing	 = 'first';
	var trigger  = 700;
	var timer	 = null;
	
	function megaMenu() {
		//sessionStorage.clear();
		USTORE.init();
		var menuItems;
		menuItems = USTORE.getSessionValue("menuItems");
		if(menuItems == null){
			// data not stored in browser, load the data from the server
			$.get('/game/mega', function(data) {
				USTORE.setSessionValue("menuItems",data);	
				buildMenus(data);	
				
			});		
		} else {
			buildMenus(menuItems);
		}		
	}
	
	function buildMenus(menuItems) {
	 	var menuItemsObj = jQuery.parseJSON(menuItems);
	
		// build game menu
		gameMenu = ' <ul id="game-sub-nav">';
		// build hunting menu
		huntingMenu = '	<ul id="hunting-sub-nav">';
		$.each(menuItemsObj,function(i,obj){
			if(i == 0) {
				$.each(obj,function(key,item){
		    		huntingMenu = huntingMenu+'<li><a href="/hunting-new-zealand/'+item.Content.slug+'" title="'+item.Content.nav+'">'+item.Content.nav+'</a></li>';
				});
			}
			if (i == 1) {
				$.each(obj,function(key,item){
		    		gameMenu = gameMenu+'<li><a href="/game/'+item.Animal.slug+'" title="'+item.title+'"><img src="'+item.Animal.image.path+'" alt="'+item.Animal.title+'"></a><a href="/game/'+item.Animal.slug+'" title="'+item.Animal.title+'">'+item.Animal.title+'</a></li>';
				});
			} 
	    });
		huntingMenu = huntingMenu+'</ul>';
		gameMenu = gameMenu+'</ul>';
		
		$('.hunting-new-zealand-nav,.game-nav').append(Arrow);
		$('.hunting-new-zealand-nav .nav_arrow a').addClass('hunting-sub');
		$('.game-nav .nav_arrow a').addClass('game-sub');
		var arrowLink = $('.nav_arrow a');
		$('#nav').after('<div id="mega"><div id="close">x</div></div>');
		var mega = $('#mega');
		
		$('#close').click(function() {
			closeMega(arrowLink,mega);
		});

		arrowLink.click(function() {
			// mega is open
			if(mega.hasClass('open')){
				if($(this).hasClass('selected')){  // the clicked menu is "selected" - remove content from mega and slide up
					closeMega(arrowLink,mega);
				// mega is open and the clicked menu is not "selected"
				// keep it open and load new menu
				} else {
					var subMenu = loadMenu($(this));
					var list = $('#mega ul');
					list.fadeOut('fast', function() {
						$('#mega ul').remove();
						mega.prepend(subMenu);
						list.fadeIn('slow');
						addHover();
	      			});
					arrowLink.removeClass('selected').html('&#9660;'); // remove selected class and make all links down arrows
					$(this).html('&#9650;').addClass('selected'); // make the clicked link an up arrow and add the "selected" class
				}
			// mega is not open.  load content and slide down	
			} else {
				var selected = $(this);
				var subMenu = loadMenu($(this));
				mega.prepend(subMenu).addClass("open");
				mega.slideDown('slow',function() {
					selected.html('&#9650;').addClass('selected');
					addHover();
				});
			}		
		});
	}
	
	function closeMega(arrowLink,mega) {
		arrowLink.removeClass('selected');
		mega.slideUp('slow',function() { 
			mega.removeClass("open");
			$('#mega ul').remove();
			arrowLink.html('&#9660;'); // make all arrows point dowm.
		});
	}
	
	function addHover() {
		$("#mega li").click(function(event){
			event.preventDefault();
			window.location = $(this).find("a:first").attr("href");  
		});
		$("#mega li").hover( function() { 
			$(this).addClass("hover"); 
		},function() {
			$(this).removeClass("hover");
		});	
	}
	
	function loadMenu(selected){
		var subMenu = '';
		if(selected.hasClass('hunting-sub')) {
			subMenu = huntingMenu;
			return subMenu;
		} 
		if(selected.hasClass('game-sub')) {
			subMenu = gameMenu;
			return subMenu;
		} 		
	}
	
	function removeMegaMenu() {
		$('.nav_arrow,#mega').remove();
	}

	// replace menus with a select
	
		
	// Create the dropdown base
	$("nav ul").after("<select id=\"main-nav\" />");
	if($("aside .sub_nav").length != 0) {
		$("#content h1.title").after("<select id=\"related-nav\" />");
		// Create default options
		$("<option />", {
		   "selected": "selected",
		   "value"   : "",
		   "text"    : "Related pages…"
		}).appendTo("select#related-nav");
		$("aside .sub_nav a").each(function() {
			 var el = $(this);
			 $("<option />", {
			     "value"   : el.attr("href"),
			     "text"    : el.text()
			 }).appendTo("select#related-nav");
		});
	}

	// Create default options
	$("<option />", {
	   "selected": "selected",
	   "value"   : "",
	   "text"    : "Go to…"
	}).appendTo("select#main-nav");
	
	// Populate dropdown with menu items
	$("nav ul > li > a").each(function() {
	 var el = $(this);
	 $("<option />", {
	     "value"   : el.attr("href"),
	     "text"    : el.text()
	 }).appendTo("select#main-nav");
	});
	
	$("#secondary-nav > li > a").each(function() {
	 var el = $(this);
	 $("<option />", {
	     "value"   : el.attr("href"),
	     "text"    : el.text()
	 }).appendTo("select#main-nav");
	});

	// let the selects work without a form and submit button, and hide by default
	$("select#main-nav, select#related-nav").change(function() {
	  	window.location.pathname = $(this).find("option:selected").val();
	}).hide();

	
	function toggleDisplay()
	{
		var width = document.documentElement.clientWidth;
		var wideMenus = $('nav ul,#secondary-nav,aside .sub_nav,#breadcrumb');
		var selects = $('select#main-nav,select#related-nav');
		if ( showing == 'first' && width <= trigger ) {
			wideMenus.hide();
			selects.show();
			showing = 'resize';
		} else if (showing == 'first' && width > trigger ) {
			megaMenu();
			showing = 'resize';	
			megaDisplay = 'on';
		} else if ( showing == 'resize' &&	width <= trigger ) {
			wideMenus.hide();
			selects.show();
			if(megaDisplay == 'on') {
				removeMegaMenu();
				megaDisplay = 'off';
			}		
		} else if ( showing == 'resize' &&	width > trigger && megaDisplay == 'off') {
			wideMenus.show();
			selects.hide();
			megaMenu();
			megaDisplay = 'on';
		}
	}
	

	// set up the toggle
	$(window).resize(function(){
		if ( timer ) {
			clearTimeout(timer);
		}
		timer = setTimeout(toggleDisplay,100);
	});
	
	toggleDisplay();
	
	
});

/** FILE SEPARATOR **/

/* https://github.com/hugeinc/USTORE.js/ */

var USTORE = (function() {
    
    var localSupport, sessionSupport, userSupport, obj, objId, objDb, seshObj, seshObjId, seshDb;
    
    var DB = {

        setValue : function(key, value, session) {
            if (localSupport) {
                if (session && sessionSupport) {
                    sessionStorage.setItem(key, value);
                } else {
                    localStorage.setItem(key, value);
                }
            } else if (userSupport) {
                if (session) {
                    seshObj.setAttribute(key,value);
                    seshObj.save(seshDb);
                } else {
                    obj.setAttribute(key, value);
                    obj.save(ieDb);
                }
            }
        },
        
        getValue : function(key, session) {
            var result = '';
            if (localSupport) {
                if (session && sessionSupport) {
                    result = sessionStorage.getItem(key);
                } else {
                    result = localStorage.getItem(key);
                }
            } else if (userSupport) {
                if (session) {
                    seshObj.load(seshDb);
                    result = seshObj.getAttribute(key);
                } else {
                    obj.load(ieDb);
                    result = obj.getAttribute(key);
                }
            }
            return result;
        },
           
        deleteValue : function(key, session) {
            if (localSupport) {
                this.setValue(key,null,session);
            } else if (userSupport) {
                if (session) {
                    seshObj.removeAttribute(key);
                    seshObj.save(seshDb);
                } else {
                    obj.removeAttribute(key);
                    obj.save(ieDb);
                }
            }
        },
        
        clearDB : function(session) {
            if (localSupport) {
                if (session) {
                    sessionStorage.clear();
                } else {
                    localStorage.clear();
                }
            } else if (userSupport) {
                IE.clearDB(session);
            }
        }
        
    }
    

    var IE = {
		// https://gist.github.com/527683
		ieVersion : function(){

		    var undef,
		        v = 3,
		        div = document.createElement('div'),
		        all = div.getElementsByTagName('i');
    
		    while (
		        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
		        all[0]
		    );
    
		    return v > 4 ? v : undef;
    
		},
        
        detectIE : function() {
			var version = IE.ieVersion();
            if (version === 6){ 
            	return true;
            }
            return false;
        },
        

        init : function() {
            
            //add meta tag
            var meta = document.createElement('meta');
            // set properties
            meta.name = "save";
            meta.content = "userdata";
            document.getElementsByTagName('head').item(0).appendChild(meta);
            
            var time = new Date().getTime();
            
            //setup IE localStorage database
            var newdiv = document.createElement('div');
            objId = 'ie-db-' + time;
            ieDb = 'userStorage';
            newdiv.setAttribute('id',objId);
            document.getElementsByTagName('body').item(0).appendChild(newdiv);
            obj = document.getElementById(objId);
            obj.style.behavior = "url('#default#userData')";
            obj.style.display = 'none';
            
            //setup IE sessionStorage database
            if (window.name === null || window.name === undefined || window.name === '') {
                window.name = 'ie-sesh-db-' + time;
            }
            
            seshObjId = window.name;
            seshDb = seshObjId;
            newdiv = document.createElement('div');
            newdiv.setAttribute('id', seshObjId);
            obj.appendChild(newdiv);
            seshObj = document.getElementById(seshObjId);
            seshObj.style.behavior = "url('#default#userData')";
            seshObj.style.display = 'none';
        },
        

        clearDB : function(session) {
            
            var time = new Date().getTime(),
                newdiv = document.createElement('div'),
                dbObj = session ? seshObj : obj,
                dbName = session ? seshDb : ieDb,
                doc = dbObj.xmlDocument, 
                attributes = doc.firstChild.attributes, 
                attr, 
                len = attributes.length;
                
            while ( 0 <= --len ) { 
                attr = attributes[len]; 
                dbObj.removeAttribute( attr.nodeName );
            }
            
            dbObj.save( dbName ); 
            
        }
        
    }   //end var IE
    
    //public functions
    return { 
        init : function() {
            if (typeof(window.localStorage) === 'object') {
                localSupport = true;
                
                //avoid a weird FF error with a little try catch
                try {
                    if (typeof(window.sessionStorage) === 'object') {
                        sessionSupport = true;
                    }
                } catch(err) {
                    sessionSupport = false;
                }
            
            } else if (IE.detectIE()) {
                
                userSupport = true;
                IE.init();
            
            }
        },
        

        setValue : function(key, value) {
            DB.setValue(key,value,false);
        },
        

        setSessionValue : function(key, value) {
            DB.setValue(key,value,true);
        },
        
  
        getValue : function(key) {
            return DB.getValue(key, false);
        },
        
        getSessionValue : function(key) {
            return DB.getValue(key, true);
        },
           
        deleteValue : function(key) {
            DB.deleteValue(key, false);
        },
        
        deleteSessionValue : function(key) {
            DB.deleteValue(key, true);
        },
        
        clearLocalStorage : function() {
            DB.clearDB(false);
        },
        
        clearSessionStorage : function() {
            DB.clearDB(true);
        },
        
        clearDOMStorage : function() {
            DB.clearDB(false); DB.clearDB(true);
        }
        
    }; //end return    
})();

/** FILE SEPARATOR **/

// http://jqueryfordesigners.com/jquery-tabs/
$(function () {
		$('div.tabs caption').hide();
		var selectedTab = window.location.hash ? window.location.hash : ':first'; 
        var tabContainers = $('div.tabs > div');
		tabContainers.hide().filter(selectedTab).show(); 
		$('a[href="'+selectedTab+'"]').addClass('selected');
        $('div.tabs ul.tabNav a').click(function () {
                tabContainers.hide();
                tabContainers.filter(this.hash).show();
                $('div.tabs ul.tabNav a').removeClass('selected');
                $(this).addClass('selected');
                return false;
        }).filter(selectedTab).click();

		if($('div.tabs').length != 0 && window.location.hash) {
			$('html,body').scrollTop(0); 
		}		
});

/** FILE SEPARATOR **/

/*
 * jQuery FlexSlider v1.8
 * http://flex.madebymufffin.com
 * Copyright 2011, Tyler Smith
 */
(function(a){a.flexslider=function(c,b){var d=c;d.init=function(){d.vars=a.extend({},a.flexslider.defaults,b);d.data("flexslider",true);d.container=a(".slides",d);d.slides=a(".slides > li",d);d.count=d.slides.length;d.animating=false;d.currentSlide=d.vars.slideToStart;d.animatingTo=d.currentSlide;d.atEnd=(d.currentSlide==0)?true:false;d.eventType=("ontouchstart" in document.documentElement)?"touchstart":"click";d.cloneCount=0;d.cloneOffset=0;d.manualPause=false;d.vertical=(d.vars.slideDirection=="vertical");d.prop=(d.vertical)?"top":"marginLeft";d.args={};d.transitions="webkitTransition" in document.body.style;if(d.transitions){d.prop="-webkit-transform"}if(d.vars.controlsContainer!=""){d.controlsContainer=a(d.vars.controlsContainer).eq(a(".slides").index(d.container));d.containerExists=d.controlsContainer.length>0}if(d.vars.manualControls!=""){d.manualControls=a(d.vars.manualControls,((d.containerExists)?d.controlsContainer:d));d.manualExists=d.manualControls.length>0}if(d.vars.randomize){d.slides.sort(function(){return(Math.round(Math.random())-0.5)});d.container.empty().append(d.slides)}if(d.vars.animation.toLowerCase()=="slide"){if(d.transitions){d.setTransition(0)}d.css({overflow:"hidden"});if(d.vars.animationLoop){d.cloneCount=2;d.cloneOffset=1;d.container.append(d.slides.filter(":first").clone().addClass("clone")).prepend(d.slides.filter(":last").clone().addClass("clone"))}d.newSlides=a(".slides > li",d);var m=(-1*(d.currentSlide+d.cloneOffset));if(d.vertical){d.newSlides.css({display:"block",width:"100%","float":"left"});d.container.height((d.count+d.cloneCount)*200+"%").css("position","absolute").width("100%");setTimeout(function(){d.css({position:"relative"}).height(d.slides.filter(":first").height());d.args[d.prop]=(d.transitions)?"translate3d(0,"+m*d.height()+"px,0)":m*d.height()+"px";d.container.css(d.args)},100)}else{d.args[d.prop]=(d.transitions)?"translate3d("+m*d.width()+"px,0,0)":m*d.width()+"px";d.container.width((d.count+d.cloneCount)*200+"%").css(d.args);setTimeout(function(){d.newSlides.width(d.width()).css({"float":"left",display:"block"})},100)}}else{d.transitions=false;d.slides.css({width:"100%","float":"left",marginRight:"-100%"}).eq(d.currentSlide).fadeIn(d.vars.animationDuration)}if(d.vars.controlNav){if(d.manualExists){d.controlNav=d.manualControls}else{var e=a('<ol class="flex-control-nav"></ol>');var s=1;for(var t=0;t<d.count;t++){e.append("<li><a>"+s+"</a></li>");s++}if(d.containerExists){a(d.controlsContainer).append(e);d.controlNav=a(".flex-control-nav li a",d.controlsContainer)}else{d.append(e);d.controlNav=a(".flex-control-nav li a",d)}}d.controlNav.eq(d.currentSlide).addClass("active");d.controlNav.bind(d.eventType,function(i){i.preventDefault();if(!a(this).hasClass("active")){(d.controlNav.index(a(this))>d.currentSlide)?d.direction="next":d.direction="prev";d.flexAnimate(d.controlNav.index(a(this)),d.vars.pauseOnAction)}})}if(d.vars.directionNav){var v=a('<ul class="flex-direction-nav"><li><a class="prev" href="#">'+d.vars.prevText+'</a></li><li><a class="next" href="#">'+d.vars.nextText+"</a></li></ul>");if(d.containerExists){a(d.controlsContainer).append(v);d.directionNav=a(".flex-direction-nav li a",d.controlsContainer)}else{d.append(v);d.directionNav=a(".flex-direction-nav li a",d)}if(!d.vars.animationLoop){if(d.currentSlide==0){d.directionNav.filter(".prev").addClass("disabled")}else{if(d.currentSlide==d.count-1){d.directionNav.filter(".next").addClass("disabled")}}}d.directionNav.bind(d.eventType,function(i){i.preventDefault();var j=(a(this).hasClass("next"))?d.getTarget("next"):d.getTarget("prev");if(d.canAdvance(j)){d.flexAnimate(j,d.vars.pauseOnAction)}})}if(d.vars.keyboardNav&&a("ul.slides").length==1){function h(i){if(d.animating){return}else{if(i.keyCode!=39&&i.keyCode!=37){return}else{if(i.keyCode==39){var j=d.getTarget("next")}else{if(i.keyCode==37){var j=d.getTarget("prev")}}if(d.canAdvance(j)){d.flexAnimate(j,d.vars.pauseOnAction)}}}}a(document).bind("keyup",h)}if(d.vars.mousewheel){d.mousewheelEvent=(/Firefox/i.test(navigator.userAgent))?"DOMMouseScroll":"mousewheel";d.bind(d.mousewheelEvent,function(y){y.preventDefault();y=y?y:window.event;var i=y.detail?y.detail*-1:y.wheelDelta/40,j=(i<0)?d.getTarget("next"):d.getTarget("prev");if(d.canAdvance(j)){d.flexAnimate(j,d.vars.pauseOnAction)}})}if(d.vars.slideshow){if(d.vars.pauseOnHover&&d.vars.slideshow){d.hover(function(){d.pause()},function(){if(!d.manualPause){d.resume()}})}d.animatedSlides=setInterval(d.animateSlides,d.vars.slideshowSpeed)}if(d.vars.pausePlay){var q=a('<div class="flex-pauseplay"><span></span></div>');if(d.containerExists){d.controlsContainer.append(q);d.pausePlay=a(".flex-pauseplay span",d.controlsContainer)}else{d.append(q);d.pausePlay=a(".flex-pauseplay span",d)}var n=(d.vars.slideshow)?"pause":"play";d.pausePlay.addClass(n).text((n=="pause")?d.vars.pauseText:d.vars.playText);d.pausePlay.bind(d.eventType,function(i){i.preventDefault();if(a(this).hasClass("pause")){d.pause();d.manualPause=true}else{d.resume();d.manualPause=false}})}if("ontouchstart" in document.documentElement){var w,u,l,r,o,x,p=false;d.each(function(){if("ontouchstart" in document.documentElement){this.addEventListener("touchstart",g,false)}});function g(i){if(d.animating){i.preventDefault()}else{if(i.touches.length==1){d.pause();r=(d.vertical)?d.height():d.width();x=Number(new Date());l=(d.vertical)?(d.currentSlide+d.cloneOffset)*d.height():(d.currentSlide+d.cloneOffset)*d.width();w=(d.vertical)?i.touches[0].pageY:i.touches[0].pageX;u=(d.vertical)?i.touches[0].pageX:i.touches[0].pageY;d.setTransition(0);this.addEventListener("touchmove",k,false);this.addEventListener("touchend",f,false)}}}function k(i){o=(d.vertical)?w-i.touches[0].pageY:w-i.touches[0].pageX;p=(d.vertical)?(Math.abs(o)<Math.abs(i.touches[0].pageX-u)):(Math.abs(o)<Math.abs(i.touches[0].pageY-u));if(!p){i.preventDefault();if(d.vars.animation=="slide"&&d.transitions){if(!d.vars.animationLoop){o=o/((d.currentSlide==0&&o<0||d.currentSlide==d.count-1&&o>0)?(Math.abs(o)/r+2):1)}d.args[d.prop]=(d.vertical)?"translate3d(0,"+(-l-o)+"px,0)":"translate3d("+(-l-o)+"px,0,0)";d.container.css(d.args)}}}function f(j){d.animating=false;if(d.animatingTo==d.currentSlide&&!p&&!(o==null)){var i=(o>0)?d.getTarget("next"):d.getTarget("prev");if(d.canAdvance(i)&&Number(new Date())-x<550&&Math.abs(o)>20||Math.abs(o)>r/2){d.flexAnimate(i,d.vars.pauseOnAction)}else{d.flexAnimate(d.currentSlide,d.vars.pauseOnAction)}}this.removeEventListener("touchmove",k,false);this.removeEventListener("touchend",f,false);w=null;u=null;o=null;l=null}}if(d.vars.animation.toLowerCase()=="slide"){a(window).resize(function(){if(!d.animating){if(d.vertical){d.height(d.slides.filter(":first").height());d.args[d.prop]=(-1*(d.currentSlide+d.cloneOffset))*d.slides.filter(":first").height()+"px";if(d.transitions){d.setTransition(0);d.args[d.prop]=(d.vertical)?"translate3d(0,"+d.args[d.prop]+",0)":"translate3d("+d.args[d.prop]+",0,0)"}d.container.css(d.args)}else{d.newSlides.width(d.width());d.args[d.prop]=(-1*(d.currentSlide+d.cloneOffset))*d.width()+"px";if(d.transitions){d.setTransition(0);d.args[d.prop]=(d.vertical)?"translate3d(0,"+d.args[d.prop]+",0)":"translate3d("+d.args[d.prop]+",0,0)"}d.container.css(d.args)}}})}d.vars.start(d)};d.flexAnimate=function(g,f){if(!d.animating){d.animating=true;d.animatingTo=g;d.vars.before(d);if(f){d.pause()}if(d.vars.controlNav){d.controlNav.removeClass("active").eq(g).addClass("active")}d.atEnd=(g==0||g==d.count-1)?true:false;if(!d.vars.animationLoop&&d.vars.directionNav){if(g==0){d.directionNav.removeClass("disabled").filter(".prev").addClass("disabled")}else{if(g==d.count-1){d.directionNav.removeClass("disabled").filter(".next").addClass("disabled")}else{d.directionNav.removeClass("disabled")}}}if(!d.vars.animationLoop&&g==d.count-1){d.pause();d.vars.end(d)}if(d.vars.animation.toLowerCase()=="slide"){var e=(d.vertical)?d.slides.filter(":first").height():d.slides.filter(":first").width();if(d.currentSlide==0&&g==d.count-1&&d.vars.animationLoop&&d.direction!="next"){d.slideString="0px"}else{if(d.currentSlide==d.count-1&&g==0&&d.vars.animationLoop&&d.direction!="prev"){d.slideString=(-1*(d.count+1))*e+"px"}else{d.slideString=(-1*(g+d.cloneOffset))*e+"px"}}d.args[d.prop]=d.slideString;if(d.transitions){d.setTransition(d.vars.animationDuration);d.args[d.prop]=(d.vertical)?"translate3d(0,"+d.slideString+",0)":"translate3d("+d.slideString+",0,0)";d.container.css(d.args).one("webkitTransitionEnd transitionend",function(){d.wrapup(e)})}else{d.container.animate(d.args,d.vars.animationDuration,function(){d.wrapup(e)})}}else{d.slides.eq(d.currentSlide).fadeOut(d.vars.animationDuration);d.slides.eq(g).fadeIn(d.vars.animationDuration,function(){d.wrapup()})}}};d.wrapup=function(e){if(d.vars.animation=="slide"){if(d.currentSlide==0&&d.animatingTo==d.count-1&&d.vars.animationLoop){d.args[d.prop]=(-1*d.count)*e+"px";if(d.transitions){d.setTransition(0);d.args[d.prop]=(d.vertical)?"translate3d(0,"+d.args[d.prop]+",0)":"translate3d("+d.args[d.prop]+",0,0)"}d.container.css(d.args)}else{if(d.currentSlide==d.count-1&&d.animatingTo==0&&d.vars.animationLoop){d.args[d.prop]=-1*e+"px";if(d.transitions){d.setTransition(0);d.args[d.prop]=(d.vertical)?"translate3d(0,"+d.args[d.prop]+",0)":"translate3d("+d.args[d.prop]+",0,0)"}d.container.css(d.args)}}}d.animating=false;d.currentSlide=d.animatingTo;d.vars.after(d)};d.animateSlides=function(){if(!d.animating){d.flexAnimate(d.getTarget("next"))}};d.pause=function(){clearInterval(d.animatedSlides);if(d.vars.pausePlay){d.pausePlay.removeClass("pause").addClass("play").text(d.vars.playText)}};d.resume=function(){d.animatedSlides=setInterval(d.animateSlides,d.vars.slideshowSpeed);if(d.vars.pausePlay){d.pausePlay.removeClass("play").addClass("pause").text(d.vars.pauseText)}};d.canAdvance=function(e){if(!d.vars.animationLoop&&d.atEnd){if(d.currentSlide==0&&e==d.count-1&&d.direction!="next"){return false}else{if(d.currentSlide==d.count-1&&e==0&&d.direction=="next"){return false}else{return true}}}else{return true}};d.getTarget=function(e){d.direction=e;if(e=="next"){return(d.currentSlide==d.count-1)?0:d.currentSlide+1}else{return(d.currentSlide==0)?d.count-1:d.currentSlide-1}};d.setTransition=function(e){d.container.css({"-webkit-transition-duration":(e/1000)+"s"})};d.init()};a.flexslider.defaults={animation:"fade",slideDirection:"horizontal",slideshow:true,slideshowSpeed:7000,animationDuration:600,directionNav:true,controlNav:true,keyboardNav:true,mousewheel:false,prevText:"Previous",nextText:"Next",pausePlay:false,pauseText:"Pause",playText:"Play",randomize:false,slideToStart:0,animationLoop:true,pauseOnAction:true,pauseOnHover:false,controlsContainer:"",manualControls:"",start:function(){},before:function(){},after:function(){},end:function(){}};a.fn.flexslider=function(b){return this.each(function(){if(a(this).find(".slides li").length==1){a(this).find(".slides li").fadeIn(400)}else{if(a(this).data("flexslider")!=true){new a.flexslider(a(this),b)}}})}})(jQuery);

/** FILE SEPARATOR **/

// pre load nav images
var cacheImage = document.createElement('img');
cacheImage.src = '/img/bg_direction_nav.png';
var cacheImage2 = document.createElement('img');
cacheImage2.src = '/img/bg_control_nav.png';

$(window).load(function() {
	// only run on game pages
	if($('#sc_animals').length > 0){
		$('html').removeClass('no-fs'); // see flexslder.css line 32
			
		// h1#id is in the format animal_x where x = animal_id		
		var parts = $('h1').attr("id").split('_');
		animal_id = parts[1];
	
		var startHTML = '<div class="flexslider"><ul class="slides">';
		var endHTML = '</ul></div>';
		var freeRangePhotos = startHTML;
		var gameRanchPhotos = startHTML;
	
		// get photos using ahah. Returns a JSON object
		var photoItemsObj = null;
		$.get('/game/animals/photos/'+animal_id, function(data) {
			photoItemsObj = jQuery.parseJSON(data);	
			slideshow(photoItemsObj); // add 
		});		
	
		function slideshow(photoItemsObj){
			var freeRangeObj = photoItemsObj.freeRange.Photo;
			var gameRanchObj = photoItemsObj.gameRanch.Photo;
		
			$.each(freeRangeObj,function(key,item){
		    	freeRangePhotos = freeRangePhotos + listItems(item,animal_id);
			});
			$.each(gameRanchObj,function(key,item){
		    	gameRanchPhotos = gameRanchPhotos + listItems(item,animal_id);
		    });


		    freeRangePhotos = freeRangePhotos + endHTML;
			gameRanchPhotos = gameRanchPhotos + endHTML;
	
			// add HTML for slideshow to the DOM
			if(freeRangeObj != '') {
				$('#free-range').append(freeRangePhotos);
			}
			if(gameRanchObj != '') {
				$('#game-ranch').append(gameRanchPhotos);
			}
		
			// start slideshow
			$('.flexslider').flexslider();
		}
	
		function listItems(item,animal_id) {
			return '<li><figure><img title="'+item.title+'" src="/uploads/animals/'+animal_id+'/'+item.filename+'" alt="'+item.title+'" /><figcaption class="flex-caption">'+item.title+'</figcaption></figure></li>';
		}
	}
});

  


/** FILE SEPARATOR **/

// http://s281.codeinspot.com/q/1778872
$(document).ready(function() {
    var imgWrappers = [];

    // iterate over each element with img.caption
    $('img.caption').each(function() {
        var $this = $(this);
        var classList = this.className;  // grab the image's list of classes, if any
        $this.wrap('<figure class="' + classList + '"></figure>'); // wrap the <img> with <figure> and add the saved classes

        // Remember the wrapper here:
        imgWrappers.push($this.parent());

        $this.after('<figcaption>' + $(this).attr('title') + '</figcaption>'); // add the caption
        $this.removeAttr('class'); // remove the classes from the original <img> element
    });

    // now iterate over each figure.caption we built, and relocate it to before its closest preceding paragraph
    $.each(imgWrappers, function(index, item) {
        $(item).parent('p').before(item);
    });

    // And if you're done with it, release it:
    imgWrappers = null;
});
