$(document).ready(function() {
    $('a.highlight_toggle').mouseover(function() {
        toggle_highlight(this.id);
        return false;
    });

    toggle_highlight('highlight_toggle_1');

    setInterval(toggle_next_highlight, 10000);
    
    $('#coda-slider-1').codaSlider({
            dynamicArrows: false,
            dynamicTabs: false,
            autoSlide: true,
            autoSlideInterval: 15000
     });

    if (!navigator.userAgent.match(/like Mac OS X/i) && !((jQuery.browser.msie) && parseInt(jQuery.browser.version, 10) < 8)) {
        headerPosition = jQuery('#floating_header').offset().top - jQuery(this).scrollTop();
        jQuery(window).scroll(function(e) {
            if ((headerPosition - jQuery(this).scrollTop()) > -115)
                jQuery('#floating_header').css('top', (headerPosition - jQuery(this).scrollTop()) + 'px');
            else
                jQuery('#floating_header').css('top', '-115px');
        });
    }


    $.fn.fitimage = function(options) {
        if (!options) options = {};
        var defaults = {
            placeholder: "data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAEBMgA7"
        };

        this.each(function() {
            var $el = $(this);

            var src = $el.attr('src');
            $el.attr('src', options.placeholder || defaults.placeholder);

            var width = options.width || $el.width();
            var height = options.height || $el.height();

            var img = new Image();
            img.onerror = function() {
                alert("error");
            };
            img.onload = function() {
                var is_tall = this.height > this.width * height / width;
                if (is_tall) {
                    size = height * this.width / this.height;
                    margin = (width - size) / 2;
                } else {
                    size = width * this.height / this.width;
                    margin = (height - size) / 2;
                }
                if (margin < 0) margin = 0;

                var adjuster = function(name, margin) {
                    var current = $el.css(name);
                    if (current && current.match(/^(\d+)px$/)) {
                        return parseInt(RegExp.$1) + margin;
                    }
                    return margin;
                };

                if (is_tall) {
                    $el.css({
                        height: height,
                        width:  size,
                        "margin-left": adjuster("margin-left", margin),
                        "margin-right": adjuster("margin-right", margin)
                    });
                } else {
                    $el.css({
                        width:  width,
                        height: size,
                        "margin-top": adjuster("margin-top", margin),
                        "margin-bottom": adjuster("margin-bottom", margin)
                    });
                }

                $el.attr("src", this.src);
            };

            img.src = src;
        });
    };
    
    $('.fit').fitimage({ placeholder: "/wp-content/themes/hbh/images/spacer.gif" });

});

function toggle_next_highlight() {
    var selected = $('a.highlight_selected');
    if(!selected.length)
        return false;

    var next = parseInt(selected.attr('id').replace('highlight_toggle_', '')) % ($('.highlight_toggle').length) + 1;

    toggle_highlight('highlight_toggle_' + next);
}

function toggle_highlight(toggle) {
    var selected = $('#' + toggle);
    if(selected) {
        count = 0;
        $('.highlight_selected').each(function(value){
                   $(this).removeClass('highlight_selected');
            count++;
                });
        selected.addClass('highlight_selected');
        selected.children('.highlight').addClass('highlight_selected');
        selected.children('.highlight_arrow').addClass('highlight_selected');
    }
}

function init_article_map() {
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function init_map_singlepoint(POI) {
    var coords = POI[0]['location'].toString().split(',');
    var latLng = new google.maps.LatLng(coords[0], coords[1]);
    var options = {
        zoom: 8,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), options);

    var point = new google.maps.LatLng(coords[0], coords[1]);
    var marker = new google.maps.Marker({
        position: point,
        map: map,
        title: POI[0]['description']
    });

}

function init_map_multipoint(POIs) {
    var latlng = new google.maps.LatLng(-34.397, 150.644);

    var options = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), options);
    var bounds = new google.maps.LatLngBounds ();

    for (idx in POIs) {
        var POI = POIs[idx];
        var coords = POI['location'].toString().split(',');
        var point = new google.maps.LatLng(coords[0], coords[1]);
        var marker = new google.maps.Marker({
            position: point,
            map: map,
            title: POI['description']
        });
        bounds.extend(point);
    }
    map.fitBounds(bounds);
}

function init_google_maps() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize_map";
    document.body.appendChild(script);
}


// Welcome page handlers
var headerheight;
// opening an internal link
function openinternal(url) {
	// Show loading stuff
	$('#pagefade').width($('body').width());
	$('#pagefade').height($(document).height());
	$('#pagefade').fadeIn(200);
	$('#loading').fadeIn(300,function(){
		if (url) {
			// hide unnecessities
			$('#content').hide();
			headerheight = $('#welcomeheader').height(); // Save header height in a variable
			// Add iframe and load content
			$('body').append('<iframe id="contentiframe" onload="iframeloaded()" name="contentiframe" src="' + url + '" frameborder="0" scrolling="auto"></iframe>');
			$('body').css('overflow','hidden');
			$('#contentiframe').height($(window).height() - 36);
		} else {
			$('#content').show();
			// Make header bigger
			$('#contentiframe').remove();
			$('#welcomeheader').animate({
				height: headerheight
			}, 300, function(){
				heightFix.footer(); // Reposition footer if needed
				$('#welcomemenubtn2').removeClass('active');
				$('#welcomemenubtn1').addClass('active');
				$('#welcomelogo').fadeIn(200, function(){
					$('body').css('overflow','auto');
					$('#pagefade').fadeOut(200);
					$('#loading').fadeOut(200);								 
				});	
			});
		}
	});
}

function iframeloaded(){
	// Make header smaller
	$('#welcomelogo').fadeOut(200);
	$('#welcomeheader').animate({
		height: $('#welcomemenu').height()
	}, 500, function(){ // Animation complete.
		$('#welcomemenubtn1').removeClass('active');
		$('#welcomemenubtn2').addClass('active');
		$('#pagefade').fadeOut(200);
		$('#loading').fadeOut(200);
	});
}

// Bind iframe size adjustment to window resize
$(window).resize(function() {
	$('#contentiframe').height($(window).height() - 36);	
});

