//console_launch();
var savesubsystem = new SaveSubsystem();
function deleteGuider(guider_name){
    Ajax_send(
      "/ajax/guiders/delete", 
       { name: guider_name },
       function(response){updateGuiderList(response);}
       );
  
}
function editGuider(event){
  var table = new GuiderTable();
  table.bind('guider-table');
  table.renderEditRow(event.element().up('tr'));
}
function acceptGuiderEdit(event){
  Ajax_send(
    "/ajax/guiders/update",
    {oldname:$F('edit-old-name'),name:$F('edit-name'),author:$F('edit-author'),sponsor:$F('edit-sponsor')},
    function(response){updateAfterEdit(response,event.element().up('tr'));}
  );
}
function cancelGuiderEdit(event){
  updateAfterEdit(null,event.element().up('tr'));
}
function updateAfterEdit(response,EditTR){
  var OrigTR = EditTR.previous("TR");
  if (response!=null){//then an edit has occured
    EditTR.remove();
    OrigTR.show();
    var table = new GuiderTable();
    table.bind('guider-table');
    table.updateRow(OrigTR,response.id);

  } else {
    EditTR.remove();
    OrigTR.show();
  }
}

//-----------------------------------------------------------------------------
// 
//-----------------------------------------------------------------------------
//Event.observe(window, 'load', function() {
//  IG_IPE('whats-this-text','whatsThisForm','questionExplanation',questionid,updateWhatsThisButton);
//});
//Event.observe(window, 'load', function() {
//  IG_IPE_single('questionText','questionForm','questionText',questionid,updateQuestionText);}
//);
Event.observe(window, 'load', MakeAnswersSortable);

function MakeAnswersSortable(){

try {
  Sortable.create('answersContainer',
      {
        tag      : "div",
        onUpdate : function(){
                     reorderTreeview(Sortable.sequence("answersContainer"));
                     Ajax_send("/ajax/answers/reorder",{ id: questionid, data: Sortable.serialize("answersContainer") },function(response){});
                   }
      }
    );
} catch(ex){}
 
  //setZIndexes();
}
function reorderTreeview(newOrder){
    var num_answers = newOrder.length;
    for(var i = 1; i < num_answers; i++){
        ktv1.getNode("a-"+newOrder[i]).moveToBelow("a-"+newOrder[i - 1]);
    }
}

function setSearchLink(id){
    $("search-link").href = id;
}
/*
  getEventTarget
  
  Helper method thst gets the event target from an event object
  It's needed because different browsers do it different ways
*/
function getEventTarget(evt){
  return (evt.target)?evt.target:(evt.srcElement)?evt.srcElement:null; 
}


///*
//
//  menutimer
//
//  This is a timer object used to create a delay before closing a menu.
//  
//  It's used to prevent the flicker that can occur as the cursor moves
//  between the elements of the menu.
//
//*/
//function menutimer(){
//  var timerid = null;
//  this.start =  function(menuitem){
//    timerid = setTimeout(function(){menuitem.style.visibility="hidden";},50);
//  }
//  this.cancel = function(){
//    if (timerid!=null)clearTimeout(timerid);
//  }
//}
///*
//  Dropdown menu code
//  
//  These two methods 
//  
//*/
//function showmenu(evt){
//
//   if (!evt) var evt = window.event;
//   if (typeof(this.igmenutimer)!="undefined") this.igmenutimer.cancel();
//   this.down(".menu").style.visibility="visible";
//}
//function hidemenu(evt){
//   if (!evt) var evt = window.event;
//   if (typeof(this.igmenutimer)=="undefined") this.igmenutimer = new menutimer();
//   this.igmenutimer.start(this.down(".menu"));
//}

function analyticsTrack(page_url){
   pageTracker._trackPageview(page_url);
   clicky.log(page_url);
   return false;
}

function feedbackCallback(email){
  return function(response){
    Effect.Fade('feedback-form');
    Effect.Appear('feedback-thanks');
    if(email != ""){
      $('feedback-email-field').innerHTML = email;
      $('feedback-thanks-email').style.display = "block";
    }else{
      $('feedback-thanks-email').style.display = "none";
    }
    $('feedback').value = "";
  }
}

