// defaults
var CONTENT_HEADER_ID = "content-header";	// page content header
var HEADER_ID = "header";
var PLAYER_ID = "player";
var PLAYER_SWF_ID = "dylan_player";
var NAV_SWF_ID = "dylan_nav";
var GEO_SWF_ID = "dylan_geo";
var GEO_SWF_OUTER_ID = "flash_geo_outer";
var GEO_TOUR_SWF_ID = "dylan_geo_tour";
var BG_ID = "body";	// #bg is another option if we switch back to that 
var FULL_LOAD_BAR_OUTER_ID = "full_load_bar_outer";
var FULL_LOAD_BAR_SWF_ID = "full_load_bar_swf";
var DEBUG_ENABLED = 0;
var _featuresLoaded = 0;
var _featuresShown = 0;
var _jqueryReady = false;

function noop()  { return false; }

$(document).ready(function() {
    _jqueryReady = true;
    if ( $('#debug').get(0) ) { DEBUG_ENABLED = 1; }
    
    if ($('#username-search-submit').length) {
        dylan.setup_user_search_events();
    }
    
});

var bg_obj = {
    path: "files/bgs/home_bg_test.jpg",
    bgcolor: "#DDDDDD",
    textcolor: "#000000",
    width: 1600,
    height: 320,
    placement: "center bottom"
};

/*
 * general purpose scrollTo since we need to bypass the built-in
 * hash-based (<a href="#id">) mechanism as we are using that for 
 * our swfaddress/ajax handling
 *
 * dest can be any jquery selector. e.g.: "div" or "#id"
 */
function scrollTo (dest)
{
  if ( ! _jqueryReady ) return;
  $.scrollTo($(dest).get(0));
}

function dylan_player (op)
{
  var _playerHeightClosed = '25px';
  var _playerHeightOpen = '500px';
  var _tourGeoTopDefault = 130;

  if ( op != "close" && op != "open" )
    return;

  var $container = $('#' + PLAYER_ID);
  var $player = $('#' + PLAYER_SWF_ID);
  var $tour_geo = $('#' + GEO_TOUR_SWF_ID);
  if ( ! $container || ! $player ) return;

  if ( op == "open" )
  {
    // see if the tour geo is active and if so, change it's fixed position
    if ( $tour_geo )
    {
      var top = (_tourGeoTopDefault + parseInt(_playerHeightOpen) - parseInt(_playerHeightClosed)) + "px";
      $('.view-footer-tour-current-list').css({ top: top });
    }

    // $container.css({ height: _playerHeightOpen });
    $container.css({ backgroundColor: 'transparent' });
    $player.css({ height: _playerHeightOpen });
    // $player.animate({ height: _playerHeightOpen}, 800);

    $container.animate({ height: _playerHeightOpen}, 800, null, function() {
      dylan_bg_adjust();
    });
  }
  else
  {
//    $container.css({ height: _playerHeightClosed });
    $container.css({ backgroundColor: '#000000' });
    $player.css({ height: _playerHeightClosed });
    $container.animate({ height: _playerHeightClosed}, 800, null, function() {
      dylan_bg_adjust();
      if ( $tour_geo )
      {
	var top = _tourGeoTopDefault + "px";
	$('.view-footer-tour-current-list').css({ top: top });
      }
    });
    //$player.animate({ height: _playerHeightClosed}, 800);
  }
  dylan_bg_adjust();
}

function dylan_features_nav (op)
{
    var _featuresHeight = '300';
    var $o = $('#dylan_features_nav');
    var $oswf = $('#dylan_features_nav_swf');
    if ( ! $o ) return;

    if ( ! op )
    {
	if ( _featuresShown == 1 ) op = "hide";
	else op = "show";
//	if ( $o.css('display') != "block" ) op = "block";
//	else op = "none";
    }
    /*
    else
    {
	if ( op == "show" ) op = "block";
	else if ( op == "hide" ) op = "none";
    }
    */

    if ( op == "show" )
    {
	var start = 50; //_featuresHeight;
	var end = 0;

	if ( _featuresShown == 0 )
	{
	    $o.css({ display: "block" });
	}

	if ( _featuresLoaded == 0 )
	{
	    if ( $o.css('display') != "block" )
		$o.css({ display: "block" });

	    //dylan_debug("Loading features nav");
	    swfobject.embedSWF('/sites/www.bobdylan.com/themes/zen/dylan/swf/DylanDock.swf',
		'dylan_features_nav_inner',
		'100%', _featuresHeight,
		'9.0.45',
		'/sites/www.bobdylan.com/themes/zen/dylan/js/swfobject/expressinstall.swf',
		{},
		{bgcolor: '#FFFFFF', menu: 'false', wmode: 'transparent'},
		{ id: 'dylan_features_nav_swf' } );
	    _featuresLoaded = 1;

	    $oswf = $('#dylan_features_nav_swf');	// need to assign now that it's been placed
	    $oswf.css({ top: _featuresHeight + "px" });	// set swf to just below the features box

	    // var s = $o[0].innerHTML.replace(/</g, "&lt;");
	    // s.replace (/>/g,"&gt;");
	    // dylan_debug(s);
	}

	// do the animation after it's loaded
	if ( _featuresShown == 0 )
	{
	    //$o.animate({ top: end +"px"}, 'slow');
	    $oswf.animate({ top: end +"px"}, 1000);
	    _featuresShown = 1;
	}
    }
    else if ( op == "hide" )
    {
	var end = _featuresHeight;
	$oswf.animate({ top: '+' + end }, 'slow', null, function() { $o.css({display: 'none'}); });
	_featuresShown = 0;
    }
}

