/*

	13twelve vs. jQuery

	This javascript is the main javascript for the sites actions.
	
*/

// --------------------------------------------------------------------------------------------------------------
// set up variables

var isSafari = false;
var isSafari3 = false;
var isSafari4 = false;
var isIE = false;
var isIE6 = false;
var isIE7 = false;
var isIE8 = false;
var isMozilla = false;
var isOpera = false;
var isMac = false;
var isiphone = false;
var isChrome = false;


// --------------------------------------------------------------------------------------------------------------
// what to do on DOM ready
$(document).ready(function(){
	runOnDOMready();	
	$(window).load(function() {
		// what to do when body loaded
		runOnLoaded();
	});
});
// what to do when window scrolls
$(window).scroll(function() { onScrollFunction(); });
// what to do when window resizes
window.onresize = onResizeFunction;

// --------------------------------------------------------------------------------------------------------------

function runOnDOMready() {
	browserTest();
	if (isIE6) {
		$("body").append('<div id="ie6" class="ie6"><p>This website may <strong>not</strong> fully support Internet Explorer 6. Your general web browsing experience will be much improved if you upgrade for free to <a href="http://www.microsoft.com/windows/products/winfamily/ie/default.mspx">Internet Explorer 7, Internet Explorer 8</a> or <a href="http://www.mozilla.com/en-US/">Mozilla Firefox</a>.</p></div>');
	}
	setUpClasses();
    tagList();
    canvasBg();
    sitewideSearchLabel();
    listingClick();
    jobsTout();
    popularTout();
    ratingAvatarHovers();
    lightboxes();
    categorySelect();
    registration();
    homepage();
    tabScroll(true);
    reflection();
    filterTypeSearch();
    eventsListing();
    mediaBrowser();
    updateSearch();
    tabs();
    searchResults();
    directoryDD();
    siteWidthFix();
}

function runOnLoaded() {}

function onResizeFunction() {
}

function onScrollFunction() {
    tabScroll(false);
}

// --------------------------------------------------------------------------------------------------------------
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ application wide functions */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (remember to test if the elements you are messing with exist) */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( eg. if (($('body.homepage'))!=""){ } ) */

// this function search and replaces a string and returns the new string
// http://www.daveshuck.com/blog/index.cfm/2006/12/13/Javascript-examples--removeElement-and-replaceAll
function replaceAll( str, searchTerm, replaceWith, ignoreCase )   {
   var regex = "/"+searchTerm+"/g";
   if( ignoreCase ) regex += "i";
   return str.replace( eval(regex), replaceWith );
}

// @ppk cookies funcs, http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

// image preloader
// http://warpspire.com/tipsresources/interface-scripting/image-preloading-revisited/
var Preloader = {
  callbacks: [],
  images: [],
  loadedImages: [],
  imagesLoaded: 0,

  add: function(image){
    if (typeof image == 'string') this.images.push(image);
    if (typeof image == 'array' || typeof image == 'object'){
      for (var i=0; i< image.length; i++){
        this.images.push(image[i]);
      }
    }
  },
  onFinish: function(func){
    if (typeof func == 'function') this.callbacks.push(func);
    if (typeof func == 'array' || typeof func == 'object'){
      for (var i=0; i< func.length; i++){
        this.callbacks.push(func[i]);
      }
    }
  },
  load: function(){
    for(var i=0; i<this.images.length; i++){
      this.loadedImages[i] = new Image();
      this.loadedImages[i].onload = function(){ Preloader.checkFinished.apply(Preloader) }
      this.loadedImages[i].src = this.images[i];
    }
  },

  checkFinished: function(){
    this.imagesLoaded++;
    if (this.imagesLoaded == this.images.length) this.fireFinish();
  },
  fireFinish: function(){
    for (var i=0; i<this.callbacks.length; i++){
      this.callbacks[i]();
    }
    this.images = [];
    this.loadedImages = [];
    this.imagesLoaded = 0;
    this.callbacks = [];
  }
}

//Convert a hex value to its decimal value - the inputted hex must be in the
//	format of a hex triplet - the kind we use for HTML colours. The function
//	will return an array with three values.
// http://www.openjs.com/scripts/graphics/hex_color_rbg_value_converter.php
function hex2num(hex) {
	if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
	hex = hex.toUpperCase();
	var hex_alphabets = "0123456789ABCDEF";
	var value = new Array(3);
	var k = 0;
	var int1,int2;
	for(var i=0;i<6;i+=2) {
		int1 = hex_alphabets.indexOf(hex.charAt(i));
		int2 = hex_alphabets.indexOf(hex.charAt(i+1)); 
		value[k] = (int1 * 16) + int2;
		k++;
	}
	return(value);
}


