/*
YAHOO.util.Event.onDOMReady(function () {
  var oMenuBar = new YAHOO.widget.MenuBar("yahoo_menu_bar", {
    autosubmenudisplay: true,
    zindex: 1000,
    showdelay: 0,
    hidedelay: 250,
    keepopen: false
  });
  var oMenu = new YAHOO.widget.Menu("sub-navigation", {
    zindex: 1000
  });
  oMenuBar.render(); 
  oMenu.render();
});
*/

function getUriPath() {
  var uri = location.href;
  var startIndex;
  if (null != uri.match("file:///") || null != uri.match("https://"))
    startIndex = 8;
  if (null != uri.match("http://"))
    startIndex = 7;
  var endIndex = uri.indexOf("/", startIndex);
  return uri.substring(endIndex, uri.length);
}

function refreshBookmarkState() {
  if ($('#bookmark').length > 0) {
    $.ajax({
      type: 'GET',
      cache: false,
      data: {
        path: encodeURI(getUriPath())
      },
      url: '/bookmarks/is_bookmarked',
      success: function(data) {
        if (data != 'Not logged in.') {
          $('#bookmark a')[(data == 'Bookmarked' ? 'add' : 'remove') + 'Class']('saved');
          $("#bookmark").css('display', 'block');
        }
      }
    });
  }
}

// The following code (up to $(document).ready())
// can go on without waitin for the DOM

refreshBookmarkState();

// get the bookmark button working
$('#bookmark a').click(function(e) {
  e.preventDefault();
  var bookmark = $(e.currentTarget);
  var data = bookmark.hasClass('saved') ? 'delete' : 'save';
  var ajaxOpts = {
    type: 'POST',
    cache: false,
    data: {
      path: encodeURI(getUriPath()),
      title: $("meta[name=title]").attr('content')
    },
    url: '/bookmarks/' + (bookmark.hasClass('saved') ? 'delete' : 'add'),
    success: function(data) {
      refreshBookmarkState();
    }
  };
  $.ajax(ajaxOpts);
});

// handle all "helps"
$('.help .topic a').click(function(e) {
  e.preventDefault();
  var parent = $(e.target).parent().parent();
  if (parent.hasClass('help-expanded')) {
    parent.removeClass('help-expanded').find('> .content').slideUp();
  } else {
    parent.addClass('help-expanded').find('> .content').slideDown();
  }
});

if ($('table.bookmarks')) {
  $('table.bookmarks a.delete').click(function(e) {
    e.preventDefault();
    var ajaxOpts = {
      type: 'POST',
      data: {
        path: encodeURI($(e.target).parent().parent('tr').find('.bookmark-title a').attr('href')),
        title: $("meta[name=title]").attr('content')
      },
      url: '/bookmarks/delete',
      success: function(data) {
        var id = parseInt(data);
        $('#bookmark-' + id).fadeOut();
      },
      error: function() {
        alert('There as an error deleting the bookmark!');
      }
    };
    $.ajax(ajaxOpts);
  });
}

