/* Quest System - Random Events JS File */
/* Copyright (c) 2005 WhuddleWorld Inc. */
var qeLocation = '';
var qeFuncCalls = new Array(); 
var arr = new Array();
var fidx = 0;
var evalStr = new Array();
var qeQuestInfo = new Object();


/*** Handles specific popups ***/
function qeHandlePopup(qeInput)
{
  qeInput.split(',');
  
}

function RunScript(id)
{
  if(qeFuncCalls[id]) {
    eval(qeFuncCalls[id]);
  }
}

function RunScripts(func)
{
  for(i = 0; i < qeFuncCalls.length; i++)
    if(qeFuncCalls[i]) { 
      eval(qeFuncCalls[i]); // + '();');
    }
}

function LoadScript(id)
{
  qeLoadJS    = evalStr[id].split(':');
  head        = document.getElementsByTagName("head")[0];
  script      = document.createElement('script');
  script.id   = qeLoadJS[2];
  script.type = 'text/javascript';
  script.src  = '/scripts/javascript/events/' + qeLoadJS[1] + '.js';
  head.appendChild(script);
  
  // Now we run the function. Give it a second to load.
  for(i = 3; i < qeLoadJS.length; i++)
    if(qeLoadJS[i] && qeLoadJS[i] != 'null') {
      qeFuncCalls[fidx] = qeLoadJS[i];
      //alert('FIDX: ' + fidx + ' FUNC: ' + qeLoadJS[i]);
      arr[fidx] = window.setTimeout('RunScript('+fidx+');', 1500);
      fidx++;
    }
}

// 
function qeXMLPost(postURI, postData, postReturnHandler)
{
  var postObj = false;
  if (window.XMLHttpRequest){
    postObj = new XMLHttpRequest();
    if (postObj.overrideMimeType)   { postObj.overrideMimeType('text/xml'); }
  } else if (window.ActiveXObject) { postObj = new ActiveXObject('Microsoft.XMLHTTP'); }
    postObj.open('POST', postURI, true);
    postObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    postObj.onreadystatechange = function() {
    if (postObj.readyState == 4) {
      //alert(postObj.responseText);

/*********/
      if(postReturnHandler == '__embedded_quest') { 
        if(postObj.responseText) {
          // We've brought back a list of JS files to dynamically load.
          qeArray = postObj.responseText.split(',');

          for(j = 0; j < qeArray.length; j++)
          {
            qeLoadJS    = qeArray[j].split(':');
            if(qeLoadJS[0] == 0) {
              evalStr[j] = qeArray[j];
              LoadScript(j);
            } else {
              evalStr[j] = qeArray[j];
              arr[j] = window.setTimeout('eval(LoadScript('+j+'));', qeLoadJS[0]);
            }
          }
           
          //setTimeout('RunScripts();', 1000);
        }
      } else {
        eval(postReturnHandler + '(postObj.responseText);');
      }
/**********/
    }
  }

  postObj.send(postData);
}


/*** Initiate random event ***/
function qeInitRealRandom(goqeLocation)
{
  qeLocation = goqeLocation;
  qeXMLPost('/scripts/php/events/randomevent.php', 'qeLocation=' + qeLocation, '__embedded_quest');  
}

function qeInitRandom(qeLocation)
{
  var strLine = "qeInitRealRandom('" + qeLocation + "');";
  setTimeout(strLine, 1000);
}

/* Statically loading extra CSS */ 
document.write('<link rel="stylesheet" href="/styles/whuddle_component.css" />');

function qeParseResult(rTxt)
{
  //alert(rTxt);
  rSplit = rTxt.split('::');
  if(rSplit[0] == 'fini' && rSplit[1]) {
    window.frames['wmInvFrame'].location.reload();
    top.msgWindow(Array(top.document.body, 280, 300), '<img src="' + rSplit[1] + '" border="0" />Congratulations! You found this school supply!', 'Great!', '', 'top.qeDoneItem();');
  } else {
    top.qeReload();
  }
}

function qeDoneItem()
{
  top.qeReload();
}

function qeNotEnoughInventory()
{
  top.msgWindow(Array(top.document.body, 240, 320), 'You are carrying too much to pick up that item.', 'OK', '', 'top.qeReload();');
}

function qeFindItem()
{
  xmlPost('/scripts/php/events/ajaxcalls.php', 'event=bts_item_find', 'top.qeParseResult');
}

function qePlaceItem(top, left, image, frame)
{
  //alert('top: ' + top + ', left: ' + left + ', image: ' + image + ', frame: ' + frame);
  if((el = document.getElementById('qePlaceThatItem')))
    el.parentNode.removeChild(el);

  if(top == -1) return false;

  theFrame = (frame == 'top') ? document : window.frames[frame].document;
  if(!top.qeQuestInfo) { qeBTSSetup(true, false, '', '', '', frame); }

  div			= theFrame.createElement('div');
  div.id		= 'qePlaceThatItem';
  div.style.position	= 'absolute';
  div.style.top		= top + 'px';
  div.style.left	= left + 'px';
  div.style.zIndex 	= '5000';
  div.innerHTML		= '<a href="#" onhover="return false;" onmouseover="return false;" onclick="top.qeFindItem(); return false;"><img style="filter: alpha(opacity=0); opacity: 0;" border="0" src="' + image + '" /></a>';
  
  if(frame == top) {
    top.document.body.appendChild(div);
  } else {
    window.frames[frame].document.body.appendChild(div);
  }
}

