function addClosedSeasonRow() {
	var parent = $(this).parent().parent().eq(0);
	var count = $(parent).children(".dateField").length;
	var newRowHtml =  '<div class="dateField">'
					+ '<div class="date_value_container"><input type="text" name="closing['+count+'].begin" class="dateRequired" value="" /></div>'
					+ '<div class="date_separator"> - </div>'
					+ '<div class="date_value_container"><input type="text" name="closing['+count+'].end" class="dateRequired" value="" /></div>'
					+ '<div class="date_message_container"><input type="text" value="" class="text closed_season_message" name="closing['+count+'].message" maxlength="256"/></div>'
					+ '<div class="btns"><input type="button" class="button trash" value="" title="Poista t\u00E4m\u00E4 jakso" /></div>'
					+ '</div>';
	$(this).parent().before(newRowHtml);
	checkDisableSubmits($(this).parents("form").get(0));
}

function removeClosedSeasonRow() {
	var frm = this.form;
	$(this).parents("div.dateField").eq(0).remove();
	checkDisableSubmits(frm);
}

//MENU ON PUBLIC SIDE
function initPublicRestaurantMenu() {
	
	var subMenuItems = new Array();
	$(".selecting_menu .type").attr('disabled', false);
	$(".selecting_menu .type").get(0).selectedIndex = 0;
	$(".selecting_menu .restaurant").attr('disabled', true);
	$(".selecting_menu .restaurant").get(0).selectedIndex = 0;
	$("#submit_restaurant").attr('disabled', true);
	$("#submit_restaurant").addClass("disabled");

	$(".selecting_menu .restaurant option").each(function(){
	      var group = $(this).parent().eq(0).attr("typeid");
	      var value = $(this).val();
	      var text = $(this).text();
	      subMenuItems.push(new Array(group, value, text));
	});

	$(".selecting_menu .type").change(function(){
		var selVal = this.options[this.options.selectedIndex].getAttribute("value");
		$(".selecting_menu .restaurant option, .selecting_menu .restaurant optgroup").remove();
		$("select.restaurant").append('<option value="">-- Valitse ravintola --</option>');
		for(var i=0; i<subMenuItems.length; i++) {
			if(subMenuItems[i][0]==selVal) {
				$("select.restaurant").append('<option value="'+subMenuItems[i][1]+'">'+subMenuItems[i][2]+'</option>');
			}
		}

		if($(".selecting_menu .type").get(0).selectedIndex>0) {
			$("select.restaurant").attr('disabled', false);
		}
		else {
			$("select.restaurant").attr('disabled', true);
		}
		$("#submit_restaurant").attr('disabled', true);
		$("#submit_restaurant").addClass("disabled");
	});
	
	$("select.restaurant").change(function(){
		if(this.options.selectedIndex>0) {
			$("#submit_restaurant").attr('disabled', false);
			$("#submit_restaurant").removeClass("disabled");
		}
		else {
			$("#submit_restaurant").attr('disabled', true);
			$("#submit_restaurant").addClass("disabled");	
		}
	});

}




$(document).ready(function() {
	$("a.btnAddClosedSeasonRow").bind("mousedown", "", addClosedSeasonRow);
	
	$('.dateField input.trash').livequery("click", removeClosedSeasonRow);
	
	$('a.editDiet').bind("click", {formId: 'dietForm'}, resetErrors);
	
    $('a.editRestaurantType').bind("click", {formId:'restaurantTypeForm'}, resetErrors);
    
    $('#select_menu').each(function(){
		initPublicRestaurantMenu();
    });
    
    
    // DIET COLORS
    $("#diet_colors .color_sample_used").each(function(){
    	$(this).addClass("usedColor");
    });
    $("div.params_container a").click(function() {
		var sp = $(this).parents("tr").eq(0).children("td.hidden-cell:last").text();
		if(sp.length<1) { //if not one of the edit links
			$(".color_sample input:radio").get(0).checked = true;
			return;
		}
		$(".usedColor").addClass("color_sample_used");
		$("input[value="+sp+"]").each(function() {
			$(this).parents("div").eq(0).removeClass("color_sample_used");
			$(this).get(0).checked = true;
		});
    });
    $(".btns_actions a.editDiet").click(function() {
    	$(".usedColor").addClass("color_sample_used");
    });
    
    
    // MENU DUPLICATING / DISABLING & ENABLING SUBMIT BUTTON
    $("#copyscreen input:submit").each(function() {
    	this.disabled = true;
    });
	$("#copyscreen input:submit").addClass("disabled");
	$("#copyscreen select[name=type], #copyscreen select[name=restaurant], #copyscreen select[name=copyId]").change(function() {
		$("#copyscreen input:submit").get(0).disabled = true; 
		$("#copyscreen input:submit").addClass("disabled");
		$(this.form).children("input:submit").addClass("disabled");
		var copyIdSel = $("#copyscreen select[name=copyId]").get(0);
		if(copyIdSel.options.selectedIndex>0) {
			$("#copyscreen input:submit").get(0).disabled = false; 
			$("#copyscreen input:submit").removeClass("disabled");
		}
	});
	
	//REMOVE CLASS non_js_hidden WHICH IS USED FOR HIDING STUFF FROM NON-JS BROWSERS
	$(".non_js_hidden").removeClass("non_js_hidden");
     
});



