/*
$('body').ajaxStart(function(){
    $('.front-node').removeClass('front-node');
    $('.jhd_slide').eq(0).html( '' );
    jhd_process_page();
    $('.jhd_slide').eq(0).html( '<img src="/sites/all/themes/jhd/images/24-0.gif" alt="" />' );

    //$('.jhd_slide').eq(0).html( 'loading' );
});

$('body').ajaxStop(function(){
    //$('#content').css('height','auto');
    $('body').removeClass('dark');
    jhd_cufon( '#content' );
});
*/

$(window).resize(function() {
    setTimeout( resetCanvas, 200);
});

$().ready(function(){
    jhd_cufon();
    jhd_process_page();

    if ( ie7 ) {
        //setInterval( function(){ resetPage(); }, 25);
    } else {
        //setInterval( resetPage, 1);
    }

    var div = '<div id="jhdScreen"></div>';
    div = $(div);
    $('body').append( div );
    $('#jhdScreen').hide();
});

function galleryWork() {
    var p = "#content"
    var parent = $( '#header' );
    //parent.append( '<div style="clear:both;"></div>' );

    var i = 0;
    parent.find('#block-views-hp_stories-block_1 .views-row').each( function() {
        var t = $(this);
        var html = t.html();
        i = i + 1;
        jhd_add_panel( html, 'homepage_thumb', p );
    });
    //$('#block-views-hp_stories-block_1').remove();
    $(p).append( '<div style="clear:both;"></div>' );

    /*
    parent.find('#block-views-hp_stories_small-block_1 .views-row').each( function() {
        var t = $(this);
        var html = t.html();
        i = i + 1;
        jhd_add_panel( html, 'homepage_thumb_small', p );
    });
    $(p).append( '<div style="clear:both;"></div>' );
    */

    parent.hide();

}


function jdh_onload() {

    setTimeout( function(){
        resetPage( false );
        resetLogo( false );

        //$('#logo').fadeIn( 700 );
        //$('#page').fadeIn( 700 );

        /* dev comment to speed render
        */
        //$('#sky_map').fadeIn( 2000, function(){
        swfobject.embedSWF("/sites/all/themes/jhd_theme/swf/jhd_home.swf", "homeFlash", "383", "115", "8.0.0", "/sites/all/themes/jhd_theme/swf/expressInstall.swf");
        $('#sky_map').fadeIn( 1, function(){
            $('body').addClass( 'dark' );
            $('#logo').show();
            $('#page').show();
            jhd_cufon();
        });

        $('body').css( 'background-color','#ccc' );
        setTimeout( function(){
            /* dev comment to speed render
            */
            initializeMap();
            $('#map_type').attr('class', map.getMapTypeId());
            setTimeout( function() {
                resetCanvas();
            }, 200);
        }, 2100);

    }, 100);

}

function resetCanvas() {
    resetContent();
    resetPage();
    resetLogo();
}

function resetContent() {
    $('#content').css('height', '');
    $('#content').css('width', '');

    var content_h = $('#content').height();
    var window_h = $(window).height();


    //if ( $('#content .front-node').length > 0 ) {
        //if ( content_h >= window_h - 20 ) {
            //$('#content').css('height', window_h - 80 + 'px');
            //$('#content').css('width', '623px');
        //}
    //} else {
        if ( content_h >= window_h - 160 ) {
            $('#content').css('height', window_h - 220 + 'px');
            $('#content').css('width', '623px');
        }
    //}
}

function resetLogo( show ) {
    if ( typeof(show) == 'undefined' ) {
        show = true;
    }
    /*
    var lw = 250;//$('#logo').width();
    if ( ($(window).width() - lw) > 0 ) {
        var left = Math.abs( $(window).width() - lw );
    } else {
        var left = 0;
    }
    left -= 10;
    $('#logo').css( 'left', left + 'px' );
    */
    if ( show ) {
        $('#logo').fadeIn('slow');
    }
}