function foo()
{
  alert('hello!');
}

function qeBTSSetup(hasTalked, hasFound, quizID, objID, npcName, speechFrame)
{
  top.qeQuestInfo['bts'] = new Array();
  top.qeQuestInfo['bts']['hasTalked'] = hasTalked;
  top.qeQuestInfo['bts']['hasFound']  = hasFound;
  top.qeQuestInfo['bts']['quizID']    = quizID;
  top.qeQuestInfo['bts']['objID']     = objID;
  top.qeQuestInfo['bts']['NPC']	      = npcName;
  top.qeQuestInfo['bts']['frame']     = speechFrame;
}

function qeTalkClue()
{
  top.multiBubbleClose('qb', top.document);
  top.qeDoQuiz();
}

function qeTalkGoAway()
{
}

function qeCloseCompletedQuest()
{
  if( (el = document.getElementById('completedQuest')) )
    el.parentNode.removeChild(el);

  top.document.location.reload();
}

function qeCompletedQuest(html)
{
  div			= document.createElement('div');
  div.id		= 'completedQuest';
  div.style.position	= 'absolute';
  div.style.width	= '280px';
  div.style.height	= '404px';
  div.style.top		= '100px';
  div.style.left	= '330px';
  div.style.zIndex	= '9000';
  div.style.padding	= '15px 20px 0';
  div.style.background  = 'url(/images/bts/CC_thanks_popup.gif) no-repeat 0 0';
  div.innerHTML		= html;
  
  top.document.body.appendChild(div);
  
}

function qeParseThisUp(rTxt)
{
  //alert(rTxt);
  top.multiBubbleClose('qb', top.document);
  rSplit = rTxt.split('::');
  if(rSplit[0] == 'null') {
    top.qeReload();
  } else if(rSplit[0] == 'completed') {
    window.frames['wmInvFrame'].location.reload();
    top.qeCompletedQuest(rSplit[1]);
  } else if (rSplit[0] == 'fini') { 
    window.frames['wmInvFrame'].location.reload();
    top.qeTalkAndFound2 = top.qeTalkAndFound2.replace(/<NPC>/, '<strong>' + rSplit[1] + '</strong>');
    top.multiBubble('qb',
                    top.qeTalkAndFound2,
                    new Array(top.qeBubbleType, 'questbub1', 'questBubble2', 'questbub2', 'questbub3'),
                    new Array('Ok', top.qeReload),
                    null,
                    top.document);
  } else {
    top.qeReload();
  }
}

function qeTalkFoundAll()
{
  xmlPost('/scripts/php/events/ajaxcalls.php', 'event=bts_npc_talk', 'top.qeParseThisUp');
}

function qeStartTalking()
{
  top.multiBubbleClose('qb', top.document);

  if(top.qeQuestInfo['bts']['hasTalked'] && !top.qeQuestInfo['bts']['hasFound']) {
    qeBTSSpeak = top.qeTalkNotFound;
    qeBTSFunc  = new Array('Ok', top.qeReload);
  } else if (!top.qeQuestInfo['bts']['hasTalked']) {
    qeBTSSpeak = top.qeNotTalked;
    qeBTSFunc  = new Array('Ok', top.qeTalkClue);
  } else if (top.qeQuestInfo['bts']['hasTalked'] && top.qeQuestInfo['bts']['hasFound']) {
    qeBTSSpeak = top.qeTalkAndFound;
    qeBTSFunc  = new Array('Ok', top.qeTalkFoundAll);
  } else {
    qeBTSSpeak = 'Please try again.';
    qeBTSFunc  = new Array('Ok', top.qeReload);
  }
  //alert('We are here.');
  top.multiBubble('qb',
                  qeBTSSpeak,
                  new Array(top.qeBubbleType, 'questbub1', 'questBubble2', 'questbub2', 'questbub3'),
                  qeBTSFunc,
                  null,
                  top.document);

}

function qeRegDone()
{
   top.multiBubbleClose('qb', top.document);
   top.multiBubble('qb',
                   'You\'ve already completed the quest. Please go find something to do!',
                   new Array(top.qeBubbleType, 'questbub1', 'questBubble2', 'questbub2', 'questbub3'),
                   new Array('Ok', top.qeReload),
                   null,
                   top.document);

}

function qeReload()
{
  if(top.multiBubbleClose) { top.multiBubbleClose('qb', top.document); }
  if(top.qeQuestInfo['bts']['frame'] != 'top') { window.frames['wmShopFrame'].location.reload(); }
  else { top.location.reload(); }
}

