/*
 * game-play.js
 *
 * Copyright (c) 2008 Tyler de Witt (tyler-dewitt.com)
 * Unauthorized reproduction or use of this code is not permitted.
 */


/* Functions that are only needed for playing the game */

function gAction() {
  this.dir=null;
  this.object_list=null;
  this.target_list=null;
  this.action_name=null;
  this.action_func=null;
  this.prompt=new Object();
  this.state="ready";
  this.close_inv=true;

  this.prompt.item=false;
  this.prompt.item_opts={inv: true, stuff_here: false};
  this.prompt.dir=false;
  this.prompt.target=false;

  this.prompt_dir=function() {
    msg(this.prompt.dir_str);
    ui.state="wait_dir"; 
  }

  this.prompt_item=function() {
    if (typeof this.prompt.item_opts=="undefined") {
      this.prompt.item_opts={inv: true, stuff_here: false};
    }

    var opts=this.prompt.item_opts;
    $("div#gen_dialog > div.item_list > *").remove();
    var k=0;
    var z="";

    var o_list=new Array();
    if (opts && opts.inv) {
      for (i in g.me.pack) { o_list.push(g.me.pack[i]); }
    }
    if (opts && opts.stuff_here) {
      var pile=g.gm.tilesAt(g.me.x,g.me.y);
      for (i in pile) { o_list.push(pile[i]); }
    }

    for (var i in o_list) {
      var o=o_list[i];
      if (this.prompt.item_func && o.has_func(this.prompt.item_func)) {
	k++;
	z = z + "<div class='item'><input type='checkbox' class='item' oid='" + o.id + "' checked='1'/>" + o.title;
	z= z + " <img src='" + image_path + o.image + "' height='20'/> </div>";
      }
    }

    if (k==0) {
      msg("You have nothing to " + this.action_name + ".");
      this.state="aborted";
      return;
    }
    
    $("div#gen_dialog > div.item_list").html(z);
    var s=this.prompt.item_str;
    if (s) {} else { "Which items to " + this.action_name + "?";}
    
    msg(s); 

    $("#gen_dialog_ok").unbind("click").bind("click", function() {
      ui.disabled=false;
      $("div#gen_dialog").jqmHide();
      var o_list=new Array();

      var j=$("div#gen_dialog > div.item_list input.item");
      for (i=0; i< j.length; i++) {
	if (j.eq(i).attr('checked') != 1) continue;
	var o=g.oi(j.eq(i).attr('oid'));
	o_list.push(o);
      }
      ui.action.object_list=o_list;
      ui.action.go(); });

    $("#gen_dialog_cancel").unbind("click").bind("click", function() {
      ui.disabled=false;
      $("div#gen_dialog").jqmHide();
      ui.action.state="completed";
      msg("Aborted"); });

    $("div#gen_dialog > div.prompt").text(s);
    ui.disabled=true;
    $("div#gen_dialog").jqm({modal: true}).jqmShow();
  }

  this.go=function() {
    ui.action=this;
    if (this.state=="aborted" || this.state=="completed") {
      return;
    }

    //check if we need to prompt for anything
    if (this.prompt.item && this.object_list==null) {
      this.state=="prompt_object";
      this.prompt_item();
      return;
    }

    //close inventory screen if specified, or if we need to get a direction
    if ((this.close_inv || this.prompt.dir) && ui.inv != null) {
      $("div#inv").hide();
      $("div#encap").show();
      ui.inv=null;
    }

    if (this.prompt.dir && this.dir==null) {
      this.state=="prompt_dir";
      this.prompt_dir();
      return;
    }
    
    //done prompting, do action
    var action=eval("g.me." + this.action_func);
    if (this.object_list==null) {
      this.object_list=new Array();
      this.object_list.push(null);
    }

    //objects prompted for
    for (i in this.object_list) {
      var o=this.object_list[i];
      if (g.me.has_func(this.action_func)) {
	action.call(g.me,o,this.dir);
	g.play();
	update_display();
      }
    }
    this.state=="completed";
  }
  if (arguments.length > 0) {
    this.load_proto(arguments[0]);
  } 
}

