// ************************************
// *                                  *
// * javascript for wizard_step_3.php *
// *                                  *
// *         image uploader           *
// *                                  *
// ************************************
// getElementById
var selectTitle = "*** Select where to place image ***";
var selectTitle1 = "*** Click Here to Place Image ***";
var defaultSelection = "Upload File - do not place";
var defaultValue= "upload_only";
var startMsgHTML=
        "        <span class='uploaded'>\n" +
        "          "+selectTitle1+"\n" +
        "        </span'>\n";

function $id(id) {
  return document.getElementById(id);
}
function isMatch(str,what){
 if (str==what)
   return true
 else
   return false
}
function Output(msg,id) {// output information to HTML, called from ParseFile
  var m = $id(id);
  m.innerHTML = msg + m.innerHTML;
}
// new image node
function NewImage(htm,p_id,new_id) {//Called from ParseFile
  var m = $id(p_id);
  var newFirstElement = document.createElement("div");
  newFirstElement.className = new_id;
  newFirstElement.innerHTML = htm;
  m.insertBefore(newFirstElement, m.firstChild);
}
// output information
function Style(style,tag,id) {//Called from ParseFile
  var m = $id(id);
  m.style[tag] = style;
}
// file drag hover
function FileDragHover(e) {  // cancel event and hover styling
  e.stopPropagation();
  e.preventDefault();
  e.target.className = (e.type == "dragover" ? "hover" : "");
}
// invalid image
function Invalidate(i,bigSize) {
  var sName = 'file_size_'+i;
  var fName = 'file_name_'+i;
  var iName = 'image_tag_'+i;
  var tName = 'file_tag_'+i;
  var e = $id(tName);
  if (bigSize) $id(sName).style.color = '#c00';
  // Create a <div> node to replace <a>
  var newFirstElement = document.createElement("div");
  // Create a text node
  var textnode = document.createTextNode("INVALID");
  newFirstElement.appendChild(textnode);
  newFirstElement.className = 'view_value';
  // remove form elements from tree
  // so they do not get submitted
  // if user doesn't delete invalid image
  document.frmWebsiteType.elements[fName].remove();
  document.frmWebsiteType.elements[iName].remove();
  e.insertBefore(newFirstElement, e.firstChild);
  e.firstElementChild.nextElementSibling.remove();
}
// file selection
function FileSelectHandler(e) {  //called from body onload to set up submit button and drag and drop properties to add files
  FileDragHover(e);   // cancel event and hover styling
  var files = e.target.files || e.dataTransfer.files;  // fetch FileList object
  for (var i = 0, f; f = files[i]; i++) {   // process all File objects
    if (image_collection.indexOf(f.name)===-1) {
      ParseFile(f,image_counter);
      UploadFile(f,image_counter);
      image_counter++;
      update_selects();
      image_collection[image_collection.length] = f.name;
      assign_unassigned_images();//Set default image placement selection to 'upload-only' for all images
      document.getElementById("pg_num3").click()
    } else {
      timed_msg('<p>Nothing to do -this file already exists.</p><p><b>'+f.name+'</b></p><p>If this is a different file, then rename it and try again..</p>',(Math.floor((Math.random() * 4) + 1)*1000)+3000);
    }
  }
}
// output file information
function ParseFile(file,cnt) {//called from FileSelectHandler() either on drag/drop or submit button for image upload
  if (file.type.indexOf("image") == 0) {
    NewImage(
      "\n  <div id='file_tag_" + cnt + "' class='file_tag'></div>\n" +
      "    <div id='file_display_" + cnt + "'\n" +
      "      class='file_display'\n" +
      "      title='" + file.name + "'\n" +
      "      style='background-image: url(\"images/NoImage.png\")'>\n" +
      "    </div>\n" +
      "    <div class='file_info'>\n" +
      "      <span class='file_name_legend'>Name:&nbsp;&nbsp;</span>" +
      "<span class='file_name' id='file_name_info_" + cnt + "'>" +
      file.name + "</span>\n" +
      "      <span class='file_type_legend'>Type:&nbsp;&nbsp;</span>" +
      "<span class='file_type'>" + file.type + "</span>\n" +
      "      <span class='file_size_legend'>Size:&nbsp;&nbsp;</span>" +
      "<span class='file_size'><span id='file_size_" + cnt + "'>" + file.size +
      "</span>&nbsp;bytes</span>\n" +
      "      <span class='file_resolution_legend'>Resolution:&nbsp;&nbsp;</span>" +
      "<span class='file_resolution' id='file_img_resolution_" + cnt +
      "'></span>\n" +
      "      <div id='file_progress_" + cnt + "' class='file_progress'></div>\n" +
      "    </div>\n"
      ,'images', 'file_id');
    // display an image
    var reader = new FileReader();
    var image = new Image();
    reader.onload = function(e) {
      Output(
        "\n      <a class='view_value'\n" +
        "       onclick='return toggle_child(this);'\n" +
        "         title='click to place image'\n" +
        "           alt='click to place image'>\n" +
        startMsgHTML +
        "      </a>\n" +
        get_selector(cnt) +
        "      <span class='i_del'>\n" +
        "        <a onclick='delete_image(this,\"" + file.name + "\",\"select\");'\n" +
        "             title='delete image'\n" +
        "               alt='delete image'\n" +
        "                id='file_delete_" + cnt + "'>\n" +
        "        </a>\n" +
        "      </span>\n" +
        "      <input type='hidden'\n" +
        "             name='file_name_" + cnt + "'\n" +
        "            value='" + file.name + "' />\n"
        ,"file_tag_" + cnt);
      Style(
        'url(\''+e.target.result+'\')'
        ,"backgroundImage"
        ,"file_display_" + cnt);
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
    // get image resolution
    var img = new Image();
    img.onload = function() {
      Output(
        this.width + "W x " + this.height + "H"
        ,"file_img_resolution_" + cnt);
      if (invalid) Invalidate(invalid[0],invalid[1]);
    }
  }
}
// upload image files
function UploadFile(file,cnt) {//called from FileSelectHandler() either on drag/drop or submit button for image upload
var xhr = new XMLHttpRequest();
  var fName = "file_progress_"+cnt;
  if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/gif" || file.type == "image/bmp")) {
    // create progress bar
    var o = $id(fName);
    var progress = o.appendChild(document.createElement("span"));
    progress.appendChild(document.createTextNode("upload " + file.name));
    if (file.size <= $id("MAX_IMAGE_SIZE").value) {
      // progress bar
      xhr.upload.addEventListener(fName, function(e) {
        var pc = parseInt(100 - (e.loaded / e.total * 100));
        progress.style.backgroundPosition = pc + "% 0";
      }, false);
      // file received/failed
      xhr.onreadystatechange = function(e) {
        if (xhr.readyState == 4) {
          x_status = xhr.status;
          if (x_status == 200) {
            progress.className = 'uploaded';
            progress.innerHTML = 'Image has been uploaded';
            var data = xhr.responseText;
            file.name = data;
            $id('file_name_info_'+cnt).innerHTML = data;
            $id('file_display_'+cnt).setAttribute('title', data);
            $id('file_delete_'+cnt).setAttribute('onclick',"delete_image(this,'"+data+"','select');");
            //                      frmWebsiteType.elements["file_name_"+cnt].name = data;
            frmWebsiteType.elements["file_name_"+cnt].value = data;
            image_collection[cnt] = data;
          } else {
            progress.className = 'failure';
            progress.innerHTML = 'error ('+xhr.status+')';
            Invalidate(cnt,false);
          }
        }
      };
      // start upload
      // if you set asynchronous to TRUE, the uploads WILL transfer asynchronously
      // however, only the last progress-bar will display correctly.
      // purely a client-side asthetics issue ... but for the speed in which the
      // files will likely xFer synchronously ... I would recommend serial xFer. djc
      xhr.open("POST", $id("upload").formAction, false);
      xhr.setRequestHeader("X-FILENAME", file.name);
      xhr.setRequestHeader("X-FOLDERNAME", $id("USERS_IMAGE_FOLDER").value);
      xhr.setRequestHeader("X-CPANELID", frmWebsiteType.elements["cuic"].value);
      xhr.send(file);
    } else {
      progress.className = 'failure';
      progress.innerHTML = "error ('file size exceeds limit')";
      invalid = [cnt,true];
      timed_msg('<p>file size exceeds limit</p><p><b>'+$id("MAX_IMAGE_SIZE").value+' byte maximum</b></p><p>file upload canceled.</p>',5000);
    }
  
  }
  else {
    alert("This is not an image file. The file extension mut be of the type jpg, bmp, gif or png.")
  }
}
// initialize
function Init() {//called from body onload to set up event listeners so submit button and drag/drop will initiate upload file
if (window.File && window.FileList && window.FileReader) {
    var fileselect = $id("fileselect"),
        filedrag = $id("filedrag"),
        submitbutton = $id("submitbutton");
    // file select
    fileselect.addEventListener("change", FileSelectHandler, false);
    // is XHR2 available?
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {
      // file drop
      filedrag.addEventListener("dragover", FileDragHover, false);
      filedrag.addEventListener("dragleave", FileDragHover, false);
      filedrag.addEventListener("drop", FileSelectHandler, false);
      filedrag.style.display = "block";
      // remove submit button
      submitbutton.style.display = "none";
    }
  }
}
function delete_image(e,f,s) { //called from x box on image in html
  if  (s==='select') {
    var agree=confirm("Are you sure you want to delete this image?");
  } else if (s==='validate') {
    var agree = true;
  }
  if (agree) {
    if (s==='select') curNode = e.parentNode.parentNode.parentNode;
    if (s==='validate') curNode = e.parentNode.parentNode;
    // delete local image copy
    curNode.parentNode.removeChild(curNode);
    // delete remote image copy
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {
      xhr.onreadystatechange = function(e) {
        if (xhr.readyState == 4) {
          x_status = xhr.status;
          if (x_status != 200) {
            alert('Deletion of\n'+$id("USERS_IMAGE_FOLDER").value+f+'\nfailed\nContact the Site Administrator.');
          }
        }
      };
      // delete remote file
      xhr.open("POST", $id("delete").formAction, true);
      xhr.setRequestHeader("X-FILENAME", f);
      xhr.setRequestHeader("X-FOLDERNAME", $id("USERS_IMAGE_FOLDER").value);
      xhr.setRequestHeader("X-CPANELID", frmWebsiteType.elements["cuic"].value);
      xhr.send('delete_file');
    }
    image_counter--;
    if (image_counter>0) {
      enum_images();
      update_selects();
    }
  }
  document.getElementById("pg_num3").click()
  return false;
}
function open_select(el){
  var iSelectCount = frmWebsiteType.elements["image_tag_0"].options.length;
  el.size = iSelectCount;
}
function close_select(el){
  el.size = 1;
}
function toggle_child(e) {// called in a tag in HTML, user input
  var parent = e.parentElement;
  var imgNum = parent.id.substring(9);
  select_title(imgNum); //select the title to give user instructions and to force a change if selection already made for 'onchange'
  if ((edit_mode===EDITING_TRUE) && e.parentNode != edit_mode_node) {
    if (validate (edit_mode_node)) 
      return;  //this doesn't make sense to me as validate will never return true?
  }
  swap_style (e.parentNode);
  open_select(e.nextElementSibling)//Open the select box
  return false;
}
function initialMsgCheck(e) {//called from swap style and body on load for pg3.  If default selection is selected, then reset initial message and css
  if (e.innerHTML.trim() == defaultSelection){ //If it was set to the initial selection,
    e.innerHTML=startMsgHTML;//  then set up the title to show it is in the default state:
    var cNum = e.parentElement.id.substring(9);
    var el_progress=document.getElementById("file_progress_"+cNum);
    var kid = el_progress.firstElementChild;
    kid.setAttribute("class","uploaded");
  }
}
function swap_style (e) {//called from toggle child and validate
  var kid = e.firstElementChild
  initialMsgCheck(kid);
  if (edit_mode===EDITING_TRUE) {
    kid.className = 'view_value';
    kid.nextElementSibling.className = 'hide_value image_tag';
    edit_mode_node = null;
    edit_mode=EDITING_FALSE;
  } else if (edit_mode===EDITING_FALSE) {
    kid.className = 'view_value hide_value';
    kid.nextElementSibling.className = 'image_tag';
    kid.nextElementSibling.focus();
    edit_mode_node = e;
    edit_mode=EDITING_TRUE;
  }
  return
}
function select_title(imgNum){
  var iSelect = frmWebsiteType.elements["image_tag_"+imgNum];
  iSelect.options[0].selected = "true";
}

