UTIL = {
  fire: function(func,funcname,args){
    var namespace = BATEMAN;
    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
      namespace[func][funcname](args);
    }
  },
  init: function() {
    var bodyId = document.body.id;
    UTIL.fire('common');
    $.each(document.body.className.split(/\s+/),function(i,classnm){
      UTIL.fire(classnm);
      UTIL.fire(classnm,bodyId);
    });
    UTIL.fire('common','finalize');
    $(document).trigger('finalized');
  }
};

BATEMAN = {
  easing: "easeOutCubic",
  common: {
    init: function() {
      UTIL.fire('common', 'polyfills');
      UTIL.fire('common', 'fonts');
      UTIL.fire('common', 'nav');
      UTIL.fire('common', 'basicThumbScroller');
      UTIL.fire('common', 'shareButtons');
      UTIL.fire('common', 'drupalForms');
      UTIL.fire('common', 'imageLazyLoader');
    },
    fonts: function() {
      WebFontConfig = {
        monotype: { projectId: '94c0f252-3f40-4b57-b92b-4c18a2956eaf' }
      };
      
      (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
      })();
    },
    nav: function() {
      var toggleBtn = $('<a id="rb_mainMenuToggle" href="#" title="Hide Menu" class="open" role="button" aria-pressed="true" aria-expanded="true">Hide Menu</a>'),
        mainMenu = $('#rb_mainMenu'),
        textWhenHidden = "Show Menu",
        textWhenVisible = "Hide Menu",
        attrWhenHidden = { 'aria-pressed': 'false', 'aria-expanded': 'false', 'title': textWhenHidden },
        attrWhenVisible = { 'aria-pressed': 'true', 'aria-expanded': 'true', 'title': textWhenVisible };
    
      // put the toggle button in the dom
      mainMenu.before(toggleBtn);
      
      // set up the click events
      toggleBtn.click(function(e) {
        e.preventDefault();     
        if (toggleBtn.hasClass('open')) {
          mainMenu.toggle('slide', 500, function() {
            toggleBtn.removeClass('open');
            toggleBtn.attr(attrWhenHidden).text(textWhenHidden);
          });
        } else {
          mainMenu.toggle('slide', 500, function() {
            toggleBtn.addClass('open');
            toggleBtn.attr(attrWhenVisible).text(textWhenVisible);
          });
        }
      });
      
      // on page load the menu will be visible, but we'll hide it after a short delay to indicate to users where to find it
      $(document).bind('finalized', function() { setTimeout("$('#rb_mainMenuToggle').click();", 1000); });
    },
    polyfills: function() {
      Modernizr.load({
        test: Modernizr.input.placeholder,
        nope: '/sites/all/themes/bateman/js/plugins/placeholder.js',
        callback: function() { $('input, textarea').placeholder(); }
      });
    },
    tooltips: function(el) {
      el.tipTip({ 
        defaultPosition: 'top', 
        edgeOffset: 8
      });
      el.focus(function() { $(this).trigger('mouseover'); });
      el.blur(function() { $(this).trigger('mouseout'); });
    },
    tooltipsleft: function(el) {
      el.tipTip({ 
        defaultPosition: 'left', 
        edgeOffset: 8
      });
      el.focus(function() { $(this).trigger('mouseover'); });
      el.blur(function() { $(this).trigger('mouseout'); });
    },
    tooltipsright: function(el) {
      el.tipTip({ 
        defaultPosition: 'right', 
        edgeOffset: 8
      });
      el.focus(function() { $(this).trigger('mouseover'); });
      el.blur(function() { $(this).trigger('mouseout'); });
    },
    basicThumbScroller: function() {
		$('.rb_thumbScroller:not(.artwork):not(.wide)').each(function() {
			if ($(this).find('li').length > 1) {
				$(this).jcarousel({
					buttonNextHTML: '<a class="rb_button icon next" title="Next">Next</a>',
					buttonPrevHTML: '<a class="rb_button icon previous" title="Previous">Previous</a>',
					easing: BATEMAN.easing,
					animation: 350,
					scroll: 1
				});
			}
		});
		$('.rb_thumbScroller.wide').each(function() {
			if ($(this).find('li').length > 1) {
				$(this).jcarousel({
					buttonNextHTML: '<a class="rb_button icon next" title="Next">Next</a>',
					buttonPrevHTML: '<a class="rb_button icon previous" title="Previous">Previous</a>',
					easing: BATEMAN.easing,
					animation: 350,
					scroll: 1,
					wrap: 'circular'
				});
			}
		});
	},
    initGrayscaleArtistThumbs: function() {
      // grayscale thumbs for webkit
      // firefox and IE get these via CSS/SVG but webkit needs canvas
      if ($.browser.webkit) {
        $(window).load(function(){
          var imgs = $('.artistThumb');
          imgs.each(function(){
            var el = $(this);
            el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998"}).insertBefore(el).queue(function(){
              var el = $(this);
              el.parent().css({"width":this.width,"height":this.height});
              el.dequeue();
            });
            this.src = BATEMAN.common.doGrayscaleArtistThumbs(this.src);
          });
        });
      }
    },
    doGrayscaleArtistThumbs: function(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();
    },
    imageLazyLoader: function() {
		$('img[data-original]').lazyload({
			effect: "fadeIn",
			event: "scrollstop"
		});
	},
	shareButtons: function() {
		var $btns = $('.st_sharethis_custom');
		$btns.click(function(e) {
			e.preventDefault();
		});
		if ($btns.length > 0) {
			Modernizr.load({
				load: 'http://w.sharethis.com/button/buttons.js',
				complete: function() {
					stLight.options({
						publisher: 'd95a84c7-7b9b-428e-85dc-db25d39be6e5',
						onhover: false
					});
				}
			});
		}
	},
	getQueryString: function() {
		var result = {},
			queryString = location.search.substring(1),
			re = /([^&=]+)=([^&]*)/g,
			m;

		while (m = re.exec(queryString)) {
			result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
		}

		return result;
	},
	drupalForms: function() {
		$('.detailMainContent input.form-submit').addClass('rb_button text white large');
		$('#rb_main #search-form #edit-submit').addClass('rb_button icon search');
		$('#rb_main fieldset.search-advanced').remove();
		$('#user-login .form-submit, #user-register .form-submit, #user-pass .form-submit').addClass('rb_button text white');
		$('#user-login').prepend('<h3>Log In to Your Account</h3>');
		$('#user-register').prepend('<h3>Register a New Account</h3>');
		$('#user-pass').prepend('<h3>Forgot your Password?</h3>');
		$('.comment_forbidden a, .comment_add a').addClass('rb_button text white');
		$('#rb_detailContainer + .box').appendTo('.detailMainContent');		
	},
    finalize: function() {
      UTIL.fire('common', 'initGrayscaleArtistThumbs');
      $('select').dropkick(); 
    }
  }
};

