//   to test, paste in Address bar: javascript:void(checkAddTo(document.forms[1]))  (or other number)

function __readAttribute(el, name){
	if( typeof(el.attributes[name]) == "object"){
		return el.attributes[name].value;
	}
	return false;
}

function checkAddTo(f)
{
  if (/Operac[\/\s](\d+\.\d+)/.test(navigator.userAgent)) return 0;
  var ar_addto = new Array();
  var ar_addto2 = new Array();

  var msg = '';

  if (typeof(f) != 'undefined' && f.elements)
  {
    for (i=0; i<f.elements.length; i++)
    {
      el = f.elements[i];
      
      // fix for firefox - must use getAttribute for non-standard html params
      var min           = __readAttribute(el, 'min');
      var max           = __readAttribute(el, 'max');
      var gridmin       = __readAttribute(el, 'gridmin');
      var step          = __readAttribute(el, 'step');
      var addto         = __readAttribute(el, 'addto');
      var addvalue      = __readAttribute(el, 'addvalue');
      var addvaluegrid  = __readAttribute(el, 'addvaluegrid');
      var multiply      = __readAttribute(el, 'multiply');
      var multiplyfield = __readAttribute(el, 'multiplyfield');
    
      // contain within limits
      if (min && (parseFloat(el.value) < min || !el.value.length || isNaN(el.value))) { el.value = min; }
      if (max && parseFloat(el.value) > max) { el.value = max; }

      // round to multiple of step
      el.roundvalue = el.value;
      if (!gridmin) { gridmin = parseFloat(min); }
      
      if (gridmin && parseFloat(el.roundvalue) < parseFloat(gridmin))
      {
        el.roundvalue = parseFloat(gridmin);
      }
      
      if (step)
      {
        el.roundvalue = 1*gridmin + 1*Math.ceil( (el.roundvalue - gridmin) / step ) * step;
      }
      

      if (addto)
      {
        if (document.getElementById)
        {
          if ((el.type == 'checkbox' || el.type == 'radio') && !el.checked)
          {
            continue;
          }
          
          option_addvalue = 0;
          option_addvalue_found = false;
          
          if (addvaluegrid) 
          {
            yfield = addvaluegrid.split(',')[0];
            gridfield = addvaluegrid.split(',')[1];
			

            
            // round yfield right now (because it might not appear until later and not have a rounded value already)
            ely = f.elements[yfield];
            if (!ely) { ely = document.getElementById('fq_' + yfield); }
			// fix for firefox - must use getAttribute for non-standard html params
			ely.min           = __readAttribute(ely, 'min');
			ely.max           = __readAttribute(ely, 'max');
			ely.gridmin       = __readAttribute(ely, 'gridmin');
			ely.step          = __readAttribute(ely, 'step');

            ely.roundvalue = ely.value;
            if (!ely.gridmin && ely.min) { ely.gridmin = parseFloat(ely.min); }

            if (ely.gridmin && parseFloat(ely.roundvalue) < parseFloat(ely.gridmin))
            {
              ely.roundvalue = parseFloat(ely.gridmin);
            }
          
            if (ely.step>0)
            {
              ely.roundvalue = 1*ely.gridmin + 1*Math.ceil( (ely.roundvalue - ely.gridmin) / ely.step ) * ely.step;
            }
 		//  alert( ely.roundvalue );
            x = parseFloat( el.roundvalue );
            y = parseFloat( ely.roundvalue );
          

            if (x && y)
            {
              eGridfield = f.elements[gridfield];
              if (!eGridfield) { eGridfield = document.getElementById('fq_' + gridfield); }
              
              grid = ',' + eGridfield.value + ',';
              gridv = grid.split(x+'x'+y+'=')[1];
              gridw = '';
              if (gridv) { gridw = gridv.split(',')[0]; }
              if (gridw) { addvalue = gridw; }
              
              //DEBUG
              //if (location.href.indexOf('debug=grid') != -1) { alert('x:'+ x + '\ny:' + y + '\ngridw:' + gridw); }
              
              if (gridw.indexOf('jumpto') == 0)
              {
                ex = gridw.split(':');
                jump_to_x = ex[1];
                jump_to_y = ex[2];
                el.value = jump_to_x;
                ely.value = jump_to_y;
                setTimeout(function() { checkAddTo(f); }, 55); // force recount
              }
            }
          } 
                   

          if (multiply)
          {
            multiply = parseFloat(multiply) ? parseFloat(multiply) : 1;
          }
          else
          {
            multiply = 1;
          }
          
          if (multiplyfield && f.elements[multiplyfield])
          {
            multiply *= parseFloat( f.elements[multiplyfield].value );
          }
          
          
          if (el.tagName.toLowerCase() == 'select' && el.options)
          {
            for (j=0; j<el.options.length; j++)
            {
            
              if (j == el.selectedIndex && el.options[j])
              {
                // use addvalue custom param per option
                if (el.options[j].getAttribute('addvalue'))
                {
                  option_addvalue = el.options[j].getAttribute('addvalue');
                  option_addvalue_found = true;
                }
                
                // extract price from option value
                // that looks like "102/DKL/prijsgroep 1 (� 50)"
                else
                {
                  ex = el.value.split(' ');
                  exx = ex[ex.length - 1].split(')');
                  exx[0] = exx[0].replace(',-', '');  // convert 695,- to 695
                  if (exx.length && !isNaN(exx[0]))
                  {
                    option_addvalue = exx[0];
                    option_addvalue_found = true;
                  }
                }
              }
            }
          }

          
          if (option_addvalue_found)
          {
            value_to_add = option_addvalue;
          }
          else
          {
            value_to_add = addvalue ? addvalue : el.value;
          }
          
          value_to_add = parseFloat( value_to_add );
          

          //DEBUG
          if (addto) { msg += el.name + ' has addto... \noptions:'+el.options+'\nel.length:'+el.length+'\nvalue_to_add is \'' + value_to_add + '\'\n\n'; }

          if (addto.split('|').length > 1)
          {
            if (!ar_addto[addto.split('|')[0]])
            {
              ar_addto[addto.split('|')[0]] = 0;
            }
            ar_addto[addto.split('|')[0]] += parseFloat(addto.split('|')[1]);
          }
          //else if (value_to_add > 0)
          else if ((''+value_to_add).length > 0)
          {
            if (!ar_addto[addto])
            {
              ar_addto[addto] = 0;
            }
            ar_addto[addto] += value_to_add * multiply;
          }
        }
      }
      
    }


    for (i in ar_addto)
    {
      el = document.getElementById('fq_'+i); 

      if (el)
      {
        tidy_value = ar_addto[i];
        if (!(''+tidy_value).split('.')[1]) { tidy_value += '.00'; }
        if ((''+tidy_value).split('.')[1] && (''+tidy_value).split('.')[1].length == 1) { tidy_value += '0'; }
        el.value = tidy_value;
        
        if (addto)
        {
          if (document.getElementById && document.getElementById('fq_'+addto))
          {
            multiply = 1;
            if (multiply)
            {
              multiply = parseFloat(multiply) ? parseFloat(multiply) : 1;
            }
            
            if (!ar_addto2[addto])
            {
              ar_addto2[addto] = ar_addto[addto] ? ar_addto[addto] : 0;
            }

            if (parseFloat(el.value) > 0)
            {
              ar_addto2[addto] += el.value * multiply;
            }
          }
        }
      }
    } //for

    for (i in ar_addto2)
    {
      el = document.getElementById('fq_'+i); 

      if (el)
      {
        el.value = ar_addto2[i];
      }
    }
             
  }
}

