/* Specialised stuff for main route entry page.  Includes route boxes
 * - using Javascript and floats we can always have the right number
 * on the page */

function $(id) {
    return document.getElementById(id);
}

function Old_Start_Page() {
    Check_Logon_Status();
    SetDurationMode();
    Arrange_Boxes();
}


function Route_Start_Page() {
    /* we call this before the page is fully loaded, so any of the
       fields may not exist.  We repeat until they are all filled.
       This prevents things like the intermediate page boxes not
       appearing if Google or Addthis is being a bit slow */
    var todo = [{id:"logon_status",
		 done:false,
		 innerh:function() {
		if(typeof(Check_Logon_Status) == 'function')
		    return Check_Logon_Status('homepage');
		else
		    return true;
	    }},
	{id:"durmode",
	 done:false,
	 innerh:function() {return SetDurationMode();}
	},
	{id:"box_holder",
	 done:false,
	 innerh:function() {return Arrange_Boxes();}
	},
	{id:"workspace",
	 done:false,
	 innerh:function() {Any_Messages(); return true;}
	},
	{id:"searchfor",
	 done:false,
	 innerh:function() {actb(document.getElementById("searchfor"),new Array(),"../cgi-bin/match.cgi");}
	}
	];
    Doemall(todo);
}

function Do_Once(todo) {
    var alldone = true;
    for(var i in todo) {
	if(todo[i].done == false) {
	    var id = document.getElementById(todo[i].id);
	    if(id) {
		todo[i].done = todo[i].innerh();
	    } else
		alldone = false;
	}
    }
    return alldone;
}

function Hide_Dur(name) {
    var thisslab = $('duration_'+name).style
	thisslab.display = "none"
	}

function Show_Dur(name) {
    var thisslab = $('duration_'+name).style
	thisslab.display = "block"
	}

function SetDurationMode() {
    if($('durmode') == null)
	return false;
    if($('duration_start') == null)
	return false;
    if($('duration_end') == null)
	return false;
    if($('duration_length') == null)
	return false;
    switch($('durmode').selectedIndex) {
    case 0: // none
	Hide_Dur("start")
	    Hide_Dur("end")
	    Hide_Dur("length")
	    break;
    case 1:  // start date
	Show_Dur("start")
	    Hide_Dur("end")
	    Hide_Dur("length")
	    break;
    case 2:  // End date
	Hide_Dur("start")
	    Show_Dur("end")
	    Hide_Dur("length")
	    break;
    case 3:  // duration
	Hide_Dur("start")
	    Hide_Dur("end")
	    Show_Dur("length")
	    break;
    case 4:  // Start and duration
	Show_Dur("start")
	    Hide_Dur("end")
	    Show_Dur("length")
	    break;
    case 5:   // End and duration
	Hide_Dur("start")
	    Show_Dur("end")
	    Show_Dur("length")
	    break;
    case 6:   // Start and end dates
	Show_Dur("start")
	    Show_Dur("end")
	    Hide_Dur("length")
	    }
    return true;
}

// a pile of functions to handle the intermediate place boxes on the route entry
// page.

function Create_A_Box(num,holds) {
    var x = $('placebox'+num);
    if(x)
	return x;
    if(holds == null || holds == "undefined")
	holds = "";
    x = document.createElement('div');
    x.style.cssFloat = 'left';
    x.style.styleFloat = 'left';
    x.style.marginRight = '20px';
    x.style.marginBottom = '8px';
    x.style.marginTop = '8px';
    x.id = 'placebox'+num;
    x.innerHTML = '<span onmouseover="PlaceMenu(\'place'+num+'\',\'pl_menu\',true)" onmouseout="PlaceMenu(\'place'+num+'\',\'pl_menu\',false)"><img src="../images/icons/dropdown.png" alt="menu"></span>&nbsp;';
    x.innerHTML += '<input type="text" name="place'+num+'" id="place'+num+'" size="25" maxlength="50" value="'+holds+'" tabindex="'+(4+num)+'" autocomplete="off">';
    $('box_holder').appendChild(x);
}

// find out how many boxes there are in a row
function Boxes_In_A_Row() {
    var num = 1*document.canalform.place_number.value;
    var npr = -1;
    var mstright = 0;
    var x;
    for(var i=0;i<num && npr == -1;i++) {
				x = document.canalform["place"+i];
				if(x.offsetLeft > mstright)
						mstright = x.offsetLeft;
				else
						npr = i;
    }
    return npr;
}

