//*** AJAX variables ************
var httpMeasureSelect;
var httpCleanupSelect;
var httpPrepSelect;
var httpIngrSelect;
var httpPicture;
var httpGradeCategories;
var httpGeneric;
//*******************************


function printing(){
	setTimeout("window.print()",1000);
}

// This function toggles the display property of the div id
function toggleLayer(vLayerId){
	var vObj
	if (document.getElementById){
		vObj = document.getElementById(vLayerId).style;
	}
	else if (document.all){
		vObj = document.all[vLayerId].style;
	}
	else if (document.layers){
		vObj = document.layers[vLayerId].style;
	}
	if (vObj){
		vObj.display = vObj.display? "":"block";
	}
}

// kindly borrowed from http://www.quirksmode.org/js/events_mouse.html
// The fuction checks if the mouse has left the top parent div
function checkMouseOut(e, html_post){
	
	var html_posting = html_post;
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	if (tg.nodeName != 'DIV') return;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg != tg && reltg.nodeName != 'BODY')
		reltg= reltg.parentNode
	if (reltg== tg) return;
	
	showGenericNoLoad(html_post);
}

function setIdToDelete(id,fieldToChange){
	fieldToChange.value = id;
	return;
}

function changeFormAction(actionText,formToChange){
	if(formToChange=="") { 
		formToChange = document.forms[0];
	}
	//formToChange = document.getElementById(formToChange);
//	formToChange = document.getElementById("phase2_form");
//alert(document.forms[0].getAttribute("action"));
//alert(formToChange.title);
//alert(actionText);
//	formToChange.action = actionText;
	formToChange.setAttribute("action",actionText);
//a  = document.forms[0];
//b  = document.forms[1];
//alert("0 = "+a.getAttribute("action"));
//alert("1 = "+b.getAttribute("action"));
//b.action = actionText;
//alert(document.forms[0].getAttribute("action"));	
	formToChange.submit();
}

function enableIngredientEditing(measureElement,cleanupElement,preparationElement){
	measureElement.disabled=false;
	cleanupElement.disabled=false;
	preparationElement.disabled=false;
	return;
}

function disableIngredientEditing(measureElement,preparationElement){
	measureElement.disabled=true;
	preparationElement.disabled=true;
	return;
}

function updateTimeTotal() {	//adds the working time to the preparation time enterede for a recipe, and shows it in div (id=time_total)
	document.getElementById('time_total_calculated').innerHTML = document.getElementById('working_time').value*1 + document.getElementById('prep_time').value*1;
	return;
}

function numbersOnly(txtElement) {	//called on event onKeyUp; allows only numbers to be entered
	var allowedChars = '0123456789';
	var strLength = txtElement.value.length;
	var newChar = txtElement.value.charAt((strLength) - 1);
	if(allowedChars.indexOf(newChar) == "-1") {
		txtElement.value = txtElement.value.substring(0, (strLength) - 1);
   }
}


function getBrowser() {
	if (document.all)
		var version=/MSIE \d+.\d+/
	
	if (!document.all)
		browser_info = navigator.appName+navigator.userAgent;
	else
		browser_info = navigator.appName+navigator.appVersion.match(version);
	if(browser_info.indexOf('Firefox') > -1) return 'Firefox';		
	if(browser_info.indexOf('Explorer') > -1) return 'Internet Explorer';
	if(browser_info.indexOf('Opera') > -1) return 'Opera';
	if(browser_info.indexOf('Safari') > -1) return 'Safari';		
}

function popUp(url) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=1020,height=700,left = 80,top = 80');");
}

function popUpListAndPrint(url) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(url, 'page" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=250,height=500,left = 80,top = 80');");
//	eval("page" + id +".document.location.href='"+url+"';")
//	eval("page" + id +".document.write('"+url+"');")
//	eval("page" + id +".print();")
//	eval("window('"+id+"').print();");
//	eval("page"+id+".window.print();");
//	self.print();
}

// ***************************************************************************************************************
// ***** AJAX CODE ***********************************************************************************************
// ***************************************************************************************************************
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    
    /*
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
*/
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else if(window.XMLHttpRequest) {
        ro = new XMLHttpRequest();
    }else{
    	ro = new ActiveXObject("Microsoft.XMLHTTP");
    }
//alert (window.XMLHttpRequest);
    return ro;


/*
	var ro;
	ro = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	return ro;
*/
}
//***************************************************************************************************************

function updateMeasureSelect(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the dummy option is selected
    httpMeasureSelect = createRequestObject();
    httpMeasureSelect.open('post', 'ajax.php?'+html_post);
    httpMeasureSelect.onreadystatechange = handleResponseMeasureSelect;
    httpMeasureSelect.send(null);
}