function submitFeedback(question){
  var feedback_text = $('feedback').value;
  var email = findEmailAddress(feedback_text);
  var my_callback = feedbackCallback(email);
    var address = $('feedback-address').value;
  Ajax_send("/ajax/feedback/submit",{ feedbackquestionid: question, feedback: feedback_text, email_address: email, tech_support: 'false', address: address}, my_callback);
  return false;
}
function submitTechSupport(question){
  var feedback_text = $('feedback').value;
  var email = $F('user-email');
  Ajax_send("/ajax/feedback/submit",{ feedbackquestionid: question, feedback: feedback_text, email_address: email, tech_support: 'true'}, techSupportCallback);
  return false;
}
function techSupportCallback(){
    Effect.Fade('technical-help-form');
    Effect.Appear('tech-support-thanks');
}
function findEmailAddress(text) {
  var filter = /([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+/;
  var email = text.match(filter);
  if(email !== null){
    return email[0];
  }else{
    return "";
  }
}

function editGuider(guider_id){
    $("guider-" + guider_id).style.display = "none";
    $("guider-" + guider_id + "-edit").style.display = $("guider-header").style.display;
}
function cancelGuiderEdit(guider_id){
    $("guider-" + guider_id + "-edit").style.display = "none";
    $("guider-" + guider_id).style.display = $("guider-header").style.display;
    return false;
}



////////////////////////////////////////////////////////////////////////
// All of the javascript related to editing questions and answers //////
////////////////////////////////////////////////////////////////////////
function toggleDefinitionsDisplay(){
  var el = $('definitions-container');
  if(el.style.display != 'block'){
    el.style.display = 'block';
    $('def-toggle').innerHTML = "Hide";
  }else{
    el.style.display = 'none';
    $('def-toggle').innerHTML = "Show";
  }
}
function deleteDefinition(def_id, g_id, q_id){
  if(confirm("Delete this definition?")){
    window.location.href = "/definition/delete/"+ def_id + "/" + g_id + "/" + q_id;
  }
  return false;
}
function showDefinitionEdit(def_id){
  $('def-'+ def_id).style.display = 'none';
  showRow($('def-edit-'+ def_id));
  return false;
}
function hideDefinitionEdit(def_id){
  showRow($('def-'+ def_id));
  $('def-edit-'+ def_id).style.display = 'none';
  return false;
}
function showRow(row){
  var base = $('addDef');
  row.style.display = base.style.display;
  return true;
}

//------------------------------------------------------------------------------
// Add pictures to answers
//
//------------------------------------------------------------------------------
Event.observe(window, 'load', addEditPictureHandlers);

function addEditPictureHandlers(){
  var icons = $$('.image-icon');
  for (var i=0; i<icons.length; i++){
      icons[i].onclick = showGallery;
  }
}

function editPicture(evt){
  if (!evt) evt = window.event;
  var target = (evt.target)?evt.target:(evt.srcElement)?evt.srcElement:null;
  var id = target.id;
  var ansid = id.substring(id.indexOf(".")+1);

  Modalbox.show("/forms/AddPicture.html",
  {
      title: "Add Picture",
      height: 400,
      afterLoad: function(){add_picture_dialog_init(ansid);}
  });

  if (evt.stopPropagation) evt.stopPropagation();
  evt.cancelBubble = true;
  return false;

}

function add_picture_dialog_init(ansid){

  $('answerid').value = ansid;

  Ajax_send(
    "/ajax/answers/getImage",
    {
       aid:   ansid
    },
    picture_update
  );
}

function picture_update(resp){
  if (resp.return_code == 0){
     $('add-picture-current-image').src=resp.image;
     $('picture-url').value = resp.image;
  } else {
     //error
  }
   
}

//------------------------------------------------------------------------------
// Answer "What's This" code
//
//------------------------------------------------------------------------------

Event.observe(window, 'load', function() {
  var icons = $$('.whats-this-icon');
  for (var i=0; i<icons.length; i++){
      icons[i].onclick = showWhatsThis;
  }
});

function showWhatsThis(evt){
  if (!evt) evt = window.event;
  var target = (evt.target)?evt.target:(evt.srcElement)?evt.srcElement:null;
  savesubsystem.saveAll();
  var row = target.up(".guider-answer");
  var textelem = row.down('.answer-whats-this');
  textelem.toggle();
  if (evt.stopPropagation) evt.stopPropagation();
  evt.cancelBubble = true;
  return false;
}
function showFeedbackForm(){
  if ($('feedback-form').visible()){
     $('feedback-form').hide();
  } else {
     $('feedback-thanks').hide();
     $('feedback-form').show();
  }
  go_1wing();
}
function showTechSupportForm(){
  if ($('technical-help-form').visible()){
     $('technical-help-form').hide();
  } else {
     $('technical-help-form').hide();
     $('technical-help-form').show();
  }
  go_1wing();
}

////////////////
Event.observe(document, 'click', function() {
  hide_all_menus(null);
});
function updateQuestionText(){
  var text = "";
  if ($('questionText').innerText){
     text = $('questionText').innerText;
  } else { 
     text = $('questionText').textContent;
  }
  if (text.length==0){
     $('questionText').textContent = "This question has no text.  Click here to add it.";
  }
  //because the question text may have changed we should check to see if we need to redirect
  //to a new url.
  Ajax_send(
    "/ajax/questions/getURL",
    {
       qid: questionid
    },
    function(resp){
      if (resp.return_code==0){
         if (resp.questionURL!=pageURL){
            window.location = resp.questionURL;

         }
      }
    }
  );
}

function saveQuestionWhatsThisText(){
  Ajax_send(
    "/ajax/questions/setExplanation",
    {
       id:   questionid,
       text: $F('whats-this-text')
    },
    function(resp){
      if (resp.return_code==0){
         updateWhatsThisButton(resp);
      }
    }
  );
}

function saveAnswerWhatsThisText(id){
  var ansid = id.substring("answer-whats-this-text.".length);
  var text = $F(id);

  Ajax_send(
    "/ajax/answers/setExplanation",
    {
       aid:   ansid,
       text:  text
    },
    function(resp){
      if (resp.return_code==0){
         updateAnswerWhatsThisButton(resp);
      }
    }
  );

}

function updateWhatsThisButton(resp){
  var text = $F('whats-this-text');
  if (text.length==0){
     $("whats-this-button").src="/images/ico-question-empty.png"
  } else {
     $("whats-this-button").src="/images/question.png"
  }
}
function updateAnswerWhatsThisButton(resp){
  var aid = resp.request.parameters.aid; 
  var text = $F("answer-whats-this-text."+aid);
  if (text.length==0){
     $('whats-this-icon.'+aid).src="/images/ico-question-empty.png";
     $('whats-this-icon.'+aid).title="Add 'What's this?' text for this answer";
  } else {
     $('whats-this-icon.'+aid).src="/images/question.png";    
     $('whats-this-icon.'+aid).title="Edit the 'What's this?' text for this answer";
  }}

//
// This method sets the z-index of all the rows.  In order for the popup menu to
// work in IE each row has to be higher in the z-index than the one after it.
//
//function setZIndexes(){
//  var elems = $$('.guider-answer');
//  for (var i=0; i<elems.length; i++){
//    var elem = elems[i];
//    elem.style.zIndex = 999-i;
//  }
//}

function sortSuccessful(response){
  alert('success '+response.responseText);
}
//------------------------------------------------------------------------------
// Title editing code
//
//------------------------------------------------------------------------------
function editTitle(){
  Modalbox.show("/forms/EditPageTitle.html",
    {
      title: "Edit Page Title",
      afterLoad: function(){edit_page_dialog_init();}
    });
}
function edit_page_dialog_init(){
  //$('new-question-link').href="/question/new/"+ansid;
  $('new-text-title').value = pagetitle;
  $('questionid').value = questionid;
  //$('topicid').value = topicid;
}
function title_save(){
  Ajax_send(
    "/ajax/questions/newTitle",
    {
       newTitle:   $F('new-text-title'),
       questionid: $F('questionid')
    },
    title_update
  );
}
function title_update(resp){
  if (resp.return_code==0) {
     window.location = resp.newurl; // go to new url
  }  
}

//------------------------------------------------------------------------------
// Delete Row handling code
//
//------------------------------------------------------------------------------
function delete_row(ctlid){
  ktv1.removeNode("a-" + ctlid);
  Ajax_send("/ajax/answers/delete",{id: ctlid},function(response){deleteSuccessful(response);});
}
function deleteSuccessful(response){
  var ctlid = "answer_"+response.request.parameters.id;
  if (response.return_code==0) {
     Effect.Fade(ctlid, { duration: 0.5, afterFinish: function() { $(ctlid).remove(); } });
  } else {
     alert("Unable to delete: "+response.message);
  }
  savesubsystem.updateEditHandlers();
}
//------------------------------------------------------------------------------
// target menu handling code
//
// toggle_target_menu() toggle the menu ovbiously but the clickSwallow
// function and the loop that sets it up are less straightforward.
// They collect the mouse up and down events and drop them so that they
// don't propogate to the scriptaculous drag and drop code.  Those
// events were triggering something that caused the answer row to
// jump a little in IE.  if we catch and drop the events the jumping
// stops.
//
// The rows are still draggable, you just have to click the row
// directly
//
//------------------------------------------------------------------------------
var elems = $$('.edit-answer');
for (var i=0; i<elems.length; i++){
    elems[i].onmousedown = clickSwallow;
    elems[i].onmouseup = clickSwallow;
    elems[i].onclick = toggle_target_menu;
}
function clickSwallow(evt){
  if (!evt) evt = window.event;
  evt.cancelBubble = true;
  if (evt.stopPropagation) evt.stopPropagation();
}
function toggle_target_menu(evt){
  if (!evt) evt = window.event;
  var target = (evt.target)?evt.target:(evt.srcElement)?evt.srcElement:null;
  var ansid = target.getAttribute("answerid");
  hide_all_menus(ansid);
  $('menu.'+ansid).toggle();
  if (!evt) evt = window.event;
  evt.cancelBubble = true;
  if (evt.stopPropagation) evt.stopPropagation();
}
function hide_all_menus(ansid){
  var elems = $$('.menu');
  for (var i=0; i<elems.length; i++){
      if (elems[i].id!="menu."+ansid){
         elems[i].hide();
      }
  }
}
// END of target menu handling code --------------------------------------------
//------------------------------------------------------------------------------
// Connect to guider code
//
//------------------------------------------------------------------------------
function formConnectToGuider(ansid){
  Modalbox.show("/forms/SelectGuider.html",
    {
      title: "Select Guider",
      afterLoad: function(){select_guider_dialog_init(gid,ansid);}
    });
}
function select_guider_dialog_init(gid,ansid){
  $('answerid').value = ansid;
  $('guiderid').value = gid;
  DisplayAvailableGuiders();  
}
function select_guider_question_dialog_init(gid,ansid){
}


//------------------------------------------------------------------------------
// Select Question Code
//
//------------------------------------------------------------------------------
function formNarrowSearch(ansid){
  Modalbox.show("/forms/SelectQuestion.html",
    {
      title: "Connect to Existing Question",
      afterLoad: function(){narrow_search_dialog_init(ansid);}
    });
}
function narrow_search_dialog_init(ansid){
  $('answerid').value = ansid;
  $('guiderid').value = gid;
  DisplayExisting();
}
function narrow_search_save(ansid,dest_gid,qid){
  Ajax_send(
    "/ajax/answers/connectDestination",
    {
       answerid:    ansid,
       guiderid:    dest_gid,
       questionid:  qid
    },
    narrow_search_update_answer
  );
}
function narrow_search_update_answer(resp){
  // Update the treeview to show that it's no longer incomplete
  $("answer-" + resp.answerid).style.color = "black";
  updateIncompleteAnswers(-1);

  var link;
  if (resp.qslug!=""){
     link="/guider/"+resp.gslug+"/"+resp.qslug+(resp.request.parameters.guiderid==null?"":"?push=true");
  }else{
     link="/question/"+resp.questionid;
  }

  $('link.'+resp.answerid).insert({after: "<a id='link."+resp.answerid+"' class='admin' href='"+link+"' title='Link to external guider'><span id='target-icon."+resp.answerid+"' class='narrow'>&nbsp;</span></a>"});
  $('link.'+resp.answerid).remove();
  if($('link'+resp.answerid)){
      $('link.'+resp.answerid).onclick="javascript:void(0)";
      $('link.'+resp.answerid).title="";
  }
}
//------------------------------------------------------------------------------
// External link creation code
//
//------------------------------------------------------------------------------
function formExternalLink(ansid){
    document.location.href = "/create/"+ gslug +"/"+ ansid +"/external";
    return true;

/*
  Modalbox.show($('ExternalLinkForm'),
    {
      title: "Direct Link To a Webpage",
      afterLoad: function(){external_link_dialog_init(ansid);}
    });
*/
}
function external_link_dialog_init(ansid){
  $("AnswerId").value = ansid;
}
function external_link_save(){

  Ajax_send(
    "/ajax/results/createExternalLink",
    {
       description: $F('LinkDescription'),
       link:        $F('Link'),
       answerid:    $F('AnswerId')
    },
    external_link_update_answer
  );
}
function external_link_update_answer(response){
  $('target-icon.'+response.answerid).insert({after: "<a id='link."+response.answerid+"' class='admin' title='"+response.description+"' onclick='window.open(\""+response.link+"\",\"iGuider\",\"width=1000,height=600,resizable,scrollbars=yes\");' href='javascript:void(0)'><span id='target-icon."+response.answerid+"' class='ext-link'>&nbsp;</span></a>"});
  $('target-icon.'+response.answerid).remove();
  $('link.'+response.answerid).title=response.description;
  $('link.'+response.answerid).href="#";
  
  // Update the treeview to show that it's no longer incomplete
  $("answer-" + response.answerid).style.color = "black";
  updateIncompleteAnswers(-1);
}

// END External link creation code ---------------------------------------------

//------------------------------------------------------------------------------
// Guider Linking Code
//
//------------------------------------------------------------------------------
function guider_link_update_answer(resp){
  $('link.'+resp.answerid).insert({after: "<a id='link."+resp.answerid+"' class='admin' href='javascript:showOtherGuider(\""+resp.gslug+"\")' title='Link to external guider'><span id='target-icon."+resp.answerid+"' class='guider'>&nbsp;</span></a>"});
  $('link.'+resp.answerid).remove();
  //if($('link'+resp.answerid)){
  //    $('link.'+resp.answerid).onclick="javascript:void(0)";
  //    $('link.'+resp.answerid).title="";
  //}
}
// End Guider Linking Code -----------------------------------------------------
//------------------------------------------------------------------------------
// Solution Page Code
//
//------------------------------------------------------------------------------
function formSolutionPage(gslug,ansid){
  Ajax_send(
    "/ajax/results/createSolutionPage",
    {
       answerid:    ansid,
       return_path: "/guider/"+gslug+"/"+ansid+"/page"
    },
    solutionPageCreated
  );
}
function solutionPageCreated(resp){
  window.location = resp.request.parameters.return_path;
}
// END Solution Page Code ------------------------------------------------------

function addAnswer(guiderslug,questionslug){

  Ajax_send(
    "/ajax/answers/createNew",
    {
       gslug: guiderslug,
       qslug: questionslug
    },
    updateAnswerList
  );  
}

function updateAnswerList(response){

  var answerid = response.answerid;
  var answertext = response.answertext;

  // Update treeview
  ktv1.getNode("q-"+questionid).addChildNode("a-"+answerid, "<a id='answer-"+ answerid +"' class='tv-incomplete' href=''>A: "+ answertext + "</a>");
  updateIncompleteAnswers(1);
  
  var answer_list_div = document.getElementById("answersContainer");
  var new_answer_div  = document.createElement("div");

  new_answer_div.className = "guider-answer";
  new_answer_div.setAttribute("id","answer_"+answerid);
  new_answer_div.style.position = "relative";
  
  // Use an array to store the answer HTML and join them before inserting into the document
  a_html = new Array("");

  a_html.push("<div class='answer-box'>");

  // Delete button
  a_html.push("<a class='answer-delete-link' onclick='return delete_row("+answerid+");' title='Delete this answer'>Delete answer</a>");

  //Place holder for destination target
  a_html.push("<a id='link."+answerid+"'><span id='target-icon."+answerid+"' class='no-target'></span></a>");


  // The answer text
  a_html.push("<span id='answertext."+answerid+"'>");
  a_html.push("<span id='answer-content-"+answerid+"'>");
  a_html.push("<input class='answer-text'  id='answer-edit-"+ answerid +"' type='text' class='answer_text'>");
  a_html.push("</span>");
  a_html.push("</span>");

  // // Add image
  // a_html.push('<img id="image-icon.'+ answerid +'" class="image-icon" src="/images/image-empty.png" title="Add an image for this answer"/> ');

  // What's this text button
  a_html.push('<img id="whats-this-icon.'+ answerid +'" class="whats-this-icon" src="/images/ico-question-empty.png" title="Add Whats this? text for this answer"/>');
  a_html.push('<div class="answer-whats-this" style="display: none;">');
  a_html.push('<textarea id="answer-whats-this-text.'+ answerid +'" class="answer-whats-this-text" ></textarea>');
  a_html.push('</div>');

  a_html.push("</div>"); //close answer box

  // Container for split button
  a_html.push("<div class='answer-destination'><span class='answer-add'>&nbsp;Add:</span> <span class='answer-button'><span style='display:block;float:right;' id='answer-button-container-"+ answerid +"'></span></span></div>");


  // Join the HTML array to create one string and then append to the document
  new_answer_div.innerHTML = a_html.join("");
  answer_list_div.appendChild(new_answer_div);
  
  // //Add new what's this text to save subsystem
  // savesubsystem.addControl($("answer-whats-this-text."+answerid),function(){ saveAnswerWhatsThisText("answer-whats-this-text."+answerid);});
  

  // Create a YUI Split Button for answer destination
  var answerButtonContainer = $("answer-button-container-"+ answerid);
  var aSplitButton5Menu = [
    { text: "Existing Question", value: answerid+"-existingquestion" },
    { text: "Link to a web page", value: answerid+"-directlink" },
    { text: "Solution Page", value: answerid+"-solution" },
    { text: "Google Search", value: answerid+"-googlesearch"},
    { text: "Bing Search", value: answerid+"-bingsearch"},
    { text: "External Guider", value: answerid+"-guider" },
    { text: "You Tube", value: answerid+"-youtube" }
  ];

  // Instantiate a Split Button using the array of YAHOO.widget.MenuItem 
  var oSplitButton5 = new YAHOO.widget.Button({ title: "Click to select an option", type: "split",  label: "New Question", name: "splitbutton5", menu: aSplitButton5Menu, container: answerButtonContainer, onclick: { fn: function(){ buttonAction(answerid);} } });
  oSplitButton5.getMenu().subscribe("click", onMenuClick);  
  oSplitButton5.on("option",updateZIndex);
  elem = $("whats-this-icon."+answerid);
  elem.onclick = showWhatsThis;
  addEditPictureHandlers();
  MakeAnswersSortable();
  setEditablePageControls();
  
  //IG_IPE_single("answertext."+answerid,'answerForm.answerId','answerText',answerid,null);
  //IG_IPE("answer-whats-this-text."+answerid,'answerForm.whatsthis','answerWhatsThisText',answerid,updateAnswerWhatsThisButton);
   
  //setZIndexes();
}

function updateIncompleteAnswers(inc){
    var cur_incomplete = $("num-incomplete").innerHTML - 0;
    var new_incomplete = cur_incomplete + inc;
    $("num-incomplete").innerHTML = new_incomplete;
}

function saveAnswerText(id){
  
  //console_write("in saveAnswerText: "+id);

  
   // Get the data
   var edit_answer_text = $("answer-edit-" + id).value;

//  // Hide the edit control
//  $("answer-content-edit-"+id).style.display = "none";
//
//  // Update and show the text
//  $("answer-content-value-"+id).innerHTML = edit_answer_text;
//  $("answer-content-value-"+id).style.display = "inline";
//  $("answer-content-edit-link-"+id).style.display = "inline";

  // Update the treeview in real time
  editTreeviewAnswer("answer-"+id, "A: " + edit_answer_text);

   // Form AJAX request
   Ajax_send(
    "/ajax/answers/set",
    {id:id, shortanswer: edit_answer_text},
    function(){ return true; }
    );
    return false;
}
function cancelEditAnswer(id){
  // Hide the edit control
  $("answer-content-edit-"+id).style.display = "none";
  // Re-display the text
  $("answer-content-value-"+id).style.display = "inline";
  $("answer-content-edit-link-"+id).style.display = "inline";
}

function saveQuestionText(){
  // Get the data
  var edit_question_text = $("question-text-field").value;

  editTreeviewQuestion("question-"+questionid, "Q: " + edit_question_text);

   // Form AJAX request
   Ajax_send(
    "/ajax/questions/set",
    {id:questionid, question_text: edit_question_text},
    updatePage
    );
   return false;
}
function updatePage(resp){
  //if (typeof resp.newURL != 'undefined'){
  //   window.location = resp.newURL;
  //}
}
function cancelEditQuestion(){

  // Hide the edit control
  $("question-text-edit").style.display = "none";

  // Update and show the text
  $("question-text-value").style.display = "inline";
  $("question-edit-link").style.display = "inline";

}

function saveGuiderName(){
   // Get the data
   var edit_guider_name = $("guider-name-field").value;

//  // Hide the edit control
//  $("guider-name-edit").style.display = "none";
//
//  // Update and show the text
//  $("guider-name-value").innerHTML = edit_guider_name;
//  $("guider-name-value").style.display = "inline";
//  $("guider-name-edit-link").style.display = "inline";

   // Form AJAX request
   Ajax_send(
    "/ajax/guiders/update",
    {slug: gslug, name: edit_guider_name},
    function(){ return true; }
    );
}
function cancelEditGuiderName(){
  // Hide the edit control
  $("guider-name-edit").style.display = "none";

  // Update and show the text
  $("guider-name-value").style.display = "inline";
  $("guider-name-edit-link").style.display = "inline";
}

function editAnswer(answerid){
    $("answer-content-value-"+answerid).style.display = "none";
    $("answer-content-edit-link-"+answerid).style.display = "none";
    $("answer-content-edit-"+answerid).style.display = "inline";
    $("answer-edit-cancel-"+answerid).style.display = "inline";
    return false;
}
function editQuestion(){
    $("question-text-value").style.display = "none";
    $("question-edit-link").style.display = "none";
    $("question-text-edit").style.display = "inline";
    $("question-edit-cancel").style.display = "inline";
    return false;
}
function editGuiderName(){
    $("guider-name-value").style.display = "none";
    $("guider-name-edit-link").style.display = "none";
    $("guider-name-edit").style.display = "inline";
    $("guider-edit-cancel").style.display = "inline";
    return false;
}

function editTreeviewAnswer(node_id, new_text){
    $(node_id).innerHTML = new_text;
}
function editTreeviewQuestion(node_id, new_text){
    $(node_id).innerHTML = new_text;
}

//function GoToWIAG(){
//  $('Main-View').hide();
//  $('WhatIsAGuider-View').show();
//  $('guided-view-tab').className = "tab";
//  $('tree-view-tab').className = "tab";
//  $('wiag-tab').className = "wiag-activeTab";
//  go_1wing();
//}
//function GoToGuidedView(){
//  $('WhatIsAGuider-View').hide();
//  $('Main-View').show();
//  $('guided-view-tab').className = "activeTab";
//  $('wiag-tab').className = "wiag-tab";
//  go_1wing();  
//}
//function GoToTreeView(){
//  $('WhatIsAGuider-View').hide();
//  $('Main-View').show();
//  $('tree-view-tab').className = "activeTab";
//  $('wiag-tab').className = "wiag-tab";
//  go_1wing();  
//}

// Lead Gen tracking
function recordLGAnswer(question_id, answer_id){
    createCookie("Question:"+question_id, "Answer:"+answer_id, 1);
}
function setLGSource(guider_slug, question_slug){
    createCookie("LGSource", guider_slug, 1);
    createCookie("LGQSource", question_slug, 1);
}
//Guider stack
function popguider(){
  var select = new Select();
  select.bind('guider-stack');
  window.location = select.getSelectedValue();
}

function saveGuiderDescription(){
   // Form AJAX request
   Ajax_send(
     "/ajax/guiders/setDescription",
     {
       gid: gid,
       description: $('guider-description').value
     },
     updateDescription
   );
}
function updateDescription(resp){
  $('guider-description-text').innerHTML = resp.description;
  $('guider-description-display').show();
  $('guider-description-edit').hide();
  $('cancel-guider-description').hide();
}
function cancelGuiderDescription(){
  $('guider-description-display').show();
  $('guider-description-edit').hide();
  $('cancel-guider-description').hide();
}