// browser test, 1312
function browserTest() {
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ some simple browser testing */
	// are we on a Mac ?
	if (navigator.appVersion.indexOf("Mac")!=-1) {
		isMac = true;
		$('body').addClass("isMac");
	}
	
	function searchVersion(browser) {
		var dataString = navigator.userAgent;
		var index = dataString.indexOf(browser);
		if (index == -1) return;
		var bVersion = parseFloat(dataString.substring(index+browser.length+1));
		return bVersion.toString().split(".")[0];
	}
	
	// Safari versioning
	isSafari = jQuery.browser.safari;
	if (isSafari) {
		$('body').addClass("isSafari");
		version = searchVersion("Version") || + "";	
		$('body').addClass("isSafari"+version);
		isSafari3 = (version == 3) ? true : false;
		isSafari4 = (version == 4) ? true : false;
	}
		
	// IE versioning
	isIE = jQuery.browser.msie;
	if (isIE) {	
		//$('body').addClass("isIE");
		version = searchVersion("MSIE") || "";
		//$('body').addClass("isIE"+version);
		isIE6 = (version == 6) ? true : false;
		isIE7 = (version == 7) ? true : false;
		isIE8 = (version == 8) ? true : false;
	}
	
	// Mozilla versioning
	isMozilla = jQuery.browser.mozilla;
	if (isMozilla) {
		$('body').addClass("isMozilla");
		version = searchVersion("Firefox") || "";
		$('body').addClass("isMozilla"+version);
	}
	
	// Opera versioning
	isOpera = jQuery.browser.opera;
	if (isOpera) {
		$('body').addClass("isOpera");
	}
	
	// iPhone
	if (navigator.userAgent.indexOf("iPhone") != -1) {
		isiphone = true;
		$('body').addClass("isIphone");
	}
}

// css class helper, 1312
function setUpClasses() {
    if (isIE6) {
        $('input[type=submit]').addClass("submit");
    	$('input[type=radio]').addClass("radio");
    	$('input[type=checkbox]').addClass("checkBox");
    	$('input[type=image]').addClass("image");
    	$('input[type=file]').addClass("file");	
    	$('input[type=text]').addClass("text");	
    	$('input[type=password]').addClass("password");	
    	$('tr:nth-child(even)').addClass("even");
    	$('li:nth-child(even)').addClass("even");
    }
	$('li:first-child').addClass("first");
	$('li:last-child').addClass("last");
	$("input[type=submit]").hover(function(){
		$(this).addClass("submitHover");
	}, function() {
		$(this).removeClass("submitHover");
	});
	$("a[href^=http]").attr("target","_blank");
	$("input[type=text], input[type=password], input[type=radio], select, textarea").focus(function(event){
	   $(this).parent("li").addClass("focus"); 
	});
	$("input[type=text], input[type=password], input[type=checkbox], input[type=radio], select, textarea").blur(function(event){
	   $(this).parent("li").removeClass("focus"); 
	});
	$(".mainCols input[type=text]:first:not(section.directory div.search input[type=text],section.search div.search input[type=text])").focus();
}

// PAGE FUNCTIONS --------------------------------------------------------------------------------------------------------------

// tag list, kjimn
function tagList() {
    $('input[id$=tag_list]').attr('autocomplete', 'off').tagSuggest({
		url: '/my/tags.js',
		delay: 100,
		tagContainer: 'div',
		separator: ', '
	});
}

//
function sitewideSearchLabel() {
    var initVal = $("#searchbar label:first").html();
    if ($("#searchbar input[type=text]").val() == "") {
		$("#searchbar input[type=text]").val(initVal);
	}
	//
	$("#searchbar input[type=text]").focus(function(){
	    $(this).val("");
	});
    $("#searchbar input[type=text]").blur(function(){
	    if ($(this).val() == "") {
			$(this).val(initVal);
		}
	});
}
function filterTypeSearch() {
    var initVal = $("div.filterType label:first").html();
	if ($("div.filterType input[type=text]").val() == "") {
		$("div.filterType input[type=text]").val(initVal);
	}
	//
	$("div.filterType input[type=text]").focus(function(){
	    $(this).val("");
	});
    $("div.filterType input[type=text]").blur(function(){
	    if ($(this).val() == "") {
			$(this).val(initVal);
		}
	});
}