var actobj = [];
function Arrange_Boxes() {
		if(typeof(document.canalform.place_number.value) == 'undefined')
				return false;
    var num = 1*document.canalform.place_number.value;
    for(var i=0;i<=num;i++) {
				Create_A_Box(i,cp_info.box[i]);
				if(typeof(actb)=='function') {
						actobj[i] = actb($('place'+i),new Array(),null);
						actobj[i].actb_delimiter = new Array(); 
				}
    }
    Complete_The_Row(num);
		return true;
}

function Complete_The_Row(lastitem) {
    // we've created the number asked for.  Now expand to a full row
    var num = lastitem + 1;
    var npr = Boxes_In_A_Row();
    if(num % npr == 0)
				return;
    var cb = num;
    num += npr - num % npr;
    for(var i=cb;i<num;i++) {
				cp_info.box[i] = '';
				Create_A_Box(i,'');
				if(typeof(actb)=='function') {
						actobj[i] = actb($('place'+i),new Array());
						actobj[i].actb_delimiter = new Array(); 
				}
    }
    document.canalform.place_number.value = num - 1;
    return num - 1;
}

function Create_At_Least_One_Box(num) {
    Create_A_Box(num,'');
    return Complete_The_Row(num);
}

// as rows are already full, this will do it
function place_add_a_row() {
    var num = 1*document.canalform.place_number.value;
    Create_At_Least_One_Box(num+1);
}

function do_insert(n) {
    var num = 1*document.canalform.place_number.value;
    if(document.canalform["place"+num].value != "") {  // last one is full
	num = Create_At_Least_One_Box(num+1);
    }
    for(var i=num-1;i>=n;i--) {
	x=i+1;
	ss = "place"+x;
	st = "place"+i;
	document.canalform[ss].value = document.canalform[st].value;
    }
    document.canalform["place"+n].value="";
}

// none of this going back to the server in the new version
function Insert_New_Row() {
    var num = document.canalform.place_number.value;
    var tbl = document.getElementById('intermeds');
    var numperrow = Boxes_In_A_Row;
    var abox = document.getElementById('placebox'+num);
    var newrow = document.createElement('tr');
    tbl.appendChild(newrow);
    for(var i=0;i<numperrow;i++) {
	var newbox = document.createElement('td');
	newrow.appendChild(newbox);
	newbox.innerHTML = abox.innerHTML;
    }
}

/* A very similar, but simpler piece of code to remove places.  This
   time we don't bother calling the server to remove empty lines (but
   they will get removed on next display) */

function deletehere(n) {
    var num = 1*document.canalform.place_number.value;
    var i = new Number;
    for(var i=n;i<num;i++) {
	var x=i;
	x++;
	ss = "place"+i;
	st = "place"+x;
	document.canalform[ss].value = document.canalform[st].value;
    }
    document.canalform["place"+num].value="";
    document.canalform["place"+n].focus();
}

// now all the functions called from the menu
function place_clear(where) {
    document['canalform'].elements[where].value='';
    KillMenu();
    document['canalform'].elements[where].focus();
    return false;
}

function place_delete(where) {
    var fm = document['canalform'].elements;
    var n,i;
    if(where == 'pl_start') {
	fm[where].value = fm['place1'].value;
	deletehere(1)    ;
    } else if(where == 'pl_end') {
	// find last place with a value
	n = 0;
	for(var i=fm['place_number'].value;i>0;i--) {
	    if(fm['place'+i].value != '' && n == 0);
	    n = i;
	}
	if(n) {
	    fm[where].value = fm['place'+n].value;
	    fm['place'+n].value = '';
	} else {
	    fm[where].value = '';
	}
    } else {
	var n = where.replace(/place/,"");
	deletehere(n);
    }
    KillMenu();
    fm[where].focus();
    return false;
}

