var mywindow;
var test1;
var field_reference;
var save_image;
var save_directory;
var current_image=0;
var last_image_menu;
var last_image_obj;
var last_image_field;
var image_copy;
var image_copy_src;
var image_copy_id;
var image_list;
var image_info;
var image_upload;
var image_td;

function copy_clip(meintext)
{

 if (window.clipboardData) 
   {
   
   // the IE-way
   window.clipboardData.setData("Text", meintext);
   
   // Probabely not the best way to detect netscape/mozilla.
   // I am unsure from what version this is supported
   }
   else if (window.netscape) 
   { 
  // dit is belangrijk maar staat nergens duidelijk vermeld:
   // you have to sign the code to enable this, or see notes below 
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   
   // maak een interface naar het clipboard
   var clip = Components.classes['@mozilla.org/widget/clipboard;1']
                 .createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return;
   
   // maak een transferable
   var trans = Components.classes['@mozilla.org/widget/transferable;1']
                  .createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;
   
   // specificeer wat voor soort data we op willen halen; text in dit geval
   trans.addDataFlavor('text/unicode');
   
   // om de data uit de transferable te halen hebben we 2 nieuwe objecten 
   // nodig om het in op te slaan
   var str = new Object();
   var len = new Object();
   
   var str = Components.classes["@mozilla.org/supports-string;1"]
                .createInstance(Components.interfaces.nsISupportsString);
   
   var copytext=meintext;
   
   str.data=copytext;
   
   trans.setTransferData("text/unicode",str,copytext.length*2);
   
   var clipid=Components.interfaces.nsIClipboard;
   
   if (!clip) return false;
   
   clip.setData(trans,null,clipid.kGlobalClipboard);
   }
   return false;
}

function restart(value)
{
	document.forms[0].elements[field_reference].value = value;
	mywindow.close();
	save_image.src = '/images/' + save_directory +'/small/' + value;
}

function newWindow(event, image, field, directory) {
}

function addSrcToDestList(src,dst,dst2) {
   // var srcList = document.getElementById(src);
	i = 0;
	if(document.forms.length > 1) {
		i = document.forms.length - 1;
	}
   var srcList = document.forms[i].elements[src];
   var destList = document.forms[i].elements[dst];
   var destList2 = document.forms[i].elements[dst2];
   var len = destList.length;
   var insert = len;
   for(var i = 0; i<destList.length; i++) {
      if ((destList.options[i] != null) && (destList.options[i].selected)) {
			insert = i;
		}
	}
   for(var i = 0; i<srcList.length; i++) {
      if ((srcList.options[i] != null) && (srcList.options[i].selected)) {
      //Check if this value already exist in the destList or not
         //if not then add it otherwise do not add it.
         var found = false;
         for(var count = 0; count < len; count++) {
            if (destList.options[count] != null) {
               if(srcList.options[i].value == destList.options[count].value) {
                  found = true;
                  break;
               }
            }
         }
         if(found != true) {
				if(insert != len) {
					for(j=len; j>insert && j>0; j--) {
						if(j == len) {
            		 	destList.options[j] = new Option(destList.options[j-1].text, destList.options[j-1].value);
            		 	destList2.options[j] = new Option(destList2.options[j-1].text, destList2.options[j-1].value);
            		 	destList2.options[j].selected = true;
						}
						else {
            		    destList.options[j].text   = destList.options[j-1].text;
            		    destList.options[j].value  = destList.options[j-1].value;
            		    destList2.options[j].text  = destList2.options[j-1].text;
            		    destList2.options[j].value = destList2.options[j-1].value;
						}
					}
                destList.options[insert].text = srcList.options[i].text;
                destList.options[insert].value = srcList.options[i].value;
            	 destList.options[insert].selected = true;
                destList2.options[insert].text = srcList.options[i].text;
                destList2.options[insert].value = srcList.options[i].value;
            	 destList2.options[insert].selected = true;
				}
				else {
            	destList.options[insert] = new Option(srcList.options[i].text, srcList.options[i].value);
            	destList2.options[insert] = new Option(srcList.options[i].text, srcList.options[i].value);
            	destList2.options[insert].selected = true;
				}
            len++;
            insert++;
         }
      }
   }
}

