/****  LISTENERS  ****/
$(function(){
    initialize(document);
    checkVideoFlashVersion();
});

var checkVideoFlashVersion = function(){
    if ($('.video').length > 0){
	    var flashVersion = detectFlashVersion();
	    if(flashVersion && flashVersion < 9){
			$('.video').append('<p style="color: #666666;">Download <a href="http://www.adobe.com/products/flashplayer/" target="_blank">Flash 9</a> for video full screen view.</p>');
	    }
    }	
};

var initialize = function(parent){};

function $zt(func){
	var old = initialize;
	initialize = function(parent){
		old(parent); 
		func(parent);
	};
}

//set up stylizing and stuff
$zt(function(parent){
	var isIE6 = $.browser.msie && parseInt($.browser.version) <= 6;
	
    // show max chars counter on textareas (no increment)
    $("textarea", parent).each(function(){
        var max  = this.getAttribute('maxlength');
        if (!max) return;
        var currentLength = this.value.length;
        var html_counter = "<div class=\"counter\">" + currentLength + " of " + max +" max characters</div>";
        $(this).after(html_counter);
        this.relatedElement = $('div.counter > span')[0];
    });

    // do actual incrementing of counter on text areas (yes increment)
    $("textarea", parent).keyup(function(){
        var currentLength = this.value.length;
        var max  = this.getAttribute('maxlength');
        if (!max) return;
        if(currentLength <= max){
            $(this).next('.counter').html(currentLength + " of " + max +" max characters");
        }
        else{
            $(this).next('.counter').html((currentLength - max) + " character(s) over " + max + " character limit");
        }
    });
    
    //if search is set to default value, clear on focus
    // NOTE: in chrome tpl, the default value of the searchbox must match what the function below is looking for (ie Search or Search Zootoo)
    $("#search-box", parent).focus(function(){
        if ($(this).attr('value') == "type your search here..."){
            $(this).attr('value', '');
        }
		$("#radios_div").attr('style', 'display:block;');
    });
    $("#close_radio").click(function(){
    	$("#radios_div").attr('style', 'display:none;');
    });
    
    // nav
    var navOver = function(el){
   		$("#radios_div").attr('style', 'display:none;');
		if(isIE6 && (!$.SelectBox)){// This is only for IE6
			$('#old_content_container select').each(function(){
				$(this).hide(); // hide all select elements
			});
		}
   		$(el).addClass('hover');
    };
    var navOut = function(el){
   		$(el).removeClass('hover');
		if(isIE6 && (!$.SelectBox)){// This is only for IE6
			$('#old_content_container select').each(function(){
				$(this).show(); // hide all select elements
			});
		}
    };
	
    $("#nav_ul .nav_li").hover(
    	function(){	navOver(this); },
    	function(){	navOut(this); }
    );
    $("#nav_ul #myzootoo").hover(
    	function(){	navOver(this); },
    	function(){	navOut(this); }
    );
    
});

/****  FUNCTIONS  ****/

//center an element
function centerElem(elem){
    var moveTo = ($('#container').width() / 2) - ($(elem).width() / 2);
    if(moveTo > 0){
        $(elem).css('left', moveTo);
    }
}

//returns the height of an element box, including margin, padding, and border
function getElemH(e){
    var prop = new Array('margin-top', 'margin-bottom', 'padding-top', 'padding-bottom', 'border-top-width', 'border-bottom-width');
    var height = $(e).height();
    
    for(var x = 0; x < prop.length; x++){
        var size = 0;
        
        if($(e).css(prop[x])){
            size = $(e).css(prop[x]).split('px');
            size = Number(size[0]);
            
            if(isNaN(size)){//for browsers that read in the em measurement (IE)
                size = $(e).css(prop[x]).split('em');
                if(isNaN(Number(size[0]))){
                    size = 0;//if it's still not a number, CSS must not have a declared size for this, so just set it to 0
                }else{
                    size = Number(size[0]) * 16; //px = em *16, http://www.mobilefish.com/tutorials/css/css_quickguide_div_examples_fluid_layouts.html
                }
            }
            height += size;
        }
    }
    return height;
}