function resetPage( show ) {
    if ( typeof(show) == 'undefined' ) {
        show = true;
    }

    var ph = $('#page').height();
    var pw = $('#page').width();

    if ( ($(window).height() - ph) > 0 ) {
        var dh = Math.abs( $(window).height() - ph );
    } else {
        var dh = 0;
    }
    if ( ($(window).width() - pw) > 0 ) {
        var dw = Math.abs( $(window).width() - pw );
    } else {
        var dw = 0;
    }

    var t = Math.round( dh / 2 );
    var l = Math.round( dw / 2 );

    //alert( h );
    //alert( w );

    $('#page').css( 'left', l + 'px' );

    /*
    if ( t < 70 ) {
        t = 70;
        h = 400;
        $('#content').css('height', h + 'px' );
    }
    */
    $('#page').css( 'top',  t + 'px' );


    //$('#page').css( 'display','block' );

    if ( show ) {
        $('#page').fadeIn('slow');
    }
}

function jhd_cufon( ele ) {
    //var sel = 'h1,h2,h3,h4,p,label,ol,ul,#site-name,#site-slogan';
    if ( ie7 ) {
        var sel = 'h1,h2.title, h3,h4,#site-name,#site-slogan,.primary-links a,.pageTextToggle h2,h2.loadingToggle';
    } else {
        var sel = 'h1,h2,h3,h4,#site-name,#site-slogan,.primary-links a';
    }
    if ( $(ele).length > 0 ) {
        Cufon.replace( $(ele).find( sel ) ,{ fontFamily: 'myriad' });
    } else {
        Cufon.replace( sel ,{ fontFamily: 'myriad' });
    }
    Cufon.now();
}

function jhd_process_page() {
    $('.links a, a#logo, .views-field-title a, .field-content a,#beta a, a.jhd_link').each(function(){
        var ele = $(this);
        ele.unbind('click').click(function(){
            $('.active').removeClass('active');
            if ( ele.parent().parent().is('.primary-links') ) {
                ele.parent().addClass('active');
            }
            jhd_load_node( ele );
            return false;
        });
    });
    $('#top').height( $().height() );
    $('#top').width( $().width() );

    //$('a.imagefield-lightbox2').nyroModal();

}


function jhd_add_panel( html, _class, parent )
{
    var html = html;

    if ( $( parent ).length > 0 ) {
        var parent = $( parent );
    } else {
        if ( $('#content .front-node').length > 0 ) {
            var parent = $('#content .front-node');
        } else {
            var parent = $('#content');
        }
    }

    var panel = $('<div class="jhd_slide_main"><div class="jhd_slide_wrapper"><div class="jhd_slide">' + html + '</div></div></div>');
    panel.addClass( _class );
    panel.hide();
    parent.append( panel );

    if (ie7 || ie8) {
        setTimeout( function() {
            jhd_cufon();

            panel.show();

            jhd_process_page();
            resetCanvas();
        }, 100 );
    } else {
        setTimeout( function() {
            jhd_cufon();
            jhd_process_page();
            resetCanvas();

            panel.show();

        }, 1 );
    }

}

function splitText( html ) {
    var html = $(html);
    var newhtml = "";
    if ( html.find('p').length > 2 );

    html.find('p')

    newhtml = html;
    return newhtml;
}

function jhd_contact() {

    var btn = $('.webform-client-form #edit-submit');
    if ( btn.length > 0 ) {

        $('.webform-client-form').eq(0).remove();

        /*
        btn.click( function() {

            var _url = $('.webform-client-form').eq(0).attr('action');

            var dataString = "";
            var dataObj = {};
            $('.webform-component input, .webform-component textarea').each( function() {
                var ele = $(this);
                var n = ele.attr('name');
                var v = ele.val();
                v = escape( v );
                dataObj[n] = v;
                dataString = dataString + n + '=' + v + '&';
            });
            //alert( dataString );
            //alert( dataObj );

            $.ajax({
              type: "POST",
              url: _url,
              //data: dataString,
              data: dataObj,
              success: function( ret ) {
                $('#content').html( ret );
                jhd_contact();
              }
            });
            return false;

        });
        */
    }
}