// initialize post-DOM ready and unobtrusive stuff here
$(document).ready(function() {
    // cufonize for people on Windows XP without cleartype
    /*
    if ($('.hasFontSmoothing-false').length > 0) {
        var rules = '#yahoo_menu_bar > .bd > ul > li > a, #highlight h1, .panel h1, #promos li span span,';
            rules += '#main > aside h2, #content h2, #content header.banner .subtitle, aside > h2';
        Cufon(rules, { fontFamily: 'OFL Sorts Mill Goudy' });
    }
    */
    
    // make the print button work
    $('a.print').click(function(e) {
        e.preventDefault();
        window.print();
    });

    // build the homepage slideshow and make it functional
    if ($('#slideshow')) {
        var dcfOptions = {
            slideType: 'fade',
            showTime: 5000,
            transitionTime: 500,
            doHoverPause: false,
            slideChange : function (curIdx) {
                $('#slideshow .nav a').removeClass('cur');
                $('#slideshow .nav a:eq('+curIdx+')').addClass('cur');
            }
        }
        $('#slideshow .slide').dumbCrossFade(dcfOptions);
        $('#slideshow').append('<a class="control prev" href="#">&lt;</a><a class="control next" href="#">&gt;</a>');
        $('#slideshow').append('<div class="nav"></div>');
        var slideCount = $('#slideshow .slide').length;
        if (slideCount > 0) {
            $('#slideshow .control').click(function(e) {
                e.preventDefault();
                var slides = $('#slideshow .slide');
                if ($(this).hasClass('prev')) {
                    $('#slideshow .slide').dumbCrossFade('previous');
                } else if ($(this).hasClass('next')) {
                    $('#slideshow .slide').dumbCrossFade('next');
                }
            });
            var nav = $('#slideshow .nav');
            for (var i = 1; i <= slideCount; i++) {
                var cur = (i==1) ? ' class="cur"' : '';
                nav.append('<a href="#"'+cur+'>'+i+'</a>');
            }
            nav.find('a').each(function() {
                $(this).click(function(e) {
                    e.preventDefault();
                    $('#slideshow .slide').dumbCrossFade('jump', parseInt(this.innerHTML)-1);
                });
            });
        }
    }

    // load latest tweet(s) on home page
    if (typeof getTwitters == 'function') {
        getTwitters('tweet', { 
            id: 'Hawaii_PCA', 
            count: 1, 
            enableLinks: true, 
            ignoreReplies: true, 
            clearContents: true,
            template: '<p>%text%</p><p class="date">Posted %time%</p>'
        });
    }
    
    if (jQuery.fn.autolink) {
        $('.autolink').autolink(true);
    }

    // load the photo gallery
    if (document.getElementById('gallery')) {
        Galleria.loadTheme('/media/js/galleria/themes/classic/galleria.classic.js');
        $('#gallery').galleria({ transition: 'fade', height: 465, popup_links: true });
    }
    
    // embed the digital dashboard
    if (document.getElementById('digital-dashboard')) {
        params = { base: '../media/assets/' }
        swfobject.embedSWF("/media/assets/HI_Master_DB.swf", "digital-dashboard", "940", "553", "9.0.0", params, params, params );
    }
    
    // homepage health tip controls
    if (document.getElementById('highlight') && $('#tips .tip').length > 1) {
        var tips = $('#tips');
        var highlightInterval = setInterval(animateTips, 4000, $('#tips'), 'next');
        var h = $('#highlight');
        h.find('.controls').removeClass('hidden').find('a').each(function() {
            $(this).click(function(e) {
                e.preventDefault();
                if (!$('#tips').hasClass('is-animating')) {
                    animateTips($('#tips'), e.target.className);
                    clearInterval(highlightInterval);
                }
            });
        });
    }
    
    if (document.getElementById('map')) {
        var searchForm = '<div><form id="map-search">';
            searchForm += '<input name="zip" id="zip" type="text" placeholder="Enter zip code">';
            searchForm += '<input type="submit" name="submit" id="map-search-submit" value="Search">';
            searchForm += '</form></div>';
        $('#content > header').addClass('map').after(searchForm);
        $('#map').show();
        var center = new google.maps.LatLng(20.8,-157.5);
        var myOptions = { zoom: 7, center: center, mapTypeId: google.maps.MapTypeId.ROADMAP };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);
        var g = new google.maps.Geocoder();
        var bounds = new google.maps.LatLngBounds();
        var infowindow = new google.maps.InfoWindow();
        var successful_addresses = 0;
        
        var addresses = [
            { address: 'Bay Clinic, Inc.|Hilo Clinic|1178 Kino‘ole St.|Hilo, HI, 96720', location: { lat: 19.7297222, lng: -155.09 } },
            { address: 'Bay Clinic, Inc.|Bay Clinic Family Health Center|73 Puuhonu Place|Suite 204|Hilo, HI, 96720', location: { lat: 19.716411, lng: -155.097001 } },
            { address: 'Bay Clinic, Inc.|Kea`au Family Health Center|16-192 Pilimua Street|Kea`au, HI, 96749', location: { lat: 19.6255555, lng: -155.0416667 } },
            { address: 'Bay Clinic, Inc.|Ka`u Family Health Center|95-5583 Mamalahoa Highway|Na`alehu, HI, 96772', location: { lat: 19.0610313, lng: -155.5837265 } },
            { address: 'Bay Clinic, Inc.|Pāhoa Family Health Center|15-2866 Pāhoa Village Road|Bldg-C|Suite-A|Pāhoa, HI, 96778', location: { lat: 19.4095008, lng: -155.0483131 } },
            { address: 'Bay Clinic, Inc.|Pāhoa Women\'s Health Clinic|15-2866 Pāhoa Village Road|Bldg-F|Suite-A|Pahoa, HI, 96778', location: { lat: 19.49786, lng: -154.950897 } },
            { address: 'Kohala Family Health Center|53-3925 Akoni Pule Highway|Kapa‘au, HI, 96755', location: { lat: 20.2147216, lng: -155.7728384 } },
            { address: 'Hāmākua Health Center|45-549 Plumeria Street|Honoka‘a, HI, 96727', location: { lat: 20.0827778, lng: -155.4725 } },
            { address: 'West Hawai‘i Community Health Center|75-5751 Kuakini Hwy, Suite 101-A|Kailua-Kona, HI, 96740', location: { lat: 19.6405556, lng: -155.9955556 } },
            { address: 'West Hawai‘i Community Health Center|Keiki Health Center|Selwyn Plaza|81-6627 Mamalahoa Hwy #106|Kealakekua, Hawaii, HI 96750', location: { lat: 19.5158391, lng: -155.9203418 } },
            { address: 'Kaua‘i Community Health Center|4643B Waimea Canyon Drive|Waimea, HI, 96796', location: { lat: 21.9911206, lng: -159.6726342 } },
            { address: 'Lana‘i Community Health Center|478 Lauhala Place|Lana‘i City, HI, 96763', location: { lat: 20.827576, lng: -156.9158583 } },
            { address: 'Lāhaina Comp. Health Center|15 Ipu Aumakua|Lāhainā, HI, 96761', location: { lat: 20.8783333, lng: -156.6825 } },
            { address: 'Kaua‘i Community Health Center|4800-D Kawaihau Road|Kapaa, HI, 96746', location: { lat: 22.1002683, lng: -159.3432198 } },
            { address: 'Lana‘i Community Health Center|478 Lauhala Place|Lana‘i City, HI, 96763', location: { lat: 20.827576, lng: -156.9158583 } },
            { address: 'Ka Hale a Ke Ola Resource Center|670-A Wai‘ale Drive|Wailuku, HI, 96793', location: { lat: 20.8911111, lng: -156.5047222 } },
            { address: 'Malama I Ke Ola Health Center|Community Clinic of Maui|1881 Nani St.|Wailuku, HI, 96793', location: { lat: 20.8889263, lng: -156.4998174 } },
            { address: 'Molokai Community Health Center|28 Kamoi Street|Suite 600|Kaunakakai, HI 96748', location: { lat: 21.0897316, lng: -157.0198046 } },
            { address: 'Hāna Health|4590 Hāna Highway|Hāna, HI, 96713', location: { lat: 20.77, lng: -155.9941667 } },
            { address: 'Kalihi-Pālama Health Center|Main Clinic|915 North King Street|Honolulu, HI, 96817', location: { lat: 21.322971, lng: -157.8680655 } },
            { address: 'Kalihi-Pālama Health Center|Ka‘a‘ahi Street Clinic|Women & Children’s Shelter|546 Ka‘a‘ahi Street|Honolulu, HI. 96817', location: { lat: 21.3347317, lng: -157.8417223 } },
            { address: 'Kalihi-Pālama Health Center|KPHC Downtown|89 South King Street|Honolulu, HI, 96813', location: { lat: 21.309293, lng: -157.862379 } },
            { address: 'Kalihi-Pālama Health Center|WIC|888 North King Street|Honolulu, HI, 96817', location: { lat: 21.322857, lng: -157.867332 } },
            { address: 'Kalihi-Pālama Health Center|Behavioral Health/Health Education|952 North King Street|Honolulu, HI, 96817', location: { lat: 21.323614, lng: -157.867922 } },
            { address: 'Kokua Kalihi Valley Comprehensive Family Services|Main Clinic|2239 North School Street|Honolulu, HI, 96819', location: { lat: 21.3406689, lng: -157.87453 } },
            { address: 'Kokua Kalihi Valley Comprehensive Family Services|Hauiki Hale|1574 Meyers Street|Honolulu, HI, 96819', location: { lat: 21.3442139, lng: -157.8774695 } },
            { address: 'Kokua Kalihi Valley Comprehensive Family Services|Kalihi Valley Homes|2243 Kalaunu Street|Honolulu, HI, 96819', location: { lat: 21.3486032, lng: -157.865664 } },
            { address: 'Kokua Kalihi Valley Comprehensive Family Services|Kuhio Park Terrace|1475 Linapuni Street|No. A-175|Honolulu, HI, 96819', location: { lat: 21.3644294, lng: -157.8689014 } },
            { address: 'Kokua Kalihi Valley Comprehensive Family Services|Senior Resource Center|1846 Gulick Avenue|Honolulu, HI, 96819', location: { lat: 21.341491, lng: -157.868788 } },
            { address: 'Ko‘olauloa Community Health and Wellness Center|Kahuku Hospital Campus|56-119 Pualalea St.|Kahuku, HI 96731', location: { lat: 21.6770439, lng: -157.9522875 } },
            { address: 'Ko‘olauloa Community Health and Wellness Center|Hauula Clinic|54-316 Kamehameha Hwy|Unit #7|Hauula, HI, 96717', location: { lat: 21.620535, lng: -157.914399 } },
            { address: 'Wai‘anae Coast Comprehensive Health Center|Main Campus|86-260 Farrington Highway|Waianae, HI, 96792', location: { lat: 21.430472, lng: -158.180054 } },
            { address: 'Wai‘anae Coast Comprehensive Health Center|James & Abigail Campbell Clinic\87-2070 Farrington Highway|Waianae, HI, 96792', location: { lat: 21.3955113, lng: -158.1611083 } },
            { address: 'Wai‘anae Coast Comprehensive Health Center|Waiola Clinic|86-120 Farrington Highway|Waianae, HI, 96792', location: { lat: 21.435179, lng: -158.1836549 } },
            { address: 'Wai‘anae Coast Comprehensive Health Center|Waipahu Clinic|Filipino Community Center|94-428 Mokuola Street, #108B|Waipahu, HI, 96797', location: { lat: 21.386753, lng: -158.0047215 } },
            { address: 'Wai‘anae Coast Comprehensive Health Center|Kapolei Clinic|91-525 Farrington Hwy|Suite 102|Kapolei, HI, 96707', location: { lat: 21.324353, lng: -158.082747 } },
            { address: 'Waikiki Health Center|Main Clinic, 277 ‘Ohua Avenue, Honolulu, Hawaii 96815', location: { lat: 21.275745, lng: -157.8206697 } },
            { address: 'Waikiki Health Center|YO Project|Youth Outreach Project|277 Ohua Avenue|Honolulu, HI, 96815', location: { lat: 21.275745, lng: -157.8206697 } },
            { address: 'Waikiki Health Center|Ho‘ola Like|277 ‘Ohua Avenue|Honolulu, HI, 96815', location: { lat: 21.275745, lng: -157.8206697 } },
            { address: "Waimanalo Health Center|41-1347 Kalaniana‘ole Highway|Waimanalo, HI, 96795", location: { lat: 21.3471, lng: -157.7154 } }
        ];
        
        for (var a=0; a < addresses.length; a++) {
            setMarkerAtLocation(addresses[a].location, addresses[a].address, map, infowindow);
        }

        $('#map-search').submit(function(evt) {
            evt.preventDefault();
            g.geocode({ address: $('#zip').val() }, function(result, status) {
                if (status != google.maps.GeocoderStatus.OK) return;
                map.setCenter(result[0].geometry.location);
                map.setZoom(11);
            });
            $('#zip').blur();
        });
    } 
});
       