gAction_protos = {
  drop: { action_name: "drop", action_func: "do_drop", prompt: {item: true, item_str: "Drop what?", item_func: "pickup"}},
  wield: { action_name: "wield", action_func: "do_wear", dir: "right_hand",close_inv: false},
  unwield: { action_name: "wield", action_func: "do_unwear", dir: "right_hand",close_inv: false},
  wear: { action_name: "wear", action_func: "do_wear", dir: "body",close_inv: false},
  unwear: { action_name: "unwear", action_func: "do_unwear", dir: "body", close_inv: false},
  thro: { action_name: "throw", action_func: "do_throw", prompt: {item: true, item_str: "Throw what?", item_func: "pickup",
                                                                    dir: true, dir_str: "Throw in what direction?",dir_func: "pickup"}},
  pickup: { action_name: "pickup", action_func: "do_pickup", prompt: {item: true, item_str: "Pickup which items?", item_func: "pickup", 
								      item_opts: {inv: false, stuff_here: true}}},
  drink: { action_name: "drink", action_func: "do_drink", prompt: {item: true, item_str: "Drink what?", item_func: "drink"}},
  read: { action_name: "read", action_func: "do_read", prompt: {item: true, item_str: "Read what?", item_func: "read"}},	
  enter: { action_name: "enter", action_func: "do_enter"},
  attack: { action_name: "attack", action_func: "do_attack", prompt: {dir: true, dir_str: "Attack what?", item_func: "attack"}},
  talk: { action_name: "talk", action_func: "do_talk", prompt: {dir: true, dir_str: "Talk to who?", item_func: "talk"}},
  look: { action_name: "look", action_func: "do_look", prompt: {dir: true, dir_str: "Look closely at what?", item_func: "look"}},
  look_inv: { action_name: "look_inv", action_func: "do_look", prompt: {item: true, item_str: "Look closely at what?", item_func: "look"}}
};

gAction.prototype.load_proto=function(s) {
  var plist=gAction_protos;
  if (plist[s] == null) {
    return false;
  }
  for (i in plist[s]) {
    this[i]=plist[s][i];
  }
  return true;
}


/* HACK: we put the timeout so that the blockUI message actually gets displayed? */

function load_game() {
  // update the block message
  $.blockUI({ message: "<h1> Loading game...</h1>" });
  setTimeout("do_loadgame()",100);
}

function do_loadgame() {
  //send the ajax request to load game
  //TODO: handle errors
  $.post("index.php", { m: "load", game_id: glob.game_id, savegame_id: glob.savegame_id, tag: glob.screen_tag}, function(data) {
    var load_o=null;
    try { 
      load_o=JSON.parse(data);
    } catch(err) {
      msg("Error loading new game");
      $.unblockUI(); 
      return;
    }

    //this will load the character as well
    g.load_game(load_o);

    $.unblockUI();
    update_display();
    screen_change_animation();
  });
}

function save_game() {
  // update the block message
  $.blockUI({ message: "<h1>Saving game...</h1>" });

  //obtain JSON representation of the current game
  var save_data=JSON.stringify(g.save_game());

  //send the ajax request to save game

  var return_data = $.ajax({type: "POST", 
				    url: "index.php", 
				    async: false, data: { m: "save", 
							       data: save_data,
							       tag: g.gm.screen_tag, 
							       savegame_id: glob.savegame_id, 
							       game_id: glob.game_id }
  }).responseText;


  //save game returns the savegame_id
  try {	
    var o=JSON.parse(return_data);
  } catch(e) {}

  if (o.result=="success") {
    glob.savegame_id=o.savegame_id;
  } else {
    return;
  }
  $.unblockUI(); 
}

function switch_screen() {
  // update the block message
  var s="do_switch_screen()";
  $.blockUI({ message: "<h1> Please wait...</h1>" });
  setTimeout(s,100);
}