function place_insert(where) {
    var fm = document.forms['canalform'].elements;  // a useful alias
    var n,i;
    if(where == 'pl_start') {
	do_insert(1);
	fm['place1'].value = fm[where].value;
	fm[where].value = '';
    } else if(where == 'pl_end') {
	// find lastmost empty space
	n = 0;
	for(var i=1*fm['place_number'].value;i>0;i--) {
	    if(fm['place'+i].value != '' && n == 0) {
		n = i+1;
	    }
	}
	if(n) {
	    fm['place'+n].value = fm[where].value;
	    fm[where].value = '';
	    if(n > 1*fm['place_number'].value) {
		fm['place_number'].value = n;
		rf = true;
	    }
	} else {   // first place must be empty
	    fm['place1'].value = fm[where].value;
	    fm[where].value = '';
	}
    } else {
	var n = where.replace(/place/,'');
	do_insert(n);
    }
    KillMenu();
    fm[where].focus();
    return false;
}

function place_lookup(where) {
    var fm = document.forms['canalform'].elements  // a useful alias
	if (fm[where].value =='') {
	    KillMenu();
	    document.forms['canalform'].elements[where].focus();
	    return false;
	}
    fm._submit[0].value = 'operate';
    fm['changeplace'].value = 'find';
    fm['unkpl'].value = fm[where].value;
    fm['fieldtochange'].value = where;
    KillMenu();
    fm._submit[0].click();
}

function place_replace(where) {
    var fm = document.forms['canalform'].elements;  // a useful alias
    fm._submit[0].value = 'operate';
    fm['changeplace'].value = 'replace';
    fm['unkpl'].value = fm[where].value;
    fm['fieldtochange'].value = where;
    fm['lastsub'].value = '';
    KillMenu();
    fm._submit[0].click();
}

function place_overnight(where) {
    alert(where);
}

function place_mooring(where) {  
    var fm = document.forms['canalform'].elements;  // a useful alias
    fm[where].value = cp_info.mooring;
    KillMenu();
    return true;
}

function place_tidyup() {
    var num = 1*document.canalform.place_number.value;
    var j = 0;
    for(var i=0; i<=num; i++) {
	document.canalform['place'+j].value = document.canalform['place'+i].value;
	if(document.canalform['place'+j].value != '')
	    ++j;
    }
    for(var j;j<=num;j++)
	document.canalform['place'+j].value = '';
    place_remove_empties();
}

// remove any completely empty rows
function place_remove_empties() {
    var a = Boxes_In_A_Row();
    var num = 1*document.canalform.place_number.value;
    var empty = true;
    // is last row entirely empty
    if((num+1) < 3*a)
				return;   // always leave two full rows
    for(var i = 0; i<a; i++) {
				if(document.canalform['place'+(num-i)].value != '')
						empty = false;
    }
    if(empty) {  // the last row is empty, so delete it
				var con = $('box_holder');
				for(var i=0; i<a; i++) {
						var b = $('placebox'+(num-i));
						con.removeChild(b);
				}
				document.canalform.place_number.value = num - a;
	// recurse for multiple empty lines
				place_remove_empties();
    }
}

function place_clearinter() {
    var num = 1*document.canalform.place_number.value;
    for(var i=0; i<=num; i++)
	document.canalform["place"+i].value = "";
}

function place_reverse() {
    var num = 1*document.canalform.place_number.value;
    var swapem = document.canalform.pl_start.value;
    document.canalform.pl_start.value = document.canalform.pl_end.value;
    document.canalform.pl_end.value = swapem;
    for(var i=0; i<=num/2; i++) {
	swindex = num - i;
	swapem = document.canalform['place'+i].value;
	document.canalform['place'+i].value = document.canalform['place'+swindex].value;
	document.canalform['place'+swindex].value = swapem;
    }
    var j = 1;
    for(var i=1; i<=num; i++) {
	document.canalform['place'+j].value = document.canalform['place'+i].value;
	if(document.canalform['place'+j].value != '')
	    ++j;
    }
    for(var j;j<=num;j++) {
	document.canalform['place'+j].value = '';
    }
}

function Clone_First() {
    document.getElementById('pl_end').value = document.getElementById('pl_start').value;
    return false;
}

// once we've finished changing the window size, we adjust the boxes
function resizeStuff() {
    var num = 1*document.canalform.place_number.value;
    Complete_The_Row(num);         // and complete any partial row
    place_remove_empties();        // delete any empty rows now at the end
}

/*
var resize_in_progress = false;

window.onresize= function() {
    if(resize_in_progress !== false) {
	clearTimeout(resize_in_progress);
    }
    resize_in_progress = setTimeout(resizeStuff, 100);
};
*/

var amiloggedon = false;

