// this set of functions is to process the POST variable to the key/value
// which setup_site.php is seeking.
// a translation for the images page, and,
// a query and then a translation for the menu page.
// followed by a submit to setup_site.php.

// added *** do a 'local_content_check'
// and if true 'confirm with user'
// current page structure 'template'
// will be overwritten.

function get_json_data(mode,data) {
//alert(data)
  var xhr = new XMLHttpRequest();
  if (xhr.upload) {
    xhr.onreadystatechange = function(e) {
      if (xhr.readyState == 4) {
        x_status = xhr.status;
        if (x_status == 200) {
          var rData = xhr.responseText;
          if (mode==='menu') {
//changes the data order here:
//alert(rData)
            do_menu(rData);
          } else if (mode==='local') {
            if (rData==='false') {
              prepare_post();
            } else if (rData==='true') {
              var can = new LertButton('Cancel', function() {
                window.location.href = 'javascript:self.close()';
              });

              var del = new LertButton('Delete', function() {
                get_json_data('delete_all',null);
              });

              var con = new LertButton('Continue', function() {
                prepare_post();
              });

              var message = "<b>Warning!</b><br><br>Your site already has content.<br><br>";
              message += "Running this wizard will apply changes to your site that will be very difficult to undo if you decide you do not want these changes.";
              message += "<br><br><table><tr><td class='col_a'><i><b>Delete</b></i>&nbsp;&nbsp;-&nbsp;</td><td>will delete ALL the current theme/style structure <b>and</b> ALL the content.</td></tr>";
              message += "<tr><td class='col_a'><i><b>Continue</b></i>&nbsp;&nbsp;-&nbsp;</td><td>will delete ALL the current theme/style structure, but will keep the current content.</td></tr>";
              message += "<tr><td class='col_a'><i><b>Cancel</b></i>&nbsp;&nbsp;-&nbsp;</td><td>will abort the wizard and return you to to the main page.</td></tr>"
              var wizard_Lert = new Lert(
                                         message,
                                         [del,con,can],
                                        {
                                         defaultButton:con,
                                         icon:'images/dialog-information.png'
                                        });

              wizard_Lert.display();

            }
          } else if (mode==='delete_all') {
            if (rData==='COMPLETE') {
                prepare_post();
            }
          }
        }
        return
      }
    };

    // start upload
    if (mode==='menu') {
      xhr.open("POST", document.getElementById("wizard_menu").formAction, true);
      xhr.setRequestHeader("X-WIZARD-DATA", "POST-DATA");
    } else if (mode==='local') {
      xhr.open("POST", document.getElementById("local_content_check").formAction, true);
      xhr.setRequestHeader("X-CPANELID", frmWebsiteType.elements["cuic"].value);
      xhr.setRequestHeader("X-WIZARD-DATA", "LOCAL-CONTENT-CHECK");
    } else if (mode==='delete_all') {
      xhr.open("POST", document.getElementById("wizard_delete_all").formAction, true);
      xhr.setRequestHeader("X-CPANELID", frmWebsiteType.elements["cuic"].value);
      xhr.setRequestHeader("X-WIZARD-DATA", "DELETE-ALL-PAGES");
    }
    xhr.send(data);
  } else {
    return
  }
}

function checkForContent() {
   // if LOCAL MODE
   if (LOCAL_MODE===true) {
     get_json_data('local',null);
   } else {
     prepare_post();
   }
}

function prepare_post() {
   var form = document.forms['frmWebsiteType'];
   var elements = form.elements;
   var menu = [];

   for (var i=0, iLen=elements.length; i<iLen; i++) {
     // set image inputs
     if (elements[i].name.indexOf("image_tag_")>-1) {
       var j = elements[i].name.substring(10);
       // don't create if it exists
       if (!elements["image_tag_"+j]) {
         var key = elements["image_tag_"+j].value;
         var data = elements["file_name_"+j].value;
         var wInput = document.createElement('input');
         wInput.setAttribute('type', 'hidden');
         wInput.setAttribute('value', data);
         wInput.setAttribute('name', key);
         form.appendChild(wInput);
       }
     }
     // create menu page_name array
     if (elements[i].name.indexOf("menu_page_name_row")>-1) {
       var j = elements[i].name.substring(18);
       menu[j] = elements["menu_page_name_row"+j].value;
     }
   }

   // request menu data
   menu = menu.toString();
 get_json_data('menu',menu);
  
   // Prevent form submission
   return false;
}

function do_menu(data) {
//alert(data)

   var form = document.forms['frmWebsiteType'];
   var elements = form.elements;
   data = JSON.parse(data);

   for (var k in data) {
     if (!elements[k]) {
       var wInput = document.createElement('input');
       wInput.setAttribute('type', 'hidden');
       wInput.setAttribute('value', data[k]);
       wInput.setAttribute('name', k);
       form.appendChild(wInput);
     }
  }
 // alert ('READY TO SUBMIT');
//  document.getElementById("wizard_submit").click();
	assign_unassigned_images();
	
	document.getElementById("setup_site_intro_div").style.display = "block";
	InitializejPlayer();
	var code = "document.getElementById('jp-play').click();";
	setTimeout(code, 1000);
	
	$.ajax({type:'POST', url: 'setup_site.php', data:$('#frmTemplateSelections').serialize(), success: function(response) {
		CompleteSetupSite(response);
	}});
}
function CompleteSetupSite(response)
{
	document.getElementById("setup_site_intro_div").style.display = "none";
	document.getElementById("setup_site_complete_div").style.display = "block";
	if (response.indexOf("<script>") > -1)	{
		var html = "";
		var js = "";
		var code = response.split("<script>");
		if (typeof(code[0]) != "undefined")
			html = code[0];
		if (typeof(code[1]) != "undefined")
			js = code[1];
		var code = js.split("</script>");
		if (typeof(code[0]) != "undefined")
			js = code[0];
		if (typeof(code[1]) != "undefined")
			html = html + code[1];
		document.getElementById("setup_site_complete_div").innerHTML = html;
		js = js.trim();
		setTimeout(js, 100);
	}
	else
		document.getElementById("setup_site_complete_div").innerHTML = response;
}