function dylan_set_bg (empty)
{
    var urlstr;

    // reset the global variable in case we get called again
    if ( empty ) bg_obj.path = "";

    if ( bg_obj.path == "" ) urlstr = "none";
    else urlstr = "url(" + bg_obj.path + ")";

    // default to black on grey
    if ( bg_obj.bgcolor == "" ) bg_obj.bgcolor = "#DDDDDD";
    if ( bg_obj.textcolor == "" ) bg_obj.textcolor = "#000000";

    dylan_debug ("dylan_set_bg(): urlstr=" + urlstr);
    $(BG_ID).css ( {
	backgroundPosition: bg_obj.placement,
	backgroundImage: urlstr,
	backgroundRepeat: "no-repeat",
	backgroundAttachment: "fixed"
    });

    if ( bg_obj.bgcolor )
      $(BG_ID).css ( { backgroundColor: bg_obj.bgcolor } );

    if ( bg_obj.textcolor )
      $(BG_ID).css ( { color: bg_obj.textcolor } );

    dylan_dispatch_bg();

    dylan_bg_adjust();
}

function dylan_dispatch_bg()
{
    SWFDispatchDual(bg_obj.bgcolor, bg_obj.textcolor,
      "changeBackground", NAV_SWF_ID);
}

function dylan_debug_toggle()
{
    if ( DEBUG_ENABLED )
    {
	var current = $('#debug').css('display');
	var new_val = (current == "none" ? "block" : "none");
	$('#debug').css({ display: new_val });
    }
}

function dylan_debug(str)
{
    if ( DEBUG_ENABLED )
    {
	var str_escaped;
	if ( typeof(str) == "string" )
	{
	  str_escaped = str.replace(/</g, "&lt;");
	  str_escaped.replace (/>/g,"&gt;");
	}
	else str_escaped = str;
	$('#debug').append(new Date() + " " + str_escaped + "<br/>");
	document.getElementById('debug').scrollTop = 100000;
    }
}

function dylan_debug_noescape(str)
{
    if ( DEBUG_ENABLED )
    {
	$('#debug').append(new Date() + " " + str + "<br/>");
	document.getElementById('debug').scrollTop = 100000;
    }
}

function dylan_window_resize()
{
    dylan_bg_adjust();
    dylan_geo_adjust();
    // having this here seems to trigger an IE loop bug
    // so it's comment out for the time being
    //placeDylanCredits();
}

/* 
 * dylan_window_view() - returns an object with the viewable window
 * area under the nav
 */
function dylan_window_view()
{
  var $ch = $('#' + CONTENT_HEADER_ID);
  var retval = {};

  var top_height = $("#" + HEADER_ID).height() + $("#" + PLAYER_ID).height();
  if ( $ch ) { top_height -= $ch.height(); }

  retval.top = top_height;
  retval.height = $(window).height() - top_height;

  return retval;
}


/* if the geo is up, resize it to the available space. this
 * is a good idea in general, but specifically fixes a display
 * bug in firefox
 */
function dylan_geo_adjust()
{
  var $geo_container = $('#' + GEO_SWF_OUTER_ID);
  if ( ! $geo_container ) return;
  var $ch = $('#' + CONTENT_HEADER_ID);

  var top_height = $("#" + HEADER_ID).height() + $("#" + PLAYER_ID).height();
  if ( $ch ) { top_height -= $ch.height(); }
  var height = ($(window).height() - top_height) + "px";
  $geo_container.css({height: height});
}