//
var doCanvasBg = false;
function canvasBg() {
    if (!isIE && $("canvas").length > 0 && $("#imgT").length > 0 && $("#imgB").length > 0 && doCanvasBg) {
        //
        var canvas = $("canvas")[0];
    	var $canvas = $("canvas:first");
    	var imgT = document.getElementById('imgT');
    	var $imgT = $('#imgT:first');
    	var imgB = document.getElementById('imgB');
    	var $imgB = $('#imgB:first');
    	var bgColor = $canvas.parent().css("backgroundColor");
    	var gradColor = $canvas.attr("gradColor");
    	var blend = $canvas.attr("blend");
    	//
    	bgColor = replaceAll(bgColor, "rgb", "");
    	bgColor = replaceAll(bgColor, "", "");
    	bgColor = bgColor.split("(");
    	bgColor = bgColor[1].split(")");
    	bgColor = bgColor[0].split(", ");
    	//
    	if(gradColor!=false) {
    	    gradColor = hex2num(gradColor);
	    }
    	//
        if(blend != "lighter" && blend != "source-over") {
            blend = "darker";
        }
    	//
    	function doBg() {
    	    if(canvas.getContext) {
    	        $("#grad, #imgT, #imgB").hide();
    	        $canvas.parent().attr("style","");
    	        //
        	    var cW = 960;
        	    var cH = $canvas.parent().height();
        	    $canvas.attr("width",cW).attr("height",cH);
        	    //
                var imgBpos = (cH > 965) ? cH - 365 : 600;
        	    //
        	    var ctx = canvas.getContext('2d');
        	    ctx.globalAlpha = 1;
                //
                if(gradColor!=false) {
                    var grad = null;
                    //
                    // set up horizontal gradient
                    grad = ctx.createLinearGradient(0,0,cW,0)
                    grad.addColorStop(0,"rgba("+bgColor[0]+", "+bgColor[1]+", "+bgColor[2]+", 1.0)");
                    grad.addColorStop(0.15,"rgba("+bgColor[0]+", "+bgColor[1]+", "+bgColor[2]+", 1.0)");  
                    grad.addColorStop(0.85,"rgba("+gradColor[0]+", "+gradColor[1]+", "+gradColor[2]+", 1.0)");
                    grad.addColorStop(1,"rgba("+gradColor[0]+", "+gradColor[1]+", "+gradColor[2]+", 1.0)");
                    //
                    // do the horizontal gradient
                    ctx.fillStyle = grad;
                    ctx.fillRect (0, 0, cW, cH);
                    //
                    // set up top right angled gradient
                    ctx.globalCompositeOperation = "darker";
                    grad = ctx.createLinearGradient(0,0,(cW/3)*2,-450);
                    grad.addColorStop(0,"rgba("+gradColor[0]+", "+gradColor[1]+", "+gradColor[2]+", 0)");  
                    grad.addColorStop(1,"rgba("+gradColor[0]+", "+gradColor[1]+", "+gradColor[2]+", 0.6)");
                    //
                    // do the top right angled gradient
                    ctx.globalAlpha = 0.15;
                    ctx.fillStyle = grad;  
                    ctx.fillRect (0, 0, cW, cH);
                } else {
                    // make a background of the bg colour
                    ctx.globalAlpha = 1;
        	        ctx.fillStyle = "rgba("+bgColor[0]+", "+bgColor[1]+", "+bgColor[2]+", 1)";  
                    ctx.fillRect (0, 0, cW, cH);
                }
                //
                // set up and blend the images on top of the colours
                ctx.globalCompositeOperation = blend;
                //
                ctx.globalAlpha = 0.25;
                ctx.drawImage(imgT,0,0,cW,600);
                ctx.globalAlpha = 0.5;
                ctx.drawImage(imgB,0,imgBpos,cW,365);
                //
                $canvas.show();
        	}
        }
        //
        //
        doBg();
        //
        //
    } else {
        $("#imgT, #grad").show();
        if ($("#content").height() < 965) {
            $("#imgB").css("bottom","auto").css("top","600px").fadeIn(3000);
        } else {
            $("#imgB").fadeIn(3000);
        }
    }
}


function listingClick() {
    if($(".listing li").length > 0 || $(".tout-listing li").length > 0) {
        $(".listing li, .tout-listing li").click(function(event){
            event.preventDefault();
            var href = $(this).find("a:first").attr("href");
            if (href != "#") {
                window.location = href;
            }
        });
        $(".listing li a, .tout-listing li a").click(function(event){
           event.stopPropagation(); 
        });
        if (isIE6) {
            $(".listing li").hover(function(){
                $(this).addClass("hover");
            }, function() {
                $(this).removeClass("hover");
            });
        }
    }
}

function lightboxes() {
    var $lbBG = $("#lb-bg");
    var $lb = $("#lb");
    var $lbC = $("#lb-content");
    //
    function openLightbox(content) {
        showLightboxBG();
        if(content.indexOf("#") != -1) { 
            $lbC.load(content, function(responseText, textStatus, XMLHttpRequest){
                if (textStatus == "success") {
                    setUpClasses();
                    $("input[type=text]:focus").blur();                    
                    $lb.fadeIn(300, function(){
                        $lb.find("input[type=text]:first").focus();
                    });
                } else {
                    $lbC.html('<p>Oops! Something went wrong. This <a href="'+content+'">link</a> should take you to where you wanted to go.</p>');
                }
            });
        } else {
           $lbC.html(content);
           setUpClasses();
           $lb.fadeIn(300);
        }
    }
    function closeLightbox() {
        hideLightboxBG();
        $lb.fadeOut(300, function(){
           $lbC.html("");
           $("input[type=text]:focus").blur();
           $(".mainCols input[type=text]:first").focus();
        });
    }
    function showLightboxBG() {
        if(isIE) {
            $lbBG.height($("#ct").height()).show();
        } else {
            $lbBG.height($("#ct").height()).fadeIn(300);
        }
    }
    function hideLightboxBG() {
        if(isIE) {
            $lbBG.hide();
        } else {
            $lbBG.fadeOut(300);
        }
    }
    //
    $("#lb-close a").click(function(event){
        event.preventDefault();
        closeLightbox();
    });
    
    $(window).keyup(function(event) {
        if(event.keyCode == 27) {
            closeLightbox();
        }
    });
    
    //
    $("#tools li.login a, .loginLB a, a.loginLB").click(function(event){
        event.preventDefault();
        var href = $(this).attr("href");
        openLightbox(href+" #login");
    });
}

