/**************************************************************************\
	* Simple Groupware 0.700                                                   *
	* http://www.simple-groupware.de                                           *
	* Copyright (C) 2002-2011 by Thomas Bley                                   *
	* ------------------------------------------------------------------------ *
	*  This program is free software; you can redistribute it and/or           *
	*  modify it under the terms of the GNU General Public License Version 2   *
	*  as published by the Free Software Foundation; only version 2            *
	*  of the License, no later version.                                       *
	*                                                                          *
	*  This program is distributed in the hope that it will be useful,         *
	*  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
	*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            *
	*  GNU General Public License for more details.                            *
	*                                                                          *
	*  You should have received a copy of the GNU General Public License       *
	*  Version 2 along with this program; if not, write to the Free Software   *
	*  Foundation, Inc., 59 Temple Place - Suite 330, Boston,                  *
	*  MA  02111-1307, USA.                                                    *
	\**************************************************************************/

function ______G_E_N_E_R_A_L______() {}

function array_contains(arr, elem) {
  for (j=0;j<arr.length;j++) if(arr[j]==elem) return true;
  return false;
}

function generate_password(field) {
  var keys = "abcdefghijklmnopqrstuvwxyz1234567890@";
  var temp = "";
  for (i=0;i<8;i++) {
    temp += keys.charAt(Math.floor(Math.random()*keys.length));
  }
  sys_alert("{t}The new password is{/t}: " + temp);
  getObj(field).value = temp;
  getObj(field+"_confirm").value = temp;
}

function ______O_T_H_E_R_S______() {}

function resize_obj(id,size) {
  var obj = getObj(id);
  if (!obj) return;
  if (obj.offsetHeight + size > 0) obj.style.height = (obj.offsetHeight + size)+"px";
}

function addupload(obj) {
  var elem = document.createElement('div');
  elem.innerHTML+='<input type="File" name="'+obj+'[]" style="width:45%;" value=""><br>';
  elem.style.paddingTop="2px";
  getObj(obj+"_div1").appendChild(elem);
}

function get_uid() {
  return (new Date()).getTime();
}

// see: https://developer.mozilla.org/en/Using_files_from_web_applications
function drop_upload(item_name,max_file_size,max_file_count,event) {
  var files = event.dataTransfer.files;
  if (!files || files.length==0) {
    files = new Array({size:0, url:true, name:event.dataTransfer.getData("Text")}); // drop URL
	if (!files[0].name) return;
  }
  var file_count = 0;
  var file_fields = document.getElementsByName(item_name+"[]");
  for (var i=0; i < file_fields.length; i++) {
    if (file_fields[i].files) file_count += file_fields[i].files.length;
	  else if (file_fields[i].value!="") file_count += 1;
  }
  if (max_file_count!="" && file_count + files.length > max_file_count) {
	sys_alert("{t}Upload failed{/t}: {t}maximum number of files exceeded.{/t} ("+max_file_count+")");
	return;
  }
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
	if (max_file_size > 0 && file.size > max_file_size) {
	  sys_alert("{t}Upload failed{/t}: {t}file is too big. Please upload a smaller one.{/t}");
	  return;
	}
	var callback = function(result) {
	  var id = get_uid();
	  var elem = document.createElement('div');
	  elem.innerHTML+='<input type="hidden" name="'+item_name+'[]" style="width:45%;" value="'+result.tmp_path+'">';
	  elem.innerHTML+='<input type="input" readonly="true" style="width:38%;" value=" '+result.basename+' ('+result.filesize+')">';
	  elem.innerHTML+='&nbsp;<a href="#" onclick="set_html(\''+id+'\',\'\'); return false;"><img src="ext/icons/empty.gif" title="{t}Delete{/t}"></a><br>';
	  elem.style.paddingTop="2px";
	  elem.id=id;
	  getObj(item_name+"_div3").appendChild(elem);
	};
	if (file.url) {
	  ajax("upload_file", [file.name], callback);
	} else {
	  ajax_binary("upload_file", file, [file.name], callback, function(event) {
		if (!event.lengthComputable) return;
		var percentage = Math.round((event.loaded * 100) / event.total);
		set_html(item_name+"_progress", (percentage!=100) ? "<br>{t}Uploading{/t}: "+file.name+": "+percentage+"%" : "");
	  });
} } }

