// ************************************
// *                                  *
// * javascript for wizard_step_2.php *
// *                                  *
// *          menu editor             *
// *                                  *
// ************************************
	//    PROGRAMMERS NOTE:  SET UP CATALOG_INDEX to be the actual position in the predefined page options list FOR THIS TO WORK!
var CATALOG_INDEX = 30;
var runOnce=false;//set_value runs twice sometimes because of onblur and onchange.... set it up to fire only once.
var isAdd=false; //True when row being added. set_value will copy the row to a new row, triggered by changing the page name to a new name.
var newRowArr,newPgArr=[]; //arrays to recreate the new page name and page file name from item selected for the new row
var edit_mode, cached_attribute_node, selected_El, val_newPgFileName, el_newPgFileName,is_install_oc,oc_page_added; 
var add_oc_toPage=0; //default on load is to NOT add opencart catalog page to menu. 
var atLoad=1; //default is for atLoad to = 1 when form 1st loads to stop multiple firing of ajax command
///WORKING ON THIS CODE://////////
function get_oc_session_vars(){
  //edit_mode=EDITING_FALSE; this is already set up when the page loade...
  $.get( "https://itsabreezewebsitebuilder.com/wizard/get_oc_session_vars.php").done(finish_get_oc_session_vars); //Reads session variable for installing open cart
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function finish_get_oc_session_vars(data){ //Reads session variable for installing open cart and adds the open cart page if it is set to 1.
  var data_arr = data.split(";");
  is_install_oc = data_arr[0];
  oc_page_added = data_arr[1];
  //Run the following sequence only when the form loads:
//alert(" is_install_oc="+is_install_oc+"  oc_page_added="+oc_page_added+" atLoad="+atLoad)
  if (atLoad==1){ 
    if ((is_install_oc==1)&&(oc_page_added == -1)){ ////Only update the Catalog once and only if it was requested by user (is_install_oc=1)
      add_oc_toPage=1;
      document.getElementById("menu_row_add").firstElementChild.firstElementChild.style.visibility='visible';
      //Cue program to branch to add a row when page name is changed with set_value():
      isAdd=true;
      //Display the selectBox to add a page:
      swap_style (document.getElementById("menu_row_add").firstElementChild);
      set_value()
      //DO NOT PUT CODE AFTER THIS... put a function in done(xxx AFTER $.post( "https://itsabreezewebsitebuilder.com/wizard/update_oc_page_added.php",{is_oc_page_added: 1}).done('') FOUND AT THE END OF setValue(), because there is a refresh of the form which loads the form again at that point.)
    }
  }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
///END...WORKING ON THIS CODE://////////

function close_select(el){
  el.size = 1;
}

function move_up(e) {
  if (edit_mode===EDITING_FALSE) {
    curNode = e.parentNode.parentNode;
    prevNode = curNode.previousElementSibling;
    if (prevNode.id != 'menu_row_0') {
      tmpHTML = curNode.innerHTML;
      curNode.innerHTML = prevNode.innerHTML;
      sync_ids(curNode.id,curNode.id.substring(9));
      prevNode.innerHTML = tmpHTML;
      sync_ids(prevNode.id,prevNode.id.substring(9));
    }
    if (prevNode.id == 'menu_row_1') {
      row_first(prevNode, "set");
      row_first(curNode, "unset");
    }
  } else if ((edit_mode===EDITING_TRUE) && e.parentNode != edit_mode_node) {
    if (validate (edit_mode_node)) return;
  }
  refresh();
  return
}

function move_down(e) {
  if (edit_mode===EDITING_FALSE) {
    curNode = e.parentNode.parentNode;
    nextNode = curNode.nextElementSibling;
    if (nextNode != null && nextNode.id != 'menu_row_add') {
      tmpHTML = curNode.innerHTML;
      curNode.innerHTML = nextNode.innerHTML;
      sync_ids(curNode.id,curNode.id.substring(9));
      nextNode.innerHTML = tmpHTML;
      sync_ids(nextNode.id,nextNode.id.substring(9));
    }
  }
  refresh();
  return
}

function delete_row(e) {
  if (edit_mode===EDITING_FALSE) {
    var agree=confirm("Are you sure you want to delete this entry?");
    if (agree) {
      var selIndex =e.parentNode.parentNode.firstElementChild.lastElementChild.options.selectedIndex //selection index for item to be removed
      curNode = e.parentNode.parentNode;
      nextNode = curNode.nextElementSibling;
      while(nextNode != null) {
        curNode.innerHTML = nextNode.innerHTML;
        sync_ids(curNode.id,curNode.id.substring(9));
        curNode = nextNode;
        nextNode = curNode.nextElementSibling;
      }
      curNode.parentNode.removeChild(curNode);
      menu_row_count--;
      // set last selected row (remove 'move_down' arrow)
      var lastID = "menu_row_"+(menu_row_count-1);
      row_last(document.getElementById(lastID),"set");
      // fix ADD row idName and className
      lastID = "menu_row_"+(menu_row_count);
      var divEl = document.getElementById(lastID);
      divEl.id = "menu_row_add";
      divEl.className = "row add_row";
      //alert("selIndex="+selIndex+" cat="+CATALOG_INDEX+" selIndex=cat ="+(selIndex===CATALOG_INDEX))
      if (selIndex===CATALOG_INDEX) //If deleting the catalog, then update the session variable showing the catalog is NOT to be installed, and then refresh the page
        $.post( "https://itsabreezewebsitebuilder.com/wizard/update_install_oc.php",{install_oc: 0}).done(finish_update_install_oc)//.done(); //Set session variable to show catalog not desired
      else
        refresh();
      return true ;
    }
  }
  return false;
}
function finish_update_install_oc(data){
  //Re-open the form to update the data
  refresh();
}
function row_last(node, state) {
  // add/remove the DOWN ARROW on the first data row after a re-order
  if (state == "unset" && node.className.indexOf(" last") != -1) {
    node.className = node.className.slice(0,-5);
  }
  if (state == "set" && node.className.indexOf(" last") == -1) {
    node.className = node.className+" last";
  }
  return
}

function row_first(node, state) {
  // add/remove the UP ARROW on the first data row after a re-order
  if (state == "unset" && node.className.indexOf(" first") != -1) {
    node.className = node.className.slice(0,-6);
  }
  if (state == "set" && node.className.indexOf(" first") == -1) {
    node.className = node.className+" first";
  }
  return
}   
function refresh(){  //swap this out for an ajax call when I have a moment....
  document.getElementById("pg_num2").click();
}
function add_row(e) { //called from pressing the + icon to add a row
   //Hide the + icon and show the select box:
   e.style.visibility='hidden';
  //Show the a tag 'page label' text:
  document.getElementById("menu_row_add").firstElementChild.firstElementChild.style.visibility='visible';
  //Cue program to branch to add a row when page name is changed with set_value():
  isAdd=true;
  //Display the selectBox to add a page:
  return toggle_child(document.getElementById("menu_row_add").firstElementChild.firstElementChild);
}

function toggle_child(e) {
  if (edit_mode===EDITING_FAILED) {
    return false;
  }
  if ((edit_mode===EDITING_TRUE) && e.parentNode != edit_mode_node) {
    if (validate (edit_mode_node)) return;
  }
  swap_style (e.parentNode);
  open_select(e.nextElementSibling)//Open the select box to edit
  e.style.cursor="pointer";
  return false;
}

function swap_style (e) {
  if (edit_mode===EDITING_TRUE) {
    e.firstElementChild.className = 'view_value';
    e.lastElementChild.className = 'edit_value hide_value';
    edit_mode_node = null;
    edit_mode=EDITING_FALSE;
  }
  else if (edit_mode===EDITING_FALSE) {
    e.firstElementChild.className = 'view_value hide_value';
    e.lastElementChild.className = 'edit_value';
    e.lastElementChild.focus();
    if (e.lastElementChild.tagName == 'INPUT') 
      e.lastElementChild.select(); //select  the contents of an input field 
    edit_mode_node = e;
    edit_mode=EDITING_TRUE;
  }
  return
}

function open_select(el,maxOptionsVisible){

  if (typeof maxOptionsVisible == "undefined") 
    maxOptionsVisible = 20;
  var iSelectCount = el.options.length;
  if (iSelectCount>maxOptionsVisible);
    var iSelectCount = maxOptionsVisible;
  el.size = iSelectCount;
}

function set_value(e) {
  var selIndex=-1;
  if ((atLoad)&&(is_install_oc)){ //called from form load, so set the index as if the user clicked on it:
    selIndex=CATALOG_INDEX;
    frmWebsiteType.elements["menu_label_name_row"+menu_row_count].options.selectedIndex=selIndex;
    atLoad=0;  //Reset to show the form is no longer loading.
  }
  else {
    selIndex=e.selectedIndex;
    if(e.selectedIndex==-1){ //if user didn't select, ignore and reset things
      e.size = 0;
      e.previousElementSibling.className = 'view_value';
      e.className = 'edit_value hide_value';
      edit_mode=EDITING_FALSE;
      restoreAddBtn();
      return
    }
  }

  if (runOnce) //Only allow this to run one time... it may be fired twice by onblur and onchange in certain situations and cause issues.
    return;
  runOnce=true;
  if (edit_mode_node){ //edit_mode_node is the span containing the  <a> tage and <select> tag for the select box choice
    validate (edit_mode_node);
    if (isAdd)
      complete_add_row();  //the element e is the <select> box
  }
  runOnce=false;
  if (selIndex==CATALOG_INDEX){
	is_install_oc=1;
  $.post( "https://itsabreezewebsitebuilder.com/wizard/update_oc_session_vars.php",{install_oc: is_install_oc, oc_page_added: 1}).done(finish_update_oc_session_vars)//.done(); //Set session variable to show it was installed
  }
  else
    //Re-open the form to update the data 
    refresh();
  return false;
}

function finish_update_oc_session_vars(){
 //Re-open the form to update the data 
 refresh(); 
}

function validate (emn){//Get the user choice and grab the data from table that has the plugin, name and menu options.
  var iSelect;
  var fn = emn.lastElementChild.value; //Get the user choice

  switch (emn.className) { //edit_mode_node is the span containing the  <a> tage and <select> tag for the select box choice
    case 'cell col_1':
      if (edit_mode=EDITING_TRUE) {
        var iCount = menu_array.length;  //menu_array was written as a variable to the page and contains the page_name and plugin_id info for each select box choice:
        var emnc = emn.firstElementChild;
        emnc.innerHTML = fn;   //Write the selection to the column1 <a> tag (this is the <a> tag)
        for (var i=0; i<iCount; i++) {
          if (menu_array[i]['link_text']===fn) {
            var emns = emn.nextElementSibling;  //This is the column2<span> that needs to be updated to match the change to col1  (hidden in page and somwhat deprecated)
            val_newPgFileName=menu_array[i]['page_name']; //This will restore the new page file name to the new row when a page has been added
            //emns.firstElementChild.innerHTML = menu_array[i]['page_name']; //Update the page name label (currently hidden)
            //emns.lastElementChild.value = menu_array[i]['page_name'];  //Update the page name label (currently hidden)
            iSelect = frmWebsiteType.elements[emns.lastElementChild.name];
            emns = emns.nextElementSibling;   //This is the column3<span>  (currently hidden in page)
            emns.childNodes[0].nodeValue = ((menu_array[i]['plugin_id']==-1)?"no":"yes");
            emns.lastElementChild.value = ((menu_array[i]['plugin_id']==-1)?"no":"yes");
            i=iCount;
          }
        }
        update_selects(emn);
      }
      break;
    case 'cell col_2':
      var pattern = /[a-z0-9._-]{3,}/i;
      if (fn.length == 0 || fn == "" ) {
        edit_mode=EDITING_FAILED;
        emn.lastElementChild.value = emn.firstElementChild.innerHTML.trim();
        window.setTimeout(function () {
          correct_entry(emn,1);
        }, 100);
      } else if (!pattern.test(fn)) {
        edit_mode=EDITING_FAILED;
        emn.lastElementChild.value = emn.firstElementChild.innerHTML.trim();
        window.setTimeout(function () {
          correct_entry(emn,2);
        }, 100);
      } else {
        edit_mode=EDITING_TRUE;
        emn.firstElementChild.innerHTML = emn.lastElementChild.value;
      }
      break;
  }

  swap_style (emn);
  return false;
}

function restoreAddBtn(){
  document.getElementById('add_icon').style.visibility='visible'; //Show the + icon:
  document.getElementById("menu_row_add").firstElementChild.firstElementChild.style.cursor="default"; //Reset turning OFF the cursor for the 'Add a Page' text: (required because original code grabs all the values from this line of code to crate the new row)}
}
function update_selects() {
  var iSelected = [];
  var iSelectCount = frmWebsiteType.elements["menu_label_name_row1"].options.length;
  var iComp = '';
  var iSelect;
  //Write the current selection to the list

  // initialize list-bit-map
  while (iSelectCount-- > 0) iComp += "0";
  iSelectCount = iComp.length;

  // populate list-bit-map with selected indexes
  var ttl_menu_row=menu_row_count; //If a new item is being added, up the count by 1:
  if (isAdd) {
    //Save the page label name to restore later
    var addRowName="menu_label_name_row"+menu_row_count;  //Get the name of the add row.
    iSelect = frmWebsiteType.elements[addRowName];  //This is the select box
    newRowArr=[addRowName,iSelect.options.selectedIndex] //Save an array with the add box row number and selected item to recreate it later through the DOM:
    //Save the page file name to restore later
    el_newPgFileName = document.getElementById("edit_fn"+menu_row_count.toString());  //This is the element name for the new page file name

    ttl_menu_row=menu_row_count+1; //Add 1 to the menum_row_count so the selections are updated in the 'add menu row'
  }
  for (var i=1; i<ttl_menu_row; i++) {
    iSelect = frmWebsiteType.elements["menu_label_name_row"+i];   //The select box goes by this name
    iSelected[iSelected.length] = iSelect.selectedIndex;
    //Create iComp, an array of 1's arranged so their # in the array matches their position in the select box items menu.
    iComp = iComp.substr(0, iSelect.options.selectedIndex) + "1" + iComp.substr(iSelect.options.selectedIndex+1);
  }
  // cycle through each select list and set disabled for already selected options
  for (var i=1; i<=menu_row_count; i++) {
    iSelect = frmWebsiteType.elements["menu_label_name_row"+i];
    if (!isAdd) {
      if (iSelect==frmWebsiteType.elements["menu_label_name_row"+menu_row_count]){ //Deselect the add row item
        iSelect.selectedIndex=-1
      }
    }
    for (var o=0; o<iSelectCount; o++) {
      if (iComp.charAt(o)==="1" && o!=iSelect.selectedIndex) {
        iSelect.options[o].disabled = true;
      } else {
        iSelect.options[o].disabled = false;
      }
    }
  }
  return
}

function complete_add_row() {
  // create NEW row
  var new_row = document.createElement('div');

  // get current ADD row for content of NEW row
  var el_add_row = document.getElementById('menu_row_add');
  var html_add_row = el_add_row.parentNode.lastElementChild.innerHTML;
  if (cached_new_row) 
    el_add_row.parentNode.lastElementChild.innerHTML = cached_new_row; //Copy the 'template'  of the add_row back over it to renew it.

  //?? truncate the content of columns 4, 5 and 6
  html_add_row = html_add_row.substring(0, (html_add_row.indexOf("col_4") - 34));

// then add back MOVE arrows and DELETE controls to NEW content
  var col_func = ["", "", "", "", "up", "down", "del"];
  for (i=4; i<=6; i++) {
    html_add_row += add_col_span(i,col_func[i]);
  }

  // modify previous LAST row className and create NEW row className
  if (menu_row_count%2 == 0) {
    new_row.className = "row even_row last";
    if (menu_row_count>1) el_add_row.previousElementSibling.className = "row odd_row";
  } 
  else {
    new_row.className = "row odd_row last";
    if (menu_row_count>1) el_add_row.previousElementSibling.className = "row even_row";
  }

  // add NEW row idName
  new_row.id = "menu_row_" + menu_row_count;

  // insert NEW row
  var my_row = el_add_row.parentNode;
  new_row.innerHTML = html_add_row;
  my_row.insertBefore(new_row,el_add_row);

  //Restore the attributes from cache (attributes were removed from cached add_row as weren't appropriate.)  
  var toNode=document.getElementById('menu_row_'+menu_row_count).firstElementChild.firstElementChild;
  cloneAttributes(cached_attribute_node,toNode)
  //Copy the new selection to the new rows selection:
  menu_row_count++;  //increment to show a new row has has been added
  sync_ids('menu_row_add',menu_row_count); // update "id's" within ADD row

  //Update the selection for page name and page file name for the NEW selected page: 
  var el_Select = frmWebsiteType.elements[newRowArr[0]];
  el_Select.selectedIndex = newRowArr[1]

  //document.getElementById('edit_fn'+(menu_row_count-1).toString()).style.display = "block"
  document.getElementById('edit_fn'+(menu_row_count-1).toString()).value=val_newPgFileName ;
  frmWebsiteType.elements["menu_label_name_row"+menu_row_count].selectedIndex=-1; //Deselect the add row item

  restoreAddBtn();

  isAdd=false; //Reset the branching variable
}


function add_col_span(col_num,col_func) {
  myString = "                  <span class='cell col_"+col_num+" e_"+col_func+"'>\n";
  if(col_num===6) {
    myString += "                  <a onclick='delete_row(this);'\n";
    myString += "                       title='delete row'\n";
    myString += "                         alt='delete row'>\n";
  } else {
    myString += "                  <a onclick='move_"+col_func+"(this);'\n";
    myString += "                       title='move row "+col_func+"'\n";
    myString += "                         alt='move row "+col_func+"'>\n";
  }
  myString += "                  </a>\n";
  myString += "                </span>\n";
  return myString;
}

function sync_ids(e,i) {
  var add_row_html = document.getElementById(e).innerHTML;
  add_row_html = add_row_html.replace(/menu_label_name_row(\d+)/, function(a,x){
    return a.replace('menu_label_name_row'+x, 'menu_label_name_row'+i);
  });
  add_row_html = add_row_html.replace(/menu_page_name_row(\d+)/, function(a,x){
    return a.replace('menu_page_name_row'+x, 'menu_page_name_row'+i);
  });
  add_row_html = add_row_html.replace(/menu_plugin_row(\d+)/, function(a,x){
    return a.replace('menu_plugin_row'+x, 'menu_plugin_row'+i);
  });
  add_row_html = add_row_html.replace(/edit_fn(\d+)/, function(a,x){
    return a.replace('edit_fn'+x, 'edit_fn'+i);
  });
  document.getElementById(e).innerHTML = add_row_html;
}

function initialize_editor() {
  row_first(document.getElementById("menu_row_1"),"set");
  var lastID = "menu_row_"+(menu_row_count-1);
  row_last(document.getElementById(lastID),"set");
}

function correct_entry(emn,eMode) {
  if (eMode == 1) alert('entry cannot be blank\n\ntry again?');
  if (eMode == 2) alert('this doesn\'t look like a valid file name\n\ntry using alphanumeric and hyphen characters only.');
  edit_mode=EDITING_FALSE
  swap_style (emn);
}

function cache_new_row() { //Grab a copy of the first add_row to use as a template to restore the add row after it has been used.
  cached_new_row = document.getElementById('menu_row_add').innerHTML;
  cached_attribute_node=document.getElementById('menu_row_1').firstElementChild.firstElementChild;
  return
}
function cloneAttributes(fromNode,toNode) { //grabs all the attributes from a node
  if (!fromNode || !fromNode.hasAttributes()) return {};
  var attrs = fromNode.attributes;
  var res = {};
  var cached_attr=[];
  for (var i = 0; i < attrs.length; i++) {
    res[attrs[i].name] = attrs[i].value;
    toNode.setAttribute(attrs[i].name, res[attrs[i].name])
  }
  return cached_attr;
}