function registration() {
    if ($("#registration-more-btn")) {
        $("#registration-more-btn").click(function(event){
            event.preventDefault();
            if(!$("#registration-more").hasClass("open")) {
                if (!isIE6) {
                    if ($("#content").height() < 965) {
                        $("#imgB").animate({top:"633px"}, 300);
                    } else {
                        $("#imgB").animate({bottom:"-26px"}, 300);
                    }
                    $("#grad").animate({ height:$("#content").height()+"px" }, 300);
                    $("#registration-more").addClass("open").show().css("height","1px").css("padding-top","0px").css("opacity","1").animate({ height:"26px", opacity:"1", paddingTop:"7px" }, 300);                    
                } else {
                    alert($("#registration-more").text());
                }
            } else {
                if (!isIE6) {
                    if ($("#content").height() < 965) {
                        $("#imgB").animate({top:"600px"}, 300);
                    } else {
                        $("#imgB").animate({bottom:"-26px"}, 300);
                    }
                    $("#grad").animate({ height:$("#content").height()+"px" }, 300);
                    $("#registration-more").removeClass("open").animate({ height:"1px", opacity:"0", paddingTop:"0px" }, 300);
                }
            }
        });
    }
}


/* K */
function jobsTout() {
	if ($('#tout-jobs').length > 0) {
		var tout = $('#tout-jobs');
		var paginator = tout.find('ul.paginator');
		var listing = tout.find('ul.tout-listing');
		
		// Paginator links
		paginator.find('a').click(function(e) {
			e.preventDefault();
			
			// Move current class
			paginator.find('li').removeClass('current');
			$(this).parents('li:first').addClass('current');
			
			// Paginate content
			var page = parseInt($(this).attr('href').match(/(\d+)$/)[1]);
			var start_item = ((page - 1) * 3) + 1;
			
			// Hide all items
			listing.find('li').hide();
			
			for (i = start_item; i < (start_item + 3); i++) {
				listing.find('li:nth-child(' + i + ')').show();
			}
		});
	}
}

function popularTout() {
	if ($('#tout-popular').length > 0) {
		var tout = $('#tout-popular');
		var tabs = tout.find('ul.timeframe');
		
		tabs.find('a').click(function(e) {
			e.preventDefault();
			tabs.find('li').removeClass('current');
			$(this).parents('li:first').addClass('current');
			
			tout.find('ul.tout-listing').hide();
			$($(this).attr('href')).show();
		});
	}
}

function categorySelect() {
	if ($('ul.labels-listing').length > 0) {
		var list = $('ul.labels-listing');
		
		links = list.find('li:not(.current) a');
		links.live('mouseover', function() { $(this).css('background-color', $(this).attr('bgcolor')); });
		links.live('mouseout', function() { $(this).css('background-color', ''); });
		
		var current = list.find('li.current a');
		current.css('background-color', current.attr('bgcolor')).parent().removeClass("current");
		
		links.live('click', function() {
		    $(this).parent().addClass("current");
		    var col = $(this).attr('bgcolor');
		    list.find('li.current a').css('background-color', col);
		});
	}
}

function ratingAvatarHovers() {
    if($(".ratings .fans li").length > 0) {
        var ratingFan = $("#rating-fan");
        $(".ratings .fans li").hover(function(){
            $("#rating-fan").html($(this).find("img").attr("alt"));
        }, function() {
            $("#rating-fan").html("");
        });
    }
}

function homepage() {
    if($(".mainCols-home").length > 0) {
        homepageFeatures();
        homepageMostRecent();
    }
}