function qeQuizFini(rTxt)
{
  //alert(rTxt);
  top.qeCloseQuizzer();
  rSplit = rTxt.split('::');
  if(rSplit[0] == 'null') { 
    top.qeReload();
    return false;
  }
  if(rSplit[1] == 'true') { finiQuiz = top.qeQuizCorrect; }
  else                    { finiQuiz = 'Sorry, you got that wrong. Try again.'; }

  top.multiBubble('qb',
                  finiQuiz,
                  new Array(top.qeBubbleType, 'questbub1', 'questBubble2', 'questbub2', 'questbub3'),
                  new Array('Ok', top.qeReload),
                  null,
                  top.document);

}

function qeDoCheckQuiz()
{
  
  xmlPost('/scripts/php/events/ajaxcalls.php', 'event=bts_fini_quiz&npc='+top.qeQuestInfo['bts']['NPC']+'&quiz='+top.qeQuestInfo['bts']['quizID']+'&answer='+top.document.getElementById('qeBTSQuizAnswer').value, 'top.qeQuizFini');  
}

function qeCloseQuizzer()
{
  if((el = top.document.getElementById('qeQuizzer')))
    el.parentNode.removeChild(el);
}

function qeDoQuiz2(rTxt)
{
  top.qeCloseQuizzer();

  div				= top.document.createElement('div');
  div.id			= 'qeQuizzer';
  div.style.position		= 'absolute';
  div.style.top			= '220px';
  div.style.left		= '360px';
  div.style.zIndex		= '5000';
  div.style.height		= '129px';
  div.style.width		= '466px';
  div.style.background		= 'url(/images/bts/tornpaper.gif) no-repeat 0 0';
  div.style.border		= '1px solid #696969';
  div.innerHTML			= '<div style="margin: 25px 0 0 30px;">' + rTxt + '<br /><input id="qeBTSQuizAnswer" type="text" size="12" />&nbsp;<input class="wwButton1" type="button" onclick="top.qeDoCheckQuiz();" value="Done" /></div>';
  
  top.document.body.appendChild(div);
 //top.msgWindow(Array(document.body, 240, 350), rTxt + '<br /><input id="qeBTSQuizAnswer" type="text" size="12" />', 'Done', '', 'top.qeDoCheckQuiz();');
}

function qeDoQuiz()
{
  top.multiBubbleClose('qb', top.document);
  if(!top.qeQuestInfo['bts']['quizID']) 
    top.msgWindow(Array(document.body, 280, 350), 'Something went awry with the quiz. Please contact an elder.', 'OK', '', '');
  else
    xmlPost('/scripts/php/events/ajaxcalls.php', 'event=bts_call_quiz&quiz=' + top.qeQuestInfo['bts']['quizID'], 'top.qeDoQuiz2'); 
}

function qeStartQuesting()
{
  top.multiBubbleClose('qb', top.document);

  var regStart2 = 'Ohh, you\'re here looking for Charlie and Chelsea\'s missing school supplies? I think I might be able to help you out a bit with that.';
  var regStart3 = 'You\'ll need to find the missing list or somehow determine just what items were on it.  Unfortunately, we don\'t have any extra copies since the school\'s photocopier is broken.';
  var regStart4 = 'I do seem to recall finding a bit of crumpled paper with some smudged lettering on it. I saved it because I had a suspicion it might be part of a more important document.';
  var regStart5 = 'I\'m fairly certain now, that it\'s part of the missing school item list. If you can figure out what it says, then you should probably start by searching for that item.';
  var regStart6 = 'I do know that I saw Charlie and Chelsea playing near the ' + top.qeRandLoc1 + ', and also spending some time around ' + top.qeRandLoc2 + ' and the ' + top.qeRandLoc3 + '. You might try looking there.';
  var regStart7 = 'Once you find the item, bring it back to me so I can hold on to it for them. I\'ll talk with the other Shopkeepers and Council members and see if they\'ve heard about any of the missing items or the list.';
  var regStart8 = 'Now, here\'s that bit of paper.';
  
  top.multiBubble('qb',
                  new Array(regStart2, regStart3, regStart4, regStart5, regStart6, regStart7, regStart8),
                  new Array('questNPCreggieBubble', 'questbub1', 'questBubble2', 'questbub2', 'questbub3'),
                  new Array('Ok', top.qeDoQuiz),
                  null,
                  top.document);

}

function qeGetStarted()
{
  var regStart = 'Greetings. If you\'ve come to read or check out books, I\'m afraid the library isn\'t quite ready to open yet.';

  top.multiBubble('qb',
                  regStart,
                  new Array('questNPCreggieBubble', 'questbub1', 'questBubble2', 'questbub2', 'questbub3'),
                  new Array('Ok', top.multiBubbleClose),
                  new Array('Talk', top.qeRegFunc),
                  top.document);

}