function addupload_url(obj) {
  var elem = document.createElement('div');
  elem.innerHTML='<input type="text" name="'+obj+'_cust[]" value="" style="width:45%; margin-top:1px;">';
  getObj(obj+"_div2").appendChild(elem);
}

function form_submit() {
  obj = getObj("asset_form").getElementsByTagName("input");
  for (i=0; i<obj.length; i++) {
    if (obj[i].onsubmit) obj[i].onsubmit();
    if (obj[i].type=="password") {
	  var id = obj[i].id;
	  if (id.indexOf("_confirm")==-1 && getObj(id+"_confirm").value!=obj[i].value) {
		sys_alert(attr(id+"_confirm","rel")+": {t}password not confirmed.{/t}");
		return false;
  } } }
  obj = getObj("asset_form").getElementsByTagName("select");
  for (i=0; i<obj.length; i++) {
    if (obj[i].name.length>0 && obj[i].multiple) {
	  if (obj[i].options.length!=0) {
	    for (i2=0; i2<obj[i].options.length; i2++) obj[i].options[i2].selected = true;
	  } else {
	    var obj2 = document.createElement("input");
		obj2.name = obj[i].name.replace("[]","");
		obj2.style.display = "none";
		obj[i].parentNode.appendChild(obj2);
  } } }
  obj = getObj("asset_form").getElementsByTagName("textarea");
  for (i=0; i<obj.length; i++) {
    if (obj[i].className=="spreadsheet") {
	  obj[i].value = getObj(obj[i].id+"_iframe").contentWindow.cellsToJS();
	}
  }
  return true;
}

function form_submit_button(goback) {
  if (!form_submit()) return;
  if (goback) getObj("form_submit_return").value = "checked";
  getObj("form_submit_b").form.submit();
}

function show_freebusy(prefix) {
  var today = val(prefix+"begin");
  var users = getObj(prefix+"participants");
  var cals = "";
  if (users.options.length>0) {
    for (var i=0;i<users.options.length;i++) {
	  if (cals.length!=0) cals += ",";
      cals += "calendar_"+users.options[i].value;
    }
	getObj("pane").src="index.php?folder="+escape(tfolder)+"&view=freebusy&markdate=day&iframe=1&find=folders|simple_sys_tree||anchor="+escape(cals)+"&today="+today;
	change_tab('tab','general');
  } else sys_alert("{t}Please select a participant.{/t}");
}

function show_freebusy_location(prefix) {
  var today = val(prefix+"begin");
  var locs = val(prefix+"location");
  if (locs) {
	getObj("pane").src="index.php?view=freebusy&markdate=day&iframe=1&find=assets|simple_calendar||location="+escape(locs)+"&today="+today;
  } else sys_alert("{t}Please select a location.{/t}");
}

function ______G_U_I__L_O_O_K_U_P_S______() {}

function commit_from_popup(ticket,selectbox,values) {
  ajax("search_data", [ticket, '#', values], function(data) {
    for (key in data) {
	  if (getObj(selectbox).options) insert_into_selectbox(selectbox, data[key], key, 1);
	    else insert_into_textarea(selectbox,key);
	}
  });
}
function search_data(inputbox,selectbox) {
  getObj(selectbox).options.length = 0;
  ajax("search_data", [attr(inputbox,"rel"), val(inputbox)], function(data) {
    for (key in data) insert_into_selectbox(selectbox, data[key], key, 0);
  });
}
function refresh_data(ticket,selectbox) {
  ajax("search_data", [ticket, ""], function(data) {
    for (key in data) insert_into_selectbox(selectbox, data[key], key, 0);
  });
}

function insert_into_textarea(id,value) {
  var left = val(id);
  left = left.replace(/, /g,",");
  var left_arr = left.split(",");
  if (!array_contains(left_arr, value)) left_arr.push(value);
  left = left_arr.sort().join(", ");
  if (left.indexOf(", ")==0) left = left.substr(2);
  if (left.lastIndexOf(", ")==left.length-2) left = left.substr(0,left.length-2);
  getObj(id).value = left;
}