function deleteFromDestList(src,dest,dest2) {
	if(document.forms.length > 1) {
		i = document.forms.length - 1;
	}
   var srcList = document.forms[i].elements[src];
   var destList = document.forms[i].elements[dest];
   var destList2 = document.forms[i].elements[dest2];
   var len = destList.options.length;
   var len2 = srcList.options.length;
   for(var i = 0; i < len2; i++) {
        srcList.options[i].selected = false;
	}
   for(var i = 0; i < len2; i++) {
   	for(var j = 0; j < len; j++) {
      	if(destList.options[j].value == srcList.options[i].value && destList.options[j].selected == true) {
        		srcList.options[i].selected = true;
			}
		}
	}
   for(var i = (len-1); i >= 0; i--) {
      if((destList.options[i] != null) && (destList.options[i].selected == true)) {
         destList.options[i] = null;
         destList2.options[i] = null;
      }
   }
}

function saveImage(image)
{
	opener.restart(image);
}

function if_thumbnail_menu(obj)
{
	var menu, image, field;
	if(image_upload) {
		image_upload.style.display = "none";
	}
	if(image_td) {
		image_td.style.paddingBottom = "";
	}
	if(image_info) {
		image_info.style.display = "none";
	}
	if(obj) {
		for(i=0; i<obj.childNodes.length; i++) {
			image_td = obj;
      	// alert(obj.childNodes[i].nodeType + ':' + obj.childNodes[i].nodeName);
			if(obj.childNodes[i].nodeName == 'TABLE') {
				menu = obj.childNodes[i];
				if(menu == last_image_menu) {
					if_thumbnail_menu_hide(); // This function clear last_image_menu - don't change
					return;
				}
			}
			if(obj.childNodes[i].nodeName == 'IMG') {
				image = obj.childNodes[i];
			}
			if(obj.childNodes[i].nodeName == 'INPUT' && obj.childNodes[i].getAttribute('id') == 'image-id') {
				field = obj.childNodes[i];
			}
			if(obj.childNodes[i].nodeName == 'DIV' && obj.childNodes[i].getAttribute('id') == 'image-info') {
				image_info = obj.childNodes[i];
// alert("UPLOAD " + obj.childNodes[i].getAttribute('id'));
			}
			if(obj.childNodes[i].nodeName == 'DIV' && obj.childNodes[i].getAttribute('id') == 'upload') {
				image_upload = obj.childNodes[i];
// alert("UPLOAD");
			}
   	}
	}

	if_thumbnail_menu_hide();

	// alert(menu + image + field);
	// return;

	if(menu) {
		// menu.value = 'inline';
		if(image.x) {
			 menu.style.left = image.x - 108;
		}
		else {
			menu.style.left = findPosX(image) - 108;
			// menu.style.left -= 108;
		}
		menu.style.display = 'block';
	}
	last_image_menu = menu;
	last_image_obj = image;
	last_image_field = field;
}

function if_thumbnail_menu_hide()
{
	if(image_info) {
		image_info.style.display = "none";
	}
	if(last_image_menu) {
		last_image_menu.style.display = 'none';
		last_image_menu = 0;
		if(image_upload) {
			image_upload.style.display = "none";
		}
		if(image_td) {
			image_td.style.paddingBottom = "";
		}
	}
}

function if_thumbnail_select_mouse_down(obj)
{
	obj.style.borderTopColor = '#999999';
	obj.style.borderBottomColor = '#FFFFFF';
}

function if_thumbnail_select_mouse_up(obj)
{
	obj.style.borderTopColor = '#FFFFFF';
	obj.style.borderBottomColor = '#999999';
}