function do_switch_screen() {
  if (typeof g.si == "undefined" || g.si==null) return;

  var load_o=null;
  g.si.from_tag=g.gm.screen_tag;
  var dest_x=g.si.door.dest_x;
  var dest_y=g.si.door.dest_y;

  var si_json=JSON.stringify(g.si);

  //load next screen
  //send the ajax request to load game
  //TODO: handle errors
  var dest_tag=g.si.door.dest_tag;

  var load_data = $.ajax({type: "POST", url: "index.php", async: false, data: { m: "load", tag: dest_tag, si: si_json, savegame_id: glob.savegame_id, game_id: glob.game_id, max_id: gGame.prototype.nextID}}).responseText;

  try { 
    load_o=JSON.parse(load_data);
  } catch(err) {
    msg("Error loading game");
    $.unblockUI(); 
    return;
  }

  //save this screen

  //if necessary, first update the door we entered with the new info of where it's going to


  if (typeof load_o.gen_info != "undefined") {
    var gi=load_o.gen_info;
    if (gi.dest_tag != null) g.si.door.dest_tag=gi.dest_tag;
    if (gi.dest_x != null) { g.si.door.dest_x=gi.dest_x; dest_x=gi.dest_x; }
    if (gi.dest_y != null) { g.si.door.dest_y=gi.dest_y; dest_y=gi.dest_y; }
    load_o.gen_info=null;
  }


  //obtain JSON representation of the current game
  var save_data="";
  try {
    save_data=JSON.stringify(g.save_game());
  } catch(e) {
    alert('problem');
  }

  //send the ajax request to save game

  var return_data = $.ajax({type: "POST", url: "index.php", async: false, data: { m: "save", data: save_data,  tag: g.gm.screen_tag, savegame_id: glob.savegame_id, game_id: glob.game_id, max_id: gGame.prototype.nextID}}).responseText;

  //save game returns the savegame_id
  try {	
    var o=JSON.parse(return_data);
  } catch(e) {}

  if (o.result=="success") {
    glob.savegame_id=o.savegame_id;
  } else {
    msg("Error saving game");
    $.unblockUI(); 
    return;
  }

  g.switch_screen(load_o,dest_x,dest_y);

  di.clearDisplayCache();
  update_display();
  screen_change_animation();

  $.unblockUI(); 
}



function get_dir(k,delta) {
  switch(k) {
  case '1': case 'b': delta.x= -1; delta.y= 1; break;
  case 'j': case '2': delta.x= 0; delta.y=1; break;
  case '3': case 'n': delta.x=1;delta.y=1; break;
  case 'h': case '4': delta.x=-1;delta.y=0; break;
  case 'l': case '6': delta.x=1;delta.y=0; break;
  case '7': case 'y': delta.x=-1;delta.y=-1; break;
  case 'k': case '8': delta.x=0;delta.y=-1; break;
  case '9': case 'u': delta.x=1;delta.y=-1; break;
  case '.': delta.x=0;delta.y=-0; break;
  default: return false;
  }
  return true;
}

// -- PLAY READY FUNCTION

ui=new Object();
ui.sound_on=true;
ui.toggle_sound=function() {
  if (ui.sound_on) {
    ui.sound_on=false;
    //stop if playing
    soundManager.stopAll();
    if (soundManager.screen_sound) {
      soundManager.destroySound(soundManager.screen_sound);
      delete soundManager.screen_sound;
    }
    $("#sound_command").text("Sound (off)");
  } else {
    ui.sound_on=true;
    screen_change_sound();
    $("#sound_command").text("Sound (on)");
  }
} 

ui.sound=function(s) {
  if (!(ui.sound_on && soundManager.game_ready)) return;
  if (typeof s=="string") {
    soundManager.play(s);
  } else if (typeof s=="object") {
    soundManager.createSound(s);
  }
}

ui.begin_action=function(s) {
  //  if (ui.action && (ui.action.state=="completed" || ui.action.state=="aborted"))
  //      return;
  ui.action=new gAction(s); 
  ui.action.go();
}