function set_value(e,i) { //Called from select box in html from user input
  if (edit_mode_node) 
    validate (edit_mode_node,i);
  update_selects();
  document.getElementById("pg_num3").click()
  return false;
}
function validate (emn,i){//called from toggle_child
  var kid_select = emn.firstElementChild.nextElementSibling;
  emn.firstElementChild.innerHTML = kid_select.options[kid_select.selectedIndex].text;
  if (isMatch(emn.firstElementChild.innerHTML,selectTitle)){//User may click away, so if the 'title', which is shown by default is the selection, then set to 'upload only' & close select box;
    var el_select=document.getElementById("image_tag_"+i);
    el_select.value=defaultValue;
    close_select(el_select)//close the select box
    emn.firstElementChild.innerHTML = defaultSelection; //if this is the title, then set it to 'update_only'.
  }
  swap_style (emn);
  if (kid_select.selectedIndex!=0) {
    $id('file_progress_'+i).firstElementChild.className = 'tagged';
    if (document.getElementById("image_tag_"+i).value == defaultValue){
      $id('file_progress_'+i).firstElementChild.className = 'uploaded';
      $id('file_progress_'+i).firstElementChild.innerHTML = 'Image has been uploaded';
    }
    else
    	$id('file_progress_'+i).firstElementChild.innerHTML = 'Image has been placed';
  }
  else {
    $id('file_progress_'+i).firstElementChild.className = 'uploaded';
    $id('file_progress_'+i).firstElementChild.innerHTML = 'Image has been uploaded';
  }
  return false;
}
function enum_images() { //Called from delete_images and body onload
  var e = document.getElementById('images').lastElementChild;
  var i = 0;
  // re-enumerate NAMES and IDS for remaining images
  while(e != null) {
    //get current enumeration
    var cNum = e.firstElementChild.id.substring(9);
    if (cNum != i) {
      document.getElementById('file_tag_'+cNum).id = 'file_tag_'+i;
      document.getElementById('file_delete_'+cNum).id = 'file_delete_'+i;
      frmWebsiteType.elements["image_tag_"+cNum].name = 'image_tag_'+i;
      frmWebsiteType.elements["image_tag_"+i].setAttribute('onchange','set_value(this,'+i+');');
      frmWebsiteType.elements["image_tag_"+i].setAttribute('onblur','set_value(this,'+i+');');
      frmWebsiteType.elements["image_tag_"+i].setAttribute("id", 'image_tag_'+i);//BK ADDED
      frmWebsiteType.elements["file_name_"+cNum].name = 'file_name_'+i;
      document.getElementById('file_name_info_'+cNum).id = 'file_name_info_'+i;
      document.getElementById('file_display_'+cNum).id = 'file_display_'+i;
      document.getElementById('file_size_'+cNum).id = 'file_size_'+i;
      document.getElementById('file_img_resolution_'+cNum).id = 'file_img_resolution_'+i;
      document.getElementById('file_progress_'+cNum).id = 'file_progress_'+i;
    }
    e = e.previousElementSibling;
    i++;
  }
}
function get_selector(cnt) {//Called from newImage as data to function Output()
  var my_selector = "      <select id= 'image_tag_" + cnt + "' name='image_tag_" + cnt + "' id='image_tag_" + cnt + "'\n" +
      "             class='hide_value image_tag'\n" +
      "          onchange='set_value(this," + cnt + ");'\n" +
      "            onblur='set_value(this," + cnt + ");'>\n" +
      "        <option value=''>"+selectTitle+"</option>\n";
  for (var i=0; i<image_label_array.length; i++) {
    my_selector += "        <option value='" +
      image_label_array[i].tag +
      "'>" + image_label_array[i].name +
      "</option>\n";
  }
  my_selector += "      </select>\n";
  return my_selector;
}
function update_selects() {//called from FileSelectHandler() either on drag/drop or submit button for image upload, select_value & delete_image on user input
  if (image_counter>0) {
    var iSelected = [];
    var iSelectCount = frmWebsiteType.elements["image_tag_0"].options.length;
    // initialize list-bit-map
    for (var i=0; i<iSelectCount; i++) iSelected[i] = '0';
    // populate list-bit-map with selected indexes
    for (var i=0; i<image_counter; i++) {
      var t = 'image_tag_'+i;
      if (frmWebsiteType.elements[t].value != 'upload_only') //Do not disable the selection for upload_only if it has been assigned, it may be assigned for multiple images
        iSelected[frmWebsiteType.elements[t].selectedIndex]='1';
    }
    // cycle through each select list and set disabled for already selected options
    for (var i=0; i<image_counter; i++) {
      var iSelect = frmWebsiteType.elements["image_tag_"+i];
      iSelect.options[0].disabled = true; //disable the title
      for (var o=1; o<iSelectCount; o++) {
        if (iSelected[o]==="1" && o!=iSelect.selectedIndex) {
          iSelect.options[o].disabled = true;
        }
        else {
          iSelect.options[o].disabled = false;
        }
      }
    }
    if (iSelected[0]==="1") {
      unassigned_image = true;
    } else {
      unassigned_image = false;
    }
  }
  return
}
function assign_unassigned_images() {
//  if ((invalid || unassigned_image) && image_counter>0) {
  if (image_counter>0) {
    for (var d=image_counter-1; d>-1; d--) {
      var dSelect = frmWebsiteType.elements["image_tag_"+d];
      if (dSelect.selectedIndex === 0) { //Then, nothing was assigned, so assign it to tag 'upload_only'
        document.getElementById("image_tag_"+d).value="upload_only";
      }
      var el = document.getElementById("file_tag_"+d);
      var kid = el.firstElementChild
     initialMsgCheck(kid)
    }
  }
  return true;
}
/*  var agree=confirm("Continue?");
    if (agree) 
      return true
    else
      return false
  }
*/
function timed_msg(msg,duration)
{
  var el = document.createElement("div");
  el.setAttribute("style","position:absolute;" +
                  "top: 40%;" +
                  "left: 50%;" +
                  "top: 50%;" +
                  "transform: translate(-50%,-50%);" +
                  "background: white url('images/upload_cancel.png') no-repeat left;" +
                  "background-origin: content-box;" +
                  "height: 100px;" +
                  "border: solid 1px #666;" +
                  "border-radius: 10px;" +
                  "padding: 10px 20px 20px 20px;" +
                  "text-align: center;" +
                  "text-indent: 60px;" +
                  "-webkit-box-shadow: 5px 5px 8px rgba(64, 64, 64, 0.75);" +
                  "-moz-box-shadow: 5px 5px 8px rgba(64, 64, 64, 0.75);" +
                  "-ms-box-shadow: 5px 5px 8px rgba(64, 64, 64, 0.75);" +
                  "-o-box-shadow: 5px 5px 8px rgba(64, 64, 64, 0.75);" +
                  "box-shadow: 5px 5px 8px rgba(64, 64, 64, 0.75);");
  el.innerHTML = msg;
  setTimeout(function(){
    el.parentNode.removeChild(el);
  },duration);
  document.body.appendChild(el);
}
function debug_images() { //spaghetti... for test?
  if (image_counter>0) {
    e = $id('file_id');
    msg = '';
    for (var d=0; d<image_counter; d++) {
      var e_kid = $id('file_tag_'+d);
      var e_kid_kid = e_kid.firstElementChild;
      msg += e_kid_kid.innerHTML + " | ";
      msg += e_kid_kid.nextElementSibling.value + "\n";
    }
    alert(msg);
  }
}
function whats_selected(cnt) { //spaghetti... for test?
var e = frmWebsiteType.elements["image_tag_"+cnt].value;
  alert(e);
  return
}