







/* 
 * Suckerfish Menus
*/

sfHover = function() {
	var sfEls = document.getElementById("nav_611603").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);



/*
 *QuickSand
 */
 (function($) {
	$.fn.sorted = function(customOptions) {
		var options = {
			reversed: false,
			by: function(a) {
				return a.text();
			}
		};
		$.extend(options, customOptions);
	
		$data = $(this);
		arr = $data.get();
		arr.sort(function(a, b) {
			
		   	var valA = options.by($(a));
		   	var valB = options.by($(b));
			if (options.reversed) {
				return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
			} else {		
				return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
			}
		});
		return $(arr);
	};

})(jQuery);

$(function() {
  
  var read_button = function(class_names) {
    var r = {
      selected: false,
      type: 0
    };
    for (var i=0; i < class_names.length; i++) {
      if (class_names[i].indexOf('selected-') == 0) {
        r.selected = true;
      }
      if (class_names[i].indexOf('segment-') == 0) {
        r.segment = class_names[i].split('-')[1];
      }
    };
    return r;
  };
  
  var determine_sort = function($buttons) {
    var $selected = $buttons.parent().filter('[class*="selected-"]');
    return $selected.find('a').attr('data-value');
  };
  
  var determine_kind = function($buttons) {
    var $selected = $buttons.parent().filter('[class*="selected-"]');
    return $selected.find('a').attr('data-value');
  };
  
  var $preferences = {
    duration: 800,
    easing: 'easeInOutQuad',
    adjustHeight: false
  };
  
  var $list = $('#list');
  var $data = $list.clone();
  
  var $controls = $('ul.splitter ul');
  
  $controls.each(function(i) {
    
    var $control = $(this);
    var $buttons = $control.find('a');
    
    $buttons.bind('click', function(e) {
      
      var $button = $(this);
      var $button_container = $button.parent();
      var button_properties = read_button($button_container.attr('class').split(' '));      
      var selected = button_properties.selected;
      var button_segment = button_properties.segment;

      if (!selected) {

        $buttons.parent().removeClass('selected-0').removeClass('selected-1').removeClass('selected-2').removeClass('selected-3').removeClass('selected-4');
        $button_container.addClass('selected-' + button_segment);
        
        var sorting_type = determine_sort($controls.eq(1).find('a'));
        var sorting_kind = determine_kind($controls.eq(0).find('a'));
        
        if (sorting_kind == 'all') {
          var $filtered_data = $data.find('li');
        } else {
          var $filtered_data = $data.find('li.' + sorting_kind);
        }
        
        if (sorting_type == 'size') {
          var $sorted_data = $filtered_data.sorted({
            by: function(v) {
              return parseFloat($(v).find('span').text());
            }
          });
        } else {
          var $sorted_data = $filtered_data.sorted({
            by: function(v) {
              return $(v).find('strong').text().toLowerCase();
            }
          });
        }
        
        $list.quicksand($sorted_data, $preferences, twofold.prepWork);
        
      }
      
      e.preventDefault();
    });
    
  }); 

  var high_performance = true;  
  var $performance_container = $('#performance-toggle');
  var $original_html = $performance_container.html();
  
  $performance_container.find('a').live('click', function(e) {
    if (high_performance) {
      $preferences.useScaling = false;
      $performance_container.html('CSS3 scaling turned off. Try the demo again. <a href="#toggle">Reverse</a>.');
      high_performance = false;
    } else {
      $preferences.useScaling = true;
      $performance_container.html($original_html);
      high_performance = true;
    }
    e.preventDefault();
  });
});







$(function () {
  // IE6 doesn't handle the fade effect very well - so we'll stick with
  // the default non JavaScript version if that is the user's browser.
  if ($.browser.msie) return;// && $.browser.version < 7
  
  $('#navigation li')
  
    // remove the 'highlight' class from the li therefore stripping 
    // the :hover rule
    .removeClass('highlight')
    
    // within the context of the li element, find the a elements
    .find('a')
    
    // create our new span.hover and loop through anchor:
    .append('<span class="hover" />').each(function () {
      
      // cache a copy of the span, at the same time changing the opacity
      // to zero in preparation of the page being loaded
      var $span = $('> span.hover', this).css('opacity', 0);
      
      // when the user hovers in and out of the anchor
      $(this).hover(function () {
        // on hover
        
        // stop any animations currently running, and fade to opacity: 1
        $(this).find('span.base').stop().fadeTo(300, 0);
        $span.stop().fadeTo(300, 1);
      }, function () {
        // off hover
        
        // again, stop any animations currently running, and fade out
        $(this).find('span.base').stop().fadeTo(300, 1);
        $span.stop().fadeTo(300, 0);
      });
    });
});