// ======================================================================================================================== //
// ======================================================================================================================== //




// Flips the style.display of the element with the given
// id between block and none
function showHide(id) {
	var element = document.getElementById(id);

	if (element.style.display != 'none') {
		element.style.display = 'none';
	} else {
		element.style.display = 'block';
	}
}
// activates / deactivates the background for popup
function popUpBg(){
	var element = document.getElementById('popup_background');

	if (element.style.display != 'none') {
		element.style.display = 'none';
	} else {
		element.style.display = 'block';
	}
}

// Hides rows of the table with the given id whose first column
// content do not match the value of the given input
function filter(input, tableId) {
  var matchAll = false;
  if(input=="Kirjoita hakusana") {
  	 matchAll = true;
  }
  var rows = document.getElementById(tableId).getElementsByTagName("tr");

  for (var i=0; i < rows.length; i++) {
    var tds = rows[i].getElementsByTagName("td");
    if (tds.length > 0) {
      if (textContent(tds[0]).toLowerCase().match(input.toLowerCase()) || matchAll) {
        rows[i].style.display = "";
      } else {
        rows[i].style.display = "none";
      }
    }
  }
} 

// if the given select has the value otherValue, then
// - hide the select
// - display a following sibling that has the same name postfixed
//   with the given postfix
function showOther(select, otherValue, postfix){
	selectedOption = select.options[select.selectedIndex];

	if (selectedOption.value == otherValue) {
		var other = select.nextSibling;
		while (other != null && other.name != (select.name + postfix)) {
			other = other.nextSibling;
		}

		if (other != null) {
			select.style.display = "none";
			other.style.display = "block";
			other.focus()
		} else {
			alert("Error: other input not found!");
		}
	}
}

// depending on the value of input.checked, show or 
// hide the elements with the given Ids. Closed is
// shown when the input.checked is true, open when not.
function setClosedStatus(isClosed, openId, closedId){
	var num = parseInt(openId.replace('d',''));
	var openClosedStatus = document.getElementById("day"+num+"open");
	openClosedStatus.value = isClosed?"":"open";
	
	var open = document.getElementById(openId);
	var closed = document.getElementById(closedId);

	for (var i = 0; i < closed.childNodes.length; i++) {
		var child = closed.childNodes[i];
		if(child.nodeName.toLowerCase() == 'input'){
			var closedMessageField = child;
		}
	}

	if (isClosed) {
		open.style.display = "none";
		closed.style.display = "block";
		closedMessageField.disabled = false;
	} else {
		closed.style.display = "none";
		open.style.display = "block";
		closedMessageField.disabled = true;
	}
}

// get the row on which the given element is on, or
// null if not found.
function getRow(element) {
	while (element != null && element.nodeName.toLowerCase() != "tr") {
		element = element.parentNode;
	}

	if (element == null) {
		alert("parent tr not found");
	}

	return element;
}

// gets the parent form of non-form elements
function getForm(element) {
    alert(element);
    while (element != null && element.nodeName.toLowerCase() != "form") {
        element = element.parentNode;
    }
    return element;
}

// Rename the fields (input and select) that are the children
// of the given element (row).
// The function replaces the any occurances of rows[n] with 
// rows[entryNum] in the field's name.
function renameRowFields(row, entryNum, arrayName) {
	if (arrayName == null || arrayName == "") {
 		arrayName = "menuItem";
	}

	var regex = new RegExp(arrayName + "\\[\\d+\\]");
	var replacement = arrayName + "[" + entryNum + "]";

	// replace row numbers in input element names
	var inputs = row.getElementsByTagName("input"); 
	for (var i=0; i < inputs.length; i++) {
		var input = inputs[i];
		input.name = input.name.replace(regex, replacement);
	}	

	// replace row numbers in select element names
	var selects = row.getElementsByTagName("select"); 
	for (var i=0; i < selects.length; i++) {
		var select = selects[i];
		select.name = select.name.replace(regex, replacement);
	}	
}

function clearRowInputs(row) {
    var inputs = row.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        var input = inputs[i];
        var type = input.type;
        switch(type) {
            case "text":
                input.value = "";
                break;
            case "checkbox":
                input.checked = false;
                break;
            default:
                break;
        }
    }
}

// Delete the meal or season row on which the given element is on,
// rename the remaining rows in the same table.
function delRow(renameIndexText, elementOnRow, arrayName) {
	// get the current row based on an element on the row
	var currentRow = getRow(elementOnRow);

	// get the table before we go and delete the row
	var table = currentRow.parentNode;

	// delete the current row
	table.deleteRow(currentRow.rowIndex - 1);

	// loops through the current day's all rows except the header row
	var rows = table.rows; 
	for (var i=0; i < rows.length; i++) { 
		var row = rows[i];

		// set the row number to the first td element, except on last row
		if(renameIndexText == true){
			if (i != rows.length - 1 && row.cells[0].innerHTML.match(/\d+\./)) {
				row.cells[0].innerHTML = row.rowIndex + ".";
			}
		}

		// rename field names
		renameRowFields(row, row.rowIndex - 1, arrayName);
	}
}

