/*
* State Main
* @author: Joseph 'Pcjoe' Florencio
* @date: 12-04-05
*/
/*
* Create global variables/arrays
*/
global_states_list = new Array();
global_current_state = false;
global_think_interval = 0;
global_ignore_next_random = false;

/*
* Create Action Object
* @param action_name: Name of action (action we reference by name)
* @param action_direct: What state will this action trigger? Can keep empty ("") if you only want to print an action_message
* @param action_message: If not empty, ALERT message that will be toggled when user attempts to trigger this state (or could alert and trigger a state)
*/
function createActionObject( action_name, action_direct, action_message )
{
  this.action_name = action_name;
  this.action_direct = action_direct;
  this.action_message = action_message;
}

/*
* Create Random Object
* @param random_percent: Integer value between 0 and 100 which denotes a percent probability
* @param random_direct: What state will this random object trigger?
*/
function createRandomObject( random_percent, random_direct )
{
  this.random_percent = random_percent;
  this.random_direct = random_direct;
}

/*
* Create State
* @param state_name: Unique identifier to classify each state
* @param state_sound: Sound that will be placed in pet sound form element
* @param state_action: Action that will be placed in pet action form element
* @param action_list: Array of action objects created through createActionObject
* @param random_list: Array of random objects created through createRandomOBject
*/
function createState( state_name, state_sound, state_action, action_list, random_list)
{
  this.state_name = state_name;
  this.state_sound = state_sound;
  this.state_action = state_action;
  this.action_list = action_list;
  this.random_list = random_list;
}

/*
* Add State
* @param state: State we're adding to the global array
*/
function addState( state )
{
  global_states_list.push(state);
}
/*
* Fill States
*/
function fillStates()
{
  addState(new createState( "happy", "Woof Woof", "Wag Tail", new Array(
                                                                        new createActionObject("play", "excited",""))
                                                            , new Array(
                                                                        new createRandomObject( 20, "lonely"),
                                                                        new createRandomObject( 80, "happy"))));
  addState(new createState( "excited", "WOOF *pat pat* WOOF", "Jumping", new Array()
                                                            , new Array(
                                                                        new createRandomObject( 50, "excited"),
                                                                        new createRandomObject( 50, "happy"))));
  addState(new createState( "lonely", "*whimper* *whimper*", "All Alone", new Array(
                                                                        new createActionObject("play", "happy",""),
                                                                        new createActionObject("yell", "scared",""))
                                                            , new Array(
                                                                        new createRandomObject( 80, "lonely"),
                                                                        new createRandomObject( 20, "sleep"))));
  addState(new createState( "scared", "*yelp* *yelp*", "Hide in Corner", new Array(), new Array(
                                                                        new createRandomObject( 50, "lonely"),
                                                                        new createRandomObject( 50, "angry"))));
  addState(new createState( "angry", "Grrrr...", "Biting", new Array(), new Array(
                                                                        new createRandomObject( 50, "angry"),
                                                                        new createRandomObject( 25, "lonely"),
                                                                        new createRandomObject( 25, "sleep"))));
  addState(new createState( "sleep", "Zzzzzzz", "Lay on Side", new Array(
                                                                        new createActionObject("yell", "scared",""))
                                                            , new Array(
                                                                        new createRandomObject( 80, "sleep"),
                                                                        new createRandomObject( 20, "hungry"))));
  addState(new createState( "hungry", "*Growl*...", "Lay on Back", new Array(
                                                                        new createActionObject("feed", "happy",""),
                                                                        new createActionObject("feedgood", "excited",""))
                                                                 , new Array()));
}

/*
* Get State By Name
* @param state_name: Looking for state with this matching name
*/
function getStateByName( state_name )
{
  // Iterate through all global states
  for(var i = 0; i < global_states_list.length; i++)
  {
    // return matching state name
    if(global_states_list[i].state_name == state_name)
    {
      return global_states_list[i];
    }
  }
  return false;
}

/*
* Initialize
*/
function Initialize()
{
  fillStates(); // Fill states
  setState( getStateByName( "happy" ) ); // Set default state
  setThinkInterval( 2000 );  // Set default think interval to every 2 seconds
  Display( getState() );    // Display initial status
  PrecacheStates();   // Precache images
  setTimeout( "stateThink()", getThinkInterval() ); // Set first state think
}

