var url = '.';

browser = navigator.appName;
if(browser.match("Microsoft"))
    window.location="help/notice.htm";

function About(){

   msg = '<pre><br>  Agile Web Developer version 1.0  <br><br>  Author: milan.popovic@gmail.com  </pre>';
   ShowDivMsg("project_div",msg);

}

function check(what){
   if(what != 'file' && document.getElementById('w_project').value == "") {ShowDivMsg("project_div","<pre>  Open project, please.  </pre>"); return false}
   if(what != 'project' && document.getElementById('w_file').value == "") {ShowDivMsg("file_div","<pre>  Open file, please!  "); return false}
   return true;
}

function clearScreen(){
    document.getElementById('source').value = "";
    document.getElementById('w_file').value = "";
    document.getElementById("result").src ="";
}

function project_open(){
    if(document.getElementById('w_file').value !== "") file_unlock();
    div = document.getElementById("project_div");
    div.innerHTML = 'Project: <input type="text" id = "project" size="12" > Password: <input type="password" id = "password" size="13" >'+  
     '<input type="button" onClick="load_project();div.style.visibility=\'hidden\';" value="Open" >'+
     '<input type="button" onClick="div.style.visibility=\'hidden\';" value="Cancel" >'
    div.style.visibility="visible";
}

function bye(){
    if(document.getElementById("w_file").value != "")
        file_unlock();
}

function project_close(){
    if(!check('project')) return;
    file_unlock();
    document.getElementById('w_project').value = "";
    document.getElementById('w_file').value = "";
    document.getElementById('source').value = "";
    document.getElementById("result").src ="";
}

function new_project(){
    div = document.getElementById("project_div");
    div.innerHTML = '<table><tr><td>Project name:</td><td><input type="text" id = "project_name" size="13" ></td></tr>'+
     '<tr><td>Project password:</td><td><input type="password" id = "p_password" size="13"></td></tr>'+  
     '<tr><td>Admin password:</td><td><input type="password" id = "a_password" size="13"></td></tr>'+  
     '<tr><input type="button" onClick="register_project();div.style.visibility=\'hidden\';" value="Submit" >'+
     '<input type="button" onClick="div.style.visibility=\'hidden\';" value="Cancel" ></tr></table>'
    div.style.visibility="visible";
}

function register_project(){
    var urlpath = url+'/php/new_project.php'
    var data = 'data='+encodeURIComponent(document.getElementById('project_name').value)+' '+
            encodeURIComponent(document.getElementById('p_password').value)+' '+
            encodeURIComponent(document.getElementById('a_password').value);
    AjaxPost(urlpath,data,"NEW_PROJECT")
}

function project_list(){
    var urlpath = url+'/php/list_of_projects.php'; 
    var params ='';
    AjaxGet(urlpath,params,"LIST_OF_PROJECTS")
}

function project_content(){
    if(!check('project')) return;//if(project==''){Msg("project_div","<pre>  Login to project, first!  </pre>");return;}
    var urlpath = url+'/php/dir.php'; 
    var params ='?dir_name='+project;
    AjaxGet(urlpath,params,"PROJECT_CONTENT")
}

function ShowDivMsg(div,msg){
    div = document.getElementById(div);
    div.innerHTML = msg+'<br><a href="javascript:CloseDiv()";>  Close...</a>';
    div.style.visibility="visible";
}

function CloseDiv(div){
  document.getElementById("project_div").style.visibility = "hidden";
  document.getElementById("file_div").style.visibility = "hidden";
}

function delete_project(){
    project=document.getElementById('w_project').value;
    if(project == "") { ShowDivMsg("project_div","<pre>  Open project, please.  </pre>"); return;}
    msg = '<pre>  Delete project: '+project+'<input type="button" value="Yes" onClick="DeleteProject()"></pre>';
             //'<input type="button" value="Cancel" onClick="document.getElementById(\'project_div\').style.visibility = \'hidden\'">';
    ShowDivMsg("project_div",msg);
}

function DeleteProject(){
    var urlpath = url+'/php/delete_project.php'
    var params ='?project='+document.getElementById('w_project').value;
    AjaxGet(urlpath,params,"DELETE_PROJECT")
}

function open_file(){
    var project = document.getElementById('w_project').value;
    if(!check('project')) return;
    div = document.getElementById("file_div");
    div.innerHTML='<fieldset> <legend>Open file</legend>'+
	            'Select file: <select name="combo" id="combo"></select></fieldset><br>'+
	            '<input type="button" value="Open" onclick="check_locked(document.getElementById(\'combo\').value)">'+
                  '<input type="button" value="Cancel" onclick="div.style.visibility=\'hidden\'">';
    div.style.visibility="visible";
    var urlpath = url+'/php/open_file.php'
    var params ='?project='+project;
    AjaxGet(urlpath,params,"OPEN_FILE")
}

function open_file_name(file){
    if(document.getElementById('w_file').value != "") file_unlock();
    document.getElementById('w_file').value = file ;
    div.style.visibility='hidden';
    file_lock();
    load_file()
}