function if_thumbnail_select(obj)
{
	if(obj.style.color) {
		obj.style.color = '';
		obj.style.background = '';
		obj.style.borderTopColor= '';
		obj.style.borderBottomColor = '';
	}
	else {
		obj.style.color = '#000000';
		obj.style.background = '#DDDDDD';
		obj.style.borderTopColor = '#FFFFFF';
		obj.style.borderBottomColor = '#999999';
	}
}

function if_section_handler(img, id)
{
	div = img.parentElement;
	none = "none";
	obj = document.getElementById(id);
	if(obj) {
		if(obj.style.display == 'none') {
			img.src = "/graphics/form_arrow_open.gif";
			none = "block";
		}
		else {
			img.src = "/graphics/form_arrow_closed.gif";
		}
	}
	while(div) {
		div = div.nextSibling;
		 alert(div.nodeName + ':' + div.className  + ':' + div.nodeValue);
		if(div.className == 'infolab-title') {
			break;
		}
		div.style.display = none;
	}
	return;
}

function if_image_cut()
{
	if(last_image_obj) {
		image_copy_src = last_image_obj.src;
		image_copy_id = last_image_field.value;
		last_image_field.value = '';
		last_image_obj.src = '/graphics/dummy.gif';
		image_info.innerHTML = '';
		image_info.style.display = 'none';
		createCookie('image_copy_id', image_copy_id, 1);
		createCookie('image_copy_src', image_copy_src, 1);
	}
}

function if_image_paste()
{
	image_copy_src = readCookie('image_copy_src');
	image_copy_id = readCookie('image_copy_id');
	if(image_copy_src) {
		last_image_obj.src = image_copy_src;
		last_image_field.value = image_copy_id;
		image_info.innerHTML = '';
	}
}

function if_image_copy()
{
	image_copy_src = last_image_obj.src;
	image_copy_id = last_image_field.value;
	// copy_clip('/images/large/' + last_image_field.value + '.jpg');
	createCookie('image_copy_id', image_copy_id, 1);
	createCookie('image_copy_src', image_copy_src, 1);
}

function if_image_next()
{
	if(image_info) {
		image_info.style.display = 'block';
	}
	if(image_list) {
		if(image_list.length) {
			current_image++;
   		if(current_image >= image_list.length) {
      		current_image = --current_image;
   		}
   		last_image_obj.src = '/images/small/' + image_list[current_image].id + '.jpg';
			last_image_field.value = image_list[current_image].id;
			n = current_image + 1;
			image_info.innerHTML = n + " of " + image_list.length;
		}
	}
}

function if_image_prev()
{
	if(image_list) {
		if(image_list.length) {
			current_image--;
   		if(current_image < 0) {
      		current_image = 0;
   		}
   		last_image_obj.src = '/images/small/' + image_list[current_image].id + '.jpg';
			last_image_field.value= image_list[current_image].id;
			n = current_image + 1;
			image_info.innerHTML = n + " of " + image_list.length;
		}
	}
}

function if_image_first()
{
	if(image_info) {
		image_info.style.display = 'block';
	}
	if(image_list) {
		if(image_list.length) {
   		current_image = 0;
   		last_image_obj.src = '/images/small/' + image_list[current_image].id + 'jpg';
			last_image_field.value= image_list[current_image].id;
			image_info.innerHTML = "1 of " + image_list.length;
		}
	}
}

function if_image_last()
{
	if(image_info) {
		image_info.style.display = 'block';
	}
	if(image_list) {
		if(image_list.length) {
			current_image = image_list.length - 1;
   		last_image_obj.src = '/images/small/' + image_list[current_image].id + '.jpg';
			last_image_field.value= image_list[current_image].id;
			image_info.innerHTML = image_list.length + " of " + image_list.length;
		}
	}
}