my_document_ready=function() {
  //use fov
  di.use_fov=1;

  //set up the UI
  $("div.pane_div div.toggle_pane").toggle(function() {
    var t=$(this).attr('target');
    $(this).text("(show)");
    $("div#" + t).hide('fast');
  }, function() {
    var t=$(this).attr('target');
    $(this).text("(hide)");
    $("div#" + t).show('fast');
  });
		
  $("ul.sf-menu").superfish({ 
    delay:       100,                            // one second delay on mouseout 
	animation:   {opacity: 'show'},
	speed:       'fast',                          // faster animation speed 
	autoArrows:  false,                           // disable generation of arrow mark-up 
	dropShadows: false                            // disable drop shadows 
	});


  
  var z="<div id='main'></div>";
  $("#encap").append(z);

  z="<div id='fov'></div>";
  $("#encap").append(z);

  /*

  //   Uncomment the following to use canvas support 
  var z="<canvas id='main' width='450' height='450'></canvas>";
  $("#encap").append(z);
  di.ctx=$("canvas#main").get(0).getContext('2d');
  
  */	    

  $("#main").css("background-position","0px 0px");
  //  $("div#main").css("background-image","url('" + image_path + g.gm.bg_image + "')");

  ui.state="move";

  /* this is just for generating some data for testing
     g.load_map();
     g.me=g.create_object('gMe');
     g.gm.placeTile(g.me,6,6);
     g.gm.screen_tag='screen1';
     save_game();
     alert('saved');
  */

  /* Start the stored nextID auto increment counter. 
     Newly created objects should not conflict with previous objects stored in other files */

  gGame.prototype.nextID=(glob.maxID >= gGame.prototype.nextID ? glob.maxID : gGame.prototype.nextID);

  /* Load the game. This will try to load the default game specified by glob.game_id,glob.savegame_id,glob.screen_tag */

  load_game();


  $(document).keypress(function(e) {
    if (ui.disabled) return false;
			 
    var k=String.fromCharCode(e.which);
    switch(e.keyCode) {
    case 37: k='4'; break;
    case 38: k='8'; break;
    case 39: k='6'; break;
    case 40: k='2'; break;
    }

    creg.unshift(k);

    if (creg.length > 10) {
      creg.pop();
    }
    var delta=new Object();

    if (ui.state=="wait_dir") {
      //revert state to move;
      ui.state="move";
      if (get_dir(k,delta) && ui.action) {
	var x=g.me.x+parseInt(delta.x);
	var y=g.me.y+parseInt(delta.y);
	ui.action.dir={ delta: delta, x: x, y: y};
	ui.action.go();
      } else {
	ui.action.state="completed";
	msg('Aborted; unknown direction');
      }
    } else if (ui.state=="move") {
      //we're just moving
      if (get_dir(k,delta)) {
	do_move(delta);
      } else {
	switch(k) {
	case '>': ui.action=new gAction("enter"); ui.action.go(); break;
	case 'i': toggle_inventory(); break;
	case 'd': ui.action=new gAction("drop"); ui.action.go(); break;
	case 'q': ui.action=new gAction("drink"); ui.action.go(); break;
	case 'r': prompt_for_item("read","read",action_read); break;
	case 'u': prompt_for_item("use","use",action_use); break;
	case 'z': ui.action=new gAction("thro"); ui.action.go(); break;
	case 'p': ui.action=new gAction("pickup"); ui.action.go(); break;
	case 't': ui.action=new gAction("talk"); ui.action.go(); break;
	case 'x': ui.action=new gAction("attack"); ui.action.go(); break;
	}
      }
    }

    //let the other characters, monsters act
    g.play();
    update_display();
    // $(this).val("");
    //
    //    $("span#maincoords").text("Main get coords: ( " + c.left + ", " + c.top + " ) ");
    return false;
  });


  $("div#encap").unbind('mouseup').bind('mouseup',function(e){ drag.inDrag=false; clearInterval(drag.timerID); });


  $("div#encap").unbind('mousemove').bind('mousemove',function(e){ 
    if (ui.disabled) return;

    if (!drag.inDrag) {
      if (ui.state=="wait_dir") {
	return false;
      }

      var p=get_game_coords(e.pageX,e.pageY);					      

      if (di.use_fov) {
	if (!g.gm.seen(p.x,p.y)) return;
      }

      var delta=new Object();
      delta.x=p.x-g.me.x;
      delta.y=p.y-g.me.y;
      var under_me=(delta.x==0 && delta.y==0);
      var o_list=g.gm.tilesAt(p.x,p.y);					   
      //display info in look pane
      if (di.use_fov) {
	show_quick_look(null);
	if (!di.in_fov(p.x,p.y)) return;
      }

      show_quick_look(o_list[0]);

      if (typeof ui.hover != "undefined" && ui.hover != null && p.x==ui.hover.x && p.y==ui.hover.y) {
	//hover already in place;
	return false;
      }

      //we're not in a drag, see if we should hover a menu
      var d=$("#encap div.context_menu");
      if (d.length != 0) d.remove();

      ui.hover=new Object();
      ui.hover.x=p.x;
      ui.hover.y=p.y;
      var ec=game_to_encap(p.x,p.y);
      ec.x += (grid_size-3);
      ec.y += 3;

      var j="<div class='context_menu' style='left: " + ec.x + "px; top: " + ec.y + "px;'>";
      var k=0;
      var flags=new Object();

      ui.action_list=new Array();
      for (var i in o_list) {
	var o=o_list[i];

	if (o.has_func("talk") && o.object_type != "gMe" && flags.talk == null) {
	  flags.talk=true;
	  var a=new gAction("talk");
	  a.dir={delta: delta, x: p.x, y: p.y};
	  ui.action_list.push(a);
	  j += "<div onmousedown=\"context_command(event," + k + ")\">Talk</div>";
	  k++;
	} 

	if ((o.has_func("look") || (o.look_str && o.look_str != "")) && flags.look == null) {
	  flags.look=true;
	  var a=new gAction("look");
	  a.dir={delta: delta, x: p.x, y: p.y};
	  ui.action_list.push(a);
	  j += "<div onmousedown=\"context_command(event," + k + ")\">Look</div>";
	  k++;
	} 

	if (under_me && o.has_func("pickup") && flags.pickup == null) {
	  flags.pickup=true;
	  var a=new gAction("pickup");
	  ui.action_list.push(a);
	  j += "<div onmousedown=\"context_command(event," + k + ")\">Pickup Items</div>";
	  k++;
	}
	if (under_me && o.has_func("enter") && flags.enter == null) {
	  flags.enter=true;
	  ui.action_list.push(new gAction("enter"));
	  j += "<div onmousedown=\"context_command(event," + k + ")\">Enter Door</div>";
	  k++;
	}
	if (o.object_type == "gMe") {
	  j += "<div onmousedown='context_command(event,toggle_inventory)'>Inventory</div>";
	  ui.action_list.push(new gAction());
	  k++;
	}
      }
      j+="</div>";
      if (k > 0) {
	$("#encap").prepend(j);
	$("#encap div.context_menu").unbind("mousemove").bind("mousemove", function(e) { return false;});
	$("#encap div.context_menu > div").hover(function() { $(this).css("background","#ffffff"); }, 
						 function() { $(this).css("background","#cccccc"); });
	ui.state="context";
      } else {
	ui.state="move";
      }
      return false;
    }

    if (typeof ui.hover != "undefined" && ui.hover != null) {
      ui.hover=null;
      var d=$("#encap div.context_menu");
      if (d.length != 0) d.remove();
      ui.state="move";
    }

    drag.current_x=e.pageX;
    drag.current_y=e.pageY;
    return false;
  });


  
  $("div#encap").unbind('mousedown').bind('mousedown', function(e){
    if (ui.disabled) return;
    var p=get_game_coords(e.pageX,e.pageY);
    
    var delta=new Object();
    delta.x=p.x-g.me.x;
    delta.y=p.y-g.me.y;

    if (ui.state=="wait_dir") {
      //revert state to move;
      ui.state="move";
      if (ui.action) {
	ui.action.dir={ delta: delta, x: p.x, y: p.y};
	ui.action.go();
      } 
    } else if (ui.state=="move" || ui.state=="context") {
      //when we're not in a drag, see if there's a default action to be performed on the clicked item
      if (Math.abs(delta.x) <=1 && Math.abs(delta.y) <= 1) {

	var o_list=g.gm.tilesAt(p.x,p.y);
	var acted=false;
	for (var i in o_list) {
	  var o=o_list[i];
	  if (o===g.me) continue;

	  //TODO check if monster is hostile and attack it instead of talking
	  if (o.has_func("talk") && o.hostile==false) {
	    var a=new gAction("talk");
	    a.dir= {delta: delta, x: p.x, y: p.y};
	    ui.action=a;
	    ui.action.go();
	    return false;
	  } else if (o.has_func("pickup") && delta.x==0 && delta.y==0) {
	    var a=new gAction("pickup");
	    ui.action=a;
	    ui.action.go();
	    return false;
	  } else if (o.has_func("enter") && delta.x==0 && delta.y==0) {
	    //only enter when we're directly over
	    var a=new gAction("enter");
	    ui.action=a;
	    ui.action.go();
	    return false;
	  }
	}
      }

      drag.inDrag=true;

      drag.current_x=e.pageX;
      drag.current_y=e.pageY;
      drag.walk_count=2;
      check_walk();
      drag.walk_count=0;
      if (drag.timerID) clearInterval(drag.timerID);
      drag.timerID=setInterval ( "check_walk()", 100 );
    }
    //prevent event from bubbling up
    return false;
  });

};