// Clones the row on which the given element is on and
// inserts it to the same table. Sets the row numbers to the
// first td and renames fields.
function addRow(elementOnRow, arrayName) {
	// get the current row based on an element on the row
	var currentRow = getRow(elementOnRow);
	var table = currentRow.parentNode;

	// do nothing if the row clicked was not the last row
	if (currentRow.rowIndex != table.rows.length) {
		return;
    }

	// clone the row
	var cloneRow = currentRow.cloneNode(true)
	
	//Set all disabled fields in the row to false
	var inputFields = currentRow.getElementsByTagName("input");
	for (var i=0; i < inputFields.length; i++) { 
		inputFields[i].disabled = false;
	}

    // clear the style of the current row
    currentRow.className = "";
	
	// set the row number to the first td element
	cloneRow.firstChild

    // set the row number to the first td element
    if (currentRow.cells[0].innerHTML == "*") {
      currentRow.cells[0].innerHTML = currentRow.rowIndex + ".";
    }

	// rename field names of the clone, clone index is currenRow rowIndex
	renameRowFields(cloneRow, currentRow.rowIndex, arrayName);
    clearRowInputs(cloneRow);
    
	// add the row to the table
	table.appendChild(cloneRow);
	
}

// Turns all forms of the given parent editable
// see editForm(form)
function editFirstForm(parent){
	var forms = parent.getElementsByTagName("form");
	if (forms.length > 0) {
		editForm(forms[0]);
	}
}

// Turns the given form editable
// - changes the class of the form from "disabled" to "editable"
// - turns all readonly fields to active
// Will do nothing if some other form is being edited
var isFormEdited = false;
function editForm(form) {
	if (isFormEdited) {
		return;
	}

	// set the class of the form
	if (form.className != null) {
		form.className = form.className.replace("disabled", "editable");
	}

	// set all fields editable
	
	var elements = form.elements;
	for (var i = 0; i < elements.length; i++) {
		//elements[i].disabled = false;
		elements[i].readOnly = false;
	}

	isFormEdited = true;
}

// Turns the given form into disabled mode
// - changes the class of the form from "editable" to "disabled"
// - turns all fields readonly
function disableForm(form) {
	isFormEdited = false;

	if (form.className != null) {
		form.className = form.className.replace("editable", "disabled");
	}

	var elements = form.elements;

	for (var i = 0; i < elements.length; i++) {
		//elements[i].disabled = true;
		elements[i].readOnly = true;
	}
}

// Enables submit button with the given id by
// - setting id not disabled 
// - setting className to "submit"
function enableSubmit(submitId) {
	document.getElementById(submitId).disabled = false;
	document.getElementById(submitId).className = 'submit';
}

// Disables submit button with the given id by
// - setting it disabled
// - setting className to "submit disabled"
function disableSubmit(submitId) {
	alert(submitId);
	document.getElementById(submitId).disabled = true;
	document.getElementById(submitId).className = 'submit disabled';
}

// Shows a warning message in a span with class warning that is the
// following sibling (transitive closure over nextSibling) of the
// given field
function showWarning(field, message, warningElementId) {
  var warning = null;

  if (warningElementId) {
    warning = document.getElementById(warningElementId); 
  } else {
    warning = field.nextSibling;
    while (warning != null && warning.className != "warning") {
      warning = warning.nextSibling;
    }  
  }
  
  if (warning != null) {      
    warning.innerHTML = message;
  } else if (message != "") {
    alert(message);
  }
}

// Given a form object and a field name, chekcs if the field value is
// empty. If so, 
// - shows the given 'emptyMessage' in a sibling element with class 'warning' 
// - change the style of the field to 'error' 
// - returns false

function checkRequiredTextField(field, emptyMessage) {
  var message = "";
  var className = "";

  if (field.value == "") {
    className = "error";
    message = emptyMessage;
  } else{
    className = "text";
  }
  
  field.className = className;

  showWarning(field, message);

  return (message == "");
}

function checkDate(field, warningMessage) {
  var message = "";
  var className = "";

  // clean out everything that is not a part of date
  field.value = field.value.replace(/[^0-9.]/, "");

  if (!isDMYDate(field.value)) {
    className = "error";
    message = warningMessage;
  } else {
    className = "text";
  }
  
  field.className = className;

  showWarning(field, message);

  return (message == "");
}

function isDMYDate(dateString) { 
	alert("isDMYDate should not be in use")

  if (!dateString.match(/^[0-3]?\d\.[0-1]?\d\.\d\d\d\d$/)) {
    // it's not even close to looking like a date
    return false;
  } else {
    // it looks like a date
    var dmyString = dateString.split(".");
    var dmy = new Array(3);

    for (var i = 0; i < dmyString.length; i++) {
      dmy[i] = parseInt(dmyString[i]);
    }

    var date = new Date();
    date.setFullYear(dmy[2], dmy[1]-1, dmy[0]);
    return (dmy[2] == date.getFullYear()) && (dmy[1]-1 == date.getMonth()) && (dmy[0] == date.getDate());
  }
}

/*
function checkRequiredNumericField(field, warningMessage) {
  var message = "";
  var className = "";

  if (field.value == "") {
    className = "error";
    message = emptyMessage;
  }else{
    className = "text";
  }
  
  field.className = className;

  showWarning(field, message);

  return (message == "");
}
*/
function checkNumeric(numberfield,minval,maxval,warningMessage) {
  var message = "";
  var className = "";
  var value = parseInt(numberfield.value);

  if (value == NaN || value < minval || value > maxval) {
    className = "error";
    message = warningMessage;
  } else {
    className = "text";
  }
  
  field.className = className;

  showWarning(field, message);

  return (message == "");
}