BATEMAN.home = {
  init: function() {
    UTIL.fire('home', 'setupRows');
    UTIL.fire('home', 'initVideo');
  },
  data: {
    "title": "Ocean Rhapsody &#8211; Orca",
    "artist": "Robert Bateman",
    "audioURL": "",
    "audioDate": "September 24, 2001",
    "associated": "info",
    "text": "Robert Bateman discusses the art, habitat and protection of the magnificent Orca whale.",
    "moreURL": "#",
    "imageURL": "",
    "ID": "grizzly"
  },
  initVideo: function() {
    if (!Modernizr.touch) {
      jwplayer('rb_emotiveWordsVideoPlayer').setup({
        modes: [
          { type: 'html5' },
          { type: 'flash', src: '/sites/default/files/jwplayermodule/player/player.swf' }
        ],
        backcolor: 'ffffff',
        displayclick: 'none',
        stretching: 'fill',
        controlbar: 'none',
        autostart: true,
        repeat: 'always',
        icons: false,
        mute: true,
        width: '100%',
        height: '100%',
        image: "video/reeds.jpg",
        levels: [
          { file: "http://64.26.178.165/sites/all/themes/bateman/video/reeds.webm" },          
          { file: "http://64.26.178.165/sites/all/themes/bateman/video/reeds.ogv" },
          { file: "http://64.26.178.165/sites/all/themes/bateman/video/reeds.mp4" },          
        ],
        events: {
          onTime: function(e) {
            // seamless looping
            if (e.position >= 7.5) { this.seek(0); }
          },
          onPlay: function(e) {
            $('#rb_emotiveWordsVideoPlayer').fadeIn(750, BATEMAN.easing);
          }
        },        
      });
      if (!Modernizr.video) {
			$('#rb_emotiveWordsVideoPlayer').show();
			$('#rb_emotiveWordsVideoPlayer_wrapper').hide().fadeIn(750, BATEMAN.easing);
	  }
    }
  },
  setupRows: function() {
    var wrapper = $('#rb_emotiveWords'),
      masterList = wrapper.children('.wordList.master'),
      words = masterList.children('li'),
      lists = new Array(4),
      rem = words.length % lists.length,
      count = 0;
    
    // distribute the number of words in the master list into 4 separate lists
    for (var i = 0; i < lists.length; i++) {
      var wordsPerList = Math.floor(words.length / lists.length); // need to reset this every time the loop runs
      
      if (rem === 1 && i === lists.length - 1) { wordsPerList++; } // list 4 will get one word more than 1-3
      else if (rem === 2 && i % 2 === 0) { wordsPerList++; } // lists 1 and 3 will get one extra word each
      else if (rem === 3 && i < lists.length - 1) { wordsPerList++; } // list 4 will get one word fewer than 1-3
      
      lists[i] = $('<ul class="wordList"/>').html(words.slice( count, count + wordsPerList )); // put the words in the list
      var row =  $('<div class="wordsRow"/>').html($(lists[i])); // put the list in a row
      wrapper.append(row); // put the row in the container
      count += wordsPerList; // keep track of our count
    }
    
    // get rid of the original list, which is empty now anyway
    masterList.remove();
    
    // word click events
    $('#rb_emotiveWords .wordList li a').click(function(e) {
      e.preventDefault();
      var word = $(this);
      if (!word.hasClass('active')) {  
    	  if($('#rb_emotiveWords .wordList li a.loading').length < 1){
    		  word.addClass('loading');
    	  }    	  
    	  var wordString = word.html();    	  
		  $.ajax({
		    type: "POST",
			dataType : 'json', // define the type of data that is going to get back from the server					   
			url: "images/get/" + wordString,
			data: $("#idForm").serialize(), // serializes the form's elements.
			success: function(data){				  
				  var artwork = data.artwork;			      
				  BATEMAN.home.data.title=artwork[0].node['title'];
				  BATEMAN.home.data.artist=artwork[0].node['artist'];                
				  BATEMAN.home.data.ID=artwork[0].node['id'];
				  BATEMAN.home.data.text=artwork[0].node['description'];
				  BATEMAN.home.data.imageURL=artwork[1].image['imagecacheurl'];				  
				  $('#node-id').val(artwork[0].node['id']);
				  $('#artworkImageName').val(artwork[1].image['name']);				  
				  BATEMAN.home.data.associated=artwork[2].associated['html'];
				  BATEMAN.home.data.associatedType = artwork[2].associated['content'];
				  UTIL.fire('home', 'toggleRow', word);
			},
			statusCode: {
			     403: function() {
				   window.location.href = "/user/login";
				 }
			}
		  });        
      }      
    });
    
    // hover events, making sure we're within the window bounds
    // these are animated via css, older browsers will just snap into place
    $('#rb_emotiveWords .wordList li:first-child a, #rb_emotiveWords .wordList li:last-child a').bind('mouseover focus', function() {
      var word = $(this),
        p = word.offset(),
        wordWidth = word.outerWidth(),
        windowWidth = $(window).width(),
        diffRight = p.left + wordWidth - windowWidth;
      
      if (diffRight > 0) { // if we're off the right edge
        word.parent().css('padding-right', diffRight*2+12+"px");
      } else if (p.left < 0) { // if we're off the left edge
        word.parent().css('padding-left', (p.left*2*-1)+12+"px");
      }
    });
    $('#rb_emotiveWords .wordList li:first-child a, #rb_emotiveWords .wordList li:last-child a').bind('mouseout blur', function() {
      $(this).parent().attr('style', '');
    });
    
    // artwork viewer arrow navigation
    $('#rb_artworkContainer .next').click(function(e) {
      e.preventDefault();
      var words = $('.wordList a'),
        thisWord = $('.wordList a.active'),
        thisIndex = words.index(thisWord);
      
      if (thisIndex >= words.length - 1) {
        thisIndex = -1;
      }
      
      words.eq(thisIndex + 1).click();
    });
    $('#rb_artworkContainer .previous').click(function(e) {
      e.preventDefault();
      var words = $('.wordList a'),
        thisWord = $('.wordList a.active'),
        thisIndex = words.index(thisWord);
      
      if (thisIndex === 0) {
        thisIndex = words.length;
      }
      
      words.eq(thisIndex - 1).click();
    });
  },
  toggleRow: function(w) {
    var triggerWord = w,
      allWords = $('#rb_emotiveWords .wordsRow .wordList li a'),
      thisRow = w.parent().parent().parent(),
      allRows = thisRow.siblings().not('#rb_artworkContainer'),
      oldRow = $('.wordsRow.active');

    triggerWord.removeClass('loading');
    
    allRows.removeClass('active').addClass('inactive');
    allWords.removeClass('active');
    thisRow.removeClass('inactive').addClass('active');
    triggerWord.addClass('active');
    
    UTIL.fire('home', 'moveViewer', [oldRow, thisRow, triggerWord]);
  },
  moveViewer: function(args) {
    var oldRow = args[0],
      thisRow = args[1],
      c = $('#rb_artworkContainer');
      
    if (!oldRow.is(thisRow)) {
      c.addClass('collapsed').slideToggle(750, BATEMAN.easing, function() { 
        $(this).prependTo(thisRow);
        UTIL.fire('home', 'showViewer', [c, false]);
      });
    } else {
      UTIL.fire('home', 'showViewer', [c, true]);
    }
  },
  showViewer: function(args) {
    var viewer = args[0],
      reuse = args[1];    
            
    // ajax to be added later, meanwhile...
    // load in some data via ajax
    
    var artworkData = BATEMAN.home.data;    
	
    // on callback, do the following
    $('.artworkTitle', viewer).html(artworkData.title); 
    $('.associated', viewer).val(artworkData.associated); 
    $('.artworkArtist', viewer).html(artworkData.artist); 
    $('.artworkMoreInfo', viewer).attr('href', artworkData.moreURL);  
    $('.artworkDate', viewer).html(artworkData.audioDate);  
    $('.artworkDescription', viewer).html(artworkData.text); 
    $('.artworkImage', viewer).html('<img src="'+artworkData.imageURL+'" alt="'+artworkData.title+'" rel="'+artworkData.ID+'" />');
    // $('.artworkAudioPlayer', viewer).doSomeStuff();  
    
    if (!reuse) {
    	$('#rb_emotiveWords').animate({'border-top-width': 0 }, 750, BATEMAN.easing);
		viewer.removeClass('hidden collapsed').hide().slideDown(750, BATEMAN.easing, function() {
			UTIL.fire('artwork', 'initMap', true);
		});
	} else {
		UTIL.fire('artwork', 'initMap', true);
	}
  }
};

BATEMAN.browser = {
  init: function() {
    UTIL.fire('browser', 'initTagBrowser');
  },
  initTagBrowser: function() {
    var types = $('.browserHeaderFilters .rb_button').not('.down'),
      items = $('.browserItems li');
    
    // on page load, "all events" selected by default
    types.eq(0).addClass('selected');

    $('.browserHeaderFilters .rb_button.down').click(function(e) {
      e.preventDefault();
      $(this).toggleClass('selected');
      types.removeClass('selected');
      if ($(this).hasClass('selected')) {
        $('.browserHeaderFiltersHidden').addClass('collapsed').filter('.'+$(this).attr('id')).removeClass('collapsed');
      } else {
        $('.browserHeaderFiltersHidden').addClass('collapsed');
      }
    });
      
    types.click(function(e) {
      e.preventDefault();

      var $this = $(this),
        id = $this.attr('id');

      $this.toggleClass('selected');
      types.not($this).removeClass('selected');

      if (id !== "item") { // is not "all events"
        if ($this.hasClass('selected')) { // isn't already selected
          if (items.filter(':visible').length > 0) { // some items currently visible
            items.stop(true, true).filter(':visible').fadeOut(350, BATEMAN.easing, function() {
              items.filter('.'+id).fadeIn(350, BATEMAN.easing);
            });
          } else { // no items currently visible
            items.filter('.'+id).fadeIn(350, BATEMAN.easing);
          }
        } else { // is already selected, so act as though you're disabling this tag, back to "all events"
          types.eq(0).click();
        }
      } else if ($this.hasClass('selected')) { // is "all events" and isn't already selected
        if (items.filter(':visible').length > 0) { // some items currently visible
          items.stop(true, true).filter(':visible').fadeOut(350, BATEMAN.easing, function() {
            items.filter('.'+id).fadeIn(350, BATEMAN.easing);
          });
        } else { // no items currently visible
          items.stop(true, true).fadeIn(350, BATEMAN.easing);
        }
      }
    });
  }
};