function show_talk(o,s) {
  //to emphasize a msg
  var pre=conjugate(o, "say", null);

  msg(pre + s);
  if (s != "nothing") {
    var im=o.image;
    if (o.photo) { im=o.photo; }
    //TODO check if im begins with http
    $("div#talk_dialog div.icon").html("<img src='" + image_path + im + "'/>");
    $("div#talk_dialog div.says").text(pre);
    $("div#talk_dialog div.content").text(s);
    ui.disabled=true;
    $("div#talk_dialog").jqm().jqmShow();
  }
}



function show_look(o) {
  //to emphasize a msg
  var s="";
  if (o.has_func("look")) {
    s=o.look();
  } else if (o.look_str) {
    s=o.look_str;
  } else if (o.descrip) {
    s=o.descrip;
  } else {
    s="Nothing special.";
  }

  msg(s);

  var im=o.image;
  if (o.photo) { im=o.photo; }
  //TODO check if im begins with http
  $("div#talk_dialog div.icon").html("<img src='" + image_path + im + "'/>");
  $("div#talk_dialog div.says").text('What you see..');
  $("div#talk_dialog div.content").text(s);
  ui.disabled=true;
  $("div#talk_dialog").jqm().jqmShow();
}



function show_quick_look(o) {
  if (o==null) {
    //in this case, clear it
    $("div#look_pane div.look_title").text("");
    $("div#look_pane div.look_descrip").text("");
    $("div#look_pane div.icon").text("");
    return;
  }

  var t="";
  if (o.title) {
    t=o.title;
  } else if (o.sub_type) {
    t=o.sub_type;
  }
  
  var d="";
  if (o.descrip) d=o.descrip;

  //TODO show more info
  if (o.displayTile==true) {
    $("div#look_pane div.icon").html("<img src='" + image_path + o.image + "' height='25' width='25'/>");
  } else {
    $("div#look_pane div.icon").html("");
  }
  $("div#look_pane div.look_title").text(t);
  $("div#look_pane div.look_descrip").text(d);
}