// Checks 
function checkRequiredCheckboxField(fields, emptyMessage, warningElementId){
    var message = emptyMessage;
    if (fields.length) {
        for (var i = 0; i < fields.length; i++){
            if (fields[i].checked) {
                message = ""; // all ok, clear message
                break;
            }
        }
    } else {
        if (fields.checked) {
            message = "";
        }
    }

    if (fields.length && fields.length > 0) {
        showWarning(fields[0], message, warningElementId);
    } else if (!fields.length) {
        showWarning(fields, message, warningElementId);
    }

    return (message == ""); // isAllOk
}


// Checks the required fields of a restaurant form
function checkRequiredRestaurantFields(form) {
  
  var isAllOk = checkRequiredTextField(form.name, "Nimi ei saa olla tyhj\u00E4");

  isAllOk = checkRequiredCheckboxField(form.type, "Ravintolalla pit\u00E4\u00E4 olla tyyppi", "restaurantTypeWarning") && isAllOk; // order is important

  if (isAllOk) {
    // show save-button
		enableSubmit('submit_for_restaurant');	
  } else {
    // disable save-button
		disableSubmit('submit_for_restaurant');
  }
}

// Checks the required fields of a user form
function checkRequiredUserFields(form) {
  
  var isAllOk = checkRequiredTextField(form.username, "K\u00E4ytt\u00E4j\u00E4nimi ei saa olla tyhj\u00E4");

  if (isAllOk) {
    // show save-button
		enableSubmit('submit_for_user');	
  } else {
    // disable save-button
		disableSubmit('submit_for_user');
  }
}

function newUser(editorId) {
  var editor = document.getElementById(editorId);

  var forms = editor.getElementsByTagName("form");

  if (forms.length != 0) {
    forms[0].reset();
  }
  
  document.getElementById('delete_for_user').style.display = "none";
  disableSubmit('submit_for_user');

  var toimipisteet = window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet;

  for (i = 0; i < toimipisteet.length; i++){
    toimipisteet[i].checked = false;
  }	

	newParameter(editorId);
}

function newRestaurant(editorId) {
	newParameter(editorId);
}

function newRestaurantType(editorId) {
	newParameter(editorId);
	document.getElementById('delete_for_restauranttype').style.display = 'none';
    //disableSubmit('submit_for_restauranttype');
}
function newMenuItemType(editorId) {
	newParameter(editorId);
	document.getElementById('delete_for_menuitemtype').style.display = 'none';
    disableSubmit('submit_for_menuitemtype');
}

// Unhides the given editor and resets the form making it ready
// for entering a new parameter
function newParameter(editorId) {
  var editor = document.getElementById(editorId);

  if (editor == null) {
    alert("newParameter(): error")
    return;
  }

  var forms = editor.getElementsByTagName("form");

  if (forms.length != 0) {
    forms[0].reset();
  }

  editor.className = "popup_panel green"
  document.getElementById(editorId + '_type_text').innerHTML = 'lis\u00E4\u00E4minen';
  popUpBg();
  editor.style.display='block';
}

function checkDietField(field, evt) {
	
	if(evt.type == "keyup" && evt.keyCode==9)return;
	if(field.getAttribute("name")=="description") {
		checkRequiredTextField(field, "Kuvaus ei saa olla tyhj\u00E4");
	} else if (field.getAttribute("name")=="abbrev") {
		checkRequiredTextField(field, "Lyhenne ei saa olla tyhj\u00E4");
	}
	checkDietSubmit(field.form);
}

function resetDietErrors(form) {
	enableSubmit('submit_for_diettype');
	form.description.className = "text";
	showWarning(form.description, "");
	form.abbrev.className = "text";
	showWarning(form.abbrev, "");
}

function checkDietSubmit(form) {
  var isAllOk = form.description.value.length>0 && form.abbrev.value.length>0;

  if (isAllOk) {
		enableSubmit('submit_for_diettype');	
  } else {
		disableSubmit('submit_for_diettype');
  }
  return isAllOk;
}

function checkMenuItemTypeFields(form) {
  var isAllOk = checkRequiredTextField(form.name, "Nimi ei saa olla tyhj\00E4");

  if (isAllOk) {
    // show save-button
		enableSubmit('submit_for_menuitemtype');	
  } else {
    // disable save-button
		disableSubmit('submit_for_menuitemtype');
  }

  return isAllOk;
}
function checkRestaurantTypeFields(form) {
  var isAllOk = checkRequiredTextField(form.name, "Nimi ei saa olla tyhj\u00E4");

  if (isAllOk) {
    // show save-button
		enableSubmit('submit_for_restauranttype');	
  } else {
    // disable save-button
		disableSubmit('submit_for_restauranttype');
  }

  return isAllOk;
}
function updateRestaurantList(value){
	//empties the restaurant list form
	for (i = 0; i < document.forms.edit_user_form.restaurant.length; i++){
		document.forms.edit_user_form.restaurant[i].checked = false;
	}
	//selects the right restaurants
	var restaurants=value.split(",");
	for (x=0; x<restaurants.length; x++){

		for (i = 0; i < document.forms.edit_user_form.restaurant.length; i++){
			if (document.forms.edit_user_form.restaurant[i].value == restaurants[x]){
				document.forms.edit_user_form.restaurant[i].checked = true;
			}
		}
	}
}