var map;
var brooklyn = new google.maps.LatLng(-27.533428, 152.99192);
function initializegmaps() {
  var stylez = [ { featureType: "landscape.man_made", elementType: "all", stylers: [ { hue: "#ff0000" }, { visibility: "on" }, { saturation: -100 }, { lightness: -92 } ] },{ featureType: "road", elementType: "all", stylers: [ { visibility: "on" }, { hue: "#0019ff" }, { saturation: -100 }, { lightness: 40 } ] },{ featureType: "poi.park", elementType: "all", stylers: [ { hue: "#f6ff00" }, { visibility: "off" } ] },{ featureType: "water", elementType: "all", stylers: [ { visibility: "on" }, { hue: "#0008ff" }, { saturation: -99 }, { lightness: -67 } ] },{ featureType: "road.local", elementType: "all", stylers: [ { visibility: "on" }, { saturation: -40 }, { lightness: -51 } ] },{ featureType: "administrative.land_parcel", elementType: "all", stylers: [ { visibility: "on" }, { saturation: -100 }, { lightness: -90 } ] },{ featureType: "poi", elementType: "all", stylers: [ { visibility: "off" } ] } ];
  var mapOptions = {
    zoom: 16,
    center: brooklyn,
    disableDefaultUI: true,
    mapTypeControlOptions: {
       mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'hiphop']
    }
  };
  map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);
  var styledMapOptions = {
      name: "Twofold"
  }
  var jayzMapType = new google.maps.StyledMapType(
      stylez, styledMapOptions);
  map.mapTypes.set('hiphop', jayzMapType);
  map.setMapTypeId('hiphop');
  setMarkers(map, beaches);
}
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("/Images/mapIcons/marker_red.png",
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(41, 47),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 9,34.
      new google.maps.Point(20, 47));
function getMarkerImage(iconColor) {
   if ((typeof(iconColor)=="undefined") || (iconColor==null)) { 
      iconColor = "red"; 
   }
   if (!icons[iconColor]) {
      icons[iconColor] = new google.maps.MarkerImage("/Images/mapIcons/marker_"+ iconColor +".png",
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 6,20.
      new google.maps.Point(0, 34));
   } 
   return icons[iconColor];
}
  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.
  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var iconImage = new google.maps.MarkerImage('/Images/mapIcons/marker_red.png',
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(41, 47),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 9,34.
      new google.maps.Point(0, 47));
  var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 34),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 34));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var iconShape = {
      coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
      type: 'poly'
  };
var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });
function createMarker(map, latlng, label, html, color) {
    var contentString = '<div class="infowindow"><strong>'+label+'</strong><br>'+html+"</div>";
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        shadow: iconShadow,
        icon: getMarkerImage(color),
        shape: iconShape,
        title: label,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
}
/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * o*/
var beaches = [
  ['Twofold', -27.533428, 152.99192, "red"]
];
function setMarkers(map, locations) {
  // Add markers to the map
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = createMarker(map,myLatLng,beach[0],beach[0],beach[3]);
  }
}
















// Grayscale w canvas method
function grayscale(src){
	var canvas = document.createElement('canvas');
	var ctx = canvas.getContext('2d');
	var imgObj = new Image();
	imgObj.src = src;
	canvas.width = imgObj.width;
	canvas.height = imgObj.height; 
	ctx.drawImage(imgObj, 0, 0); 
	var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
	for(var y = 0; y < imgPixels.height; y++){
		for(var x = 0; x < imgPixels.width; x++){
			var i = (y * 4) * imgPixels.width + x * 4;
			var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
			imgPixels.data[i] = avg; 
			imgPixels.data[i + 1] = avg; 
			imgPixels.data[i + 2] = avg;
		}
	}
	ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
	return canvas.toDataURL();
}



