(function(){
    var placeholder = function(evt) {
        var e = evt.target;
        var p = e.getAttribute("placeholder");
        if(p == null || p === undefined)
            return;
        $(e).removeClass("placeholder");
        if(evt.type == "focus" && e.value == p) {
            e.value = "";
        } else if(e.value.match(/^\s+$|^$/)) {
            e.value = p;
            $(e).addClass("placeholder");
        }
    };
    

    var formSubmit = function(evt) {
        $(evt.target).find("input[placeholder]").triggerHandler("focus");
    };

    var toGoCheckbox = function(evt) {
        var id = evt.target.value;
        toGoSelectItem(id, this.checked);
    };
   
    var toGoGrid = function(evt) {
        evt.preventDefault();
        var id = $(evt.target).parent().get(0).id;
        id = id.match(/-(\d+)$/)[1];
        toGoShowInfo(id);
        return id;
    };
    
    var toGoGridToggle = function(evt) {
        var id = toGoGrid(evt);
        var selected = $("#cb-" + id).get(0).checked;
        toGoSelectItem(id, !selected);
    };
    
    var toGoMenus = function(evt) {
        var role = $("#role-select").get(0).value;
        var region = $("#region-select").get(0).value;
        var expertise = $("#expertise-select").get(0).value;
        
        var active	= $(this).get(0).value;
        var current	= $(this).attr("id");
        
        if(role == "potential-client" || role == "media-pr")
        {
            $("#contact-block").show();
		}
        else
        {
            $("#contact-block").hide();
		}
        
        if(!role || !region || !expertise) {
            // $("#personalize-block, #download-block").hide();
            // return;
        }
        
        $("#personalize-block, #download-block").show();
        
    
        for(var id in ibest.toGo)
        {
            var t = ibest.toGo[id];
            
            //	We want the grid to change on every select change
            if ( jQuery.inArray(active, t.tags) >= 0 )
            {
                toGoSelectItem(id, true);
			}
            else
            {
            	if ( current == "role-select" )
            	{
					toGoSelectItem(id, false);
            	}
			}
            
          
        }
    };
    
    //	This function catches all outbound links and opens them in new window.
/**/	var allLinks = function(evt){    	
    	};
   
		var mapDataHide = function(evt) {
        if(evt) evt.preventDefault();
        $("#map-data-expanded>li").slideUp("fast");
    };

    
    var mapDataShow = ibest.mapDataShow = function(id) {
        mapDataHide();
		$("#" + id).slideDown();
		return void 0;
    };
    
/*  */   
  var mapInit = function(i, e) {
        ibest.map = new GMap2(e);
        var map = ibest.map;
        map.addControl(new GSmallMapControl());
        map.setCenter(new GLatLng(0, -20), 2);
        map.setMapType(G_NORMAL_MAP);

		if ( window.location.pathname.indexOf('current-field-work') == -1 ) /* Use the default icon on the current field work page */
		{
	        var icon = new GIcon();
	        icon.image = "/static/images/map-marker.png";
	        icon.shadow = "/static/images/map-marker-shadow.png";
	        icon.iconSize = new GSize(22, 34);
	        icon.shadowSize = new GSize(36, 37);
	        icon.iconAnchor = new GPoint(11, 34);
	        icon.infoWindowAnchor = new GPoint(25, 20);
	        var options = { icon: icon };
		}
		else
		{
			var options;
		}
       
		var sel = $('#locations a.selected');
		var selLat = $(sel).attr('lat');
		var selLng = $(sel).attr('lng');
		
		$('#locations a.studio-title').click(function() {
			//$("#map-data-expanded>li").slideUp("fast");
			var ref		= $(this).attr('href');
			var which	= ref.slice(ref.indexOf('#')+1);
			ibest.mapDataShow('location-'+which);
			
			var lat = $(this).attr("lat") || 0;
            var lng = $(this).attr("lng") || 0;
			if (lat == 0 && lng == 0)
			{
				return;
			}
            var loc = $(this).attr("loc") || '';
            var point = new GLatLng(lat, lng);
            var marker = new GMarker(point, options);
            map.addOverlay(marker);
			
			var point2 = new GLatLng(Number(lat) + 15, lng - 7.5);
			map.setZoom(12);
			map.panTo(point2);
			setTimeout(function() {
				var p = $('#map-data>li[lat='+lat+'][lng='+lng+']');
                marker.openInfoWindowHtml($(p).html(), {
					maxWidth: 320
				});
			}, 500);
		});
		
        $("#map-data>li").each(function(i, e) {
            var lat = e.getAttribute("lat") || 0;
            var lng = e.getAttribute("lng") || 0;
            var loc = e.getAttribute("loc") || '';
            var point = new GLatLng(lat, lng);
            var marker = new GMarker(point, options);
            map.addOverlay(marker);
			
			if ( selLat == lat && selLng == lng )
			{
				var point2 = new GLatLng(Number(lat) + 15, lng - 7.5);
				map.setZoom(12);
				map.panTo(point2);
				setTimeout(function() {
	                marker.openInfoWindowHtml(e.innerHTML, {
						maxWidth: 320
					});
				}, 1000);
			}
			
            GEvent.addListener(marker, "click", function(){
				var z = map.getZoom();
				// Yes, I am painfully aware this is ugly. It's not
				// my fault the map won't center properly so we have
				// to fudge the map's panning a bit. Feel free to
				// come up with a nifty algorithm to calculate these
				// values a bit more prettily [sic]. Or better yet,
				// fix the bug that causes infowindows to be clipped.
				var adjust =
					(z == 1) ? 18 :
					(z == 2) ? 15 :
					(z == 3) ? 12 :
					(z == 4) ? 8 :
					(z == 5) ? 4 :
					(z == 6) ? 2.25 :
					(z == 7) ? 1.25 :
					(z == 8) ? .6 :
					(z == 9) ? .25 :
					(z == 10) ? .1 :
					(z == 11) ? .04 :
					(z == 12) ? .02 :
					(z == 13) ? .01 :
					(z == 14) ? .005 :
					(z == 15) ? .0025 :
					(z == 16) ? .0001 :
					0;
				adjust = (adjust > 0) ? adjust : 0;
				var point2 = new GLatLng(Number(lat) + adjust, lng - (adjust/2));
				map.setZoom(12);
				map.panTo(point2);	// Pan to our temporary location first...
				setTimeout(function() {
	                marker.openInfoWindowHtml(e.innerHTML, {
						maxWidth: 320
					});
				}, 300);	// This pans to the "real" location after a 300ms delay. That (usually) results in a more accurate display.
            });
        });
    };
    
    
    var speakersSelectorClick = function(evt) {
        evt.preventDefault();
        var c = $(evt.target).attr("class");
        $("#speakers-grid-selector li").removeClass("active");
        $(evt.target).parents("li").addClass("active");
        $("#speakers-grid li").removeClass("active");
        $("#speakers-grid li." + c).addClass("active");
        $("#speakers-grid").addClass("filtered");
    };
    

    var slideToggle = function(evt) {
        evt.preventDefault();
        var href = this.getAttribute("href").replace(/^[^\#]+/, "");
        var e = $(href);
        if(e.is(":visible")) {
            $(this).removeClass("active");
            e.slideUp("fast");
        } else  {
            $(this).addClass("active");
            e.slideDown("fast");
        }
    };
 
    
    var fadeToggle = function(evt) {
        evt.preventDefault();
        var href = this.getAttribute("href").replace(/^[^\#]+/, "");
        var e = $(href);
        if(e.is(":visible")) {
            $(this).removeClass("active");
            e.fadeOut("fast");
        } else  {
            $(this).addClass("active");
            e.fadeIn("fast");
        }
    };
    
    
 /**/ 
 	var featuredOn = function(evt) {
        $(this).animate({zIndex: 10, left: "-10px", top: "-31px", width: "183px", height: "112px"}, 99);
    };
    
 
    var featuredOff = function(evt) {
        $(this).animate({zIndex: 0, left: "0px", top: "0px", width: "165px", height: "51px"}, 99);
    };
    
    
    var tripleOn = function(evt) {
        $(this).animate({zIndex: 100, width: "450px"}, 99).find(".frame").fadeIn(99);
    };
    
    
    var tripleOff = function(evt) {
        $(this).animate({zIndex: 0, width: "310px"}, 99).find(".frame").fadeOut(99);
    };
    
   
    var selectFilter = function(evt) {
        $(this).parent().get(0).className = this.value;
    };    
    

    /* setup */
    $(document).ready(function() {
		var zI = 1;
		
		/* Removes dotted line around clicked links */
		$('a').focus(function() {
			$(this).blur();
		});
		
		$('a').click(allLinks);
		
		$('a.vibest').click(function(evt) {
			evt.preventDefault();
			var size = $(this).attr('rel').split('x');
			var vidWin = window.open($(this).attr('href'),"vibest","width="+size[0]+",height="+size[1]+",toolbar=no,status=no");
		});
				
        $("form").submit(formSubmit);
        
        $("input[placeholder], input.sprite").focus(placeholder).blur(placeholder).triggerHandler("blur");

		// Handle external links
		$("a[@rel=external]").click(function(evt) {
			evt.preventDefault();
			window.open(this.href);
		});
		
		$('#locations').accordion({ 
			header: "a.studio-title",
			active: false,
			alwaysOpen: false,
			animated: false,
			autoHeight: false,
			fillSpace: true,
			//header: 'a.studio-title',
			navigation: true,
			navigationFilter: function() {
				if (window.location.hash != '') {
					return this.id == 'accordion-' + window.location.hash.substring(1);
				}
			}
		}).bind('accordionchange', function(evt, ui) {
			var el = $('#locations a');
			$.each(el, function() {
				if ( $(this).hasClass('selected') )
				{
					$(this).children('span.plus-minus').text('[ - ]');
				}
				else
				{
					$(this).children('span.plus-minus').text('[ + ]');
				}
			});
		});
		
		var loca = $('#locations a');
		$.each(loca, function() {
			if ( $(this).hasClass('selected') )
			{
				$(this).children('span.plus-minus').text('[ - ]');
			}
			else
			{
				$(this).children('span.plus-minus').text('[ + ]');
			}
		});
		
		$('#locations a.studio-more').click(function()
		{
			//var which = ($(this).attr('href')).substring(1);
			var ref		= $(this).attr('href');
			var which	= ref.slice(ref.indexOf('#')+1);
			ibest.mapDataShow('location-'+which);
		});
		$('#locations a.studio-title').click(function(evt) {
			$(this).next('div.studio-info').children().hide().fadeIn('slow');
		});
		
         
        $(".slide-toggle").click(slideToggle); 
 
        $(".fade-toggle").click(fadeToggle);
     
        $("#featured li a").hover(featuredOn, featuredOff);
        $("#triple a").hover(tripleOn, tripleOff);
        
        $(".grid-cb").change(toGoCheckbox);
        $("#grid>li").click(toGoGrid);
        $("#grid>li").dblclick(toGoGridToggle);
        $("#alpha form#to-go select").change(toGoMenus);

        $("#map-data-expanded .close").click(mapDataHide);
        $(".map-data-show").click(mapDataShow);
        $("#map").each(mapInit);
		$("#map > div").css('background-color', '#99B3CC');

		if ( window.GUnload ) // Only applies if Google Maps is used
		{
			$(window).unload(GUnload); // Google's built-in memory leak fixer
		}
        
        $("#speakers-grid-selector a").click(speakersSelectorClick);
		
		var speakersTopicsActive;

		$('#speakers-grid li').hover(
			function() {
			
				var activeTopic = $('#speakers-grid-selector li.active');
				
				// Find the currently selected topic, if any, so 
				// that we may return to it later
				speakersTopicsActive = $(activeTopic).children('a').attr('class');
	
				// Take away the .active class from the currently selected
				// topic, if any
				$(activeTopic).removeClass('active');
				
				// Gather the hovered item's topics
				var c = $(this).attr("class").split(' ');
				// Iterate through the topics
				$.each(c, function() {
					// Give each topic a class of .active
					$('#speakers-grid-selector li a.' + this).parent().addClass('active');
				});
			
			}, function() {
	
				$('#speakers-grid-selector li.active').removeClass('active');
				if (speakersTopicsActive) {
					$('#speakers-grid-selector li a.' + speakersTopicsActive).parent().addClass('active');
				}
			
		});
		


		

	 });
})();