function jhd_load_node( ele ) {
    var url = ele.attr('href');
    var data = null;

    data = {
        'jhd_load_node' : true
    };

    //$('body').addClass('dark');
    $('body').removeClass('gallery');
    $('.gallery-item').removeClass('gallery-item');

    $('.front-node').removeClass('front-node');
    //$('.front').removeClass('front');

    $('#content').eq(0).html( '' );
    jhd_process_page();
    jhd_add_panel( '<img style="float:left;" src="/sites/all/themes/jhd_theme/images/24-0.gif" alt="" /> <h2 class="loadingToggle" style="float:left;padding-left: 10px;">Loading</h2><div style="clear: both;"></div>', 'loading' );

    setTimeout( resetPage, 1);

    jhd_cufon( '#content' );

    $('#header').hide();
    $('#jhdScreen').hide();
    $('body').removeClass('screen_on');

    $.get( url, data, function(html) {

        var newhtml = splitText(html);
        $('#content').html( newhtml );

        jhd_contact();

        jhd_cufon( '#content' );

        var isflash = $('#homeFlash');
        if ( isflash.length > 0 ) {
            swfobject.embedSWF("/sites/all/themes/jhd_theme/swf/jhd_home.swf", "homeFlash", "383", "115", "8.0.0", "/sites/all/themes/jhd_theme/swf/expressInstall.swf");
        }

        jhd_process_page();
        resetCanvas();
        if (ie7) {
            setTimeout( function(){ window.resizeBy(1,1); }, 200);
        }

    });

}

// Google Maps
// API 3.0

var mapTypes = {};

// set up the map types
mapTypes['moon'] = {
  getTileUrl: function(coord, zoom) {
    return getHorizontallyRepeatingTileUrl(coord, zoom, function(coord, zoom) {
      var bound = Math.pow(2, zoom);
      return "http://mw1.google.com/mw-planetary/lunar/lunarmaps_v1/clem_bw/" +
             + zoom + "/" + coord.x + "/" + (bound - coord.y - 1) + '.jpg';
    });
  },
  tileSize: new google.maps.Size(256, 256),
  isPng: false,
  maxZoom: 9,
  minZoom: 4,
  radius: 1738000,
  name: 'Moon',
  credit: 'Image Credit: NASA/USGS'
};

mapTypes['sky'] = {
  getTileUrl: function(coord, zoom) {
    return getHorizontallyRepeatingTileUrl(coord, zoom, function(coord, zoom) {
      return "http://mw1.google.com/mw-planetary/sky/skytiles_v1/" +
             coord.x + "_" + coord.y + '_' + zoom + '.jpg';

    });
  },
  tileSize: new google.maps.Size(256, 256),
  isPng: false,
  maxZoom: 13,
  minZoom: 4,
  radius: 57.2957763671875,
  name: 'Sky',
  credit: 'Image Credit: SDSS, DSS Consortium, NASA/ESA/STScI'
};

mapTypes['mars_elevation'] = {
  getTileUrl: function(coord, zoom) {
    return getHorizontallyRepeatingTileUrl(coord, zoom, function(coord, zoom) {
      return getMarsTileUrl("http://mw1.google.com/mw-planetary/mars/elevation/", coord, zoom);
    });
  },
  tileSize: new google.maps.Size(256, 256),
  isPng: false,
  maxZoom: 8,
  minZoom: 4,
  radius: 3396200,
  name: 'Mars Elev.',
  credit: 'Image Credit: NASA/JPL/GSFC'
};

mapTypes['mars_visible'] = {
  getTileUrl: function(coord, zoom) {
    return getHorizontallyRepeatingTileUrl(coord, zoom, function(coord, zoom) {
      return getMarsTileUrl("http://mw1.google.com/mw-planetary/mars/visible/", coord, zoom);
    });
  },
  tileSize: new google.maps.Size(256, 256),
  isPng: false,
  maxZoom: 9,
  minZoom: 4,
  radius: 3396200,
  name: 'Mars Vis.',
  credit: 'Image Credit: NASA/JPL/ASU/MSSS'
};