BATEMAN.filter = {
  hoverBox: {},
  init: function() {
    UTIL.fire('artwork', 'initTagScroller');
    UTIL.fire('filter', 'initHoverBox');
    UTIL.fire('filter', 'initFilterOverlay');
  },
  initHoverBox: function() {
	var box = {
		wrap: $('<div class="filterHoverBoxWrap" />'),
		el: $('<div class="filterHoverBox"/>'),
		img: $('<img/>'),
		btns: $('<div class="filterHoverButtons"/>'),
		btnView: $('<a class="rb_button text" title="View Details">View Details</a>')				
	};
	
	box.btns.append(box.btnView);
	box.el.append(box.img, box.btns);
	box.wrap.append(box.el);
	
	$('.filterResults').append(box.wrap);
	
	UTIL.fire('common', 'tooltips', box.btns.children('.icon'));
	
	this.hoverBox = box;
	
	$('.filterResults .thumb').bind('mouseenterintent focus', function() {
		UTIL.fire('filter', 'showHoverBox', $(this));
	});
	
  },
  showHoverBox: function(t) {
	var box = this.hoverBox,
		target = t;

	box.el.hover(function() {
		box.wrap.show();
	}, function() {
		UTIL.fire('filter', 'hideHoverBox');
	});
	
	box.img.attr('src', target.children('img').attr('src'));
	box.btnView.attr('href', target.attr('href'));	

	var to = target.children('img').offset(),
		tl = to.left - 40 < 0 ? -10 : to.left - 40,
		tt = to.top - 200,
		tw = $('body').width() - 60;
		
	tl = tl + (target.children('img').width() + 10) > tw ? tw - (target.children('img').width() + 10) : tl;
	
	box.wrap.css({
		marginLeft: tl,
		marginTop: tt
	}).stop(true, true).fadeIn(500, BATEMAN.easing);
  },
  hideHoverBox: function() {
	this.hoverBox.wrap.fadeOut(500, BATEMAN.easing);
  },  
  initFilterOverlay: function() {
		var overlay = $('#rb_filterOverlay');
		
		// make sure we can tab to everything
		$('label', overlay).attr('tabindex', '0');

		// 'cache' active filters on page load
		$('input:checked', overlay).next('label').addClass('active-filter');
		
		// events
		UTIL.fire('common', 'tooltips', $('a.close', overlay));
		$('a.close', overlay).click(function(e) {
			e.preventDefault();
			UTIL.fire('filter','hideFilterOverlay');
		});
		$('.rb_button.edit').click(function(e) {
			e.preventDefault();
			UTIL.fire('filter','showFilterOverlay');
			$('label.active-filter:not(.selected)', overlay).click();
		});
		
		$('label.rb_button', overlay).click(function() {
			var group = $(this).parents('.filterOverlayGroup');
			group.find('.selected').not($(this)).removeClass('selected').prev('input').removeAttr('checked');
			$(this).toggleClass('selected');

			if (!group.find('.selected').length) {
				group.find('.filter-all').addClass('selected');
			}
		});
		
		$('.rb_button.down.right', overlay).addClass('collapsed').click(function(e) {
			e.preventDefault();
			$(this).toggleClass('active').siblings().removeClass('active');
			
			if ($(this).hasClass('active')) {
				$(this).siblings('.filterOverlayGroupHidden').addClass('collapsed').filter('.'+$(this).attr('id')).removeClass('collapsed');
			} else {
				$(this).siblings('.filterOverlayGroupHidden').addClass('collapsed');
			}
		});

		// 'all of type' buttons		
		$('.filterOverlayGroup:not(:first-child)', overlay).each(function() {
			var allBtn = $('<a href="#" class="rb_button text selected filter-all"/>');
			var type = $(this).find('legend h3').text();
			allBtn.text("All " + type);
			$(this).children('legend').after(allBtn);
			allBtn.click(function(e) {
				e.preventDefault();
				$(this).parents('.filterOverlayGroup').find('.selected').removeClass('selected').prev('input').removeAttr('checked');
				$(this).addClass('selected');
			});
		});

		// browse buttons
		$('.rb_button.browse').click(function(e) {
			e.preventDefault();
			UTIL.fire('filter', 'resetFilterOverlay');
			UTIL.fire('filter', 'showFilterOverlay');
		});
		
		// form events
		$('.formOptionLink.reset', overlay).click(function(e) {
			e.preventDefault();
			UTIL.fire('filter', 'resetFilterOverlay');
		});
		$('#rb_filterOverlay_submit').click(function(e) {
	      e.preventDefault();
	    
	      // perform test to see how many results we get back here
	      var isChecked = false;
		  $("#idForm input[type='checkbox']:checked").each(function() {
			  isChecked = true;
			  //return false;
		  });			
		  if(isChecked){
			  $.ajax({
					  type: "POST",
					  dataType : 'json', // define the type of data that is going to get back from the server					   
					  url: "/search/artwork",
					  data: $("#idForm").serialize(), // serializes the form's elements.
					  success: searchResults
				});				
				return false;
		  }else{
			    $('#result_message').html("Nothing has been selected.");			 
		  }
		  return false;
	    });    
	  },	
  showFilterOverlay: function() {
    var overlay = $('#rb_filterOverlay');
    $('#rb_main').addClass('clearHeight');
    overlay.fadeIn(500, BATEMAN.easing);
  },
  hideFilterOverlay: function() {
    var overlay = $('#rb_filterOverlay');
    overlay.fadeOut(500, BATEMAN.easing, function() {
      $('#rb_main').removeClass('clearHeight');
    });
  },
  resetFilterOverlay: function() {
	var form = $('#rb_filterOverlay form');
	form.get(0).reset();
	$('label', form).removeClass('selected');
	$('input', form).removeAttr('checked');
  }
};