function homepageFeatures() {
    if($(".features").length > 0) {
        var lastH2 = $(".mainCols-home .features h2:last");
        var tabs = $(".mainCols-home .features h2 a") 
        var uls = $(".mainCols-home .features ul");
        var ulWidth = 0;
        //
        uls.each(function(i){
            if (i == 0) {
                ulWidth = $(this).width();
                $(this).css("width",ulWidth+"px").css("opacity","1");
            } else {
                $(this).css("width","0px").css("opacity","0");
            }
        });
        lastH2.css("float","right");
        //
        tabs.each(function(i){
            var $this = $(this);
            var h2 = $this.parent();
            var index = i;
            //
            $this.click(function(event){
                event.preventDefault();
                if(!h2.hasClass("active")) {
                    if (index == 2) {
                        lastH2.css("float","left");
                    } else {
                        lastH2.css("float","right");
                    }
                    $(".mainCols-home .features h2.active").removeClass("active").next().animate({
            		    width: "0px", 
            		    opacity: 0
            		}, 400, function(){
            		    $(this).hide();
            		});
            		h2.addClass("active").next().css("display","inline").css("float","left").animate({
            		    width: ulWidth+"px", 
            		    opacity: 1
            		}, 400);
                }
            });
        });
        //
        $(".mainCols-home .features ul li").click(function(event){
            event.preventDefault();
            var href = $(this).find("a:first").attr("href");
            if (href != "#") {
                window.location = href;
            }
        });
        $(".mainCols-home .features ul li a").click(function(event){
           event.stopPropagation(); 
        });     
    }
}

function homepageMostRecent() {
    if($(".recent").length > 0) {
        //
        // Slider:
        //
        // some set up vars:
        var animating = false;
        var sliders = $("#mr-contents ul"); 
        var slider = $("#mr-contents ul:first"); 
        var slideDistance = 495;
        var startPos = 35;
        var currentPos = 35;
        var itemsVisible = 3;
        var animSpeed = 450;
        var maxSlides = Math.ceil(slider.find("li").length/itemsVisible) - 1;
        var btnNext = $("#mr-controls .next a");
        var btnPrev = $("#mr-controls .prev a");
        // some house keeping
        btnNext.removeClass("disabled");
        btnPrev.addClass("disabled");
        //
        // Move the sliders
        //
        function move(direction) {
            // check to see if already animating
            if (!animating) {
                animating = true;
                // works out where to send the slider to next
                // and the range of whats open (used to work out whether to show the current css class or not)
                if(direction == "prev") {
                    currentPos = (currentPos + slideDistance);
                } else {
                    currentPos = (currentPos - slideDistance);
                }
                // we might need those buttons to work
                updateBtns();
                // move the slider
                slider.animate({
        		    left: currentPos+"px"
    		    },animSpeed, function(){
    		        // reset the bubble var
    		        animating = false;
    		    });
            }
        }
        //
        // btn clicks
        //
    	btnPrev.click(function(event){
    	   event.preventDefault();
    	   if(!$(this).hasClass("disabled")){
    	       move("prev");
    	   }    	   
    	});
    	btnNext.click(function(event){
    	    event.preventDefault();
    	    if(!$(this).hasClass("disabled")){
        	       move("next");
        	   }
    	});
	    //
	    // TABs
	    //
	    $("#mr-tabs a").each(function(i){
	        var $this = $(this);
	        var index = i;
	        $this.click(function(event){
	            event.preventDefault();
	            if(!$this.parent().hasClass("current") && !animating){
	                // check to see if already animating
                    animating = true;
	                $("#mr-tabs li.current").removeClass("current");
	                $this.parent().addClass("current");
	                updateSliders(index)               
            	}
            	
	        });
	    });
	    //
	    // Update the buttons
	    //
	    function updateBtns() {
	        btnPrev.removeClass("disabled");
            btnNext.removeClass("disabled");
	        // just testing to see if we need the btns
            if(currentPos == startPos) {
                btnPrev.addClass("disabled");
            } else if (currentPos == ((maxSlides * slideDistance*-1)+startPos)) {
                btnNext.addClass("disabled");
            }
	    }
	    //
	    // Swap the sliders
	    //
	    function updateSliders(index) {
	        slider.fadeOut(animSpeed/2, function(){
	            slider = sliders.eq(index);
                slider.fadeIn(animSpeed/2, function(){
                    // reset the bubble var
    		        animating = false;
                });
                if (slider.find("li").length <= itemsVisible) {
                    btnPrev.addClass("disabled");
                    btnNext.addClass("disabled");
        	    } else {
                    maxSlides = Math.ceil(slider.find("li").length/itemsVisible) - 1;
                    currentPos = (replaceAll(slider.css("left"), "px", "")) * 1;
                    updateBtns();
                } 
	        });
	    }
	    
    }
}

function tabScroll(init) {
    if($("#h1") && !isIE6) {
        var $h1 = $("#h1");
        if(init){
            $h1.css("position","absolute");
        } else {
            if ($("body:first").scrollTop() >= 143) {
                $h1.css("position","fixed").css("top","0px");
            } else {
                $h1.css("position","absolute").css("top","143px");
            }
        }
    }
}