function editUser(elementOnRow) {

  var editor = document.getElementById("editscreen_user");
  var forms = editor.getElementsByTagName("form");
  
  if (forms.length != 0) {
    forms[0].reset();
  }
  enableSubmit('submit_for_user');
/*  document.getElementById('delete_for_user').style.display = "block"; */

  editParameter(elementOnRow, "editscreen_user", "username,id,,restaurant");

  var styleattr=document.createAttribute("class");
  styleattr.nodeValue="popup_panel red"
  editor.setAttributeNode(styleattr);
  document.getElementById('editscreen_user_type_text').innerHTML = 'muokkaaminen';
}

function editRestaurantType(elementOnRow) {
  editParameter(elementOnRow, "editscreen_toimipistetyypit", "id,name");
  var editor = document.getElementById("editscreen_toimipistetyypit");
  var forms = editor.getElementsByTagName("form");
  document.getElementById('delete_for_restauranttype').style.display = "block";

  var styleattr=document.createAttribute("class");
  styleattr.nodeValue="popup_panel red"
  editor.setAttributeNode(styleattr);
  document.getElementById('editscreen_toimipistetyypit_type_text').innerHTML = 'muokkaaminen';
  enableSubmit('submit_for_restauranttype');
}

function editMenuItemType(elementOnRow) {
  editParameter(elementOnRow, "editscreen_konseptinimikkeet", "id,name,color");
  var editor = document.getElementById("editscreen_konseptinimikkeet");
  var forms = editor.getElementsByTagName("form");
  document.getElementById('delete_for_menuitemtype').style.display = "block";
  //updateColorSamples('', 'menu_item_type_colors', 'color\\d+');
  updateColorSamples("FIXME", 'menu_item_type_colors', "color0", null, new Array());

  var styleattr=document.createAttribute("class");
  styleattr.nodeValue="popup_panel red"
  editor.setAttributeNode(styleattr);
  document.getElementById('editscreen_konseptinimikkeet_type_text').innerHTML = 'muokkaaminen';
}

// Edit the current row with the given editor. The row columns are
// mapped to the named fields. The fields parameter is a comma separated
// list of field names to map to. If a column is not to be mapped, then
// do not give the column a name. E.g. "foo,,bar" maps first column to
// field foo, second is ignored and third to bar.
function editParameter(elementOnRow, editorId, fields) {
  var editor = document.getElementById(editorId);
  var form = editor.getElementsByTagName("form")[0];
  var fieldNames = fields.split(",");

  // get the current row based on an element on the row
  var currentRow = getRow(elementOnRow);

  var cells = currentRow.cells;

  // loop through row cells (columns) and field names
  for (var i = 0; ((i < cells.length) &&
                   (i < fieldNames.length)); i++) {

    if (fieldNames[i] == "") {
      // if the field name is empty, then go to next field
      continue;
    }

    var value = textContent(cells[i]);

    setFieldValue(form, fieldNames[i], value);
	//updates the restaurant list
	if (fieldNames[i] == 'restaurant'){
		updateRestaurantList(value);
	}
  }
  popUpBg();
  editor.style.display='block';
}
function deleteUser(id, editorId){
	popUpBg();
	showHide(editorId);
}
function deleteRestaurant(id){
	
}
function deleteParameter(id, editorId){
    var doSubmit = confirm('Haluatko todella poistaa t\u00E4m\u00E4n parametrin? Toimenpide on peruuttamaton.');
	if(doSubmit) {
        popUpBg();
        showHide(editorId);
    }
    return doSubmit;
}

var unfiltered; // holds all existing restaurants
var unfilteredWeeks; // holds all existing weekmenus for all restaurants

// copies the restaurants select's elements to a hidden and disabled select
function copyUnfilteredOptions(selectElement, target) {
    //alert(restaurantSelect);
    //target = new Object();
    target.tip = new Object();
    target.tip.innerHTML = selectElement.options[0].innerHTML;
    target.tip.value = selectElement.options[0].value;
    var optGroups = selectElement.getElementsByTagName("OPTGROUP");
    for (var i = 0; i < optGroups.length; i++) {
        if (!target[optGroups[i].getAttribute("typeId")]) {
            target[optGroups[i].getAttribute("typeId")] = new Array();
        }
        var childOpts = optGroups[i].getElementsByTagName("OPTION");
        for (var j = 0; j < childOpts.length; j++) {
            var newOpt = new Object();
            newOpt.value = childOpts[j].value;
            newOpt.innerHTML = childOpts[j].innerHTML;
            target[optGroups[i].getAttribute("typeId")].push(newOpt);
        }
    }
}