BATEMAN.bigMap = {
		map: null,
		artworkMarkers: [],
		trailMarkers: [],
		eventMarkers: [],
		init: function() {
			UTIL.fire('bigMap', 'initMap');
		},
		initMap: function() {
			if (typeof google !== "undefined" && !$('html').hasClass('ie7')) {
				var mapCenter = new google.maps.LatLng(48.429314,-123.468904), // Royal Roads University by default
					mapZoom = 4,
					providedCenter = BATEMAN.common.getQueryString().center;
				
				// if there's a provided lat/long in the query string, center there
				if (providedCenter !== undefined) {
					providedCenter = providedCenter.split(', ');
					mapCenter = new google.maps.LatLng(providedCenter[0],providedCenter[1]);
					mapZoom = 10;
				}

				var mapOptions = {
					center: mapCenter,
					zoom: mapZoom,
					minZoom: 3,
					mapTypeControlOptions: {
						mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]
					},
					mapTypeId: google.maps.MapTypeId.TERRAIN,
					streetViewControl: false
				};
				
				BATEMAN.bigMap.map = new google.maps.Map(document.getElementById("bigMapCanvas"), mapOptions);

				// marker control panel
				var RBMarkersControlDiv = document.createElement('DIV'),
					RBMarkersControl = new BATEMAN.bigMap.RBMarkersControl(RBMarkersControlDiv, BATEMAN.bigMap.map);
				BATEMAN.bigMap.map.controls[google.maps.ControlPosition.TOP_CENTER].push(RBMarkersControlDiv);

				// optionally show a type of pins on load
				google.maps.event.addListenerOnce(BATEMAN.bigMap.map, 'idle', function() {
					var typeQS = BATEMAN.common.getQueryString().show;
					if (typeQS !== undefined) {
						var typeToShow = "#bigmap-" + typeQS;
						$(typeToShow).click();
					}
				});
			}
		},
		RBMarkersControl: function(container, map) {
			var markersControl = $('<div id="bigMapMarkersControl" />');
			markersControl.append('<h2>Display on Map</h2>');
			markersControl.append('<a id="bigmap-artwork" class="rb_button icon text artwork" title="Display Artwork on Map">Artwork</a>');
			markersControl.append('<a id="bigmap-trails" class="rb_button icon text trails" title="Display Trails on Map">Trails</a>');
			markersControl.append('<a id="bigmap-events" class="rb_button icon text events" title="Display Events on Map">Events</a>');
			markersControl.appendTo(container);

			$('.rb_button', markersControl).click(function(e) {
				e.preventDefault();
				$(this).toggleClass('selected');

				var $this = $(this);

				switch ($(this).attr('id')) {
					case "bigmap-artwork":
						if ($this.hasClass('selected')) {
							// artwork marker pins and infoboxes
							if (BATEMAN.bigMap.artworkMarkers.length < 1) {
								$this.addClass('loading');
								$.getJSON("map/artwork", function(data) {
									$.each(data.artworks, function() {
										var coords = new google.maps.LatLng(this.artwork.latitude, this.artwork.longitude),
											content = '<ul class="rb_thumbList medium clearfix"><li><div class="thumbWrap"><a class="thumb" href="'+this.artwork.path+'">';
											content += '<img src="'+this.artwork.image+'" alt="" />';
											content += '<div class="thumbMeta">';
											content += '<span class="thumbSubhead">'+this.artwork.artist+'</span>';
											content += '<span class="thumbHead">'+this.artwork.title+'</span>';
											content += '</div></a></div></li></ul>';

										BATEMAN.bigMap.RBMarkerArtwork(content, coords);
									});

									for (var i in BATEMAN.bigMap.artworkMarkers) {
										BATEMAN.bigMap.artworkMarkers[i].setMap(BATEMAN.bigMap.map);
									}

									$this.removeClass('loading');
								});
							} else {
								for (var i in BATEMAN.bigMap.artworkMarkers) {
									BATEMAN.bigMap.artworkMarkers[i].setMap(BATEMAN.bigMap.map);
								}
							}
						} else {
							for (var i in BATEMAN.bigMap.artworkMarkers) {
								BATEMAN.bigMap.artworkMarkers[i].setMap(null);
							}
						}
						break;
					case "bigmap-trails":
						if ($this.hasClass('selected')) {
							// trail marker pins and infoboxes
							if (BATEMAN.bigMap.trailMarkers.length < 1) {
								$this.addClass('loading');
								$.getJSON("map/trail", function(data) {
									$.each(data.trails, function() {
										var coords = new google.maps.LatLng(this.trail.latitude, this.trail.longitude),
											content = '<a href="#">'+this.trail.title+'</a>';

										BATEMAN.bigMap.RBMarkerTrail(content, coords);
									});

									for (var i in BATEMAN.bigMap.trailMarkers) {
										BATEMAN.bigMap.trailMarkers[i].setMap(BATEMAN.bigMap.map);
									}

									$this.removeClass('loading');
								});
							} else {
								for (var i in BATEMAN.bigMap.trailMarkers) {
									BATEMAN.bigMap.trailMarkers[i].setMap(BATEMAN.bigMap.map);
								}
							}
						} else {
							for (var i in BATEMAN.bigMap.trailMarkers) {
								BATEMAN.bigMap.trailMarkers[i].setMap(null);
							}
						}
						break;
					case "bigmap-events":
						if ($this.hasClass('selected')) {
							// event marker pins and infoboxes
							if (BATEMAN.bigMap.eventMarkers.length < 1) {
								$this.addClass('loading');
								$.getJSON("map/event", function(data) {
									$.each(data.events, function() {
										var coords = new google.maps.LatLng(this.event.latitude, this.event.longitude),
											content = '<span class="subhead">'+this.event.date+'</span><a href="'+this.event.path+'">'+this.event.title+'</a>';

										BATEMAN.bigMap.RBMarkerEvent(content, coords);
									});

									for (var i in BATEMAN.bigMap.eventMarkers) {
										BATEMAN.bigMap.eventMarkers[i].setMap(BATEMAN.bigMap.map);
									}

									$this.removeClass('loading');
								});
							} else {
								for (var i in BATEMAN.bigMap.eventMarkers) {
									BATEMAN.bigMap.eventMarkers[i].setMap(BATEMAN.bigMap.map);
								}
							}
						} else {
							for (var i in BATEMAN.bigMap.eventMarkers) {
								BATEMAN.bigMap.eventMarkers[i].setMap(null);
							}
						}
						break;
				}

			});
		},
		RBMarkerArtwork: function(content, loc) {
			var obj = BATEMAN.bigMap,
				iconMarkOff = new google.maps.MarkerImage('/sites/all/themes/bateman/images/rbc_map_artwork_off.png', new google.maps.Size(29, 36), new google.maps.Point(0, 0), new google.maps.Point(14,36)),
				mark = new google.maps.Marker({
					optimized: true,
					position: loc,
					icon: iconMarkOff,
					title: "Click for more information about this Artwork"
				});
				
			obj.artworkMarkers.push(mark);
				
			var boxContent = document.createElement('div');
			boxContent.className = 'artworkMarkerBox';
			boxContent.innerHTML = ""+content;
			var box = new InfoBox({
					content: boxContent,
					maxWidth: 168,
					alignBottom: true,
					boxClass: "floatCloseBtn",
					pixelOffset: new google.maps.Size(-83,-35),
					closeBoxMargin: "5px 5px 10px 0px",
					closeBoxURL: "/sites/all/themes/bateman/images/rbc_buttonClose_large.png",
					pane: "floatPane"
				});
				
			google.maps.event.addListener(mark, 'click', function() {
				box.open(obj.map, mark);
			});
		},
		RBMarkerTrail: function(content, loc) {
			var obj = BATEMAN.bigMap,
				iconMarkOff = new google.maps.MarkerImage('/sites/all/themes/bateman/images/rbc_map_trail_off.png', new google.maps.Size(29, 36), new google.maps.Point(0, 0), new google.maps.Point(14,36)),
				mark = new google.maps.Marker({
					optimized: true,
					position: loc,
					icon: iconMarkOff,
					title: "Click for more information about this Trail"
				});
				
			obj.trailMarkers.push(mark);
				
			var boxContent = document.createElement('div');
			boxContent.className = 'textMarkerBox';
			boxContent.innerHTML = ""+content;
			var box = new InfoBox({
					content: boxContent,
					maxWidth: 260,
					alignBottom: true,
					pixelOffset: new google.maps.Size(-125,-35),
					closeBoxMargin: "5px 5px 10px 0px",
					closeBoxURL: "/sites/all/themes/bateman/images/rbc_buttonClose_large.png",
					pane: "floatPane"
				});
				
			google.maps.event.addListener(mark, 'click', function() {
				box.open(obj.map, mark);
			});
		},
		RBMarkerEvent: function(content, loc) {
			var obj = BATEMAN.bigMap,
				iconMarkOff = new google.maps.MarkerImage('/sites/all/themes/bateman/images/rbc_map_event_off.png', new google.maps.Size(29, 36), new google.maps.Point(0, 0), new google.maps.Point(14,36)),
				mark = new google.maps.Marker({
					optimized: true,
					position: loc,
					icon: iconMarkOff,
					title: "Click for more information about this Event"
				});
				
			obj.eventMarkers.push(mark);
				
			var boxContent = document.createElement('div');
			boxContent.className = 'textMarkerBox';
			boxContent.innerHTML = ""+content;
			var box = new InfoBox({
					content: boxContent,
					maxWidth: 260,
					alignBottom: true,
					pixelOffset: new google.maps.Size(-125,-35),
					closeBoxMargin: "5px 5px 10px 0px",
					closeBoxURL: "/sites/all/themes/bateman/images/rbc_buttonClose_large.png",
					pane: "floatPane"
				});
				
			google.maps.event.addListener(mark, 'click', function() {
				box.open(obj.map, mark);
			});
		}
	};


