/* ===========================================================================
    In-page building search
*/

$(document).ready(function(){
    
  jQuery.expr[':'].Contains = function(a,i,m){
      return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
  };
  
  list = $("#buildings"); // The list of things to search
  $("#building-search")
    .change( function () {
      var filter = $(this).val();
      if(filter) {
        // this finds all links in a list that contain the input,
        // and hide the ones not containing the input while showing the ones that do
        $(list).find("h4 a:not(:Contains(" + filter + "))").parent().parent().hide('slow');
        $(list).find("h4 a:Contains(" + filter + ")").parent().parent().show('slow'); //slideDown();
      } else {
        $(list).find(".building-listing").slideDown();
      }
      return false;
    })
  .keyup( function () {
      $(this).change();
  });

  galleries_list = $("#all-galleries"); // The list of things to search
  $("#gallery-search")
    .change( function () {
      var filter = $(this).val();
      if(filter) {
        // this finds all links in a galleries_list that contain the input,
        // and hide the ones not containing the input while showing the ones that do
        $(galleries_list).find("a:not(:Contains(" + filter + "))").parent().parent().slideUp();
        $(galleries_list).find("a:Contains(" + filter + ")").parent().parent().slideDown();
      } else {
        $(galleries_list).find("div").slideDown();
      }
      return false;
    });
 // .change( function () {
 //     $(this).change();
 // });
 // 
  
});


/* ===========================================================================
    In-page gallery search.
    Can/should be generalized, since it's the same as the in-page building search 
*/

$(document).ready(function(){
  
});


  
/* ===========================================================================
    Gallery navigation
*/
$(function(){
	$('#slideshow').slides({
	  autoHeight: true,
	  slidesLoaded: function () {
	    $(".slides_control").height($(".imagesClass:first").height()); 
	    $(".slides_control").css("min-height", $(".imagesClass:first").height()); 
	    
	  },
		preload: true,
		preloadImage: 'img/loading.gif',
		effect: 'slide, fade',
		crossfade: true,
		slideSpeed: 350,
		fadeSpeed: 500,
		generateNextPrev: true,
		generatePagination: false
	});
});


/* ===========================================================================
    Code to display a form placeholder in browsers that don't support
    the 'placeholder' attribute
*/
/* This code is licensed under Creative Commons Attribution 3.0    *
 * You may share and remix the script so long as you attribute the *
 * original author, Andrew January.                                *
 * http://creativecommons.org/licenses/by/3.0/                     */

$(document).ready(function() {
    // Check to see if the browser already supports placeholder text (introduced in HTML5). If it does,
    // then we don't need to do anything.
    var i = document.createElement('input');
    if ('placeholder' in i) {
        return;
    }
    
	var isPassword = function(input) {
		return $(input).attr('realType') == 'password';
	}
	
	var valueIsPlaceholder = function(input) {
		return input.value == $(input).attr('placeholder');
	}

	var showPlaceholder = function(input, loading) {
		// FF and IE save values when you refresh the page. If the user refreshes the page
		// with the placeholders showing they will be the default values and the input fields won't
		// be empty. Using loading && valueIsPlaceholder is a hack to get around this and highlight
		// the placeholders properly on refresh.
		if (input.value == '' || (loading && valueIsPlaceholder(input))) {
			if (isPassword(input)) {
				// Must use setAttribute rather than jQuery as jQuery throws an exception
				// when changing type to maintain compatability with IE.
				// We use our own "compatability" method by simply swallowing the error.
				try {
					input.setAttribute('type', 'input');
				} catch (e) { }
			}
			input.value = $(input).attr('placeholder');
			$(input).addClass('placeholder');
		}
	}
	
	var hidePlaceholder = function(input) {
		if (valueIsPlaceholder(input) && $(input).hasClass('placeholder')) {
			if (isPassword(input)) {
				try {
					input.setAttribute('type', 'password');
					// Opera loses focus when you change the type, so we have to refocus it.
					input.focus();
				} catch (e) { }
			}
			
			input.value = '';
			$(input).removeClass('placeholder');
		}
	}
	
	$(':text[placeholder],:password[placeholder]').each(function(index) {
		// We change the type of password fields to text so their placeholder shows.
		// We need to store somewhere that they are actually password fields so we can convert
		// back when the users types something in.
		if ($(this).attr('type') == 'password') {
			$(this).attr('realType', 'password');
		}

		showPlaceholder(this, true);
		
		$(this).focus(function() { hidePlaceholder(this) });
		$(this).blur(function() { showPlaceholder(this, false) });
	});
});



/* ===========================================================================
    Google maps
    Used on building pages
*/
var geocoder;
var map;

var customIcons = {
  restaurant: {
    icon: '/hd/workspace/images/icons/good.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  },
  bar: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  }
};

function initialize() {
    
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(42.331427,-83.045754);
  var myOptions = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    zoomControl: true,
    mapTypeControl: false,
    streetViewControl: false,
  }
  
  var overview = {
    zoom: 11,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    zoomControl: true,
    mapTypeControl: false,
    streetViewControl: false,
  }
  
  var near = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    zoomControl: true,
    mapTypeControl: false,
    streetViewControl: false,
  }
  
  
  
  if ($('#map-canvas').length) {
      map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
      codeAddress();
  };
  
  if ($('#buildings-map').length) {
    map_far = new google.maps.Map(document.getElementById("buildings-map"), overview);
    map_near = new google.maps.Map(document.getElementById("buildings-map-near"), near);
    maps = [map_far, map_near];
    var infoWindow = new google.maps.InfoWindow;

    // Change this depending on the name of your PHP file
    downloadUrl("/hd/buildings-georss", function(data) {
      var xml = data.responseXML;
      var markers = xml.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
        var name = markers[i].getAttribute("name");
        var slug = markers[i].getAttribute("slug");
        var image = markers[i].getAttribute("image");
        var path = "http://historicdetroit.org/images/2/50/50/5/images/" + image;
        var html = "<b><a href='" + slug + "'>" + name + "</a></b> <img src='" + path + "' height='50' width='50' alt='' />";

        var point = new google.maps.LatLng(
            parseFloat(markers[i].getAttribute("lat")),
            parseFloat(markers[i].getAttribute("lng")));
        var icon = customIcons['restaurant'];
        for (var m = 0; m < maps.length; m++) {
            var marker = new google.maps.Marker({
              map: maps[m],
              position: point,
              icon: icon.icon,
              shadow: icon.shadow
            });
            
            bindInfoWindow(marker, maps[m], infoWindow, html);
        }
      }
    });
  }
}


function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}

function downloadUrl(url,callback) {    
 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequest;


 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request, request.status);
   }
 };

 request.open('GET', url, true); 
 request.send(null); 
}    


function doNothing() {}

function codeAddress() {
  var address = document.getElementById("address").innerHTML.trim();
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
      });      
    } else {
        // Hide the map if geocode was unsuccessful
        document.getElementById('map-canvas').style.display = 'none';    
    }
  });
}