function check_locked(file){
    project = document.getElementById('w_project').value;
    var path = "lockfile.dat";
    var urlpath = url+'/php/check_lock.php';
    var params ='?lockfile='+path+'&project='+project+'&file='+file;
    AjaxGet(urlpath,params,"CHECK_LOCK")
}

function close_file(){
    if(!check('file')) return;
    file_unlock();
    document.getElementById('source').value = "";
    document.getElementById('w_file').value = "";
    document.getElementById("result").src ="";
    }

function upload_file(){
    if(!check('project')) return;
    div = document.getElementById("file_div");
    div.innerHTML='<form action="php/upload.php" method="post" enctype="multipart/form-data" target="upload_target" onSubmit="document.getElementById(\'proj\').value=document.getElementById(\'w_project\').value">'+
                   '<label>File:  <input name="myfile" type="file" size="30" />'+
                   '</label><br>'+
                   '<input type="hidden" name="proj" id="proj">'+
                   '<label>   <input type="submit" name="submitBtn" class="sbtn" value="Upload" />'+
                   '</label>'+
                   '<label>   <input type="button" value="Cancel" onclick="div.style.visibility=\'hidden\'">'+
                   '</label>'+
                   '<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>'+
                   '</form>';
    div.style.visibility="visible";
}

function addCombo(options) {
    var textb = document.getElementById("txtCombo");
    var combo = document.getElementById("combo");
    var option = document.createElement("option");
    op = options.split(",");
    for(i=0; i < op.length; i++){
	   var option = document.createElement("option");
         option.text = op[i];
	   option.value = op[i];
         if(op[i] == ",") break;
	   try {
		combo.add(option, null); //Standard
	   }catch(error) {
		combo.add(option); // IE only
	   }
    }
}

function load_file(){
    var filename = document.getElementById('w_file').value;
    var project = document.getElementById('w_project').value;
    if(!check('both')) return;//
    var urlpath = url+'/php/load_file.php';
    var params ='?project='+project+'&filename='+filename;
    AjaxGet(urlpath,params,"LOAD_FILE");
}

function delete_file(){
    
    if(!check('both')) return;
    filename = document.getElementById('w_file').value;
    msg = '<pre>  Delete file: '+filename+'? <input type="button" value="Yes" onClick="DeleteFile()"></pre>';
    ShowDivMsg("file_div",msg);
}

function DeleteFile(){
    var filename = document.getElementById('w_file').value;
    var project = document.getElementById('w_project').value;
    var urlpath = url+'/php/remove_file.php'
    var params ='?project='+project+'&filename='+filename;
    AjaxGet(urlpath,params,"REMOVE_FILE");
    file_unlock();
    clearScreen();
}


function save_file_as(){
    if(!check('project')) return;//if(project==''){ ShowDivMsg("project_div","<pre>  Login to project, first! </pre>"); return; }
    div = document.getElementById("file_div");
    div.innerHTML = 'File name: <input type="text" id = "file_name" size="12" > '+  
     '<input type="button" onClick="file_unlock();document.getElementById(\'w_file\').value=document.getElementById(\'file_name\').value; file_lock();save_file();div.style.visibility=\'hidden\';" value="Save" >'+
     '<input type="button" onClick="div.style.visibility=\'hidden\';" value="Cancel" >'
    div.style.visibility="visible";
}

function new_file(){
    if(!check('project')) return;//if(project==''){ ShowDivMsg("project_div","<pre>  Login to project, first!  </pre>"); return; }
    div = document.getElementById("file_div");
    div.innerHTML = 'File name: <input type="text" id = "file_name" size="12" > '+  
     '<input type="button" onClick="save_new_file(document.getElementById(\'file_name\').value)" value="Create" >'+
     '<input type="button" onClick="div.style.visibility=\'hidden\';" value="Cancel" >'
    div.style.visibility="visible";
}

function save_new_file(name){
    var valid = /^(\w)+(\.?)(\w{0,})$/;
    if(!valid.test(name)) {
        ShowDivMsg("file_div","<pre>  Invalid file name: "+name+'  </pre>');
        return;
    }
    file_unlock();
    document.getElementById('w_file').value=name;
    file_lock();
    document.getElementById('source').value = "";
    document.getElementById("result").src ="";
    ext = name.split(".");
    switch(ext[1]){
        case "htm": htmlTemplate(); break;
        case "html": htmlTemplate(); break;
        case "php": phpTemplate();break;
        case "py": pythonTemplate(); break;
        case "pl": perlTemplate();break;
        default: break;
    }
    save_file();
    div.style.visibility='hidden'
}

function save_file(){
    var filename = document.getElementById('w_file').value;
    var project = document.getElementById('w_project').value;
    filename=filename.replace(" ",""); // no space in file name
    if(!check('both')) return;
    var path = encodeURIComponent(filename);
    var urlpath = url+'/php/save_file.php'
    var data = 'data='+project+':::'+filename+':::'+encodeURIComponent(document.getElementById('source').value);
    AjaxPost(urlpath,data,"SAVE_FILE")
}

