// *** jquery code *** //
$(document).ready(function() {
	
	var endTime = (new Date()).getTime();
    var secondsLoading = (endTime - window.startTime)/1000;
	var minimal = (secondsLoading >15)? true:false;
	//minimal = true;
	//alert("Load minimal:"+minimal);
	
	$.getScript("/jscript/jquery.pngFix.js", function(){
		$(document).pngFix();
	});
	
	
	$("#nav li").hover(
		function(){ $("ul", this).fadeIn("fast"); }, 
		function() { } 
	);
	if (document.all) {
		$("#nav li").hoverClass("sfHover");
	}
	
	if($("#quick_links").length >0){
		//alert("quick links found");
		$("#quick_links").click(function(){  
			slider_zindex = $("#slider").css("z-index");
         	$("#quick_links_menu").animate({"opacity": "toggle"}, { duration: "slow" });
			return false;
     	});
		
		$("#quick_links_close").click(function(){  
         	$("#quick_links_menu").animate({"opacity": "toggle"}, { duration: "slow" });
			return false;
     	}); 
		
		
	}
	if($("#translate_link").length >0){

		$("#translate_link").click(function(){  
         	$("#translate_menu").animate({"opacity": "toggle"}, { duration: "slow" });
			return false;
     	});
		
		$("a.translate_link_close").click(function(){  
         	$("#translate_menu").animate({"opacity": "toggle"}, { duration: "slow" });
			return false;
     	}); 
		
		
	}
	
	/*
	if($("#intro_events").length>0){
		$("#intro_events ul").mouseover(function () {
		  $("#intro_events ul").addClass("events_expanded");
		});
		$("a.events_close").click(function(){  
         	$("#intro_events ul").removeClass("events_expanded");
			return false;
     	}); 
	}
	*/
	
	var nice_browser = false;
	if($.browser.msie && parseFloat(jQuery.browser.version)>6){
		nice_browser = true;
		
	}
	
	if($.browser.mozilla && parseFloat(jQuery.browser.version)>=1.9){
		nice_browser = true;
	}
	
	if($.browser.opera){
		// good browser, few visitors. Most opera users know what to do if page isn't working.
		nice_browser = true;
	}
	if($.browser.safari){
		// not enough visitors to be picky about versions. Let all through.
		nice_browser = true;
	}

	if(nice_browser && minimal===false){
		if ( $("#slider").length > 0 ) {
				
			// start slider once jquery plugin is loaded.
			$.getScript("/jscript/easySlider.js", function(){
				$("#slider").easySlider({
					auto: true,
					continuous: true,
					numeric: true,
					pause: 5600,
					thumbnails: true
				});
			
				if ( $("#home_marketing").length > 0 ) {
					 $.ajax({
					   type: "GET",
					   url: "/includes/home/marketing.php",
					   dataType: "text",
					   cache:false,
					   success: function(banners){
						 //alert(banners);
						 $("#home_marketing").livequery(function(){
							 $("#home_marketing").html(banners);
								$("#shop_banners").easySlider({
									auto: true,
									continuous: true,
									numeric: true,
									pause: 5600,
									numericId: 'controls_shop'
								});
							 
								 $("#zoo_banners").easySlider({
									auto: true,
									continuous: true,
									numeric: true,
									pause: 5600,
									numericId: 'controls_zoo'
								});
							
						 }).css("height","160px").css("overflow","hidden");
						 
						 
					   }
					 });
				}
			
			
			});
			
		}
		

		
	} else {
		// no fancy slider banner - just the regular banner
		$("#slider ul li").not(":first").css("display","none");
		$("#slider").css("margin-bottom","10px");

	}
	
	if($("#home_news_subscribe").length>0){
																										   
		$("#home_news_subscribe").submit(function(){
			var nl_email = $("#newsletter_txt").val();
			/*
			if(isValidEmail(nl_email)==false) {
				alert("Invalid email address");
				return false;
			}
			*/
			var actionUrl = $("#home_news_subscribe").attr("action")+"?email="+escape(nl_email);
			var pLeft = (screen.width - 380)/2;
			var pTop = (screen.height - 500)/2;
			var features = 'width=380,height=500,left = ' + pLeft + ',top=' + pTop +',resizeable,scrollbars';
			var opened = window.open(actionUrl, 'formpopup', features);
			if(!opened) alert("Newsletter subscription has been\n blocked by a pop up blocker.");
			return false;
		});
	}
	
	if($(".newwindow").length>0){
		$.getScript("/jscript/jquery.popupWindow.js", function(){
		});
	}
	
	// for conservation section, load conservation js file
	if($("#conservation").length>0){
		$.getScript("/jscript/conservation.js");
	}
	
	if($("#about-us")){
		$.getScript("/jscript/about-us.js");
	}
	
});
// *** jquery code *** //
$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};