var twofold = {
  
  init : function() {
    twofold.prepNavigation();
    twofold.prepSliders();
    twofold.prepTooltips();
    twofold.prepScrollers();
    twofold.prepHand();
    twofold.prepWork();
    twofold.prepRounded();
//    initializegmaps();
  }
  
  ,prepNavigation : function() {
    $('#nav_611603 li').each(function() {
      if (!$(this).hasClass('selected'))
        $(this).find('a').prepend('<span class="base"></span>');
    });
    
  	//Hide (Collapse) the toggle containers on load
  	$(".toggle_container").hide(); 
  	//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
  	$("span.trigger").click(function(){
  		$(this).toggleClass("active").next().slideToggle("slow");
  		return false; //Prevent the browser jump to the link anchor
  	});
  }

  ,prepSliders : function() {
    $('#slider1 li:first .slider-text').css({ marginLeft: '480px' });
    $('#slider1').anythingSlider({
   		startStopped    : false, // If autoPlay is on, this can force it to start stopped
			width           : 1920,   // Override the default CSS width
			height          : 1000,   // Override the default CSS width
			theme           : 'minimalist-round',
			buildArrows     : true,
			autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
			resumeDelay     : 10000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
			onSlideComplete : function(slider){
				// alert('Welcome to Slide #' + slider.currentPage);
			}
			,onSlideBegin : function(slider) {
			  var target_slide = $('li.activePage').next();
			  if ($('li.activePage').length == 0 || target_slide.length == 0) target_slide = $('#slider1 li:first').next().next();
			  var target_text = target_slide.find('.slider-text');
			  target_text.animate({
			    marginLeft: '480px'
			  }, 1000, 'easeInOutExpo');
			}
			,onSlideComplete : function(slider) {
			  var target_slide = $('li.activePage').next();
			  target_slide.find('.slider-text').css({ marginLeft: '1280px' });
			}
		});
		$('#slider2').anythingSlider({
			width               : 546,   // if resizeContent is false, this is the default width if panel size is not defined
			height              : 512,   // if resizeContent is false, this is the default height if panel size is not defined
			resizeContents      : false,
			theme           : 'minimalist-round',
			buildArrows     : false,
			pauseOnHover    : true,      //
			autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
			resumeDelay     : 17000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
			onSlideComplete : function(slider){
				// alert('Welcome to Slide #' + slider.currentPage);
			}
		});
		
		// External Link
		$("a.muppet").click(function(){
			$('#slider1').anythingSlider(5);
			$(document).scrollTop(0);
			return false;
		});
		// Report Events to console & features list
		$('#slider1').bind('before_initialize initialized swf_completed slideshow_start slideshow_stop slideshow_paused slideshow_unpaused slide_init slide_begin slide_complete', function(e, slider){
			// show object ID + event (e.g. "slider1: slide_begin")
			var txt = slider.$el[0].id + ': ' + e.type + ', now on panel #' + slider.currentPage;
			$('#status').text(txt);
			if (window.console && window.console.firebug){ console.debug(txt); } // added window.console.firebug to make this work in Opera
		});
		// Add a slide
		var imageNumber = 1;
		$('button.add').click(function(){
			$('#slider1')
				.append('<li><img src="images/slide-tele-' + (++imageNumber%2 + 1)  + '.jpg" alt="" /></li>')
				.anythingSlider(); // update the slider
		});
		$('button.remove').click(function(){
			if ($('#slider1').data('AnythingSlider').pages > 1) {
				$('#slider1 > li:not(.cloned):last').remove();
				$('#slider1').anythingSlider(); // update the slider
			}
		});
  }
  
  ,prepTooltips : function() {
    $('a.tipsy-trigger').tipsy({
      gravity: 's', 
      offset: -48, 
      fade: true
    });
  }
  
  ,prepScrollers : function() {
    $("#toTop").scrollToTop({speed:1000,ease:"easeInOutExpo",start:0});
    $('.work-splitter-top li:last a').click(function() {
      $('html,body').animate({ scrollTop: '670' }, 500, 'easeInOutExpo');
      return false;
    });
  }
  
  ,prepHand : function() {
    $('#iphone').hover(function() {
      $(this).stop().animate({ width: "255px" }, 500, 'easeInOutExpo');
    }, function() {
      $(this).stop().animate({ width: '54px' }, 800, 'easeInOutExpo');
    });
  }
  
  ,prepWork : function() {
    /*$(".image-grid li").live("mouseover mouseout", function(event) {
      if ( event.type == "mouseover" ) {
        event.stopPropagation();
        $(this).find('strong').animate({ top: '0px' });
        $(this).find('span').animate({ top: '34px' });
      } else {
        $(this).find('strong').animate({ top: '-60px' });
        $(this).find('span').animate({ top: '-34px' });
      }
    });*/
    
    $('.image-grid li').hover(function() {
      $(this).find('strong').animate({ top: '0px' });
      $(this).find('span').animate({ top: '34px' });
    }, function() {
      $(this).find('strong').animate({ top: '-60px' });
      $(this).find('span').animate({ top: '-34px' });
    });
  }
  
  ,prepRounded : function() {
    
    var myBorder = RUZEE.ShadedBorder.create({ corner:25, shadow:0 });
    $(".rounded-splitter").each(function() {
      myBorder.render($(this));
    })
    
    var myBorder1 = RUZEE.ShadedBorder.create({ corner:20, shadow:0 });
    $(".rounded-20, .rounded-comments").each(function() {
      myBorder1.render($(this));
    })
    
    var myBorder2 = RUZEE.ShadedBorder.create({ corner:8, shadow:0 });
    $(".rounded-8, .pagination").each(function() {
      myBorder2.render($(this));
    })

  }

}

$(document).ready(twofold.init);

// On window load. This waits until images have loaded which is essential
$(window).load(function() {
  if ($('body').hasClass('Contact')) initializegmaps();
  applesearch.init();
  
	// Fade in images so there isn't a color "pop" document load and then on window load
	$(".item img").fadeIn(300);
	// clone image
	$('.item img').each(function(){
		var el = $(this);
		el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
			var el = $(this);
			el.parent().css({"width":this.width,"height":this.height});
			el.dequeue();
		});
		this.src = grayscale(this.src);
	});
	// Fade image 
	$('.item img').mouseover(function(){
		$(this).parent().find('img:first').stop().animate({opacity:1}, 300);
	})
	$('.img_grayscale').mouseout(function(){
		$(this).stop().animate({opacity:0}, 1000);
	});
});