function checkFields(targetForm, params){
	params = eval(params);
	var count_errors = 0
	for (i in params){
		if(params[i].type == 'text'){
			label = document.getElementById('label_'+params[i].name);
			if(!targetForm.elements['answer['+params[i].id+']'].value.length){
				label.className = 'error';
				count_errors++;
			}else{
				label.className = '';
			}
		}
	}
	return !count_errors;
}


function setDateTimeFields(oForm, fq, isodate)
{
  // check if each field exists before assigning, so this function
  // can also be used for date field-sets instead of datetime field-sets
  if (oForm.elements[ 'answer['+fq+'][0]' ]) { oForm.elements[ 'answer['+fq+'][0]' ].value = isodate.substring(0,4); }
  if (oForm.elements[ 'answer['+fq+'][2]' ]) { oForm.elements[ 'answer['+fq+'][2]' ].value = isodate.substring(5,7); }
  if (oForm.elements[ 'answer['+fq+'][4]' ]) { oForm.elements[ 'answer['+fq+'][4]' ].value = isodate.substring(8,10); }
  if (oForm.elements[ 'answer['+fq+'][6]' ]) { oForm.elements[ 'answer['+fq+'][6]' ].value = isodate.substring(11,16); }
}


function detectOpener(fId)
{
  if (f = document.forms[fId])
  {
    if (f.elements)
    {
      for (i=0; i<f.elements.length; i++)
      {
        if (f.elements[i].value == 'opener' || f.elements[i].value == 'windowopener')
        {
          if (window.opener)
          {
            f.elements[i].value = window.opener.location.href;
          }
          else
          {
            f.elements[i].value = '[url autodetection failed]';
          }
        }
      }
    }
  }
}