function reflection(el,cW,cH) {
    var el = el ? el : false;
    var cW = cW ? cW : 225;
    var cH = cH ? cH : 171;
    //
    if(($(".reflection").length > 0 && !isIE) || (el != false && !isIE)) {        
        var canvas = el ? el : $("canvas.reflection")[0];
    	var $canvas = el ? $(el) : $("canvas.reflection:first");
    	//
    	var img = new Image();    	
    	//
    	function doReflection() {
    	    if(canvas.getContext) {
    	        //
        	    $canvas.attr("width",cW).attr("height",cH);
        	    //
        	    var ctx = canvas.getContext('2d');
        	    //
        	    ctx.save();
        	    //
        	    ctx.globalAlpha = 0.25;
        	    ctx.translate(0,cH);
                ctx.scale(1,-1);
        	    ctx.drawImage(img,0,0,cW,cH);
        	    //
        	    ctx.restore();
        	    //
        	    var grad = ctx.createLinearGradient(0,0,0,60);
        	    if (el) {
        	        grad.addColorStop(0,"rgba(229, 229, 229, 0)");
                    grad.addColorStop(0.5,"rgba(229, 229, 229, 1.0)");
                    grad.addColorStop(1,"rgba(229, 229, 229, 1.0)");
        	    } else {
                    grad.addColorStop(0,"rgba(255, 255, 255, 0)");
                    grad.addColorStop(1,"rgba(255, 255, 255, 1.0)");
                }
                //
                ctx.globalAlpha = 1;
                ctx.fillStyle = grad;  
                ctx.fillRect (0, 0, cW, cH);
                //
                $canvas.fadeIn(3000);
        	}
        }
        //
    	img.onload = function(){
    	    doReflection();
    	}
    	img.src = $canvas.parent().find("img:first").attr("src");
    }
}


// open, closed, disabled

function eventsListing() {
    if($(".year-month").length > 0 && !isIE6) {
        var animating = false;
        var eventHeight = $("ul.events li:first").height() + (replaceAll($("ul.events li").css("border-bottom-width"), "px", "") * 1)|| 135;
        var eventsListSpacing = (replaceAll($("ul.events").css("margin-bottom"), "px", "") * 1) + (replaceAll($("ul.events").css("margin-top"), "px", "") * 1) + (replaceAll($("ul.events").css("padding-bottom"), "px", "") * 1) + (replaceAll($("ul.events").css("padding-top"), "px", "") * 1) || 19;
        var monthInitHeight = $(".months > li h4").height() || 37;
        // 
        $(".months > li:not(.disabled)").each(function(){
            $(this).css("height",$(this).height()+"px");
        });
        $(".months > li.disabled h4 a").click(function(e){
            e.preventDefault();
        });
        $(".months > li:not(.disabled) h4 a").click(function(e){
            e.preventDefault();
            var $this = $(this).parent().parent();
            var monthTotalHeight = 0;
             $this.find("ul.events > li").each(function(i){         
                 var thisLi = $(this).height() + (replaceAll($("ul.events > li").css("margin-bottom"), "px", "") * 1) + (replaceAll($("ul.events > li").css("margin-top"), "px", "") * 1) + (replaceAll($("ul.events li").css("border-bottom-width"), "px", "") * 1);
                 monthTotalHeight = monthTotalHeight + thisLi + 10;
            });
            monthTotalHeight = monthTotalHeight + monthInitHeight + eventsListSpacing;
            //
            if (animating == false) {
                animating = true;
                if($this.hasClass("open")) {
                    $this.removeClass("open").addClass("closed").css("height",$this.height()+"px").animate({
                        height: monthInitHeight+"px"
                    }, 300, function(){ animating = false; });
                    if (isIE) {
                           var gradH = $("#grad").height();
                           $("#grad").height(gradH+"px").animate({ height: (gradH - monthInitHeight)+"px" }, 300);
                       }
                } else {
                    $this.removeClass("closed").addClass("open").css("height","37px").animate({
                        height: monthTotalHeight+"px"
                    }, 300, function(){ animating = false; });
                    if (isIE) {
                       var gradH = $("#grad").height();
                       $("#grad").height(gradH+"px").animate({ height: (gradH + monthTotalHeight)+"px" }, 300);
                   }
                }
            }
        });
    }
}