BATEMAN.artwork = {
  init: function() {
    UTIL.fire('artwork', 'resizeContainer');
    UTIL.fire('artwork', 'initMap');
    UTIL.fire('artwork', 'initInfoPanel');
    UTIL.fire('artwork', 'initTools');
    UTIL.fire('artwork', 'initTagScroller');
    UTIL.fire('artwork', 'initArtworkThumbScroller');
    UTIL.fire('filter','initFilterOverlay');
    $(window).resize(function() { UTIL.fire('artwork', 'resizeContainer'); });
  },
  collectionOptions: '',
  initTools: function() {
    var btns = $('#rb_artworkContainer .artworkTools .rb_button.icon, #rb_artworkContainer .artworkMeta .collapse');
    UTIL.fire('common', 'tooltips', btns);
    btns.focus(function() { $(this).trigger('mouseover'); });
    btns.blur(function() { $(this).trigger('mouseout'); });

    // add to collection button
    $('.collections-add').click(function(e) {
      e.preventDefault();      
      $.ajax({
		  type: "GET",
		  dataType : 'json', // define the type of data that is going to get back from the server					   
		  url: "/get/user/mycollections",		  
		  data: js=1, 
		  success: function(data){
			  BATEMAN.artwork.collectionOptions = [];
			  $.each(data.collections, function(key, val) {
				  BATEMAN.artwork.collectionOptions += '<option value="' + key + '">' + val + '</option>';
			  });
			  BATEMAN.artwork.addToCollection();
		  },
		  statusCode: {
			 403: function() {
			   window.location.href = "/user/login";
			 }
		  }
	  });                             
    });
    
    // add expert insight button
	$('.insight-add').click(function(e) {
		e.preventDefault();
		BATEMAN.artwork.addExpertInsight.init();
	});
	
	// delete expert insight button
    $('.insight-delete').click(function(e) {
      e.preventDefault();
      BATEMAN.artwork.deleteExpertInsight.init();
    });
  },
  initInfoPanel: function() {
    // append collapse button
    var collapseBtn = $('<a href="#" class="rb_button icon collapse" title="Collapse This Panel">Collapse This Panel</a>');
    collapseBtn.click(function(e) {
      e.preventDefault();
      UTIL.fire('artwork','toggleInfo');
    });
    $('#rb_artworkContainer .artworkMeta').prepend(collapseBtn);

    // QR code help
    var qrBtn = $('#rb_artworkContainer .artworkMeta .qr-code-help'),
      qrTip = $('<div/>');
      qrTip.append('<h3>QR Codes</h3>');
      qrTip.append('<div class="qrCodeSample"/>');
      qrTip.append('<p>A QR code is a type of barcode that can be read quickly with some mobile phones. The button to the left will create a card with the artwork details and the QR code that contains a link to this page.</p>');

    qrBtn.attr('title', '').tipTip({
      defaultPosition: 'right', 
      content: qrTip,
      edgeOffset: 20,
      maxWidth: '250px',
      cssClass: 'rb_qrHelpTip'
    });
    qrBtn.focus(function() { $(this).trigger('mouseover'); });
    qrBtn.blur(function() { $(this).trigger('mouseout'); });

    // related links toggle
	$('#related_links ul').hide();
	$('#related_links .trigger').click(function(e) {
		e.preventDefault();
		$(this).toggleClass('open').siblings('ul').slideToggle(350, BATEMAN.easing);
	});
    
    // video overlays
    $('.relatedVideo .videoWrap').click(function(e) {
      e.preventDefault();

      var $this = $(this),
        title = $this.find('.videoTitle').text();

      var d = $('<div id="rb_videoOverlay"/>');
      d.append('<h3 class="dialogSubheading">'+ title +'</h3>');

      // the embed code for the video needs to be constructed here
      d.append('<div id="videoArea"/>');

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        width: 640
      });
      
      //set up jwplayer for the video
      //-need the video url
      //-need the thumbnail
      var videoURL = $this.find('.videoURL').val();      
      var videoThumb = $this.find('img').attr('src');      
      
      jwplayer('videoArea').setup({
			width: 640,
			height: 280,
			skin: "/sites/all/themes/bateman/js/plugins/jwplayer/bateman/bateman.zip",
			modes: [
				{ type: "html5" },
				{ type: "flash", src: "/sites/default/files/jwplayermodule/player/player.swf" }
			],
			levels: [
				{ file: videoURL }, // standard def source				
			],
			image: videoThumb // poster frame		       
		});
      
    });

    // stories
    var numStories = $('.relatedStoriesList li').length;
	if (numStories > 1) {
		$('.relatedStories .relatedStoriesWrap').jcarousel({
			buttonNextHTML: '<a class="rb_button icon white small next" title="Next">Next</a>',
			buttonPrevHTML: '<a class="rb_button icon white small previous" title="Previous">Previous</a>',
			easing: BATEMAN.easing,
			animation: 350,
			scroll: 1,
			initCallback: function(carousel) {
				var dots = $('<ul class="dotNav"/>');
				for (var i = 0; i < numStories; i++) { dots.append('<li><a href="#">' + (i+1) + '</a></li>'); }
				$('a', dots).eq(0).addClass('active').end().click(function(e) {
					e.preventDefault();
					var $this = $(this);
					carousel.scroll($.jcarousel.intval($this.text()));
					$('a', dots).removeClass('active').filter($this).addClass('active');
				});
				dots.appendTo('.relatedStoriesWrap');
				$('.relatedStoriesWrap .next').click(function(e) {
					if (!!$(this).not('.jcarousel-next-disabled').length && !carousel.animating) {
						$('a.active', dots).removeClass('active').parent().next().children('a').addClass('active');
					}
				});
				$('.relatedStoriesWrap .previous').click(function(e) {
					if (!!$(this).not('.jcarousel-prev-disabled').length && !carousel.animating) {
						$('a.active', dots).removeClass('active').parent().prev().children('a').addClass('active');
					}
				});
			}
		});
	}
    
    // preliminary works overlays
	$('.relatedArt .preliminaryWork').click(function(e) {
		e.preventDefault();

		var $this = $(this);
		
		var workData = {
			"title": $this.find('.title').val(),
			"description": $this.find('.description').val(),
			"imageURL": $this.find('.imagepath').val()
		};

		var d = $('<div id="rb_prelimArtOverlay"/>');
		d.append('<h3 class="dialogSubheading">'+ workData.title +'</h3>');
		d.append('<p>' + workData.description + '</p>');
		d.append('<div class="prelimArt"><img src="' + workData.imageURL + '" /></div>');

		d.dialog({
			modal: true,
			resizable: false,
			draggable: false,
			width: 800,
			position: ["center",125]
		});
	});

    // location
	var loc = $.trim($('.relatedLocation .locationInfo').text()),
		mapIMG = $('<img alt="Artwork Location Map"/>'),
		mapBtn = $('<a class="rb_button text white" title="View Large Map">Large Map</a>'),
		mapURL = "http://maps.googleapis.com/maps/api/staticmap?center=";

	mapURL += loc;
	mapURL += "&markers=color:0xCC3300|" + loc;
	mapURL += "&size=280x280";
	mapURL += "&maptype=terrain";
	mapURL += "&zoom=10";
	mapURL += "&sensor=false";
	mapURL = encodeURI(mapURL);

	mapIMG.attr('src', mapURL);
	mapBtn.attr('href', "/map?center=" + encodeURI(loc) + '&show=artwork');
	$('.relatedLocation .locationWrap').append(mapIMG).append(mapBtn);

    // accordion init
    $(document).bind('finalized', function() {
      $('#rb_artworkContainer .artworkRelated').accordion({
        autoHeight: false,
        collapsible: true,
        active: false,
        animated: BATEMAN.easing
      });
    });
  },
  initTagScroller: function() {
	var tagScroller = $('#rb_artworkContainer .filterTags');

	if (tagScroller.children('ul').children('li').length > 0) {
	  tagScroller.jcarousel({
		buttonNextHTML: '<a class="rb_button icon next" title="Next">Next</a>',
		buttonPrevHTML: '<a class="rb_button icon previous" title="Previous">Previous</a>',
		easing: BATEMAN.easing,
		animation: 350,
		scroll: 1,
		itemFallbackDimension:300
	  });
	  $('#rb_artworkContainer .filterButtons .edit').click(function(e) {
		e.preventDefault();
		UTIL.fire('filter','showFilterOverlay');
	  });
	} else {
	  $('#rb_artworkContainer .filterButtons .edit').hide();
	}
  },
  initArtworkThumbScroller: function() {
    var items = $('.rb_thumbScroller.artwork li'),
      activeItem = $('.rb_thumbScroller.artwork li.active'),
      i = items.index(activeItem);
      
    $('.rb_thumbScroller.artwork').jcarousel({
      buttonNextHTML: '<a class="rb_button icon next" title="Next">Next</a>',
      buttonPrevHTML: '<a class="rb_button icon previous" title="Previous">Previous</a>',
      easing: BATEMAN.easing,
      animation: 350,
      itemFallbackDimension:300,
      scroll: 2,
      start: i
    });
    
    $('.rb_thumbScroller.artwork .thumb').each(function() {
      var $this = $(this),
        img = $this.find('img'),
        out = '<img src="'+img.attr('src')+'" /><div class="tipText">'+img.attr('alt')+'</div>';
      $this.tipTip({
        defaultPosition: 'top', 
        edgeOffset: -19,
        content: out,
        maxWidth: "135px",
        cssClass: 'rb_thumbScrollerTip'
      });
      $this.focus(function() { $this.trigger('mouseover'); });
      $this.blur(function() { $this.trigger('mouseout'); });
    });
  },
  map: null,
  insightMarkers: [],
  insightData: [],
  minZoom: 1,
  maxZoom: 5,
  mapLatLng: null,
  initMap: function(hideInfoButton) {
    if (typeof google !== "undefined" && !$('html').hasClass('ie7')) {
      var obj = BATEMAN.artwork,
        minz = BATEMAN.artwork.minZoom,
        maxz = BATEMAN.artwork.maxZoom;

      // center for the map
      obj.mapLatLng = new google.maps.LatLng(0, 0);

      // swap out the JPEG for the google map viewer
      var container = $('#rb_artworkContainer'),
        image = container.children('.artworkImage').children('img'),
        imageID = image.attr('rel'),
        imageWrap = image.parent(),
        mapCanvas = $('<div id="artworkMapCanvas"/>');
		
		// sort out the initial zoom level based on available real estate
		var initialz = null,
			hz = Math.floor(imageWrap.width() / 512) || minz,
			vz = Math.floor(imageWrap.height() / 1024) || minz;
		if (hz <= vz) { initialz = hz; }
		else { initialz = vz; }

		image.replaceWith(mapCanvas);
      
      var ARTWORK = 'artwork',
        artworkTypeOptions = {
          getTileUrl: function(coord, zoom) {
            var normalizedCoord = BATEMAN.artwork.getNormalizedCoord(coord, zoom);
            if (!normalizedCoord) { return null; }
              var bound = Math.pow(2, zoom);
              var img_nm = $('#artworkImageName').val();              
			  var img_fmt_idx = img_nm.indexOf('.'); 
			  return "/sites/default/files/artworks/tiles/" + img_nm.substring(0, img_fmt_idx) + "/" + zoom + "/" + normalizedCoord.x + "-" + normalizedCoord.y + ".jpg";
		  },
          tileSize: new google.maps.Size(256, 256),
          maxZoom: maxz,
          minZoom: minz,
          name: 'Artwork',
          credit: '&copy; Robert Bateman Centre. All rights reserved.'
        },
        mapOptions = {
          backgroundColor: "#000000",
          center: obj.mapLatLng,
          zoom: initialz,
          mapTypeControl: false,
          mapTypeControlOptions: {
            mapTypeIds: [ARTWORK]
          },
          mapTypeID: ARTWORK,
          panControl: false,
          streetViewControl: false,
          scaleControl: false,
          zoomControl: Modernizr.touch,
          zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.RIGHT_BOTTOM
          }
        };
        
      obj.map = new google.maps.Map(document.getElementById("artworkMapCanvas"), mapOptions);
      
      // set the map type
      var artworkMapType = new google.maps.ImageMapType(artworkTypeOptions);
      obj.map.mapTypes.set(ARTWORK, artworkMapType);
      obj.map.setMapTypeId(ARTWORK);
      
      // add markers
	  $.ajax({
		  type: "GET",
		  dataType : 'json', // define the type of data that is going to get back from the server					   
		  url: "/insight/get/" + $("#node-id").val(),		  
		  data: js=1, 
		  success: function(data){
			var insights = data.result;
			if (insights.length > 0) { $('.insight-delete').css('display', 'inline-block'); }
			jQuery.each(insights, function() {			    				    				    
		     var content = '<span class="expertText">'+this.insight.insight+'</span><span class="expertName"><a href="/user_profile/public/'+this.insight.uid+'">'+this.insight.name+'</a></span>',
			 coords = new google.maps.LatLng(this.insight.latitude, this.insight.longitude);
		     eid = this.insight.eid;
		     obj.ExpertInsightMarker(content, coords, eid);
			});
		  },
		  statusCode: {
				 403: function() {
				   window.location.href = "/user/login";
				 }
		  }
	  });
	  	  
      // add the zoom control
      if (!Modernizr.touch) {
        var RBzoomControlDiv = document.createElement('DIV'),
          RBzoomControl = new BATEMAN.artwork.RBZoomControl(RBzoomControlDiv, image, obj.map);
        obj.map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(RBzoomControlDiv);
      }
      
      // add the info button, or not if we're on the emotive words page
		if (!hideInfoButton) {
			var RBinfoControlDiv = document.createElement('DIV'),
				RBinfoControl = new BATEMAN.artwork.RBInfoControl(RBinfoControlDiv, obj.map);
			obj.map.controls[google.maps.ControlPosition.TOP_LEFT].push(RBinfoControlDiv);
		} else { // add the associated content overlay button instead
			$('.artworkImage').addClass('wide');

			var RBAssociatedContentControlDiv = document.createElement('DIV'),
				RBAssociatedContentControl = new BATEMAN.artwork.RBAssociatedContentControl(RBAssociatedContentControlDiv, obj.map);
			obj.map.controls[google.maps.ControlPosition.TOP_LEFT].push(RBAssociatedContentControlDiv);
		}
      
		$('.artworkImage').addClass('short');
      // fade custom controls on hover
		var customControls;
		google.maps.event.addListenerOnce(obj.map, 'idle', function() {
			customControls = $('.artworkMapControl, a[href*="terms_maps.html"], img[src*="google_white.png"], img[src*="rbc_artwork_insight_off.png"]');
			customControls.delay(1000).animate({ opacity: 0.01 }, 350, BATEMAN.easing);
		});

		$('#artworkMapCanvas').hoverintent(function() {
			var boxes = $('.infoBox');
			customControls.add(boxes).animate({ opacity: 1 }, 350, BATEMAN.easing);
			$('.artworkImage').removeClass('short', 750, BATEMAN.easing);
			$('.artworkFilters').addClass('collapsed', 750, BATEMAN.easing, function() {
				UTIL.fire('artwork','resizeContainer');
			});
		}, function() {
			// if there are any infoboxes open, we need to hide them too
			var boxes = $('.infoBox');
			customControls.add(boxes).animate({ opacity: 0.01 }, 350, BATEMAN.easing);
			$('.artworkImage').addClass('short', 750, BATEMAN.easing);
			$('.artworkFilters').removeClass('collapsed', 750, BATEMAN.easing, function() {
				UTIL.fire('artwork','resizeContainer');
			});
		});
    }
  },  
  ExpertInsightMarker: function(content, loc, eid) {
		var obj = BATEMAN.artwork,
			iconMarkOff = new google.maps.MarkerImage('/sites/all/themes/bateman/images/rbc_artwork_insight_off.png', new google.maps.Size(76, 76), new google.maps.Point(0, 0), new google.maps.Point(38, 38)),
			iconMarkOn = new google.maps.MarkerImage('/sites/all/themes/bateman/images/rbc_artwork_insight_on.png', new google.maps.Size(76, 76), new google.maps.Point(0, 0), new google.maps.Point(38, 38)),
			mark = new google.maps.Marker({
				optimized: false,
				position: loc,
				map: obj.map,
				icon: iconMarkOff,
				title: "Click to reveal this Expert Insight"
			});
			
		obj.insightMarkers.push(mark);
			
		var boxContent = document.createElement('div');
		boxContent.className = 'artworkInsightBox';
		boxContent.innerHTML = ""+content;
		var box = new InfoBox({
				content: boxContent,
				maxWidth: 0,
				pixelOffset: new google.maps.Size(-338,-38),
				closeBoxMargin: "8px 16px 8px 8px",
				closeBoxURL: "/sites/all/themes/bateman/images/rbc_buttonClose_small.png",
				pane: "floatPane"
			});
		
		google.maps.event.addListener(mark, 'click', function() {
			box.open(obj.map, mark);
			mark.setIcon(iconMarkOn);

			var text = $('.expertText', $(boxContent)).text();
			text = text.split('');
			if (text.length > 100) {
				var c = $('.expertText', $(boxContent));
				var n = c.siblings('.expertName').children('a');
				var t = $('<a href="#" class="trigger">&hellip; Read More</a>');
				var btnText = "View " + n.text() + "'s Profile";
				t.click(function(e) {
					e.preventDefault();

					var d = $('<div id="rb_contentOverlay"/>');
					d.append('<h3 class="dialogSubheading">Expert Insight from ' + n.text() + '</h3>');
					d.append('<div class="expertText"><p>' + c.html() + '</p></div>');
					d.dialog({
						modal: true,
						resizable: false,
						draggable: false,
						width: 640,
						close: function() {
							d.dialog('destroy').remove();
						},
						buttons: [
							{ text: btnText, click: function() { window.location = n.attr('href'); } }
						]
					});
				});
				c.addClass('too-tall');
				c.after(t);
			}
			
			$(document).trigger({
		        type: 'rbcinsightclicked',
		        eid: eid,
		        econtent: $('.expertText', $(boxContent)).html()
		      });
		});
		
	google.maps.event.addListener(box, 'closeclick', function() {
		mark.setIcon(iconMarkOff);
	});
  },
  RBZoomControl: function(container, thumb, map) {
    var zoomArea = $('<div class="artworkMapControl" id="artworkMapZoom"/>'),
      zoomSlider = $('<div id="artworkMapZoomSlider"/>'),
      zoomOverview = $('<div id="artworkMapZoomOverview"/>'),
      zoomOut = $('<a href="#" class="zoomButton out" title="Zoom Out">Zoom Out</a>'),
      zoomIn = $('<a href="#" class="zoomButton in" title="Zoom In">Zoom In</a>'),
      minz = BATEMAN.artwork.minZoom,
      maxz = BATEMAN.artwork.maxZoom,
      curz = map.getZoom();
    
    // put elements together
    zoomSlider.add(zoomOverview).add(zoomOut).add(zoomIn).appendTo(zoomArea);
    zoomArea.appendTo(container);
    
    // activate the jquery ui slider
    zoomSlider.slider({
      min: minz,
      max: maxz,
      value: curz,
      step: 1,
      animate: 150,
      slide: function(event, ui) {
        map.setZoom(ui.value);
      }
    });   
    
    // event bindings
    thumb.bind('contextmenu', function() { return false; }).bind('mousedown', function() { return false; }).appendTo(zoomOverview);
    zoomOut.add(zoomIn).click(function(e) {
      e.preventDefault();
      var $this = $(this);
      zoom = map.getZoom();
      zoom = $this.hasClass('out') ? zoom - 1 : zoom + 1;
      map.setZoom(zoom);
    });
    google.maps.event.addDomListener(map, 'zoom_changed', function(e) {
      newZoom = map.getZoom();
      zoomSlider.slider('value', newZoom);
    });
  },
  RBInfoControl: function(container, map) {
    var infoButton = $('<a class="artworkMapControl" id="artworkMapInfo" title="Toggle Artwork Information">Toggle Artwork Information</a>');
    infoButton.appendTo(container);
    infoButton.click(function(e) {
      e.preventDefault();
      UTIL.fire('artwork','toggleInfo');
    });
  },
  RBAssociatedContentControl: function(container, map) {
		var contentButton = $('<a class="artworkMapControl" id="artworkMapContent" title="Toggle Associated Content">Toggle Associated Content</a>'),
			contentType = BATEMAN.home.data.associatedType;
			
		contentButton.addClass(contentType).appendTo(container).click(function(e) {
			e.preventDefault();
	
			var jwskin = "/sites/all/themes/bateman/js/plugins/jwplayer/bateman/bateman.zip",
				jwswf = "/sites/default/files/jwplayermodule/player/player.swf";
			
			var content = BATEMAN.home.data.associated;
			var d = $('<div id="rb_contentOverlay"/>'),
				detailURL = '/node/' + BATEMAN.home.data.ID;
				d.append(content);
	
			var w, h = 'auto', initFunc;
	
			switch (contentType) {
				case 'info':
					w = 320;
					initFunc = function() {
						// nothing here
					};
					break;
				case 'audio':
					w = 320;
					h = 160;
	
					var audioTitle = $('.audioTitle', d).text();
					$('.audioTitle', d).remove();
					d.prepend('<h3 class="dialogSubheading">'+audioTitle+'</h3>');
	
					initFunc = function() {
						$('input.audio', d).each(function() {
							var $this = $(this);
							var audioPlayer = $this.attr('id') + "-main",
								audioURL = $this.val();
							jwplayer(audioPlayer).setup({
								width: 280,
								height: 31,
								controlbar: {
									idlehide: false,
									position: "bottom"
								},
								dock: false,
								skin: jwskin,
								modes: [
									{ type: "html5" },
									{ type: "flash", src: jwswf }
								],
								file: audioURL
							});
						});
					};
					break;
				case 'video':
					w = 640;
					h = 440;
	
					var videoTitle = $('.videoTitle', d).text(),
						videoURL = $('.videoURL', d).val(),
						videoThumb = $('.videoThumb img', d).attr('src');
					$('.videoWrap', d).remove();
					d.prepend('<h3 class="dialogSubheading">'+videoTitle+'</h3>');
					d.append('<div id="videoArea"/>');
	
					initFunc = function() {
						jwplayer('videoArea').setup({
							width: 640,
							height: 360,
							skin: jwskin,
							modes: [
								{ type: "html5" },
								{ type: "flash", src: jwswf }
							],
							levels: [
								{ file: videoURL }
							],
							image: videoThumb
						});
					};
					break;
				case 'story':
					w = 320;
					initFunc = function() {
						// nothing here
					};
					break;
			}
	
			d.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: w,
				height: h,
				position: ["center",125],
				buttons: {
					"More Info": function() {
						window.location = detailURL;
					}
				},
				open: initFunc,
				close: function() {
					d.dialog('destroy').remove();
				}
			});
		});
	},
  getNormalizedCoord: function(coord, zoom) {
    var y = coord.y,
      x = coord.x,
      tileRange = 1 << zoom;
    if (y < 0 || y >= tileRange) { return null; }
    if (x < 0 || x >= tileRange) { return null; }
    var ret = { x: x, y: y };
    return { x: x, y: y };
  },
  resizeContainer: function() {
    var obj = BATEMAN.artwork,
      container = $('#rb_artworkContainer'),
      imageContainer = container.children('.artworkImage'),
      winHeight = $(window).height(),
      clearance = ($('#rb_emotiveWords').length === 0) ? 215 : 515, // 215 for artwork detail view, 515 for home page emotive words piece
      newHeight = winHeight - clearance;
    container.css('min-height', newHeight);
    // imageContainer.css('margin-bottom', clearance);
    if (obj.map) { google.maps.event.trigger(obj.map, 'resize'); }
  },
  toggleInfo: function() {
	$('#rb_artworkContainer .artworkMeta').toggleClass('collapsed', 500, BATEMAN.easing);
	$('#artworkMapInfo').fadeToggle(350, BATEMAN.easing);
	$('#rb_artworkContainer .artworkImage').toggleClass('wide', 500, BATEMAN.easing, function() {
		UTIL.fire('artwork','resizeContainer');
	});
  },
  addToCollection: function() {
    var d = $('<div/>');	
	var html = '';	
    html += '<h3 class="dialogSubheading">Add To Collection</h3>';    
    html += '<select name="select-a-collection" tabindex="1"><optgroup label="Select a Collection">';
    html += BATEMAN.artwork.collectionOptions;     		
    html += '</optgroup></select>';
    html += '<p><label>Create New Collection <input name="new-collection" type="text" placeholder="New Collection" /></label></p>';
    d.append(html);
    d.dialog({
      modal: true,
      resizable: false,
      draggable: false,
      open: function() {
        d.children('select').dropkick();
      },
      buttons: {
        "Add Artwork": function() {
        	//get the three pieces of data:
        	//1. node id
        	var nodeId = 0;
        	if($("#node-id").val()){
          	  nodeId = $("#node-id").val();
          	}
        	//2. collection id
        	var collId = 0;        	
        	if($('[name="select-a-collection"]').val()){
        	  collId = $('[name="select-a-collection"]').val();
        	}
        	//3. new collection name        	
        	var newColl = "";
        	if($('[name="new-collection"]').val()){        		
        		newColl = $('[name="new-collection"]').val();
          	}
        	
        	var request = $.ajax({
      		  type: "POST",
      		  dataType : 'json', // define the type of data that is going to get back from the server					   
      		  url: "/json/add/mycollections/" + nodeId + '/' + collId + '/' + newColl,
      		  data: js=1, 
      		  success: function(data){
      			BATEMAN.artwork.collectionOptions = [];
      			d.dialog("close").dialog("destroy");
                d.html('<h3 class="dialogSubheading">Done!</h3><p>' + data.success +  '</p>');
                d.dialog({
                  modal: true,
                  resizable: false,
                  draggable: false,
                  height: 70,
                  open: function() {
                    $('.ui-dialog').delay(2500).fadeOut(function() { d.dialog("close").dialog("destroy").remove(); });
                  }
                });
      		  },
      		  statusCode: {
   			    403: function() {
   			     window.location.href = "/user/login";
   			    }
   		      }
      	    });
        }
      }
    });
  },  
  addExpertInsight: {
	newMarker: null,
	insightData: {		
		nid: null,
		lat: null,
		long: null,
		insight: ""
	},
	handhold: {
		curtain: null,
		help: null,
		buttons: null,
		blankBtn: null
	},
	init: function() {
		var obj = BATEMAN.artwork.addExpertInsight,
			map = BATEMAN.artwork.map;

		obj.insightData.nid = $('#node-id').val();

		obj.handhold.curtain = $('<div id="rb_curtain" />');
		obj.handhold.help = $('<div class="instructions" />');
		obj.handhold.buttons = $('<div class="buttons" />');
		obj.handhold.blankBtn = $('<a href="#" class="rb_button text"></a>');
		
		obj.handhold.help.appendTo(obj.handhold.curtain);
		obj.handhold.buttons.appendTo(obj.handhold.curtain);

		$('#artworkMapCanvas').addClass('curtained');
		obj.handhold.curtain.prependTo('body').fadeIn(function() {
			// set up instructions and buttons
			obj.handhold.help.html("Move the red marker to the position where you'd like to place your Expert Insight.");
			var doneBtn = obj.handhold.blankBtn.clone(false).text('Next Step'),
				cancelBtn = obj.handhold.blankBtn.clone(false).text('Cancel');
			cancelBtn.click(function(e) {
				e.preventDefault();
				obj.cancel();
			});
			doneBtn.click(function(e) {
				e.preventDefault();
				obj.contentEntry();
			});
			obj.handhold.buttons.append(cancelBtn).append(doneBtn);

			// put the marker on the map and keep track of where it is
			obj.newMarker = new google.maps.Marker({
				position: map.getCenter(),
				map: map,
				draggable: true
			});
			obj.updatePosition();
			google.maps.event.addListener(obj.newMarker, 'position_changed', function() {
				obj.updatePosition();
			});
		});
	},
	contentEntry: function() {
		var obj = this,
			d = $('<div/>');

		obj.handhold.curtain.hide().remove();
		$('#artworkMapCanvas').removeClass('curtained');

		d.html('<h3 class="dialogSubheading">Compose your Expert Insight</h3>');
		d.append('<p>Enter your Expert Insight below.</p>');
		d.append('<textarea maxlength="1000" id="insightText"></textarea>');
				
		d.dialog({
			modal: true,
			resizable: false,
			draggable: false,
			width: 400,
			buttons: {
				"Cancel": function() {
					obj.cancel(d);
				},
				"Save Expert Insight": function() {
					obj.insightData.insight = $('#insightText').val();
					var insight = $.param(obj.insightData);                    
					d.html('<h3 class="dialogSubheading">Saving&hellip;</h3>').dialog("option", "buttons", []).dialog("option", "height", 30);

					$.post("/insight/add?" + insight, function(data) {
						d.dialog("close").dialog("destroy");
						d.html('<h3 class="dialogSubheading">Done!</h3><p>This Expert Insight has been successfully added.</p>');
						d.dialog({
							modal: true,
							resizable: false,
							draggable: false,
							height: 100,
							open: function() {
								$('.ui-dialog').delay(2500).fadeOut(function() { location.reload(true); });
							},
							close: function() { obj.cancel(); }
						});
					}).error(function(data) {
						console.log(data);
						d.dialog("close").dialog("destroy");
						d.html('<h3 class="dialogSubheading">Error!</h3><p>Something went wrong saving your Expert Insight. Please refresh the page and try again.</p>');
						d.dialog({
							modal: true,
							resizable: false,
							draggable: false,
							height: 130,
							close: function() { obj.cancel(); }
						});
					});
				}
			}
		});
	},
	updatePosition: function() {
		var obj = this;
		obj.insightData.lat = obj.newMarker.getPosition().lat();
		obj.insightData.long = obj.newMarker.getPosition().lng();
	},
	cancel: function(dialog) {
		this.newMarker.setMap(null);

		if (!!dialog) { dialog.dialog("close").dialog("destroy").remove(); }

		this.handhold.curtain.fadeOut(function() {
			$(this).remove();
			$('#artworkMapCanvas').removeClass('curtained');
		});
	}
  },
  deleteExpertInsight: {
	    handhold: {
	      curtain: null,
	      help: null,
	      buttons: null,
	      blankBtn: null
	    },
	    init: function() {
			var obj = BATEMAN.artwork.deleteExpertInsight;

			obj.handhold.curtain = $('<div id="rb_curtain" />');
			obj.handhold.help = $('<div class="instructions" />');
			obj.handhold.buttons = $('<div class="buttons" />');
			obj.handhold.blankBtn = $('<a href="#" class="rb_button text"></a>');
			
			obj.handhold.help.appendTo(obj.handhold.curtain);
			obj.handhold.buttons.appendTo(obj.handhold.curtain);

			$('#artworkMapCanvas').addClass('curtained');
			obj.handhold.curtain.prependTo('body').fadeIn(function() {
				// set up instructions and buttons
				obj.handhold.help.html("Click on the Expert Insight you'd like to delete.");
				var cancelBtn = obj.handhold.blankBtn.clone(false).text('Cancel');
				cancelBtn.click(function(e) {
					e.preventDefault();
					obj.cancel();
				});
				obj.handhold.buttons.append(cancelBtn);

				// snag the marker click event
				$(document).one('rbcinsightclicked', function(e) {
					obj.confirmation(e.eid, e.econtent);
				});
			});
		},
	    confirmation: function(id, text) {
	      var obj = this,
	        eid = id,
	        content = text,
	        d = $('<div/>');

	      obj.handhold.curtain.hide().remove();
	      $('#artworkMapCanvas').removeClass('curtained');

	      d.html('<h3 class="dialogSubheading">Are you sure you want to delete this Expert Insight?</h3>');
	      d.append('<p>' + content + '</p>');
	          
	      d.dialog({
	        modal: true,
	        resizable: false,
	        draggable: false,
	        width: 640,
	        buttons: {
	          "Cancel": function() {
	            obj.cancel(d);
	          },
	          "Delete Expert Insight": function() {
	            d.html('<h3 class="dialogSubheading">Deleting&hellip;</h3>').dialog("option", "buttons", []).dialog("option", "height", 30);

	            var deleteURL = "/insight/delete/" + eid;

	            $.get(deleteURL, function(data) {
	              d.dialog("close").dialog("destroy");
	              d.html('<h3 class="dialogSubheading">Done!</h3><p>This Expert Insight has been deleted.</p>');
	              d.dialog({
	                modal: true,
	                resizable: false,
	                draggable: false,
	                height: 100,
	                open: function() {
	                  $('.ui-dialog').delay(2500).fadeOut(function() { location.reload(true); });
	                },
	                close: function() { obj.cancel(); }
	              });
	            }).error(function(data) {
	              d.dialog("close").dialog("destroy");
	              d.html('<h3 class="dialogSubheading">Error!</h3><p>Something went wrong deleting your Expert Insight. Please refresh the page and try again.</p>');
	              d.dialog({
	                modal: true,
	                resizable: false,
	                draggable: false,
	                height: 130,
	                close: function() { obj.cancel(); }
	              });
	            });
	          }
	        }
	      });
	    },
	    cancel: function(dialog) {
	      if (!!dialog) { dialog.dialog("close").dialog("destroy").remove(); }

	      this.handhold.curtain.fadeOut(function() {
	        $(this).remove();
	        $('#artworkMapCanvas').removeClass('curtained');
	      });
	    }
	  }  
  
};