function check_walk() {
  if (!drag.inDrag) return;
  drag.walk_count++;
  if (drag.walk_count < 1) return;

  var v=$("div#encap").offset();
  var x= drag.current_x-v.left;
  var y= drag.current_y-v.top;

  //      $("span#coords").text("Encap Coords ( e.pageX , e.pageY ) - " + divCoords);
     
  tx=parseInt(x/grid_size);
  ty=parseInt(y/grid_size);
    
  tx_mid=parseInt(max_x/(grid_size* 2));
  ty_mid=parseInt(max_y/(grid_size *2));

  //  $("span#mapcoords").text(tx + ", " + ty + "( " + tx_mid + ", " + ty_mid);
  var x_offset=0;
  var y_offset=0;

  if (tx > tx_mid) { x_offset++; } else if (tx < tx_mid) { x_offset--; }
  if (ty > ty_mid) { y_offset++; } else if (ty < ty_mid) { y_offset--; }
  //  var dir={delta: {x: x_offset, y: y_offset} , x: g.me.x+x_offset, y: g.me.y+y_offset};

  do_move({x: x_offset, y: y_offset});
}

function do_move(delta) {
  var dir={delta: delta , x: g.me.x+delta.x, y: g.me.y+delta.y};

  var acted=false;
  if (!(delta.x ==0 && delta.y ==0)) {
    var o_list=g.gm.tilesAt(dir.x,dir.y);
    for (var i in o_list) {
      var o=o_list[i];
      if (o===g.me) continue;
      if (o.has_func("attack") && o.hostile==true) {
	var a=new gAction("attack");
	a.dir=dir;
	ui.action=a;
	ui.action.go();
	acted=true;
      }
    }
    if (!acted) {
      g.me.slant_move(dir.delta);
      g.play();
      update_display();
    }
  }
}