function mediaBrowser() {
    // MEDIA BROWSER
    $("div.media").each(function(){
        // store reference to this element
        var $this = $(this);
        //
        // The image swapping:
        //
        // some set up vars:
        var swapping = false;
    	var media_main = $this.find(".media-main:first");
    	var current = 0;
    	var videoString = "";
    	//
    	// some house keeping
    	$this.find(".thumbs li.video a").append('<span class="video"></span>');
    	$this.find(".thumbs li a").append('<canvas style="display: none;"></canvas>');
    	$this.find(".thumbs canvas").each(function(i){ reflection(this,78,59); });
    	$this.find(".thumbs li:first").addClass("current").find("a:first").append('<span class="current"></span>');
    	//	
    	// if video
    	if ($this.find(".thumbs li:first").hasClass("video")) {
    	    media_main.find('script').remove();
    	    media_main.find('style').remove();
    	    videoString = media_main.html();
    	    console.log(videoString);
    	}
    	// what to do if you click a thumbnail
    	$this.find(".thumbs li a").click(function(event){
    		event.preventDefault();
    		// watch for bubbling and already selected
    		if (!swapping && !$(this).parent().hasClass("current") && !$(this).parent().hasClass("video")) {
    		    
    		    // grab the values clicked image
    		    var newImg = $(this).attr("href");
    		    var index = $(".thumbs li a").index(this);
    		    swapping = true;
    		    //
    		    // fade the various bits out
    		    if ($(this).parent().siblings(".current").hasClass("video")) {
    		        // image faded out, set up preloading in the next image
                    Preloader.add(newImg);
    				Preloader.onFinish(function() {
    				    // next image loaded
    				    // change the attributes/content of things
    				    media_main.html('<img src="'+newImg+'" style="opacity: 0;" />');
    				    var img = media_main.find("img:first");
    					// bring them back in
    					img.animate({ 
                		    opacity: "1.0"
    					},300, function(){
    					    // remember to reset the bubbling var
    				        swapping = false;
    					});
    				});
    				Preloader.load();
    		    } else {
    		        var img = media_main.find("img:first");
    		        img.animate({
            		    opacity: "0.0"
        		    },300, function(){
        		        // image faded out, set up preloading in the next image
                        Preloader.add(newImg);
        				Preloader.onFinish(function() {
        				    // next image loaded
        				    // change the attributes/content of things
        					img.attr("src",newImg);
        					// bring them back in
        					img.animate({ 
                    		    opacity: "1.0"
        					},300, function(){
        					    // remember to reset the bubbling var
        				        swapping = false;
        					});
        				});
        				Preloader.load();
        			});
        		}
    		    // update the current status indicator	    		
    			$(this).parent().siblings(".current").removeClass("current").find("span.current").fadeOut(250, function(){ $(this).remove(); });
    			$(this).parent().addClass("current").find("a:first").append('<span class="current" style="display: none;"></span>').find("span.current").fadeIn(250);
    			
    		} else if (!swapping && !$(this).parent().hasClass("current") && $(this).parent().hasClass("video")) {
    		    
    		    var index = $(".thumbs li a").index(this);
    		    swapping = true;
    		    //
    		    if (!$(this).parent().siblings(".current").hasClass("video")) {
    		        media_main.find("img:first").animate({
            		    opacity: "0.0"
        		    },300, function(){
        		        //
        		        media_main.html(videoString);
            		    // remember to reset the bubbling var
        		        swapping = false;
        		    });
    		    } else {
    		        //
        		    media_main.html(videoString);
        		    // remember to reset the bubbling var
    		        swapping = false;
    		    }    		    
		        // update the current status indicator	    		
    			$(this).parent().siblings(".current").removeClass("current").find("span.current").fadeOut(250, function(){ $(this).remove(); });
    			$(this).parent().addClass("current").find("a:first").append('<span class="current" style="display: none;"></span>').find("span.current").fadeIn(250);
    			    			
    		}
    	});
    	//
        // The thumbs slider:
        //
        // some set up vars:
        var sliding = false;
        var slider = $this.find(".thumbs ul:first"); 
        var slideDistance = 540;
        var startPos = 0;
        var currentPos = 0;
        var itemsVisible = 6;
        var maxSlides = Math.ceil(slider.find("li").length/itemsVisible) - 1;
        //
        if ($this.parents("#projects").length > 0) {
            slideDistance = 450;
            itemsVisible = 5;
        }
        //
        // some house keeping
        if (maxSlides > 0) {
            $this.find(".next a").removeClass("disabled");
            $this.find(".prev a").addClass("disabled");
        } else {
            $this.find(".next a").hide();
            $this.find(".prev a").hide();
        }
        //
        function move(direction) {
            // check to see if already sliding
            if (!sliding) {
                sliding = true;
                // works out where to send the slider to next
                // and the range of whats open (used to work out whether to show the current css class or not)
                if(direction == "prev") {
                    currentPos = (currentPos + slideDistance);
                } else {
                    currentPos = (currentPos - slideDistance);
                }
                // we might need those buttons to work
                $this.find(".prev a").removeClass("disabled");
                $this.find(".next a").removeClass("disabled");
                // just testing to see if we need the btns
                if(currentPos == startPos) {
                    $this.find(".prev a").addClass("disabled");
                } else if (currentPos == ((maxSlides * slideDistance*-1)+startPos)) {
                    $this.find(".next a").addClass("disabled");
                }
                // move the slider
                slider.animate({
        		    left: currentPos+"px"
    		    },450, function(){
    		        // reset the bubble var
    		        sliding = false;
    		    });   
            }
        }
        // btn clicks
    	$this.find(".prev a").click(function(event){
    	   event.preventDefault();
    	   if(!$(this).hasClass("disabled")){
    	       move("prev");
    	   }    	   
    	});
    	$this.find(".next a").click(function(event){
    	    event.preventDefault();
    	    if(!$(this).hasClass("disabled")){
        	       move("next");
        	   }
    	});
    	//
    });
}