BATEMAN.detail = {
  init: function() {
    // nothing yet
  }
};

BATEMAN.feature = {
  init: function() {
    UTIL.fire('feature', 'initFeatureTabs');
    UTIL.fire('feature', 'initFeatureSlider');
    UTIL.fire('feature', 'initVideoSlider');
  },
  initFeatureTabs: function() {
	$('#rb_featureContainer .featureTabs').tabs({
		select: function (e, ui) {
			$('#rb_featureContainer .featureTabs > .view-all').hide().eq(ui.index).show();
		}
	});
  },
  initFeatureSlider: function() {
		var featureContainer = $('#rb_featureContainer');
		var featureText = $('.featureSlider .pane', featureContainer);
		if (featureText.height() > 400) {
			featureText.addClass('collapsed');
			var more = $('<a href="#" class="moreLink caps" title="Click to show more"></a>');
			more.click(function(e) {
				e.preventDefault();
				$(this).toggleClass('less');
				featureText.toggleClass('collapsed', 500, BATEMAN.easing);
			});
			featureText.append(more);
		}
  },
  initVideoSlider: function() {
	// video overlays
	$('.thumb[title="Play this video"]').click(function(e) {
		e.preventDefault();

		var $this = $(this),
			title = $this.find('.thumbHead').text();

		var d = $('<div id="rb_videoOverlay"/>');
		d.append('<h3 class="dialogSubheading">'+ title +'</h3>');
		d.append('<div id="videoArea"/>');

		d.dialog({
			modal: true,
			resizable: false,
			draggable: false,
			width: 640,
			close: function() {
				d.dialog("destroy").remove();
			}
		});

		//set up jwplayer for the video
		var videoURL = $this.find('.videoURL').val();
		var videoThumb = $this.find('img').attr('src');

		jwplayer('videoArea').setup({
			width: 640,
			height: 360,
			skin: "/sites/all/themes/bateman/js/plugins/jwplayer/bateman/bateman.zip",
			modes: [
				{ type: "html5" },
				{ type: "flash", src: "/sites/default/files/jwplayermodule/player/player.swf" }
			],
			levels: [
				{ file: videoURL } // standard def source
			],
			image: videoThumb // poster frame
		});
	});
  }      
};