function getDateTime(oForm, fq)
{
  isodate = '';
  isodate += oForm.elements[ 'answer['+fq+'][0]' ].value;
  isodate += '-';
  isodate += oForm.elements[ 'answer['+fq+'][2]' ].value;
  isodate += '-';
  isodate += oForm.elements[ 'answer['+fq+'][4]' ].value;
  isodate += ' ';
  isodate += oForm.elements[ 'answer['+fq+'][6]' ].value;
  return isodate;
}

// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function')
  {
    window.onload = func;
  }
  else
  {
    window.onload = function()
    {
      oldonload();
      func();
    }
  }
}


// turn multiple checkboxes on or off
//
//  example usage:
//   multicheck( ['cbid1','cbid2','cbid3'], 1 );
//
function multicheck( ar_id, state )
{
  for (i = 0; i < ar_id.length; i++)
  {
    obj = document.getElementById(ar_id[i]);
    if (obj) {  obj.checked = state; }
  }
}

//change the opacity for different browsers
function changeOpac(opacity, id)
{
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = 'alpha(opacity=' + opacity + ')';
}

function myFileBrowser3(type,width,height) {
	
    var ed = tinyMCE.activeEditor;
    ed.windowManager.open({
    	url : "/admin/?"+type+"&richeditor=tinymce",
    	width : width + parseInt(ed.getLang('amadeo_draft.delta_width', 0)),
    	height : height + parseInt(ed.getLang('amadeo_draft.delta_height', 0)),
    	movable : true,
    	inline : true
    });
	return false;
}


function myCustomExecCommandHandler3(cmd, ui, val) {
    
    //alert(cmd + " - " + ui + " - " + val);
    
    var linkElm, imageElm, ed;
    
    
	switch (val) {
		case "mceAdvLink":
		case "mceLink":
			ed = tinyMCE.activeEditor;
			linkElm = ed.dom.getParent(ed.selection.getNode(), "a");

			if (linkElm == null){
				myFileBrowser3('pop_link=frameset',400,600);
                return true;
			}
            break;
			
		case "mceAdvImage":
		case "mceImage":
			ed = tinyMCE.activeEditor;
			imageElm = ed.dom.getParent(ed.selection.getNode(), "img");
            
			if (imageElm == null){
                myFileBrowser3('task=pop_file_frameset',640,480);
                return true;
			}
            break;
            
        default: return false;
	}
    
	return false; // Pass to next handler in chain
}

 function Set_time(argObj){
					  	var time_field = document.getElementById(argObj.id+"_time");
					 	 	if(time_field.value == '' || time_field.value == ' ' || time_field.value == '0'){
					 	 		var date = new Date();
					  		var time = date.toTimeString();
					 	 		time_field.value = time.substr(0,8);
					 		}
}
					 