function updateCleanupSelect(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the dummy option is selected
    httpCleanupSelect = createRequestObject();
    httpCleanupSelect.open('post', 'ajax.php?'+html_post);
    httpCleanupSelect.onreadystatechange = handleResponseCleanupSelect;
    httpCleanupSelect.send(null);
}

function updatePrepSelect(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the dummy option is selected
    httpPrepSelect = createRequestObject();
    httpPrepSelect.open('post', 'ajax.php?'+html_post);
    httpPrepSelect.onreadystatechange = handleResponsePrepSelect;
    httpPrepSelect.send(null);
}

function updateIngrSelect(ingredient_id,mode,ingredient_number,select_name,ingredient_menu_level) {
    httpIngrSelect = createRequestObject();
    httpIngrSelect.open('post', 'ajax.php?mode='+mode+'&ingredient_id='+ingredient_id+'&ingredient_number='+ingredient_number+'&select_name='+select_name+'&ingredient_menu_level='+ingredient_menu_level);
	httpIngrSelect.onreadystatechange = handleResponseIngrSelect;
    httpIngrSelect.send(null);
}

function showPicture(picture_id,mode,div_name) {
    if(picture_id=="") return; 	//ensure that no update takes place if the link is incomplete
    httpPicture = createRequestObject();
    httpPicture.open('post', 'ajax.php?mode='+mode+'&picture_id='+picture_id+'&div_name='+div_name);
	httpPicture.onreadystatechange = handleResponsePicture;
    httpPicture.send(null);
}

function showGradeCategories(recipe_id,action) {
    httpGradeCategories = createRequestObject();
    httpGradeCategories.open('post', 'ajax.php?mode=grade_categories&action='+action+'&recipe_id='+recipe_id);
	httpGradeCategories.onreadystatechange = handleResponseGradeCategories;
    httpGradeCategories.send(null);
}

//this function should be used for all ajax updates. The html_post variable defines all parameters to be send through POST and received by ajax.php
function showGeneric(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the link is incomplete
		//alert(html_post);
    httpGeneric = createRequestObject();
    httpGeneric.open('post', 'ajax.php?'+html_post);
		httpGeneric.onreadystatechange = handleResponseGeneric;
    httpGeneric.send(null);
}

// This function is identical to the above, except that no load layer is shown 
function showGenericNoLoad(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the link is incomplete
		//alert(html_post);
    httpGeneric = createRequestObject();
    httpGeneric.open('post', 'ajax.php?'+html_post);
	httpGeneric.onreadystatechange = handleResponseGenericNoLoad;
    httpGeneric.send(null);
}

function showToolbox(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the link is incomplete
//alert(html_post);
    httpGeneric = createRequestObject();
    httpGeneric.open('post', 'ajax_toolbox.php?'+html_post);
	httpGeneric.onreadystatechange = handleResponseGeneric;
    httpGeneric.send(null);
}

function updateHelpPosition(html_post) {
    if(html_post=="") return; 	//ensure that no update takes place if the link is incomplete
		//alert(html_post);
    httpGeneric = createRequestObject();
    httpGeneric.open('post', 'ajax.php?'+html_post);
		httpGeneric.onreadystatechange = handleUpdateHelpPosition;
    httpGeneric.send(null);
}

//***************************************************************************************************************

function handleUpdateHelpPosition(){
	if(httpGeneric.readyState == 4){
		var response = httpGeneric.responseText;
		//alert(response);
	}
}

function handleResponseMeasureSelect() {
    if(httpMeasureSelect.readyState == 4){
		var response = httpMeasureSelect.responseText;
		var update = new Array();

		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)

			//change the content of the element
			document.getElementById(update[0]).innerHTML = update[1];
		}
    }
}

function handleResponseCleanupSelect() {
    if(httpCleanupSelect.readyState == 4){
		var response = httpCleanupSelect.responseText;
		var update = new Array();

		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)

			//change the content of the element
			document.getElementById(update[0]).innerHTML = update[1];
		}
    }
}

function handleResponsePrepSelect() {
    if(httpPrepSelect.readyState == 4){
		var response = httpPrepSelect.responseText;
		var update = new Array();

		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)

			//change the content of the element
			document.getElementById(update[0]).innerHTML = update[1];
		}
    }
}

function handleResponseIngrSelect() {
    if(httpIngrSelect.readyState == 4){
		var response = httpIngrSelect.responseText;
		var update = new Array();

		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)

			//change the content of the element
			document.getElementById(update[0]).innerHTML = update[1];
		}
    }
}

function handleResponsePicture() {
    if(httpPicture.readyState == 4){
		var response = httpPicture.responseText;
		var update = new Array();

		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)

			//change the content of the div
			document.getElementById(update[0]).innerHTML = update[1];
		}
    }
}