/*
mapTypes['mars_infrared'] = {
  getTileUrl: function(coord, zoom) {
    return getHorizontallyRepeatingTileUrl(coord, zoom, function(coord, zoom) {
      return getMarsTileUrl("http://mw1.google.com/mw-planetary/mars/infrared/", coord, zoom);
    });
  },
  tileSize: new google.maps.Size(256, 256),
  isPng: false,
  maxZoom: 9,
  minZoom: 4,
  radius: 3396200,
  name: 'Mars Infrared',
  credit: 'Image Credit: NASA/JPL/ASU'
};
*/

// Normalizes the tile URL so that tiles repeat across the x axis (horizontally) like the
// standard Google map tiles.
function getHorizontallyRepeatingTileUrl(coord, zoom, urlfunc) {
  var y = coord.y;
  var x = coord.x;

  // tile range in one direction range is dependent on zoom level
  // 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc
  var tileRange = 1 << zoom;

  // don't repeat across y-axis (vertically)
  if (y < 0 || y >= tileRange) {
    return null;
  }

  // repeat across x-axis
  if (x < 0 || x >= tileRange) {
    x = (x % tileRange + tileRange) % tileRange;
  }

  return urlfunc({x:x,y:y}, zoom)
}

function getMarsTileUrl(baseUrl, coord, zoom) {
  var bound = Math.pow(2, zoom);
  var x = coord.x;
  var y = coord.y;
  var quads = ['t'];

  for (var z = 0; z < zoom; z++) {
    bound = bound / 2;
    if (y < bound) {
      if (x < bound) {
        quads.push('q');
      } else {
        quads.push('r');
        x -= bound;
      }
    } else {
      if (x < bound) {
        quads.push('t');
        y -= bound;
      } else {
        quads.push('s');
        x -= bound;
        y -= bound;
      }
    }
  }

  return baseUrl + quads.join('') + ".jpg";
}

var map;
var mapTypeIds = [];

// Setup a copyright/credit line, emulating the standard Google style
var creditNode = document.createElement('div');
creditNode.id = 'credit-control';
creditNode.style.fontSize = '11px';
creditNode.style.fontFamily = 'Arial, sans-serif';
creditNode.style.margin = '0 2px 2px 0';
creditNode.style.whitespace = 'nowrap';
creditNode.index = 0;

function setCredit(credit) {
  creditNode.innerHTML = credit + ' -';
}

function initializeMap() {

    // push all mapType keys in to a mapTypeId array to set in the mapTypeControlOptions
    for (var key in mapTypes) {
        mapTypeIds.push(key);
    }

    var mapOptions = {
        zoom: 0,
	//zoom: 9,
        center: new google.maps.LatLng(60, -50),
        //center: new google.maps.LatLng(58.9, -51.8),
        mapTypeControlOptions:
        {
            mapTypeIds: mapTypeIds,
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            position: google.maps.ControlPosition.BOTTOM
        },
        navigationControlOptions: {
            //style: google.maps.NavigationControlStyle.SMALL,
            style: google.maps.NavigationControlStyle.SMALL,
            position: google.maps.ControlPosition.RIGHT_BOTTOM
        }
    };
    map = new google.maps.Map(document.getElementById("sky_map"), mapOptions);

    // push the credit/copyright custom control
    map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(creditNode);

    // add the new map types to map.mapTypes
    for (key in mapTypes) {
        map.mapTypes.set(key, new google.maps.ImageMapType(mapTypes[key]));
    }

    // handle maptypeid_changed event to set the credit line
    google.maps.event.addListener(map, 'maptypeid_changed', function() {
        $('#map_type').attr('class', map.getMapTypeId());
        setCredit(mapTypes[map.getMapTypeId()].credit);
    });

    // start with the mars elevation map type
    map.setMapTypeId('mars_elevation');
    //map.setMapTypeId('sky');

    if ( ie7 ) {
        setTimeout( function(){ window.resizeBy(1,1); }, 200);
    }
    //clearMarkers( map );

}

//function clearMarkers( map ) {
    //for(var i=0; i < map.markers.length; i++){
        //map.markers[i].setMap(null);
    //}
    //map.markers = new Array();
//}