function screen_change_animation() {
  if (g.gm.descrip && g.gm.descrip != "") { msg(g.gm.descrip);  }
  screen_change_sound();
}

function screen_change_sound() {
    
  if (soundManager.screen_sound && g.gm.sound==soundManager.screen_sound) {
    //do nothing, it's already playing
    return;
  }
    
  if (g.gm.sound && g.gm.sound != "") {
    //stop if playing
    if (soundManager.screen_sound) {
      soundManager.destroySound(soundManager.screen_sound);
      delete soundManager.screen_sound;
    }

    soundManager.screen_sound=g.gm.sound;

    ui.sound({id: soundManager.screen_sound, url: sound_path + soundManager.screen_sound, autoPlay: true, autoLoad: true, onfinish: function() {ui.sound(soundManager.screen_sound); }});
  }

  }
function hit_animation(id) {
  $("div#o" + id).html("<div style='width: 50px; height: 50px; background: #990011; opacity: 0.5; filter:alpha(opacity=50);'>");

  ui.sound('hit');
  setTimeout ( "remove_animation(" + id + ")",200);  
}

function remove_animation(id) {
  var d=$("div#o" + id);
  if (d.length > 0) d.html("");
}

function build_context(id,e) {
  var o=g.oi(id);
  if (o == null) return;
  if (ui.inv.target_id == id) return;

  ui.inv.target_id=id;
  
  var delta=$("#inv"+id).offset();
  var p=$("#inv div.item_list").offset();
  delta.top += (6 /* - p.top */);
  delta.left += (50 /* - p.left */);
  
  var j="<div class='context_menu' style='position: absolute; left: " + 50 + "px; top: " + 6 + "px;'>";
  var k=0;
  var flags=new Object();
  ui.action_list=new Array();
  if (o.has_func("drink")) {
    var a=new gAction("drink");
    a.object_list=new Array(o);
    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Drink</div>";
    k++;
  } 

  if (o.has_func("read")) {
    var a=new gAction("read");
    a.object_list=new Array(o);
    ui.inv.update_list=new Array(o);
    ui.action_list.push(a);
    j += "<div class='invcontext'  onmousedown=\"inv_context_command(event," + k + ")\">Read</div>";
    k++;
  } 

  if (o.has_func("look") || (o.look_str && o.look_str != "")) {
    var a=new gAction("look_inv");
    a.object_list=new Array(o);
    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Look</div>";
    k++;
  } 

  if (!o.worn && o.has_func("wield")) {
    var a=new gAction("wield");
    a.dir=o.place;
    a.object_list=new Array(o);
    ui.inv.update_list=new Array(o,g.me.worn[a.dir]);
    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Wield</div>";
    k++;
  } 

  if (o.worn && o.has_func("wield")) {
    var a=new gAction("unwield");
    a.dir=o.place;
    a.object_list=new Array(o);
    ui.inv.update_list=new Array(o,g.me.worn[a.dir]);
    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Unwield</div>";
    k++;
  } 

  if (!o.worn && o.has_func("wear")) {
    var a=new gAction("wear");
    a.dir=o.place;
    a.object_list=new Array(o);
    ui.inv.update_list=new Array(o,g.me.worn[a.dir]);

    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Wear</div>";
    k++;
  } 

  if (o.worn && o.has_func("wear")) {
    var a=new gAction("unwear");
    a.dir=o.place;
    a.object_list=new Array(o);
    ui.inv.update_list=new Array(o,g.me.worn[a.dir]);
    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Unwear</div>";
    k++;
  } 


  if (!o.worn) {
    var a=new gAction("thro");
    a.object_list=new Array(o);
    ui.action_list.push(a);
    j += "<div class='invcontext' onmousedown=\"inv_context_command(event," + k + ")\">Throw</div>";
    k++;
  } 

  var d=$("div#inv div.context_menu");
  if (d.length != 0) d.remove();

  if (k > 0) {
    $("#inv"+id).append(j);
    //    $("div#inv div.item_list").append(j);
    $("div#inv div.context_menu").unbind("mousemove").bind("mousemove", function(event) { return false; });

    //    $("div#inv div.context_menu").unbind("mouseout").bind("mouseout", function(e) { return false;});
        $("div#inv div.context_menu > div").hover(function() { $(this).css("background","#ffffff"); return false; }, 
        					      function() { $(this).css("background","#cccccc"); return false; });

	//$("div#inv div.context_menu > div").unbind("mousemove").bind("mousemove", function(e) { return false;});




  } 
}
function inv_title(o) {
  var n=o.title;
  var mods=new Array();

  if (o.state) {
    if (o.state.mod && o.state.mod != 0) {
      var s=(o.state.mod > 0 ? "+" : "");
      mods.push(s+o.state.mod);
    }
    if (o.state.cursed) {
      mods.push("cursed");
    }
  }
  if (o.worn) {
    mods.push(o.worn);
  }
  if (mods.length > 0) {
    n += "(";
    for(var i=0;i<mods.length;i++) {
      if (i!=0) n+=", ";
      n += mods[i];
    }
    n += ")";
  }
  return n;

}
function inv_update(id) {
  var o=g.oi(id);
  if (o==null) return false;
  var n=inv_title(o);

  var d=$("div#inv" + o.id + " span.title");
  if (d.length > 0) d.text(n);
}
function toggle_inventory() {
  if (ui.inv != null) {
    ui.inv=null;
    $("div#inv").hide();
    $("div#encap").show();
  } else {
    ui.inv=new Object();
    //prepare inventory screen
    var z="";
    $("div#inv > div.item_list > div").remove();

    for (var i in g.me.pack) {
      var o=g.me.pack[i];
      var n=inv_title(o);

      z = z + "<div class='item' id='inv" + o.id + "' oid='" + o.id + "'>";
      z = z + "<input type='checkbox' class='item' oid='" + o.id + "' />";
      z = z + " <img src='" + image_path + o.image + "' height='20'/> <span class='title'>" + n + "</span></div>";
    }
    
    $("div#inv > div.item_list").html(z);
    $("div#inv  div.item").bind("mousemove", function(e) { if (e.stuff) { return false; } else {build_context($(this).attr('oid'),e); return false;}});

    $("div#encap").hide();
    $("div#inv").show();
  }  
}