function insert_into_selectbox(selectbox,text,value,selectitem) {
  if (text=="") return;
  var obj = getObj(selectbox);
  var options = obj.options;
  var i=0;
  var insert_id = 0;
  if (options.length > 0) {
    for (i=0; i<options.length; i++) {
      if (options[i].value==value) {
	    if (selectitem) options[i].selected = true;
	    return;
	  }
    }
	for (i=options.length-1; i>=0; i--) {
	  if (value > options[i].value) {
		insert_id = i+1;
		break;
	  } else {
		options[i+1] = new Option(options[i].text,options[i].value);
	  }
	}
  }
  obj.options[insert_id] = new Option(text,value);
  if (selectitem) obj.options[insert_id].selected = true;
  if (selectitem && obj.size>1) {
	for (i=0; i<options.length; i++) options[i].selected = true;
  }
}

function additems(field) {
  var objs = document.getElementsByClassName(field+"_custom");
  for (var i=0; i<objs.length; i++) additem(field,objs[i]);
}

function additems_atcursor(field) {
  var objs = document.getElementsByClassName(field+"_custom");
  for (var i=0; i<objs.length; i++) additem_atcursor(field,objs[i]);
}

function additem(id,right) {
  // left: textarea
  if (right==null) return;
  if (typeof(getObj(id).options) == "undefined") {
    var options_right = right.options;
	if (options_right==null) {
	  insert_into_textarea(id,right.value);
	  right.value = "";
	} else {
      for (var i=0; i<options_right.length; i++) {
        if (options_right[i].selected) {
		  options_right[i].selected = false;
		  insert_into_textarea(id,options_right[i].value);
	} } }
  } else {
    // right: input
    if (typeof(right.options)=="undefined" && right.value!="") {
	  insert_into_selectbox(id,right.value,right.value,1)
  	  right.value = "";
	  return;
    }
    // right: select
    if (right.options==null) return;
    options_right = right.options;
    for (var i=0; i<options_right.length; i++) {
      if (options_right[i].selected) {
	    options_right[i].selected = false;
	    if (options_right[i].value=="---") continue;
	    insert_into_selectbox(id,options_right[i].text,options_right[i].value,1)
} } } }

function additem_atcursor(id,right) {
  var left = getObj(id);
  var options_right = right.options;
  if (options_right!=null) {
    for (var i=0; i<options_right.length; i++) {
      if (options_right[i].selected) {
		options_right[i].selected = false;
		if (left.selectionStart) {
		  left.value = left.value.substring(0,left.selectionStart)+options_right[i].value+"\n"+left.value.substring(left.selectionStart);
		} else {
		  left.value += "\n"+options_right[i].value;
  } } } }
  left.focus();
}

function removeitem(id) {
  var left = getObj(id);
  for (i=left.options.length-1; i>=0; i--) {
    if (left.options[i].selected) left.removeChild(left.options[i]);
  }
}

// Copyright (C) 2001-2007 Patrick R. Michaud (pmichaud § pobox.com)
function insMarkup(mopen, mclose, mtext, id) {
  var tarea = document.getElementById(id);
  if (tarea.setSelectionRange > "") {
    var p0 = tarea.selectionStart;
    var p1 = tarea.selectionEnd;
    var top = tarea.scrollTop;
    var str = mtext;
    var cur0 = p0 + mopen.length;
    var cur1 = p0 + mopen.length + str.length;
    while (p1 > p0 && tarea.value.substring(p1-1, p1) == ' ') p1--; 
    if (p1 > p0) {
      str = tarea.value.substring(p0, p1);
      cur0 = p0 + mopen.length + str.length + mclose.length;
      cur1 = cur0;
    }
    tarea.value = tarea.value.substring(0,p0)
      + mopen + str + mclose
      + tarea.value.substring(p1);
    tarea.focus();
    tarea.selectionStart = cur0;
    tarea.selectionEnd = cur1;
    tarea.scrollTop = top;
  } else if (document.selection) {
    var str = document.selection.createRange().text;
    tarea.focus();
    range = document.selection.createRange()
    if (str == "") {
      range.text = mopen + mtext + mclose;
      range.moveStart('character', -mclose.length - mtext.length );
      range.moveEnd('character', -mclose.length );
    } else {
      if (str.charAt(str.length - 1) == " ") {
        mclose = mclose + " ";
        str = str.substr(0, str.length - 1);
      }
      range.text = mopen + str + mclose;
    }
    range.select();
  } else { tarea.value += mopen + mtext + mclose; }
  return;
}