function setMarkerAtLocation(location, address, map, infowindow) {
  var loc = new google.maps.LatLng(location.lat, location.lng);
  var marker = new google.maps.Marker({ map: map, position: loc, title: 'HPCA: Location' });
  setMarkerMessage(map, marker, address.replace(/\|/g, "<br>"), infowindow);
}

function setMarker(address, map, infowindow) {
  var g = new google.maps.Geocoder();
  g.geocode({ address: address }, function(result, status) {
    if (status != google.maps.GeocoderStatus.OK) return;
    var marker = new google.maps.Marker({ map: map, position: result[0].geometry.location, title: 'HPCA: ' + address });
    setMarkerMessage(map, marker, address, infowindow);
  });
}

function setMarkerMessage(map, marker, message, infowindow) {
  google.maps.event.addListener(marker, 'click', function() {
    var content = '<span style="display: block; font-size: 110%; margin-right: 20px;">' + message + '</span>';
    infowindow.setContent(content);
    infowindow.open(map, marker);
  });
}

function animateTips(tips, direction) {
  var tips = $(tips);
  var height = tips.find('.tip:first').height();
  var duration = 500;
  var animationClass = 'is-animating';

  switch (direction) {
    case 'next':
      tips.addClass(animationClass);
      var remove = false;
      if (tips.position().top + height < height) {
        tips.append(tips.find('.tip:first').clone());
        remove = true;
      }
      tips.animate({ top: '-=' + height }, function() {
        if (remove) {
          tips.find('.tip:first').remove();
          tips.css({ top: '-' + height + 'px' });
        }
        tips.removeClass(animationClass);
      });
    break;
    case 'prev':
      tips.addClass(animationClass);
      var remove = false;
      if (tips.position().top >= 0) {
        tips.prepend(tips.find('.tip:last').clone()).css({ top: '-' + height + 'px' });
        remove = true;
      }
      tips.animate({ top: '+=' + height }, function() {
        if (remove) {
          tips.find('.tip:last').remove();
          tips.css({ top: '0px' });
        }
        tips.removeClass(animationClass);
      });
    break;
  }
}