function tabs() {
    if($(".directory .tabs").length > 0) {
        $(".directory .tabs").each(function(){
           var $this = $(this);
           var anchorCurrent = "";
           var anchors = [];
           //
           if($this.find(".current").length > 0) {
               anchorCurrent = $this.find(".current a").attr("href");
           } else {
               anchorCurrent = $this.find("li:first").addClass("current").find("a").attr("href");
           }
           //
           $this.find("a").each(function(i){
              var anchor = $(this).attr("href");
              anchors[i] = $(anchor);
              if (anchor != anchorCurrent) {
                  $(anchor).hide();
              }
              //
              $(this).click(function(event){
                  event.preventDefault();
                  if(!$this.parent().hasClass("current")) {
                        $.each(anchors, function(i,val) {
                            val.hide();
                        });
                        $(anchor).show();
                        $(this).parent().addClass("current").siblings().removeClass("current"); 
                        if ($("#content").height() < 965) {
                            $("#imgB").css("bottom","auto").css("top","600px");
                        } else {
                            $("#imgB").css("top","auto").css("bottom","0px");
                        }
                  }
              });
           });           
        });
    }
}

function updateSearch() {
    if(!isIE) {
        if($("section.directory div.search, section.search div.search").length > 0) {
            var $this = $("section.directory div.search").length > 0 ? $("section.directory div.search") : $("section.search div.search");
            var animating = false;

    		if($("section.directory").length > 0) {
    			animating = true;
    			$this.find("h3:first").parent().addClass("search-open").css("height", "37px").animate({
    				height: "244px"
    			}, 300, function() {
    				animating = false;
    				$this.find("input[type=text]:first").focus();
    			});
    		}

            // search-open
            //
            $this.find("h3:first").click(function(e){
                e.preventDefault();
                var $$this = $(this).parent();
                //
                if (animating == false) {
                    animating = true;
                    if($$this.hasClass("search-open")) {
                        $$this.removeClass("search-open").css("height","244px").animate({
                            height: "37px"
                        }, 300, function(){ animating = false; $this.find("input").blur(); });
                    } else {
                        $$this.addClass("search-open").css("height","37px").animate({
                            height: "150px"
                        }, 300, function(){ animating = false; $this.find("input[type=text]:first").focus(); });
                    }
                }
            });
        }   
    }
}

function searchResults() {
    if($("section.search").length > 0 && !isIE) {
        $("section.search div.section:not(div.section-disabled, div.section-noFunc)").each(function(){
            var $this = $(this);
            var animating = false;
            var height = $this.height();
            //
            $this.find("h3:first").click(function(e){
                e.preventDefault();
                //
                if (animating == false) {
                    animating = true;
                    if($this.hasClass("section-open")) {
                        $this.removeClass("section-open").css("height",height+"px").animate({
                            height: "37px"
                        }, 300, function(){
                            animating = false;
                            if ($("#content").height() < 965) {
                                $("#imgB").css("bottom","auto").css("top","600px");
                            } else {
                                $("#imgB").css("top","auto").css("bottom","0px");
                            }
                        });
                    } else {
                        $this.addClass("section-open").css("height","37px").animate({
                            height: height+"px"
                        }, 300, function(){ 
                            animating = false; 
                            if ($("#content").height() < 965) {
                                $("#imgB").css("bottom","auto").css("top","600px");
                            } else {
                                $("#imgB").css("top","auto").css("bottom","0px");
                            }
                        });
                    }
                }
            }); 
        });
    }
}

function directoryDD() {
   if($("#dd-directory").length > 0) {
       var $dd = $("#dd-directory:first");
       var $tools = $("#tools:first");
       var animating = false;
       
       $tools.find(".directory a:first").click(function(e) {
           e.preventDefault();
           //
           if (animating == false) {
               animating = true;
               if($tools.hasClass("open")) {
                   $tools.removeClass("open").css("height","210px").animate({ height: "33px" }, 300, function() { animating = false; })
                   if (isIE) {
                       var gradH = $("#grad").height();
                       $("#grad").height(gradH+"px").animate({ height: (gradH - 177)+"px" }, 300);
                   }
               } else {
                    $tools.addClass("open").css("height","33px").animate({ height: "210px" }, 300, function() { animating = false; })
                    if (isIE) {
                        var gradH = $("#grad").height();
                        $("#grad").height(gradH+"px").animate({ height: (gradH + 177)+"px" }, 300);
                    }
               }
           }
       });
   }
}

function siteWidthFix() {
    console.log($(window).width());
}