// fills id select element with ids that have a matching id type id in their label
function showFilteredSelect(typeId, selectElement, source, secondaryElement) {
    // remove all options (and groups)
    selectElement.options.length = 0;
    selectElement.innerHTML = "";
    // add the tip option
    //alert(document.getElementById("palmia_restaurants_unfiltered").getElementsByTagName("OPTION").length );
    addSelectOption(source.tip, selectElement);
    selectElement.options[0].selected = true;
    selectElement.options[0].defaultSelected = true;
    selectElement.selectedIndex = 0;
    // only fill the options and enable id select if we have a proper type selection
    if(secondaryElement) {
        secondaryElement.selectedIndex = 0;
        secondaryElement.options[0].selected = true;
        secondaryElement.options[0].defaultSelected = true;
        secondaryElement.disabled = true;
    }
    if (!typeId || typeId == "") {
        selectElement.disabled = true;
        return;
    }
    
    var filteredOptions = source[typeId];
    if (filteredOptions && filteredOptions.length) {
        for (var i = 0; i < filteredOptions.length; i++) {
            addSelectOption(filteredOptions[i], selectElement);
        }
    }
    
    // enable and focus restaurant select
    selectElement.disabled = false;
}

// adds option to the id select, takes input from unfiltered
function addSelectOption(sourceOption, selectElement) {
    //alert(document.getElementById("palmia_restaurants_unfiltered"));
    //alert(sourceOption);
    selectElement.options.length++;
    //document.forms.select_menu.id.options[document.forms.select_menu.id.options.length-1] = new Option();
    //alert(sourceOption.value);
    if (sourceOption.value)
        selectElement.options[selectElement.options.length-1].value = sourceOption.value;
    if(sourceOption.innerHTML)
        selectElement.options[selectElement.options.length-1].innerHTML = sourceOption.innerHTML;
}

function showMenu(id, formElement) {
    // only submit if we have a valid selection (i.e. the user has selected an option other than the tip option)
    if ( id != null && id != "" ) {
        // disable type form item so it won't get submitted, not really necessary.
        //document.forms.select_menu.type.disabled = true;
        if (formElement.restaurant) {
            // show weekmenus of the restaurant
            //alert("show filtered weeks");
        } else {
            formElement.submit();
        }
    }
}

function initRestaurantSelection(selectForm) {
    selectForm.type.disabled = false;
    selectForm.type.style.visibility = "visible";
    selectForm.type.selectedIndex = 0;
    selectForm.type.options[0].selected = true;
    selectForm.type.options[0].defaultSelected = true;
    unfiltered = new Object();
    if (selectForm.restaurant) {
        selectForm.restaurant.disabled = true;
        unfilteredWeeks = new Object();
        copyUnfilteredOptions(selectForm.restaurant, unfiltered);
        copyUnfilteredOptions(selectForm.copyId, unfilteredWeeks);
        selectForm.copyId.disabled = true;
    } else {
        copyUnfilteredOptions(selectForm.id, unfiltered);
        selectForm.id.disabled = true;
    }
}

// IE6 FIXS

ie6_hover = function() {
	var sfEls = document.getElementsByTagName("button");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" button_hover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" button_hover\\b"), "");
		}
	}
}

// HELPERS:

// recursively walk down the DOM tree and return all nodes whose
// className matches the given regex
function getElementsByClassName(parent, classNameRegex, elements) {
  if (elements == null) {
    elements = new Array();
  }
  
  var children = parent.childNodes;

  for (var i = 0; i < children.length; i++) {
    var child = children[i];

    if (child.className != undefined) {
      if (child.className.match(classNameRegex)) {
        //alert("Matched "+child.className+" to "+classNameRegex+", called by "+getElementsByClassName.caller);
        elements.push(child);
      }

      getElementsByClassName(child, classNameRegex, elements);
    }
  }

  return elements;
}

// get all fields of a form that match the given name
function getFieldsByName(form, name) {
  var elements = new Array();
  //alert("getFieldsByName");
  var regex = new RegExp("^" + name + "$");
  
  var fields = form.elements;

  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];

    if (field.name.match(regex)) {
      elements.push(field);
    }
  }

  return elements;
}

// Sets the value of a field in a form
function setFieldValue(form, fieldName, value) {

  var fields = getFieldsByName(form, fieldName);
  var type = null;
  
  if (fields.length > 0) { 
    // fields found, check type
    type = fields[0].type;
    
    if (type == "hidden" || type == "text" || type == "textarea") {
      fields[0].value = value;
    } else if (type == "radio" || type == "checkbox") {
      // loop through the fields and select the one with the given value
      for (var j = 0; j < fields.length; j++) {
        if (fields[j].value == value) {
          fields[j].checked = true;
        }
      }
    } else {
      alert("setFieldValue(): not implemented for type " + type);
    }
  } else {
    alert("no field " + fieldNames[i]);
    return;
  }
}

function copyMenu(){
	popUpBg();
	showHide('copyscreen');
	return true;
}
function openMenuCopy(week){
	popUpBg();
	document.getElementById('copyscreen').style.display='block';
}
function openMenuPreview(form){
	popUpBg();
	document.getElementById('previewscreen').style.display='block';
}
function saveForm(form){

}

/* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
This notice must stay intact for legal use.
Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

function fadeHideElement(el,milli) {
		// Get the opacity style parameter from the image
		var currOpacity = document.getElementById(el).style.opacity;
		if(currOpacity != 0) { // if not faded
			fade(el, milli, 100, 0);
		} else { // else the images is already faded
			fade(el, milli, 0, 100);
		}
		
	} 
	
/* changeOpacity() uses three different opacity settings to
   achieve a cross-browser opacity changing function.  This
   function can also be used to directly change the opacity
   of an element. */