// Zoo Weekly Tabs -- start //
var panes          = new Array();
var visiblePaneIds = new Array();
var weightingTable = new Array();

setupWeightingTable();

function setupPanes(containerId) {
  
  panes[containerId] = new Array();
  var maxHeight      = 0; 
  var maxWidth       = 0;

  var container = document.getElementById(containerId);
  var paneContainer = container.getElementsByTagName("div")[0];
  var paneList = paneContainer.childNodes;
  
  for (var i=0; i < paneList.length; i++ ) {
    var pane = paneList[i];
    if (pane.nodeType != 1) continue;
    if (pane.offsetHeight > maxHeight) maxHeight = pane.offsetHeight;
    if (pane.offsetWidth  > maxWidth ) maxWidth  = pane.offsetWidth;
    panes[containerId][pane.id] = pane;
    pane.style.display = "none";
  }
  
  paneContainer.style.height = maxHeight + "px";
  paneContainer.style.width  = maxWidth + "px";

  var randPane = getWeightedRandomPane(containerId);

  if (panes[containerId][randPane] == null) {
	document.getElementById(containerId).style.display = "none";
	return;
  }
  var visiblePane = panes[containerId][randPane].id;
  visiblePaneIds[visiblePaneIds.length] = visiblePane;

  var selectedLink = visiblePane.replace("-tab","-a");
  document.getElementById(selectedLink).onclick();
}

function setupWeightingTable() {
  var zooweeklyWeights = [["zooweekly-diaries-tab", 1], ["zooweekly-news-tab", 1], ["zooweekly-gossip-tab", 1]];
  loadWeights("zooweekly", zooweeklyWeights);
}

function loadWeights(containerId, weightsToLoad) {

  weightingTable[containerId] = new Array();

  var count = 0;
  for (var i=0; i < weightsToLoad.length; i++) {
    for (var j=0; j < weightsToLoad[i][1]; j++) {
      weightingTable[containerId][count] = weightsToLoad[i][0];
	  count++;
	}
  }
}

function getWeightedRandomPane(containerId) {

  if (weightingTable[containerId] != undefined) {
    var randArrayIndex = Math.round(Math.random() * (weightingTable[containerId].length-1));
    return weightingTable[containerId][randArrayIndex];
  }
  return false;
}

function showPane(paneId, activeTab) {
  for (var con in panes) {
    activeTab.blur();
    activeTab.className = "tab-active";
    if (panes[con][paneId] != null) { 
      var pane = document.getElementById(paneId);
      pane.style.display = "block";
      var container = document.getElementById(con);
      var tabs = container.getElementsByTagName("ul")[0];
      var tabList = tabs.getElementsByTagName("a")
      for (var i=0; i<tabList.length; i++ ) {
        var tab = tabList[i];
        if (tab != activeTab) tab.className = "tab-disabled";
      }
      for (var i in panes[con]) {
        var pane = panes[con][i];
        if (pane == undefined) continue;
        if (pane.id == paneId) continue;
        pane.style.display = "none";
      }
    }
  }
  return false;
}
// Zoo Weekly Tabs -- end //

// pop up script -- start //
var sUserAgent = navigator.userAgent.toLowerCase();
var isOp = (sUserAgent.indexOf('opera')!=-1)?true:false;
function pop(oAnchor,sProps,sWindow){
	var sUrl = '';
	if(oAnchor.getAttribute) sUrl = oAnchor.getAttribute('href');
	if(sUrl=='') sUrl = oAnchor.href;
	if(sUrl=='') return true;
	var sWindowName = sWindow?sWindow:'reusedWindow';
	if(!sProps) sProps = null;
	
	// get digits out of passed props for width and height
	var sPropsdigits = new Array();
	sPropsdigits = sProps.match(/\d+/g); //returns the array [8,15]
	var pLeft = (screen.width - sPropsdigits[0])/2;
	var pTop = (screen.height - sPropsdigits[1])/2;
	
	// add left and top positions to sProps for centering window
	sProps += ', left = ' + pLeft + ',top=' + pTop;

	if(sUrl) var oPopup = window.open(sUrl,sWindowName,sProps);
	if(oPopup && !isOp) oPopup.focus();
	if(!oPopup){
		alert("Please disable your popup blocking software.");
	}
	return (oPopup)?false:true;
}
function switchImg(sImg,sSrc){
	oImg = document.images[sImg];
	return !(oImg.src = 'img/' + sSrc);
}
function verifyKey(oElement,oEvent){
	if(oEvent.keyCode==13 && oElement.onclick) oElement.onclick();
}
// pop up script -- end //

