/*

	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() {
    $('a#moreResultsBtn').click(front_ajax_pagination_handler);
	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>');
	}
	cufonText();
	setUpClasses();
	listingClick();
	home_map();
	mapControls();
	home_listing();
	showPassword();
	sitewideSearch();
	login();
	toutFilter();
	mediaBrowser();
	discussions();
	directoryAz();
	
	safariTest();
}

function runOnLoaded() {
}

function onResizeFunction() {
}

function onScrollFunction() {
}

function front_ajax_pagination_handler(e) {
	e.preventDefault();
	$.getScript(this.href);
}


// --------------------------------------------------------------------------------------------------------------
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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"); 
	});
}

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

function cufonText() {
    if (typeof(Cufon) != "undefined") {
        Cufon.set('fontFamily', 'FS Albert');
        Cufon.replace('#nav a', {
        	hover: true
        });
        Cufon.replace('.fR', {
        	hover: true, 
        	hoverables: { a:true, h2:true, span:true }
        });
    }
}

function redoCufon() {
    Cufon.replace('.fR', {
    	hover: true, 
    	hoverables: { a:true, h2:true, span:true }
    });
}

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

function mapControls() {
    if($(".home-map").length > 0) {
    	$("ul.tabs li a.events").click(function(event) {
    		event.preventDefault();
    		$("ul.tabs li").removeClass("active");
    		$(this).parent().addClass("active");
    		var markers = rm.markers;
    		for(i = 0; i < markers.length; i++) {
    			markers[i].hide();
    			if(markers[i].type == "event") {
    				markers[i].show();
    			}
    		}
    	});
    	$("ul.tabs li a.news").click(function(event) {
    		event.preventDefault();
    		$("ul.tabs li").removeClass("active");
    		$(this).parent().addClass("active");
    		var markers = rm.markers;
    		for(i = 0; i < markers.length; i++) {
    			markers[i].hide();
    			if(markers[i].type == "story") {
    				markers[i].show();
    			}
    		}
    	});
    	$("ul.tabs li a.companies").click(function(event) {
    		event.preventDefault();
    		$("ul.tabs li").removeClass("active");
    		$(this).parent().addClass("active");
    		var markers = rm.markers;
    		for(i = 0; i < markers.length; i++) {
    			markers[i].hide();
    			if(markers[i].type == "company") {
    				markers[i].show();
    			}
    		}
    	});
    }
}

function home_map() {
    if($(".home-map").length > 0) {
        $("h1 a").addClass("disabled");
        $(".home-map .explore a, .home-map header").click(function(event) {
            event.preventDefault();
            if (isIE) {
                $(".home-map header, .home-map .explore a").hide();
                $(".home-map .tabs li a").eq(0).animate({
                    left: 0
                }, 300, function(){
                    $(".home-map .tabs li a").eq(1).animate({
                        left: 0
                    }, 200, function(){
                       $(".home-map .tabs li a").eq(2).animate({ left: 0 }, 100); 
                    });
                });
            } else {
                $(".home-map header, .home-map .explore a").fadeOut(250, function(){
                    $(".home-map .tabs li a").eq(0).animate({
                        left: 0
                    }, 300, function(){
                        $(".home-map .tabs li a").eq(1).animate({
                            left: 0
                        }, 200, function(){
                           $(".home-map .tabs li a").eq(2).animate({ left: 0 }, 100); 
                        });
                    });
                });   
            }         
            $(".home-map").addClass("home-map-active");
            $("h1 a").removeClass("disabled");
        });
        $("h1 a").click(function(event) {
            event.preventDefault();
            $(".home-map-active .tabs li a").eq(2).animate({
                left: "21px"
            }, 100, function(){
                $(".home-map .tabs li a").eq(1).animate({
                    left: "21px"
                }, 100, function(){
                    $(".home-map .tabs li a").eq(0).animate({ 
                       left: "21px" 
                    }, 100, function(){
                        var date = new Date();
                        var curDate = null;
                        do { curDate = new Date(); } 
                        while(curDate-date < 250);
                        if (isIE) {
                            $(".home-map header, .home-map .explore a").show();
                        } else {
                            $(".home-map header, .home-map .explore a").fadeIn(250);
                        }
                    }); 
                });
            }); 
            $("h1 a").addClass("disabled");
            $(".home-map").removeClass("home-map-active");        
        });
    }
}

function home_listing() {
    if($(".home-listing").length > 0) {
        // accordion
        var $open = $(".home-listing h2:first");
        var animating = false;
        //        
        function openListing(el) {
            var $section = el.parent().parent();
            var $container = $section.find(".listing-container");
            var $paginator = $section.find(".listing-paginator");            
            //
            $section.animate({ height: "216px" }, 300, function(){});
            $container.animate({ height: "186px" }, 300, function(){});
            $paginator.fadeIn(300, function(){ 
                $section.addClass("home-listing-open");
                animating = false;
            });
            //
            $open = el;
        }
        function closeListing(el) {
            animating = true;
            //
            var $section = $open.parent().parent();
            var $container = $section.find(".listing-container");
            var $paginator = $section.find(".listing-paginator");            
            //
            $section.animate({ height: "30px" }, 300, function(){});
            $container.animate({ height: "0px" }, 300, function(){});
            $paginator.fadeOut(300, function(){ 
                $section.removeClass("home-listing-open"); 
                openListing(el); 
            });
        }
        //
        $(".home-listing h2").click(function(event){
            event.preventDefault();
            $section = $(this).parent().parent()
            
            if (!$section.hasClass("home-listing-open") && !animating) {
                closeListing($(this));
            }
        });
        //
        // slider
        $(".home-listing").each(function(){
           slider($(this).find(".listing-container"), $(this).find(".listing"), 690, 3, 1, 0);
        });
    }
}

function slider(sliderContainer, sliderInner, slideAmount, itemsVisible, currentSet, budge) {
    // set up
    var sliderContainer = sliderContainer || false;
    var sliderInner = sliderInner || false;
    var slideAmount = slideAmount || false;
	var itemsVisible = itemsVisible || false;
	var currentSet = currentSet || 1;
	var budge = budge || 0;
	
	if (sliderContainer && sliderInner && slideAmount && itemsVisible) {
	
	    // house keeping
    	var currentSliderPos = budge + ((currentSet - 1) * slideAmount * -1);
    	var paginator = sliderContainer.parent().find("ul[class*=paginator]");
    	// bubble
    	var sliderMoving = false;
    	var maxSet = Math.ceil(sliderInner.children().length/itemsVisible);
		
    	// set up
    	sliderInner.css({ left: currentSliderPos });
		
    	// the slider functions
    	function moveSlider(direction) {
    		if (!sliderMoving) {
    			calculateNextPosition(direction);
    			sliderMoving = true;
    			sliderInner.animate({
    				left: currentSliderPos					
    			}, 500, function(){ sliderMoving = false; });
    			updatePaginator();
    		}
    	}		
    	// calculate the next position of the slider
    	function calculateNextPosition(direction) {
    		if(direction == 'right') {
    			currentSliderPos -= slideAmount;
    			currentSet++;
    		} else if (direction == 'left') {			
    			currentSliderPos += slideAmount;
    			currentSet--;
    		} else {
    		    currentSliderPos = budge + ((direction-1) * slideAmount * -1);
    		    currentSet = direction;
    		}
    	}
	
    	// update paginator links
    	function updatePaginator() {
    		if(currentSet == 1) {
    			paginator.find("li.prev a").hide();
    			paginator.find("li.next a").show();
    		} else if (currentSet == maxSet) {
    			paginator.find("li.next a").hide();
    			paginator.find("li.prev a").show();
    		} else {
    			paginator.find("li.next a").show();
    			paginator.find("li.prev a").show();
    		}
    		paginator.find("li.current").removeClass("current");
    		paginator.find("li").eq(currentSet-1).addClass("current");
    	}
    	
    	function setUpPaginator() {
    	    if (currentSet == 1 && maxSet == 1) {
    	        paginator.find("li.next a").hide();
    			paginator.find("li.prev a").hide();
    			paginator.addClass("hide");
    	    } else {
    	        var pages = "";
    	        for (i=0;i<maxSet;i++) {
    	            pages = pages + '<li><a href="#">'+(i+1)+'</a></li>';
    	        }
    	        paginator.prepend(pages);
    	        updatePaginator();    	        
    	        // add some events to the slider buttons
            	paginator.find("li a").click(function(e){
            		e.preventDefault();
            		var index = paginator.find("li a").index(this);
            		if (index < maxSet && !$(this).parent().hasClass("current")) {
            		    moveSlider(index+1);   
            		}
            	});
            	paginator.find("li.prev a").click(function(e){
            		e.preventDefault();
            		moveSlider('left');
            	});
            	paginator.find("li.next a").click(function(e){
            		e.preventDefault();
            		moveSlider('right');
            	});
	        }
    	}        
        
        function init() {
            setUpPaginator();
        }
        
        init();
    }
}

function showPassword() {
    if($("li.show_password").length > 0) {
        $("li.show_password").each(function(){
            function showHide(el) {          
                if (el.find("input[type=checkbox]").is(':checked')) {
                    el.parents("form").find("input[type=password]").each(function(){
                        $(this).replaceWith('<input type="text" name="'+$(this).attr("name")+'" value="'+$(this).attr("value")+'" id="'+$(this).attr("value")+'" class="wasPassword" autocomplete="off" />');
                    });                    
                } else {
                    el.parents("form").find("input.wasPassword").each(function(){                        
                        $(this).replaceWith('<input type="password" name="'+$(this).attr("name")+'" value="'+$(this).attr("value")+'" id="'+$(this).attr("value")+'" />');
                    });
                }
            }            
            $(this).change(function(event){
                showHide($(this));
            });            
            showHide($(this)); 
        });
    }
}

function login() {
    if($("li.sii").length > 0 && !isIE) {
        var animating = false;
        var open = false;
        var loginbox = $("#loginbox");
        var container = $("#tools .container");
        //        
        function openLogin() {
            container.animate({ paddingTop: "148px" }, 300, function(){
                $("#loginbox input[type=text]:first").focus();
                animating = false;
                open = true;
            });
            loginbox.show();
            $("li.sii").addClass("current");
        }
        function closeLogin() {
            container.animate({ paddingTop: "0px" }, 300, function(){
                animating = false;
                open = false;
                loginbox.hide();
            });
            $("li.sii").removeClass("current");
        }
        //
        $("li.sii a").click(function(event){
            event.preventDefault();
            if (!animating) {
                animating = true;
                if(!open) {
                    openLogin();    
                } else {
                    closeLogin();
                }
            }
        });
        
        $("body").click(function(event){
            if (open) {
                event.preventDefault();
                closeLogin();
            }
        });

        $("#loginbox").click(function(event){
            event.stopPropagation();
        });
    }
}

function sitewideSearch() {
    var initVal = $("#searchbox label:first").html();
    if ($("#searchbox input[type=text]").val() == "") {
		$("#searchbox input[type=text]").val(initVal);
	}
	//
	$("#searchbox input[type=text]").focus(function(){
	    $(this).val("");
	});
    $("#searchbox input[type=text]").blur(function(){
	    if ($(this).val() == "") {
			$(this).val(initVal);
		}
	});
	
	var open = false;
	var animating = false;
	
	function openSearch() {
	    $("#searchbox").show().css("width","1px").animate({ width: "190px" }, 300, function(){
            animating = false;
            open = true;
            $("#searchbox input[type=text]").focus();
        });
	}
	function closeSearch() {
	    $("#searchbox").animate({ width: "0px" }, 300, function(){
            $("#searchbox").hide();
            animating = false;
            open = false;
            $("#searchbox input[type=text]").blur();
        });
	}
	
	$("#tools nav li.ss a").click(function(event){
	    event.preventDefault();
	    animating = true;
	    if (!open) {
	        openSearch();	        
	    } else {
	        closeSearch();
	    }
	});
	
	$("body").click(function(event){
        if (open) {
            event.preventDefault();
            closeSearch();
        }
    });
    
    $("#searchbox").click(function(event){
        event.stopPropagation();
    });
}

function toutFilter() {
    var initVal = $("#tout-filter label:first").html() || $("#tout-filter-events input[type=text]").val();
    if ($("#tout-filter input[type=text], #tout-filter-events input[type=text]").val() == "") {
		$("#tout-filter input[type=text], #tout-filter-events input[type=text]").val(initVal);
	}
	//
	$("#tout-filter input[type=text], #tout-filter-events input[type=text]").focus(function(){
	    $(this).val("");
	});
    $("#tout-filter input[type=text], #tout-filter-events input[type=text]").blur(function(){
	    if ($(this).val() == "") {
			$(this).val(initVal);
		}
	});
	$("#tout-filter input[type=submit], #tout-filter-events input[type=submit]").click(function(){
	    if ($(this).parents("form").find("input[type=text]").val() == initVal) {
	        $(this).parents("form").find("input[type=text]").val("");
	    }
	    $(this).parents("form").submit();
	});

	if ($("#tout-filter-events").length > 0 && !isIE6) {
	    $("#tout-filter-events li.selector input[type=radio]").eq(0).attr("checked",true); 
	    $("#tout-filter-events ul.selector li").click(function(event){
	        var index = $("#tout-filter-events ul.selector li").index(this);
	        var selectorContainer = $(this).parents("li.selector");
	        selectorContainer.find("input[type=radio]").eq(index).attr("checked",true);
	        $(this).addClass("current").siblings().removeClass("current");
	    });
	}
}


function mediaBrowser() {
    // MEDIA BROWSER
    $("div.media").each(function(){
        // store reference to this element
        var $this = $(this);
    	//
        // The thumbs slider:
        //
        // some set up vars:
        var sliding = false;
        var slider = $this.find(".thumbs ul:first"); 
        var slideDistance = 672;
        var startPos = 0;
        var currentPos = 0;
        var itemsVisible = 7;
        var maxSlides = Math.ceil(slider.find("li").length/itemsVisible) - 1;
        //
        // 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");
        	}
    	});
    	//
        // The image swapping:
        //
        // some set up vars:
        var swapping = false;
    	var media_main = $this.find(".media-main:first");
    	var current = 0;
    	//
    	// some house keeping
        $this.find("ul.thumbs li:first").addClass("current");
    	//	
    	// what to do if you click a thumbnail
    	$this.find("ul.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
                $this.find(".youtube-player").attr("src", "").hide();
    		    var newImg = $(this).attr("href");
    		    var index = $(".thumbs li a").index(this);
    		    swapping = true;
    		    //
    		    // fade the various bits out 
    		    var img = media_main.find("img:first");
		        var backImgString = "<img src="+img.attr("src")+" id='backImg' />";
		        $(backImgString).insertBefore(img);
		        // 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 and bring them back in
					img.show().attr("src",newImg).css("top","-323px").animate({ 
            		    top: "0px"
					},300, function(){
					    // remember to reset the bubbling var
				        swapping = false;
				        $("#backImg").remove();
					});
                });
				Preloader.load();
    			
    		    // update the current status indicator
    		    var $thisLi = $(this).parent();
    			$thisLi.siblings(".current").removeClass("current").find("img:first").css("top","0px");
    			$thisLi.addClass("current").find("img:first").css("top","0px").animate({ top: "36px" }, 300);
    		}
    		
    		if(!swapping && !$(this).parent().hasClass("current") && $(this).parent().hasClass("video")) {
    		    media_main.find("img:first").hide();
    		    var embedsrc = $(this).attr("rel");
    		    $this.find(".media-main").find(".youtube-player").attr("src", "http://www.youtube.com/embed/" + embedsrc).show();
    		    
    		    var li = $(this).parent();
    		    li.siblings(".current").removeClass("current");
    		    li.addClass("current");
    		}
    	});
    	//
    });
}

function discussions() {
	if($("section.forum").length > 0 && !$("section.show").length > 0) {
		$("ul.forum li").hover(function() {
			$(this).css({
				cursor: 'pointer'
			}).click(function() {
				window.location = $(this).find("a").attr("href");
			});
		});
	}
	if($("section.show").length > 0) {
		$("a.add-comment").click(function(event) {
			event.preventDefault();
			$("form.forum_post").slideToggle();
		});
	}
}

function safariTest() {
	// var winWidth = $(window).width();
	// 	console.log(winWidth);
	// 	console.log("");
	// 	$("*").each(function(el, i) {
	// 		//console.log($(this));	
	// 		// console.log(i+": "+$(this).outerWidth());
	// 		if ($(this).outerWidth() > winWidth) {
	// 			$(this).addClass("bang");
	// 			console.log("banged!");
	// 		}
	// 	});	
}

function directoryAz() {
    $("#showaz").click(function(event) {
        event.preventDefault();
        $(".bar .options:first li").removeClass("current");
        $(this).parent().addClass("current");
        redoCufon();
        $("ul.options-az:first").fadeIn().addClass("open");
    });
    
    $(".options-az:first a").click(function(event) {
//        event.preventDefault();
        var clicked = $(this),
            letter = clicked.text().toLowerCase();
        
        $(".options-az li").removeClass("current");
        clicked.parent().addClass("current");
        redoCufon();
        
    });
}