function dylan_bg_adjust()
{
    // position[0] = horizontal position, position[1] = vertical position
    var min_height = $("#" + HEADER_ID).height() + $("#" + PLAYER_ID).height();
    var bg_pos_str = $(BG_ID).css("backgroundPosition");
    var bg_position = bg_obj.placement.split(" ");
    var new_position = [ bg_position[0], bg_position[1] ];;
    var css_position;

    // deal with an IE bug
    if ( bg_pos_str && bg_pos_str.length > 0 )
	css_position = bg_pos_str.split(" ");
    else
	css_position = [ '', '' ];

    /*
    dylan_debug ("bg: hor=" + bg_position[0] + " vert=" + bg_position[1]
	+ "css: hor=" + css_position[0] + " vert=" + css_position[1]
	+ " header_height=" + $("#" + HEADER_ID).height()
	+ " dylan_nav_height=" + $("#dylan_nav").height()
	+ " player_height=" + $("#" + PLAYER_ID).height());
    */

    // bottom-positioned backgrounds need to be set to anchor the bottom
    // with a minimum spacing on the top which means they have to be 
    // absolute positioned
    if ( bg_position[1] == "bottom" || bg_position[1] == "100%" )
    {
	var y_offset = $(window).height() - bg_obj.height;
	// dylan_debug ("bg: y_offset = " + y_offset + " min_height = " + min_height);

	// if browser window is smaller than our min height, limit to that
	if ( y_offset < min_height )
	{
	    y_offset = min_height;
	    new_position[1] = y_offset + "px";
	}
    }
    else if (bg_position[1] == "top" || bg_position[1] == "0" || bg_position[1] == "0%")
    {
	new_position[1] = min_height + "px";
    }

    if ( css_position[0] != new_position[0] || css_position[1] != new_position[1] )
    {
	var pos_str = new_position[0] + " " + new_position[1];
	$(BG_ID).css ({ backgroundPosition: pos_str });
	// dylan_debug("bg: new setting: " + $(BG_ID).css ('backgroundPosition'));
    }

//    dylan_debug( "window height = " + $(window).height() + " body height = " + $(document.body).height() + " bg height = " + bg_obj.height);
}

/*
 * SWFDispatch() - send a message to a swf object
 */
function SWFDispatch(value, setter, id) {
    dylan_debug("swfdispatch(" + value + "," + setter + "," + id +")");
    var obj = document.getElementById(id);
    if (obj) {
	if (obj.parentNode && typeof obj.parentNode.so != "undefined") {
	    dylan_debug(obj);
	    dylan_debug(obj.parentNode);
	    dylan_debug(typeof obj.parentNode.so);
	    obj.parentNode.so.call(setter, value);
	} else {
	    if (!(obj && typeof obj[setter] != "undefined")) {
		var objects = obj.getElementsByTagName('object');
		var embeds = obj.getElementsByTagName('embed');
		obj = ((objects[0] && typeof objects[0][setter] != "undefined") ? 
		    objects : ((embeds[0] && typeof embeds[0][setter] != "undefined") ? 
			embeds[0] : null));
	    }
	    if (obj) {
		obj[setter](value);
		dylan_debug ("Sent " + value + " (" + typeof(value) + ") to " + id + "." + setter + "()");
	    }
	    else dylan_debug("Couldn't find object's ExternalInterface for " + setter + " to send");
	} 
    } else if (obj = document[id]) {
	if (typeof obj[setter] != "undefined")
	    obj[setter](value);
    }
}

function SWFDispatchDual(value1, value2, setter, id) {
    dylan_debug("swfdispatchdual(" + value1 + "," + value2 + "," + setter + "," + id +")");
    var obj = document.getElementById(id);
    if (obj) {
	if (obj.parentNode && typeof obj.parentNode.so != "undefined") {
	    dylan_debug(obj);
	    dylan_debug(obj.parentNode);
	    dylan_debug(typeof obj.parentNode.so);
	    obj.parentNode.so.call(setter, value1, value2);
	} else {
	    if (!(obj && typeof obj[setter] != "undefined")) {
		var objects = obj.getElementsByTagName('object');
		var embeds = obj.getElementsByTagName('embed');
		obj = ((objects[0] && typeof objects[0][setter] != "undefined") ? 
		    objects : ((embeds[0] && typeof embeds[0][setter] != "undefined") ? 
			embeds[0] : null));
	    }
	    if (obj) {
		obj[setter](value1, value2);
		dylan_debug ("Sent " + value1 + " (" + typeof(value1) + ") and " + value2 + " (" + typeof(value2) + ") to " + id + "." + setter + "()");
	    }
	    else dylan_debug("Couldn't find object's ExternalInterface for " + setter + " to send");
	} 
    } else if (obj = document[id]) {
	if (typeof obj[setter] != "undefined")
	    obj[setter](value1, value2);
    }
}


function handleSongTourEvent(event) {
    SWFDispatch(event.value, "changeSongTour", PLAYER_SWF_ID);
}

function handleSongEvent(event) {
    SWFDispatch(event.value, "changeSong", PLAYER_SWF_ID);
}

function handleVideoEvent(event) {
    SWFDispatch(event.value, "changeVideo", PLAYER_SWF_ID);
}

