function showPanel(id) {
  var tabs   = $('#details-tabs li');
  var panels = $('#details-content div.panel')
  var panel  = $(id + '-tab')
  
  if (panel.length == 0) {
    return false
  }
    
  panels.hide()
  panel.show()
  tabs.removeClass('active')

  $('a[href$="' + id + '"]', tabs).parent().addClass('active')
  return true
}

function showModal(id) {
  $(".modal").hide();
  $(id).center().center().show();
}

function hideModals() {
  $('.modal').hide();
}

function getScrollY() {
  return $(window).scrollTop();
}

function handleHash(hash) {
  if (typeof hash != 'string') return;
  
  var parts  = hash.split('/')
  var panel  = parts[0]
  var action = parts.length > 1 ? parts[1] : 'index'
  
  showPanel(panel)
  
  switch(action) {
  case 'new':
    User.isGuest ? showModal('#modal-signin') : null;
    break;
  } // end switch
}

$.fn.center = function(options) {
  var w = this.width();
  var h = this.height();
  var max = 450;
  var css = {}
  var css = {
    left: '50%',
    top:  '50%',
    marginLeft: -parseInt(w/2) + 'px',
    marginTop:  -parseInt(h/2) + parseInt(getScrollY()) + 'px'
  };
  
  if (h > max) {
    $.extend(css, {
      top: '75px',
      marginTop: 0
    })
  }
    
  return this.css(css)
}

$(document).ready(function() {
  handleHash(document.location.hash)
  // $('a:not([href*="' + document.location.host + '"])')
  //   .not('[href^=/]')
  //   .not('[href^=#]')
  //   .attr('target', '_blank');
  
  $('#details-tabs li a').add('ul.links a').click(function() {
    var url = $(this).attr('href')
    var index = url.indexOf('#')

    if (index > 0) {
      url = url.slice(index)
    }
    
    showPanel(url)
  })
  
  $('input:hidden[name=back]').each(function() {
    var v = $(this).val()
    if (v == '' || v == null) {
      $(this).val(document.location.href)
    }  
  })  
    
  $("#about-popup").click(function() {
      $("#about-popup").hide(500);
  });
  
  $("#results li").hover(function() {
      $(this).addClass("hover");
  },
  function() {
      $(this).removeClass("hover");
  });
  
  
  $("#header a#arrow").toggle(
    function() {
      $('body').removeClass('has-sidebar');
      $(this).addClass("arrow-right");
      $(this).html("Show");
      $('#sidebar').width(0);
      window_resize()
    },
    function() {
      $('body').addClass('has-sidebar');
      $(this).removeClass("arrow-right");
      $(this).html("Hide");
      $('#sidebar').width(375);
      window_resize()
    }
  );
  
  $(".cancel-modal").click(function() {
    $(this).closest(".modal").hide();

    if ($('body').hasClass('modal-page')) {
      window.location.pathname = "/";
    }
    
    return false;
  })
    
  $("a[rel=modal]").click(function() {
    var id = $(this).attr('href');
    showModal(id)
    return false
  });
  
  $(".hide-search").click(function() {
      $("#search-bar").hide();
      $(this).hide();
      $(".show-search").show();
  });
  
  $(".show-search").click(function() {
      $("#search-bar").show();
      $(this).hide();
      $(".hide-search").show();
  });
  
  $('#results')
    .find('li:first').addClass('first').end()
    .find('li:last').addClass('last').end()
  
  try {
    var markers = GoogleMap.markers();  
    $('img[marker]').click(function() {
      var marker = markers[$(this).attr('marker')];
      GEvent.trigger(marker, 'click');
    }).css('cursor', 'pointer')
  } catch(error) {}
  
  $('#nav_print').click(function() {
    window.print();
    return false;
  })
  
  var link_box = $('#link-box')
  var link     = $('#link')
  var nav_link = $('#nav_link')
  
  nav_link.click(function() {
    // save the base URL from the original input value
    if (!link.data('baseURL')) {
      link.data('baseURL', link.val())
    }
    
    var url  = link.data('baseURL')
    var map  = $.gmap;
    var hash = document.location.hash;
    
    if (map) {
      // add listener to close the link box
      if (map.link_box_hook_installed == null) {
        var f = function() { link_box.hide() }        
        GEvent.addListener(map, 'click',     f)
        GEvent.addListener(map, 'movestart', f)
        map.link_box_hook_installed = true
      }
      
      var point = map.getCenter().toUrlValue()
      var zoom  = map.getZoom()

      url += url.indexOf('?') < 0 ? '?' : '&'
      url += 'll=' + point + '&z=' + zoom
    }
    
    if (hash != '') { url += hash }

    link_box.show()
    link.val(url).select().focus()
    return false;
  })
  
  link_box.find('a.close').click(function() {
    link_box.hide()
    return false
  })
  
  
  $('a.get-directions').click(function() {
    var $$ = $(this);
    var name = $$.attr('data-name');
    
    $('#resource_name').html(name)
    $('#directions_form').attr('action', this.href);
    showModal('#modal-directions');
    return false;
  })
  
  $('input').hint();
  
  // $.fn.thumbnail = function(size) {
  //   return $(this).load(function() {
  //     var $$ = $(this)
  //     if ($$.width() > size) $$.css({width: size})
  //   }).trigger('load')
  // }
  // 
  // $('img.thumbnail').thumbnail(75)

  $.fullWidth  = {
    elements: $('body.largemap').find("#main, #map"),
    offset:   function() { return $('#sidebar').width() + 1; }
  }

  $.fullHeight = {
    elements: $('#content').add($.fullWidth.elements),
    offset:   function() { return 25; }
  }
  
  var window_resize = function() {
    $.fullWidth.elements.width(   getWindowWidth()  - ($.fullWidth.offset)() );
    $.fullHeight.elements.height( getWindowHeight() - ($.fullHeight.offset)());
    try { $.gmap.checkResize(); } catch(err) {}
  }

  window_resize(); // for good browsers
  window.setTimeout(window_resize, 100); // for horrIEble browsers
  $(window).resize(window_resize);
});


function getWindowWidth() {
    var windowWidth = 0;
    if (typeof(window.innerWidth) == 'number') {
        windowWidth = window.innerWidth;
    }
    else {
        if (document.documentElement && document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        }
        else {
            if (document.body && document.body.clientWidth) {
                windowWidth = document.body.clientWidth;
            }
        }
    }
    return windowWidth;
}

function getWindowHeight() {
    var windowHeight = 0;
    if (typeof(window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
    }
    else {
        if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
        }
        else {
            if (document.body && document.body.clientHeight) {
                windowHeight = document.body.clientHeight;
            }
        }
    }
    return windowHeight;
}
        