// Tensid Java Library
// written by Konrad Baechler, commonly known as guru k.
// (c) 2003+ Tensid AG, www.tensid.ch
// 
// THIS IS NOT FREEWARE // IT'S CARDWARE
// If you want to use it (or parts of it), simply send us a postcard from where you work:
// Tensid AG, Bahnhofstrasse 14, 6340 Baar, Switzerland
//
// Please send all improvements to support@tensid.ch. Thanks!
// No liabilities for the use of this code.

function navigate(pg)
{
  window.location.href = pg; 
} // function navigate(pg)

function createhtmltextarea(n, h, mode, stylesheet, overwrite)
// string: n; name of object, like "myHTMLbox"
// string: h; height of object in pixels, like "120px"
// string: mode, either 'text' or 'html'
// string: stylesheet, contains the path to the stylesheet
// boolean: overwrite -> take the existing object and change the config
{ 
 
  if (overwrite)
  { 
    var config = document.all[n].config;
//    var editor_obj = document.all["_" + n + "_editor"];
	document.all["_" + n + "_toolbar"].outerHTML = "";
	document.all["_" + n + "_editor"].outerHTML = "";
	document.all["_" + n + "_cMenu"].outerHTML = "";
/*
  var editor = '<span id="_'+objname+'_toolbar"><table border=0 cellspacing=0 cellpadding=0 bgcolor="buttonface" style="padding: 1 0 0 2" width=' + config.width + ' unselectable="on"><tr><td>\n'
  + toolbar
  + '</td></tr></table>\n'
  + '</td></tr></table></span>\n'
  + '<textarea ID="_' +objname + '_editor" style="width:' +config.width+ '; height:' +config.height+ '; margin-top: -1px; margin-bottom: -1px;" wrap=soft></textarea>';

  // add context menu
  editor += '<div id="_' +objname + '_cMenu" style="position: absolute; visibility: hidden;"></div>';
*/
  }
  else
  {
    var config = new Object();
  }
	
  config.width = "100%";
  if (mode == 'html')
  {
    config.transform = "simplehtml";
    config.stylesheet = stylesheet;
    config.fontstyles = [{
      name: "Normal",
      className: "editor_normal"
      },{
      name: "Heading 1",
      className: "editor_h1"
      },{
      name: "Heading 2",
      className: "editor_h2"
      },{
      name: "Heading 3",
      className: "editor_h3"
      },{
      name: "Heading 4",
      className: "editor_h4"
      }];

    config.bodyStyle = 'background-color: white;';
    config.debug = 0;

    config.toolbar = [
      ['popupeditor','separator','objects'],
      ['linebreak'],
	  ['fontstyle'],
      ['bold','italic','underline','separator'],
      ['subscript','superscript','separator'],
      ['OrderedList','UnOrderedList','separator'],
	  ['HorizontalRule','Createlink']
	  ];
  }
  else if (mode == 'text')
  {
    config.transform = "text";
    config.stylesheet = "";
    config.bodyStyle = 'background-color: white; font-family: "Courier"; font-size: 11px;';
    config.debug = 0;

    config.toolbar = [
      ['popupeditor','separator','database']
	  ];
  }
  else {alert('Error in setting up the editor.'); return false; }  	

  config.height = h;
  if (overwrite)
  { 
    document.all[n].config = config;
    editor_generate(n, config);
//    editor_setmode(n, "wysiwyg");
  }
  else
  {
	editor_generate(n, config);
  }
}

function checkUpload(uploadfield, language)
{
  var ret = true;
  if (!(uploadfield.value == "") && !(uploadfield.value == null)) 
  {
    validformFile = /(.htm|.html|.jpg|.jpeg|.gif|.pdf|.doc|.xls)$/i;

    if(!validformFile.test(uploadfield.value))
    {
	  switch (language)
      {
        case "10001": // german
          alert("Es werden nur JPG, GIF, PDF, HTML, MSWord oder MSExcel Dateien unterstützt.\nBitte wählen Sie eine andere Datei.");
	      break;
        case "10002": // french
          alert("Only JPG, GIF, PDF, HTML, MSWord or MSExcel files are supported.\nPlease try again.");
	      break;
        default: //english by default
          alert("Only JPG, GIF, PDF, HTML, MSWord or MSExcel files are supported.\nPlease try again.");
	      break;
      } // switch
      uploadfield.focus();
      ret = false;
    }
  }
  return (ret);
} // checkUpload