function inv_mul_command() {
  ui.item_prompt="inventory";
  var n=$("div#inv select").attr("value");

  var a=new gAction(n);
  var o_list=new Array();

  var j=$("div#inv > div.item_list input.item");
  for (i=0; i< j.length; i++) {
    if (j.eq(i).attr('checked') != 1) continue;
    var o=g.oi(j.eq(i).attr('oid'));
    o_list.push(o);
  }
  a.object_list=o_list;
  ui.action=a;
  ui.action.go();
}

function inv_context_command(event,action_id) {
  var d=$("div#inv div.context_menu");
  if (d.length != 0) d.remove();
  ui.inv.target_id = 0;

  if (typeof action_id=="function") {
    action_id();
  } else {
    ui.action_list[action_id].go();
  }

  if (ui.inv != null && ui.inv.update_list != null) {
    for (i in ui.inv.update_list) {
      var o=ui.inv.update_list[i];
      if (o && o.id)
	inv_update(o.id);
    }
  }
}

function context_command(event,action_id) {
  if (event.stopPropagation) event.stopPropagation(); 
  event.cancelBubble=true; 
  event.returnValue=false; 

  var d=$("#encap div.context_menu");
  if (d.length != 0) d.remove();

  if (typeof action_id=="function") {
    action_id();
  } else {
    ui.action_list[action_id].go();
  }

  ui.hover=null;
  ui.state="move";
  return false;
}

function end_game() {
  g.object_list=new Object();
  g.dead=true;
  drag.inDrag=false;
  ui.disabled=true;
  $("div#endgame_dialog").jqm({modal: true}).jqmShow();
}