/*
* Invoke Action
* @param invoked_action: action to find and envoke
*/
function invokeAction( action_name )
{
  var current_state = getState();
  for(var i = 0; i < current_state.action_list.length; i++)
  {
    // Found state
    if(current_state.action_list[i].action_name == action_name)
    {
      // Print message if there is any
      if(current_state.action_list[i].action_message != "")
      {
        alert(current_state.action_list[i].action_message);
      }
      // Switch state if there is any to switch to
      if(current_state.action_list[i].action_direct != "")
      {
        // Find and set state if it exists
        var state_switch = getStateByName(current_state.action_list[i].action_direct);
        if(state_switch)
        {
          // Set state
          setState(state_switch);
          // Print current state
          Display( getState() );
          // Ignore next random
          setIgnoreNextRandom(true);
        }
      }
      break;
    }
  }
}

/*
* Get Random Number
* @return: Random integer between 0 and 100
*/
function getRandomNumber()
{
  return Math.round(Math.random()*100);
}

/*
* Random Think
*/
function randomThink()
{
  var rand_num = getRandomNumber();
  
  var current_state = getState();
  var startPer = 0;
  // Iterate through all random objects
  for(var i = 0; i < current_state.random_list.length; i++)
  {
    // In percent range, invoke action
    if(rand_num >= startPer && rand_num <= (startPer+current_state.random_list[i].random_percent))
    {
      // Find state we want to switch to
      var state_switch = getStateByName(current_state.random_list[i].random_direct);
      if(state_switch)
      {
         // Set state
         setState(state_switch);
         // Print current state
         Display( getState() );
      }
      break;
    }
    // Add percent and continue
    startPer = startPer + current_state.random_list[i].random_percent;
  }
}

/*
* Display
* @param state: State object, copy data from state to html forms
*/
function Display( state )
{
  // Print data to form and update picture
  document.forms[0].sound.value = state.state_sound;
  document.forms[0].action.value = state.state_action;
  document.petimg.src = "images/" + state.state_name + ".jpg";
}

/*
* Precache
*/
function PrecacheStates()
{
  // Iterate through all states and precache images
  for(var i = 0; i < global_states_list.length; i++)
  {
    precacheImage("images/" + global_states_list[i].state_name + ".jpg");
  }
}

/*
* Accessors
*/
function setState( state ) { global_current_state = state; }
function getState() { return global_current_state; }
function setThinkInterval( interval ) { global_think_interval = interval; }
function getThinkInterval() { return global_think_interval; }
function setIgnoreNextRandom( ignore ) { global_ignore_next_random = ignore; }
function getIgnoreNextRandom() { return global_ignore_next_random; }

/*
* State Think
*/
function stateThink()
{
  // Don't randomly pick states while we're in the game
  if(inFocus == "form")
  {
    // Ignore this random, we had a recent state change
    if(getIgnoreNextRandom())
    {
      setIgnoreNextRandom(false);
    }
    else
    {
      // Random think
      randomThink();
    }
  }
  // Print current state
  Display( getState() );
  // Set next think
  setTimeout( "stateThink()", getThinkInterval() );
}

/*
* Play with dog button
*/
function playDog()
{
  if(getState().state_name == "hungry")
  {
    alert("Your dog is too hungry to play with you.");
  }
  else if(getState().state_name == "scared")
  {
    alert("Your dog is too scared to play with you.");
  }
  else if(getState().state_name == "angry")
  {
    alert("Your dog doesn't want to play with you, it's pissed off at you.");
  }
  else if(getState().state_name == "sleep")
  {
    alert("You can't play catch with a sleeping dog.");
  }
  else
  {
    focusGame();
  }
}

/*
* Feed Dog
*/
function feedDog()
{
  // First value will feed regular, everything else will feed it extra good food to make it go to excited
  if(document.forms[1].foodtype.selectedIndex == 0)
  {
    invokeAction("feed");
  }
  else
  {
    invokeAction("feedgood");
  }
  // hide food menu
  showFood(false);
}

/*
* Attempt to Feed the Dog
*/
function attemptFeed()
{
  // Only feed if the dog is in the hungry state
  if(getState().state_name != "hungry")
  {
    alert("Your dog isn't hungry.");
  }
  // Show food box
  else
  {
    showFood(true);
  }
}

/*
* Yell at Dog
*/
function yellDog()
{
  invokeAction("yell");
}

// Initialize! HACK: Give the html page a breif second of time to load so we won't get errors accessing it
setTimeout( "Initialize()", 0 );