function checkCSVUpload(uploadfield, language)
{
  var ret = true;
  if (!(uploadfield.value == "") && !(uploadfield.value == null)) 
  {
    validformFile = /(.csv)$/i;

    if(!validformFile.test(uploadfield.value))
    {
	  switch (language)
      {
        case "10001": // german
          alert("Es werden nur Komma-separierte-Dateien (*.csv) unterstützt.\nBitte wählen Sie eine andere Datei.");
	      break;
        case "10002": // french
          alert("Only comma separated files (*.csv) are supported.\nPlease try again.");
	      break;
        default: //english by default
          alert("Only comma separated files (*.csv) are supported.\nPlease try again.");
	      break;
      } // switch
      uploadfield.focus();
      ret = false;
    }
  }
  return (ret);
} // checkCSVUpload

function DeleteConfirmation(language)
// supported languages: 10000 English, 10001 German, 10002 French
{
  switch (language)
  {
    case 10001:
      return confirm("Wollen Sie die gewählten Datensätze wirklich löschen?");
	  break;
    case 10002:
      return confirm("Do you really want to delete the selected records?");
	  break;
    default:
      return confirm("Do you really want to delete the selected records?");
	  break;
  } // switch
} 

function DeleteRecordsConfirmation(language)
// supported languages: 10000 English, 10001 German, 10002 French
{
  switch (language)
  {
    case 10001:
      return confirm("Alle dem Ordner zugeordnete Datensätze werden\n ebenfalls gelöscht. Wollen Sie wirklich alle löschen?");
	  break;
    case 10002:
      return confirm("All subordinated records of this folder are going to\n be deleted too. Do you really want to delete them all?");
	  break;
    default:
      return confirm("All subordinated records of this folder are going to\n be deleted too. Do you really want to delete them all?");
	  break;
  } // switch
} 

function previewwindow(template_id, mode, flds) 
// integer: template_id; contains the template id from DB
// mode: string; contains either "text" or "html"
// flds: string; contains the commaseperated db-field list, referring to the
//               Contents
// arrContent: array of string; contains the content itself 
{
  var target = 'nl_generic_preview.php?p_template_id=' + template_id + 
	 '&mode=' + mode + '&arrKeys=';

  flds = flds.replace(/\s*/gi, ''); // remove all white spaces
	
 	target += flds + '&arrContent=';

  var arrFlds = flds.split(',');
  
	var arrContent = "";
		
	for (var i in arrFlds) 
	{
		var fldVal = document.all[arrFlds[i]].value;
		arrContent += fldVal;
		if (i < arrFlds.length - 1)
		{
		  arrContent += '###@@tendel@@###';
		}
	} // for
  
	arrContent = escape(arrContent);
	
	target += arrContent;
	
  window.open(target,"Preview",'dependent=yes,resizable=yes,scrollbars=yes,status=yes,width="80%",height="80%",left=0,top=0');
	
//  showModalDialog(target, 'Preview',
//                     'resizable: yes; help: no; status: yes; scroll: auto; ');
} // function previewwindow
 
 
// Image functions

function ts_swapImgRestore() { //v3.0
  var i,x,a=document.ts_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function ts_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.ts_p) d.ts_p=new Array();
    var i,j=d.ts_p.length,a=ts_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.ts_p[j]=new Image; d.ts_p[j++].src=a[i];}}
}