function handleResponseGradeCategories() {
    if(httpGradeCategories.readyState == 4){
		//change the content of the div
		document.getElementById("recipe_grade_categories").innerHTML = httpGradeCategories.responseText;
    }
}

function XXXhandleResponseGeneric() {
    if(httpGeneric.readyState == 4){
		var response = httpGeneric.responseText;
		var update = new Array();

		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)

		//alert(update[0]);
			//change the content of the div
			document.getElementById(update[0]).innerHTML = update[1];
		}
    }
}

//test af multiple div-opdateringer
function handleResponseGeneric(vLoad) {
		//alert(httpGeneric.readyState);
    if(httpGeneric.readyState == 4){
    	elem = document.getElementById('load_container').style;
			elem.visibility = 'hidden'; //added to get rid of load div box blocking for underlying elements //AKM 020906
			//document.getElementById('load_container').innerHTML = '';

			var response = httpGeneric.responseText;
			var update = new Array();
		
			
			//alert(response);
			if(response.indexOf('||') != -1) {
				update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)
				
				//alert(update[0]);
				//alert(update[1]);
				
	
				for(i=0;i<update.length;i++){
					//change the content of the div
					document.getElementById(update[i]).innerHTML = update[i+1];
					i++;
				}
			}
    }
    else {
    	showLoad(httpGeneric.readyState);
    }
}

// this is the same as above, except that no load is shown
function handleResponseGenericNoLoad(vLoad) {
		//alert(httpGeneric.readyState);
  if(httpGeneric.readyState == 4){

  	elem = document.getElementById('load_container').style;
		elem.visibility = 'hidden'; //added to get rid of load div box blocking for underlying elementsw //AKM 020906
//		document.getElementById('load_container').innerHTML = '';

		var response = httpGeneric.responseText;
		var update = new Array();
	
		
		//alert(response);
		if(response.indexOf('||') != -1) {
			update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)
		
			for(i=0;i<update.length;i++){
				//change the content of the div
				document.getElementById(update[i]).innerHTML = update[i+1];
				i++;
			}
		}
	}
}

/*
//test af multiple div-opdateringer
function handleResponseGeneric(vLoad) {
   
			var response = httpGeneric.responseText;
			var update = new Array();
					
			if(response.indexOf('||') != -1) {
				update = response.split('||'); //the id of the element is stored before the '||' (returned from ajax.php)
				for(i=0;i<update.length;i++){
					//change the content of the div
					if(httpGeneric.readyState < 4){
						document.getElementById(update[i]).innerHTML = httpGeneric.readyState*25+'%';
					}
					else{
						document.getElementById(update[i]).innerHTML = update[i+1];
						i++;
					}
				}
			}
}
*/

// shows the load sequence
/*function showLoad(vLevel){
		httpLoad = createRequestObject();
		httpLoad.open('post','load.php?level='+vLevel);
		httpLoad.onreadystatechange = handleLoad;
		httpLoad.send(null);
		
}

// handles the load communication with serverside script
function handleLoad(){
		alert(httpLoad.readyState+' '+httpGeneric.readyState
		if(httpLoad.readyState == 4){
				var response = httpLoad.responseText;
				var update = new Array();
			
				if(response.indexOf('||') != -1){
						update = response.split('||');
						
						document.getElementById(update[0]).innerHTML = update[1];
				}
			}
		
}*/

function showLoad(vLevel){
		var vTop = screen.awailHeight/2;
		var vLeft = screen.width/2;
		
		elem = document.getElementById('load_container').style;
		
		/*************************************************/
		//NEW: Script ensures that the loading-div is always visible
    	if (browser.isIE) {
    		//do nothing	
    	}else{
			var scrollTop = document.body.scrollTop;
			if (scrollTop == 0) {
				if (window.pageYOffset)
					scrollTop = window.pageYOffset;
				else
					scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
			var posy = scrollTop + 120; 
			elem.marginTop = posy+'px';
		}
		/*************************************************/

		elem.height = '100px';
		elem.visibility = 'visible'; //ensures that load div is shown //AKM 020906
}

//***************************************************************************************************************
//***************************************************************************************************************
//***************************************************************************************************************

// Determine browser and version.
function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;
  
  //alert(dragObj.elNode.id);

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";
  
  //alert('left:'+dragObj.elNode.style.left+' top: '+dragObj.elNode.style.top);

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.
  
  /*
  if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;*/

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
 	//alert('left:'+dragObj.elNode.style.left+' top: '+dragObj.elNode.style.top);
  updateHelpPosition("mode=update_help_position&action="+dragObj.elNode.id+"&left="+dragObj.elNode.style.left+"&top="+dragObj.elNode.style.top);
}