function changeOpacity(el,opacity) {
	var image = document.getElementById(el);
	// For Mozilla
	image.style.MozOpacity = (opacity / 100);
	// For IE
	image.style.filter = "alpha(opacity=" + opacity + ")";
	// For others
	image.style.opacity = (opacity / 100);
	// hides the element after the fade
	if(opacity == 0){
		image.style.display = 'none';
	}
}

/* fade() will fade the image in or out based on the starting
   and ending opacity settings.  The speed of the fade is 
   determined by the variable milli (total time of the fade
   in milliseconds)*/
function fade(el,milli,start,end) {
	var fadeTime = Math.round(milli/100);
	
	var i = 0;  // Fade Timer
	// Fade in
	if(start < end) {
		for(j = start; j <= end; j++) {
			// define the expression to be called in setTimeout()
			var expr = "changeOpacity('" + el + "'," + j + ")";
			var timeout = i * fadeTime;
			// setTimeout will call 'expr' after 'timeout' milliseconds
			setTimeout(expr,timeout);
			i++;
		}
	}
	// Fade out
	else if(start > end) {
		for(j = start; j >= end; j--) {
			var expr = "changeOpacity('" + el + "'," + j + ")";
			var timeout = i * fadeTime;
			setTimeout(expr,timeout);
			i++;
		}
	}
} 

// NOT USED:


function open_edit_user(type, screen_id, id){
	
	var styleattr=document.createAttribute("class");
		
  /* empty all the selections for default */

	/* q1 */
	document.getElementById('editeduser_id').value = '';
	document.edit_user_form.q1.value = '';

	/* q2 rooli */
	for (i = 0; i < document.edit_user_form.q2.length; i++){
		document.edit_user_form.q2[i].checked = false;
	}

	/* q3 tyhjenn\u00E4 toimipaikat */
	for (i = 0; i < window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet.length; i++){
		window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet[i].checked = false;
	}
	
	document.edit_user_form.q3.value = '';

	if(type == 'edit'){		
		document.getElementById('editeduser_id').value = id;
		styleattr.nodeValue="popup_panel red"
      document.getElementById(screen_id).setAttributeNode(styleattr);
		document.edit_user_form.q1.value = document.forms[id].nimi.value;

		for (i = 0; i < document.edit_user_form.q2.length; i++){
			if (document.edit_user_form.q2[i].value == document.forms[id].tyyppi.value){
				document.edit_user_form.q2[i].checked = true;
			}
		}

		var user_toimipisteet=(document.forms[id].toimipisteet.value).split(",");

		for (x=0; x<user_toimipisteet.length; x++){

			for (i = 0; i < window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet.length; i++){
				if (window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet[i].value == user_toimipisteet[x]){
					window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet[i].checked = true;
					/*alert('num='+window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet.length+', cur_row='+window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet[i].value+' comp val = '+user_toimipisteet[x]);*/
				}
			}
		}
		document.edit_user_form.q3.value = document.forms[id].toimipisteet.value;
		document.getElementById('submit_for_user').setAttribute('name','user_edited');

	}else{
		styleattr.nodeValue="popup_panel green"
      document.getElementById(screen_id).setAttributeNode(styleattr);

		document.getElementById('submit_for_user').setAttribute('name','user_added');
	}
	document.getElementById(screen_id).style.display='block';
}


function edit_user(form){

	var categories = new Array();
	for (var i=0; i < window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet.length; i++){
		if(window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet[i].checked){
			// populate array with checked values:
			categories[categories.length] = window.frames['toimipistelistaus'].document.toimipiste_valinnat.toimipisteet[i].value;
		}
	}
	//change array to a string for sending via form:
	var categoryvalues = categories.toString();
	document.edit_user_form.q3.value = categoryvalues;
	//alert(document.edit_user_form.q3.value);
	
	return true;
	document.getElementById('editscreen').style.display='none'
    }

function edit_toimipaikka(form){
	document.getElementById('submit_for_toimipaikka').setAttribute('name','toimipaikka_added');
}

function flipArrow(id){

	var img = document.getElementById(id);
	var filepath = img.src;

	if (filepath.match('arrow_right_white.gif')) {
		filepath = filepath.replace("arrow_right_white.gif", "arrow_down_white.gif");
	} else {
		filepath = filepath.replace("arrow_down_white.gif", "arrow_right_white.gif");
	}

	img.src = filepath;
}

function textContent(element) {
  if (element != null) {
    if (element.textContent != undefined) { // supports textContent
      return element.textContent;
    } else if (element.innerText != undefined) { // supports innerText
      return element.innerText;
    } else { // only standard, use recursion
      var txt = "";
      for(var i=0; i<pNode.childNodes.length;i++) {
		var cn = pNode.childNodes[i];
		if(cn.nodeName=="#text") {
		  txt += cn.nodeValue;
		} else {
		  txt += textContent(cn);
		}
	  }
	  return txt;
	}
  }
}

var usedDietColors = new Array();