//returns the width of an element box, including margin, padding, and border
function getElemW(e){
    var prop = new Array('margin-left', 'margin-right', 'padding-left', 'padding-right', 'border-left-width', 'border-right-width');
    var width = $(e).width();
    
    for(var x = 0; x < prop.length; x++){
        var size = 0;
        size = $(e).css(prop[x]).split('px');
        if(size != ''){
            size = Number(size[0]);
            if (isNaN(size)){//for browsers that read in the em measurement (IE)
//                size = $(e).css(prop[x]).split('em');
//                size = Number(size[0]) * 16; //px = em *16, http://www.mobilefish.com/tutorials/css/css_quickguide_div_examples_fluid_layouts.html
				size = 0;	// josh fix: the above lines just dont work!
            }
            width += size;
        }
    }
    return width;
}

//returns an element's style size
function getElemStyleSize(elem,style){
    var size = $(elem).css(style).split('px');
    size = Number(size[0]);
    if (isNaN(size)){//for browsers that read in the em measurement (IE)
//        size = $(elem).css(style).split('em');
//        size = Number(size[0]) * 16; //px = em *16, http://www.mobilefish.com/tutorials/css/css_quickguide_div_examples_fluid_layouts.html
		size = 0;	// josh fix: the above lines just dont work!
    }
    return size;
}

//get the page height, taken from http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/index.html
function getPageH(){
    var pageHeight = 0;
    if (window.innerHeight){
    	pageHeight = window.innerHeight
    }
    else if (document.documentElement && document.documentElement.clientHeight){
    	pageHeight = document.documentElement.clientHeight
    }
    else if (document.body){
    	pageHeight = document.body.clientHeight
    }
    return pageHeight;
}

//detect the version of Flash a user is using (if any), based on http://www.quirksmode.org/js/flash.html
function detectFlashVersion(){
    var flashinstalled = 0;
    var flashversion = 0;
    MSDetect = "false";
    if (navigator.plugins && navigator.plugins.length){
    	x = navigator.plugins["Shockwave Flash"];
    	if (x){
    		flashinstalled = 2;
    		if (x.description){
    			y = x.description;
    			flashversion = y.charAt(y.indexOf('.')-1);
    		}
    	}
    	else{
    		flashinstalled = 1;
    	}
    	if (navigator.plugins["Shockwave Flash 2.0"]){
    		flashinstalled = 2;
    		flashversion = 2;
    	}
    }
    else if (navigator.mimeTypes && navigator.mimeTypes.length){
    	x = navigator.mimeTypes['application/x-shockwave-flash'];
    	if (x && x.enabledPlugin){
    		flashinstalled = 2;
    	}
    	else{
    		flashinstalled = 1;
    	}
    }
    else{
    	MSDetect = "true";
    }
    
    if(flashinstalled > 0){
        return flashversion;
    }
    
    // IE flash detection.
    for(var i=9; i>0; i--){
    	flashversion = 0;
    	try{
    		var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
    		flashversion = i;
    		return flashversion;
    	}
    	catch(e){
    	}
    }
    
    return false;
}

//Get URL parameters, http://www.netlobo.com/url_query_string_javascript.html
function gup(name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null ){
        return "";
    }
    else{
        return results[1];
    }
}

//get X and Y scroll values, http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

//temporarily displays a confirmation notice centered on the browser, this can be called via ajax or in www config on a page load (via the session)
function displayNotice(sticky){
    //initialize the display of the notice
    $('#notice').css('visibility','hidden');
    $('#notice').css('display','block');
    //position the notice
    centerElem('#notice');
	$('#notice').css('top', ((getPageH() / 2) - ($('#notice').height() / 2) + getScrollXY()[1]) + 'px');
	//show the notice for 5 secs, note: cannot use jquery show() method, as we need the width to center the item before display
	$('#notice').css('visibility','visible');

    if (sticky) {
    	$('#notice #sticky').css('display', 'block');
    } else {
    	setTimeout("$('#notice').fadeOut('slow')", 9000);
    	$('#notice #sticky').css('display', 'none');
    }
}

// closes the notice
function closeNotice(){
   	$('#notice').fadeOut('fast');
}
$(document).ready(function(){
	$("#nav_ul li").hover(
		function(){ $("ul", this).fadeIn("fast"); }, 
		function() { } 
	);
  	if (document.all) {
			$("#nav_ul li").hoverClass ("sfHover");
		};
});
	  
$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};


function loadScript(url){
	var scripts = document.getElementsByTagName("script");
	var loaded = false;
	for (var i = 0; i < scripts.length; i++) {
		if (scripts[i].src.indexOf(url) != -1) {
			loaded = true;
			break;
		}
	}
	if (!loaded) {
		var e = document.createElement("script");
		e.src = url;
		e.type = "text/javascript";
		document.getElementsByTagName("head")[0].appendChild(e);
		// console.log('loadScript: '+url);		
	}
}