/////////////////// START AJAX sign up form code ////////////////////////
function isValidEmail(email, required) 
{
	if (required==undefined) 
	{
		required=true;
	}
	if (email==null) 
	{
		if (required) 
		{
			return false;
		}
		return true;
	}
	if (email.length==0) 
	{  
		if (required) 
		{
			return false;
		}
		return true;
	}
	if (! allValidChars(email)) 
	{
		return false;
	}
	if (email.indexOf("@") < 1) 
	{
		return false;
	}
	else if (email.lastIndexOf(".") <= email.indexOf("@")) 
	{
		return false;
	} 
	else if (email.indexOf("@") == email.length) 
	{
		return false;
	} 
	else if (email.indexOf("..") >=0) 
	{
		return false;
	} 
	else if (email.indexOf(".") == email.length) 
	{
		return false;
	}
	return true;
}
				
function allValidChars(email) 
{
	var parsed = true;
	var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
	for (var i=0; i < email.length; i++) 
	{
		var letter = email.charAt(i).toLowerCase();
		if (validchars.indexOf(letter) != -1)
		continue;
		parsed = false;
		break;
	}
	return parsed;
}
				   
var http_request = false;

function makePOSTRequest(url, parameters) 
{
	http_request = false;
	if (window.XMLHttpRequest) 
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			http_request.overrideMimeType('text/xml');
		}
	} 
	else if (window.ActiveXObject) 
	{
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{}
		}
	}
	if (!http_request) 
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}
				      
	http_request.onreadystatechange = function ()
	{
		document.getElementById('subscribeForm').innerHTML = "<p class='requiredField'>Loading..</p>";
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200) 
			{
	        	document.getElementById('subscribeForm').innerHTML = "<p><span style='color:green;'>Thank you for registering</span> Please check your e-mail to confirm your registration.</p>";		
	        } 
	        else 
	        {			
	        	alert('There was a problem with the request.');
	        }
		}
	}
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.send(parameters);
	return true;
}

// START Zoo weekly sign up form //
function validatezw() 
{
	if (! isValidEmail(document.signup.email.value)) 
	{
		document.getElementById('invalidEmail').innerHTML = "Please enter a valid email address<br />";
		return false;
	}
	getZw(document.getElementById('signup'));
	return true;
}
				   
function getZw(obj) {
	var poststr = "email=" + encodeURI( document.getElementById("email").value);
	makePOSTRequest('/zoo-weekly/process.php', poststr);
}			   

function clearZw() {
	if (document.signup.email.value == 'Enter Email') {
		document.signup.email.value = '';
	}
}
// END Zoo weekly sign up form //

// START Animal Facts sign up form //
function validateaf() 
{
	if (! isValidEmail(document.facts.email.value)) 
	{
		document.getElementById('invalidEmail').innerHTML = "Please enter a valid email address<br />";
		return false;
	}
	getAf(document.getElementById('facts'));
	return true;
}
				   
function getAf(obj) {
	var poststr = "email=" + encodeURI( document.getElementById("email").value);
	makePOSTRequest('/animal-facts/process.php', poststr);
}			   

function clearAf() {
	if (document.facts.email.value == 'Enter Email') {
		document.facts.email.value = '';
	}
}
// END Animal Facts sign up form //

/////////////////// END AJAX sign up form code ////////////////////////

// Utilities font sizer //
var curFontSize = 1;
var fontModifier = 0.1;

function fontSize(act) {
    if (document.getElementById) {
        storyBody = document.getElementById("content");
		
        if (act === 1) {
            curFontSize += fontModifier;
            curFontSize = Math.min(curFontSize, 1.4);
        } else if (act === 0) {
            curFontSize -= fontModifier;
            curFontSize = Math.max(curFontSize, 1);
        }
        storyBody.style.fontSize = curFontSize + "em";
		
    }
	return(false);
}
// end Utilities font sizer //

//Gets the browser specific XmlHttpRequest Object
// *** ajax DOM test *** //
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		 //Internet Explorer
		 try {
		  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		 } catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		 }
	}
	return xmlHttp;
}

function getTweet(getTweets,tweetstart){

	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
	 alert ("Browser does not support HTTP Request")
	 return false;
	}
		
	var url ="/includes/twitter.inc.php";
	var data = "getTweets=" + getTweets + "&tweetstart="+tweetstart;
	data = data + "&ajaxid="+Math.random()
	
	xmlHttp.onreadystatechange= function () 
	{ 
	
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		{ 
			document.getElementById('tweet').innerHTML=xmlHttp.responseText 
		} else {
			document.getElementById('tweet').innerHTML="Getting Tweet ... ";
		}
		return false;
	}
	
	xmlHttp.open('POST', url, true);
	xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(data);
	return false;
}