function file_lock(){
    var filename = document.getElementById('w_file').value;
    project = document.getElementById('w_project').value;
    var path = "lockfile.dat";
    filename=filename;
    var urlpath = url+'/php/lock_file.php';
    var params ='?lockfile='+path+'&project='+project+'&file='+filename;
    AjaxGet(urlpath,params,"LOCK_FILE")
}

function file_unlock(){
    var filename = document.getElementById('w_file').value;
    project = document.getElementById('w_project').value;
    var path = "lockfile.dat";
    var urlpath = url+'/php/unlock_file.php';
    var params ='?lockfile='+path+'&project-'+project+'&file='+filename;
    AjaxGet(urlpath,params,"UNLOCK_FILE")
}

function run(how){
    if(!check('both')) return;//if(project==''){ShowDivMsg("project_div","<pre>  Login to project, first!  </pre>");return;}
    save_file();
    var filename = document.getElementById('w_file').value;
    var project =document.getElementById('w_project').value;
    run_file= url+'/'+'projects/'+project+'/'+filename
    document.getElementById("result").contentWindow.document.write("Please wait...");
    if(how== 'test') 
	setTimeout('document.getElementById("result").src = run_file',3000);  
    else
  	setTimeout("window.open(run_file,'Test')",3000);
}

function load_project(){
    project = document.getElementById('project').value;
    password = document.getElementById('password').value;
    var path = url+'/php/login.php'
    var params ='?project='+project+'&password='+password;
    AjaxGet(path,params,"LOAD_PROJECT")
}

function AjaxGet(urlpath,params,callId){
    var req = null; 
    urlpath = urlpath+params
    if(window.XMLHttpRequest)
        req = new XMLHttpRequest(); 
    else if (window.ActiveXObject){
  		req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(req == null){ alert("Request not created");return;}
    req.onreadystatechange = function(){ 
   		if(req.readyState == 4)  AjaxResponse(req.responseText,callId);	
    };            
    req.open('GET', urlpath, true); 
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    req.send(null); 
}

function AjaxPost(urlpath,data,callId){
    var http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
         		// set type accordingly to anticipated content type
            		http_request.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject){
	    try{ http_request = new ActiveXObject("MSXML2.XMLHTTP.6.0");  }catch(e){}
  	    try{ if(!http_request) http_request = new ActiveXObject("MSXML2.XMLHTTP");  }catch(e){}
    }
    if (!http_request) { alert('Cannot create XMLHTTP instance');	return false;}
    http_request.onreadystatechange =  function () {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                AjaxResponse(http_request.responseText,callId);         
         	} else {
                alert('There was a problem with the request.');
         	}
        }
    }         
    http_request.open("POST", urlpath, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", data.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(data);
}

function AjaxResponse(response,callId){
    switch(callId){
        case 'LOAD_FILE': 	document.getElementById('source').value = response;
	      break;
        case 'SAVE_FILE' : ;
		break;
        case 'RUN_FILE':   ;
            break;
        case 'NEW_PROJECT': ShowDivMsg("project_div","<pre>  "+response+'  </pre>');
            break;
        case 'OPEN_FILE': addCombo(response);
            break;
        case 'LOAD_PROJECT': if(response.match("Wrong")!= null) { ShowDivMsg("project_div","<pre>  "+response+'  </pre>'); break;}
                             document.getElementById("w_project").value=response;
                             clearScreen();
	      break;
        case 'LIST_OF_PROJECTS': ShowDivMsg("project_div",response);
            break;
        case 'PROJECT_CONTENT': ShowDivMsg("project_div",'<pre>  '+response+'  </pre>');
            break;
        case 'DELETE_PROJECT': ShowDivMsg("project_div","<pre>  Project " + response + " deleted  </pre>");
			document.getElementById('w_project').value="";
   			document.getElementById('w_file').value="";
            break;
        case 'REMOVE_FILE': ShowDivMsg("file_div",response);//document.getElementById('w_file').value=""; 
            break;
        case 'UNLOCK_FILE': //alert(response);
            break;
        case 'CHECK_LOCK': if(response.match(/LOCKED/)!=null) ShowDivMsg("file_div","<pre>  File in use, try later.  </pre>");
                           else open_file_name(response);
            break;
        default:
    }
}

function phpTemplate(){
    document.getElementById("source").value = "<?php\n\r?>";
}

function htmlTemplate(){
    document.getElementById("source").value = "<html>\n\r<head>\n\r<title>\n\r</title>\n\r<script>\n\r</script>\n\r</head>\n\r<body>\n\r</body>\n\r<html>";
}

function jsTemplate(){
    document.getElementById("source").value ="";
}

function pythonTemplate(){
    document.getElementById("source").value ='#!/usr/bin/python\n\rprint "Content-type: text/html"\n\rprint\n\r';
}

function perlTemplate(){
    document.getElementById("source").value ='#!/usr/bin/perl\n\rprint "Content-type: text/html\\n\\n";';

}

function Help(){
  window.open("help/help.htm","Help");
}