function if_image_new()
{
	// alert("New " + image_td.style.marginBottom);
	image_td.style.paddingBottom = "35px";
	image_upload.style.display = "block";
	if(image_info) {
		image_info.style.display = 'none';
	}
	// window.location = "?factory=db&menu=channel&channel=60";
}

function if_image_edit()
{
	if(last_image_field.value) {
		window.location = "?factory=db&menu=channel&channel=60&image_id=" + last_image_field.value;
	}
}

function if_image_find(e, s)
{
	if(image_upload) {
		image_upload.style.display = "none";
	}
	if(window.event) {
		var e = window.event;
	}
	else if(e.keyCode == 13) {
		e.returnValue=false; 
		e.preventDefault(); 
		e.stopPropagation(); 
	}
	if(e.keyCode != 13) {
		return(true);
	}

	http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = alertContents;
	http_request.open('GET', '/index.php?factory=db&menu=image_find&search_string=' + s, true);
	http_request.send(null);

	return(false);
}

function alertContents()
{
	var j=0,len=0,n=0;

	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			var root_node = xmldoc.getElementsByTagName('root').item(0);
			var row_node=root_node.getElementsByTagName('row');
			len = row_node.length;
			image_list = new Array(len);
			for(i=0; i<len; i++) {
				if(row_node.item(i).childNodes.length != 3) {
					continue;
				}
				var id = row_node.item(i).childNodes[0].childNodes[0].nodeValue;
				if(id) {
					image_list[j] = new Object();
					image_list[j].id = id;
					image_list[j].directory = row_node.item(i).childNodes[1].childNodes[0].nodeValue;
					// image_list[j].file = row_node.item(i).childNodes[2].childNodes[0].nodeValue;
					if(j == 0) {
						last_image_obj.src = src = '/images/small/' + image_list[j].id + '.jpg';
						last_image_field.value= image_list[i].id;
						current_image = 0;
						image_info.innerHTML = "1 of " + len;
						image_info.style.display = 'block';
					}
					j++;
				}
			}
		} else {
			alert('There was a problem with the request.');
		}
	}
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

var sum_month = new Array(13);
var sum_person = new Array();
var sum_project = new Array();

function sum_used_update(month, row, value)
{
	hours_total = 0;
	hours_total_project = 0;
	year_total = 0;
	sum_project[month][row] = value;
	sum_month[month][row] = value;
	for(i=1; i<=12; i++) {
		hours_total_project += Number(sum_project[i][row]);
	}
	for(i=1; i<sum_month[month].length; i++) {
		hours_total += Number(sum_month[month][i]);
	}
	object = document.getElementById("sum_project_total[" + row + "]");
	object.innerHTML = hours_total_project;
	object = document.getElementById("sum_month_total[" + month + "]");
	object.innerHTML = hours_total;
	for(i=1; i<=12; i++) {
		object = document.getElementById("sum_month_total[" + i + "]");
		year_total += Number(object.innerHTML);
	}
	object = document.getElementById("total_year");
	object.innerHTML = year_total;
}

function sum_month_update(month, row, value)
{
	hours_total = 0;
	hours_total_person = 0;
	year_total = 0;
	sum_person[month][row] = value;
	sum_month[month][row] = value;
	for(i=1; i<=12; i++) {
		hours_total_person += Number(sum_person[i][row]);
	}
	for(i=1; i<sum_month[month].length; i++) {
		hours_total += Number(sum_month[month][i]);
	}
	object = document.getElementById("sum_person_total[" + row + "]");
	object.innerHTML = hours_total_person;
	object = document.getElementById("sum_month_total[" + month + "]");
	object.innerHTML = hours_total;
	for(i=1; i<=12; i++) {
		object = document.getElementById("sum_month_total[" + i + "]");
		year_total += Number(object.innerHTML);
	}
	object = document.getElementById("total_year");
	object.innerHTML = year_total;
}