function handleGeoRotateEvent(event,id) {
  if ( ! id ) id = GEO_TOUR_SWF_ID;
  SWFDispatch(event.value, "rotateTo", id);
}

function showFullLoadBar ()
{
  full_load_bar_display("show");
}

function hideFullLoadBar ()
{
  full_load_bar_display("hide");
}

function full_load_bar_display (op)
{
  // this is not ready for primetime yet
  return;

  dylan_debug("Full load bar display(" + op + ")");
  if ( op != "show" && op != "hide" )
    return;

  // first make sure it's not there already regardless of whether
  // we are showing or hiding. fading and hiding aren't working
  // right now
  if ( op == "hide" )
  {
    dylan_debug("Hiding " + FULL_LOAD_BAR_SWF_ID);
    $("#" + FULL_LOAD_BAR_OUTER_ID).fadeOut(1000,function(){ $("#" + FULL_LOAD_BAR_SWF_ID).remove(); });
    return;
  }

  dylan_debug("Removing " + FULL_LOAD_BAR_SWF_ID);
  $("#" + FULL_LOAD_BAR_SWF_ID).remove();
  $("#" + FULL_LOAD_BAR_OUTER_ID).css({display: "block"});

  var window_view_info = dylan_window_view();

  dylan_debug("Loading full load bar at top=" + window_view_info.top + " height=" + window_view_info.height);

  var div = document.createElement('div');

  $("#" + FULL_LOAD_BAR_OUTER_ID).css({
    position: 'absolute',
    top: window_view_info.top + "px",
border: "1px solid green",
    left: '0',
    zIndex: '100',
    width: '100%',
    height: window_view_info.height + "px"
  });

  $(div).attr({id: FULL_LOAD_BAR_SWF_ID});

  $('#' + FULL_LOAD_BAR_OUTER_ID).append(div);

  dylan_debug("Loading swf into " + FULL_LOAD_BAR_SWF_ID);
  swfobject.embedSWF('/sites/www.bobdylan.com/themes/zen/dylan/swf/Unknown5.swf',
    FULL_LOAD_BAR_SWF_ID,
    //'100%', '100%',
    '100%', '500',
    '9.0.45',
    '/sites/www.bobdylan.com/themes/zen/dylan/js/swfobject/expressinstall.swf',
    {},
    {menu: 'false', wmode: 'transparent'},
    { id: FULL_LOAD_BAR_SWF_ID } );

}

function placeDylanCredits()
{
  var wh = $(window).height();
  var $credits = $(dylanCreditsTarget);

  if ( ! $credits || ! $credits.offset() )
    return;

  // set margintop to 0 as default
  $credits.css( {marginTop: "5px"} );

  // if we aren't at the bottom of the screen, pad things out
  var bottom = $credits.offset().top + $credits.height();
  if ( bottom < wh )
  {
    h  = wh - bottom - 5;
    if ( h < 0 ) h = 5;
    dylan_debug("credits margin set to " + h + " wh="+ wh + " bottom="+bottom);
    $credits.css ( {marginTop: h} );
  }
}

function killLoadingText() {
  $("#loading_singles").css({display: 'none'});
}

/**
 * Namespace object for dylan code
 */
var dylan = {};

/**
 * Setup event handling for user selection
 */
dylan.setup_user_search_events = function() {
    $('#username-search-submit').click(dylan.goto_user);
    
    $('.member-search-toggle').click(function() {
        $('#member-search-container').toggle();
        return false;
    });
    
    if (dylan.get_querystring_value('sf') == 'country') {
        $('#member-search-container').toggle();
    }
    
    $('#member-search-country').change(function() {
        window.location = '/#/userlist?sf=country&cc=' + $('#member-search-country').val(); 
    });
}

/**
 * Handle autocomplete selection on /userlist username search
 */
dylan.goto_user = function(user_id) {
    var username = $('#usersearch').val();
    if (username) {
        var post_data = $('#usersearch').serialize();
        $.post('/userlist/profile_get_path', post_data, function(responseText, textStatus, XMLHTTPRequest) {
            var response = eval('(' + responseText + ')');
            if (response['status'] == 'success') {
                window.location = response['profile_path'];
            } else {
                alert('sorry, we\'re unable to take you to that profile');
            }

        });
    } else {
        alert('Please start typing a username to search.');
        $('#usersearch').focus();
    }
}

/*
* Gets the value for the passed querystring parameter name
*/
dylan.get_querystring_value = function(param_name) {
    var url = window.location.toString();
    var url_parts = url.split("?");
    
    var ret_value = null;
    
    if (url_parts.length == 2) {
        var vars = url_parts[1].split("&");
    
        for (var i=0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == param_name) {
                ret_value = pair[1];
            }
        }    
    }
    
    return ret_value;
}