function ts_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=ts_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function ts_swapImage() { //v3.0
  var i,j=0,x,a=ts_swapImage.arguments; document.ts_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=ts_findObj(a[i]))!=null){document.ts_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// needed for depending drop downs
function DepSwitch(arrDep, frm, master) {
	mnp = document.getElementById("p_" + master).value;
	mop = document.getElementById("p_" + master + "_old").value;
	if (mnp == mop) { return true; }
	var n_dep_dd = "";
	for ( var i in arrDep ) {
		n_dep_dd = "dd_span_" + arrDep[i] + mnp;
		document.getElementById(n_dep_dd).style.display = "block";
		document.getElementById(document.getElementById(n_dep_dd).getAttribute("tensid_id")).value = "";
		n_dep_dd = "dd_span_" + arrDep[i] + mop;
		document.getElementById(n_dep_dd).style.display = "none";
		document.getElementById(document.getElementById(n_dep_dd).getAttribute("tensid_id")).value = "";
		document.getElementById(document.getElementById(n_dep_dd).getAttribute("tensid_v_id")).value = 0;
  } // for
} // function DepSwitch

function TensidGenericFormCheck(f, arrCheck)
{
  // set the return variable
  var ret = false;
  // change the vars below to change the rulez
  var email = /^[a-zA-Z0-9\.\-_]+[a-zA-Z0-9_]{1}@[a-zA-Z0-9\.\-_]+([a-zA-Z0-9_]{1}\.[a-zA-Z]{2,4})$/;
  var notnull = /[^\s]+/ ;
  var notzero = /[^\s0]+/ ;
  var phone = /^\+[1-9]+[\s]?([0-9\s]+)[0-9\s]{0,}/ ;
  var number = /[\-\+]?[\d]+/ ;
  var positivenumber = /[1-9][\d]*/ ;
  
  if (arrCheck) {
    msg = 'Form Error.';
	// scan the form
    for (var i=0; i < f.length; i++) {
	  var notnullflag = true;
	  if (f.elements[i].getAttribute("tensidcheck") == true) {
			msg = arrCheck[f.elements[i].getAttribute("tensidmsg")];
 	    	re = f.elements[i].getAttribute("tensidformat");
	    	if (re == 'email') { re = email; }
	    	else if (re == 'notnull') { re = notnull; }
	    	else if (re == 'phone') { re = phone; }
	    	else if (re == 'notzero') { re = notzero; }
	    	else if (re == 'number') { re = number; }
	    	else if (re == 'positivenumber') { re = positivenumber; }

			if (f.elements[i].getAttribute("tensidnull"))
			{ notnullflag = !f.elements[i].getAttribute("tensidnull"); }

/*			if (f.elements[i].getAttribute("tensidnull"))
			{ 
				if (f.elements[i].getAttribute("tensidnull") == 0) { notnullflag = true; }
				else if (f.elements[i].getAttribute("tensidnull") == 1) { notnullflag = false; }
			}
*/
			if (re == email || re == notnull || re == notzero) { 
				if (f.elements[i].value) {
					f.elements[i].value = f.elements[i].value.replace(/^\s+/g, ''); 
				  	f.elements[i].value = f.elements[i].value.replace(/\s+$/g, ''); 
				} // if
    		}

			// trim the string, phone
			if (re == phone) { // remove all non numeric characters
				if (f.elements[i].value) {
			  		f.elements[i].value = f.elements[i].value.replace(/[^0-9\+\s]+/g, ' ');
			  		// replace all consequent spaces by one space
			  		f.elements[i].value = f.elements[i].value.replace(/[\s]{2,}/g, ' ');
  	    			//trim the string
			  		f.elements[i].value = f.elements[i].value.replace(/^\s+/g, ''); 
			  		f.elements[i].value = f.elements[i].value.replace(/\s+$/g, ''); 
				} // if
			} // if (re == phone)

			if ( ( ( notnullflag == false ) && ( f.elements[i].value == '' ) ) || ( re.test(f.elements[i].value) ) ) { 
				ret = true; 
			} else { 
				ret = false; break; 
			}
	  	} // if (f.elements[i].tensidcheck == true)
	} // for (var i=0; i < f.length; i++)

	if (!ret) { 
		alert(msg); 
      	if (f.elements[i]) {
	    	if (f.elements[i].getAttribute("type") != 'hidden') { f.elements[i].focus(); }
	  	}
    }
  } // if (arrCheck)
  return ret; 
}  // TensidGenericFormCheck(f, arrCheck)