BATEMAN.accounts = {
  init: function() {
    UTIL.fire('common', 'tooltips', $('.rb_button.help'));
    $('.rb_button.help').click(function(e) {
    	UTIL.fire('accounts','showHelpOverlay', true);
    });
  },
  showHelpOverlay: function(force) {
		var helpOverlay = $('#rb_profileWelcome');

		if ($('#showHelp').val() === "true" || !!force) {
			helpOverlay.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: 750
			});
		}
	},
  dashboard: function() {
    // fire the 'welcome' dialog
    UTIL.fire('accounts','showHelpOverlay');
  },
  profileEdit: function() {
    // delete account button
    $('.rb_button.profile-delete').click(function(e) {
      e.preventDefault();
      
      var d = $('<div/>');
      d.html('<h3 class="dialogSubheading">Are you sure you want to delete your account?</h3><p>You will lose any saved Collections or Stories. This cannot be undone.</p>');

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "no-close",
        buttons: {
          "Delete My Account": function() {
            // do stuff here to delete the user's account
          },
          "Cancel": function() {
            d.dialog("close").dialog("destroy").remove();
          }
        }
      });
    });
  },
  collections: function() {
    // nothing to see here
  },
  collectionsEdit: function() {
    var coll = $('.rb_thumbList.collection-items');
    UTIL.fire('common', 'tooltips', $('.rb_button.delete', coll));

    // delete artwork buttons
    $('.rb_button.delete', coll).click(function(e) {
      e.preventDefault();
      var item = $(this).parents('li');

      var d = $('<div/>');
      d.html('<h3 class="dialogSubheading">Are you sure you want to remove this from your collection?</h3><p>This action cannot be undone.</p>');

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "no-close",
        buttons: {
          "Remove this Artwork": function() {
            d.dialog("close").dialog("destroy").remove();
            item.fadeOut(500, BATEMAN.easing);
          },
          "Cancel": function() {
            d.dialog("close").dialog("destroy").remove();
          }
        }
      });
    });

    // save collection buttons
    $('.rb_button.collection-save').click(function(e) {
      e.preventDefault();
      var btn = $(this);

      btn.after('<div class="rb_spinner white"/>');

      // put stuff in here to save the collection
      // then do this on callback:
      var d = $('<div/>');
      d.html('<h3 class="dialogSubheading">Collection Saved</h3><p>Your changes to this artwork collection were saved successfully.</p>'); // may need some logic for error messaging here

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        open: function() {
          $('.ui-dialog').delay(2500).fadeOut(function() { d.dialog('close'); });
        }
      });

      $('.rb_spinner').remove();
    });

    // delete collection buttons
    $('.rb_button.collection-delete').click(function(e) {
      e.preventDefault();

      var d = $('<div/>');
      d.html('<h3 class="dialogSubheading">Are you sure you want to delete this collection?</h3><p>This action cannot be undone.</p>');

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "no-close",
        buttons: {
          "Delete This Collection": function() {
            // put stuff here to delete the collection
          },
          "Cancel": function() {
            d.dialog("close").dialog("destroy").remove();
          }
        }
      });
    });
  },
  stories: function() {
    if (!!Modernizr.generatedcontent) {
      $('.storyPreviewText').each(function() {
        var $this = $(this);
        
        if (parseInt($this.height(), 10) > 195) { // 195 = about 7 lines of text, give or take
          $this.addClass('collapsed', 500, BATEMAN.easing);

          var more = $('<a href="#" class="moreLink caps" title="Click to show more"></a>');

          more.click(function(e) {
            e.preventDefault();
            $(this).toggleClass('less');
            $this.toggleClass('collapsed', 500, BATEMAN.easing);
          });

          $this.after(more);
        }
      });
    }
  },
  storiesEdit: function() {
    // save story buttons
    $('.rb_button.story-save').click(function(e) {
      e.preventDefault();
      var btn = $(this);

      btn.after('<div class="rb_spinner white"/>');

      // put stuff in here to save the collection
      // then do this on callback:
      var d = $('<div/>');
      d.html('<h3 class="dialogSubheading">Story Saved</h3><p>Your changes to this story were saved successfully.</p>'); // may need some logic for error messaging here

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "no-close",
        buttons: {
          "OK": function() {
            d.dialog("close").dialog("destroy").remove();
          }
        }
      });

      $('.rb_spinner').remove();
    });

    // delete story buttons
    $('.rb_button.story-delete').click(function(e) {
      e.preventDefault();

      var d = $('<div/>');
      d.html('<h3 class="dialogSubheading">Are you sure you want to delete this story?</h3><p>This action cannot be undone.</p>');

      d.dialog({
        modal: true,
        resizable: false,
        draggable: false,
        dialogClass: "no-close",
        buttons: {
          "Delete This Story": function() {
            // put stuff here to delete the collection
          },
          "Cancel": function() {
            d.dialog("close").dialog("destroy").remove();
          }
        }
      });
    });
  }
};

BATEMAN.e404 = {
		init: function() {
			BATEMAN.home.initVideo();
		}
	};

var searchResults = function(data) {
  // The data parameter is a JSON object.
  if(data.result > 0 ){		    		
	$('#idForm').submit();
	return true;		    
  }else{
    $('#result_message').html("There are no results for this search.");
  }
  return false;
}

// kick it off
$(function() { UTIL.init(); });