function editDiet(elementOnRow) {

  var editor = document.getElementById("editscreen_erityisruokavaliot");
  
  var forms = editor.getElementsByTagName("form");
 
  document.getElementById('delete_for_diettype').style.display = "block";
  var styleattr=document.createAttribute("class");
  styleattr.nodeValue="popup_panel red";
  editor.setAttributeNode(styleattr);

  document.getElementById('editscreen_erityisruokavaliot_type_text').innerHTML = 'muokkaaminen';
    //alert("Element: " + elementOnRow);
    
   // if (!usedDietColors || usedDietColors.length == 0) {
   //     //alert("dietColors init");
   //     initColorSamples(usedDietColors, "diet_colors", "color_sample_used");
   // }
   // var cells = getRow(elementOnRow).cells;
   // updateColorSamples(textContent(cells[2]), "diet_colors", "color_sample", textContent(cells[cells.length-1]), usedDietColors);
     editParameter(elementOnRow, "editscreen_erityisruokavaliot", "id,abbrev,description,");

    
}

// gets all used colors inside container, removes them from the DOM
function initColorSamples(usedArray, containerId, className) {
	/*
    if (!usedArray) {
        usedArray = new Array();
    }
    // get all colors from elements in class color_sample_used and remove them from the document
    var usedColorElements = getElementsByClassName(document.getElementById(containerId), new RegExp('\\b'+className+'\\b'), null);
    for ( var i = 0; i < usedColorElements.length; i++ ) {
        usedArray.push(usedColorElements[i].getElementsByTagName("INPUT")[0].value);
        usedColorElements[i].parentNode.removeChild(usedColorElements[i]);
    }
    //alert("initColorSamples finished, found "+usedColorElements.length+" used colors");
    */
}

// hides all used colors except for the given activeColor, which it selects. If activeColor is null, first color is selected.
// also sets the text inside the color boxes to the parameter's abbreviation (i.e. the provided text param)
function updateColorSamples(text, containerId, className, activeColor, usedArray) {
/*
    //alert("updateColorSamples called, active color is "+activeColor+", className is "+className+", container id is "+containerId+", called by "+updateColorSamples.caller);
    if (text == null || text == "") {
        text = "&nbsp;";
    }
    // hide all elements in given class that have a color that's in the given array
    if (!document.getElementById(containerId)) {
        //alert("Container not found");
    }
    var colorElements = getElementsByClassName(document.getElementById(containerId), new RegExp('\\b'+className+'\\b'), null);
    //var colorElements = getElementsByClassName(document.getElementById(containerId), new RegExp("(^|\\\\s)" + className + "(\\\\s|$)"), null);
    if(!colorElements) {
        //alert("element array is null");
    } else if(colorElements.length == 0) {
        //alert("No elements found with class "+className);
    } else {
        //alert(colorElements.length + " color elements found");
    }
    var useDefault = true;
    //for (i in colorElements) {
    for (var i = 0; i < colorElements.length; i++) {
        //alert("Class: "+colorElements[i].className);
        //alert(colorElements[i].getElementsByTagName("INPUT").length);
        //break;
        var elementInput = colorElements[i].getElementsByTagName("INPUT")[0];
        var elementColor = elementInput.value;
        
        colorElements[i].getElementsByTagName("SPAN")[0].innerHTML = text;
        if (elementColor == activeColor) {
            useDefault = false;
            // unselect default color
            //colorElements[0].getElementsByTagName("INPUT")[0].checked = false;
            // select input
            elementInput.checked = true;
            elementInput.disabled = false;
            // unhide element
            colorElements[i].style.display = "block";
        } else if (contains(usedArray, elementColor)) {
            //alert("Hiding color "+elementColor+" as used");
            colorElements[i].style.display = "none";
            elementInput.checked = false;
            elementInput.disabled = true;
        } else {
            elementInput.checked = false;
            elementInput.disabled = false;
            colorElements[i].style.display = "block";
        }
    }
    if(useDefault) {
        colorElements[0].getElementsByTagName("INPUT")[0].checked = true;
        colorElements[0].getElementsByTagName("INPUT")[0].disabled = false;
    }
    //alert("updateColorSamples finished");
    //alert("updateColorSamples done");
    */
}

function updateColorSamplesText(text, containerId, className) {
    var colorElements = getElementsByClassName(document.getElementById(containerId), new RegExp('\\b'+className+'\\b'), null);
    for (var i = 0; i < colorElements.length; i++) {
        colorElements[i].getElementsByTagName("SPAN")[0].innerHTML = text;
    }
    //alert("updateColorSamplesText done");
}

function newDietType(editorId) {
	var forms = document.getElementById(editorId).getElementsByTagName("form");

	//resetDietErrors(forms[0]);

	newParameter(editorId);
	
	document.getElementById('delete_for_diettype').style.display = 'none';
        if (!usedDietColors || usedDietColors.length == 0) {
        //alert("dietColors init");
        initColorSamples(usedDietColors, "diet_colors", "color_sample_used");
    }
    // (text, containerId, className, activeColor, usedArray) 
    updateColorSamples("", "diet_colors", "color_sample", null, usedDietColors);
    //disableSubmit('submit_for_diettype');
}

function contains(sourceArray, value) {
    for (v in sourceArray) {
        if (sourceArray[v] == value) {
            return true;
        }
    }
    return false;
}

/*
var counter = new Array();

function something(input) {
	if (counter[input] == null) {
		counter[input] = 1;
      	} else {
        	counter[input]++;
      	}
}
*/

