var isIE;
var isOpera;
var isSafari;

// http://be.twixt.us/jquery/formSubmission.php
$.fn.ajaxSubmit = function(e) { /* Change a form's submission type to ajax */
    this.submit(function(){
        var params = {}; $(this) .find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea") .filter(":enabled") .each(function() {
            params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
        }); params['_AJAX']='1'; $("body").addClass("curWait"); $.post(this.getAttribute("action"), params, function(xml){
            $("body").removeClass("curWait"); strError = "Unable to submit form. Please try again later."; oFocus = null;
            $("AjaxResponse", xml).each(function() {
                strRedirect = this.getAttribute("redirecturl"); strError = this.getAttribute("error"); oFocus = this.getAttribute("focus");
            }); if (strError.length == 0) {
                window.location = strRedirect;
            } else {
                alert("The following errors were encountered:\n" + strError); $("div.formErrors").html("<h3>Error<\/h3><ul>" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal"); if (oFocus) $("#" + oFocus).get(0).focus();
            }
        }); return false;
    }); return this;
}

/* drag & drop magical selection list
 * Geinspireeerd door: http://www.ibrow.com/demos/drag_and_drop/v1.html */
function prep_selecttable(selectNr)
{
if(!selectNr) selectNr = '1';
    $('#selectable'+selectNr+' select#origlist>option').addClass('s'+selectNr+'list1');
    $('#selectable'+selectNr+' select#savedlist>option').addClass('s'+selectNr+'list2');


    $('#selectable'+selectNr+' option').each(function(i){
        $(this).Draggable({
            zIndex: 	1000,
            ghosting:	true,
            revert: true,
            opacity: 	0.7
        });
    });


    /**
     * Create the droppable area
     **/
    $('#selectable'+selectNr+' #savedlist').Droppable(
        {
            accept : 's'+selectNr+'list1',
            ondrop:	function (drag)
                {
                    add_to_listname('#savedlist',drag,selectNr);
                },
            fit: true
        }
    );

    $('#selectable'+selectNr+' #origlist').Droppable(
        {
            accept : 's'+selectNr+'list2',
            ondrop:	function (drag)
                {
                    add_to_listname('#origlist',drag,selectNr);
                },
            fit: true
        }
    );
}

/**
 * add_to_listname()
 * Adds items from one list to the a new list
 **/
function add_to_listname(tolistname,e,listNr) {

    var ddconf = {
                zIndex: 	1000,
                ghosting:	true,
                revert: true,
                opacity: 	0.7
    };
	// remove the old option from the original list
    $('#selectable'+listNr+' option[value="'+e.value+'"]').remove();

    o = '<option class="'+(e.className=='s'+listNr+'list1'?'s'+listNr+'list2':'s'+listNr+'list1')+'" value="'+e.value+'">'+e.text+'</option>';
	// append new option to saved list
	$('#selectable'+listNr+' '+tolistname).append(o);
    $('#selectable'+listNr+' option[value="'+e.value+'"]').Draggable(ddconf);

    if(tolistname=='#origlist') // if we're deselecting remove
        $('#selectable'+listNr+' #hidden'+listNr+' input[value="'+e.value+'"]').remove();
    else // otherwise, add hidden input field
        $('#selectable'+listNr+' #hidden'+listNr).append('<input type="text" name="selectable'+listNr+'[]" value="'+e.value+'"/>');
}


function getRandomChar(number, lower, upper) {
  var numberChars = "0123456789";
  var lowerChars = "abcdefghijklmnopqrstuvwxyz";
  var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var charSet = '';
  if (number == true)
  charSet += numberChars;
  if (lower == true)
  charSet += lowerChars;
  if (upper == true)
  charSet += upperChars;
  return charSet.charAt(Math.floor(Math.random()*(charSet.length+1)));
}
function makePass(len)
{
str = getRandomChar(false, true, true);//niet met decimal beginnen
for(n=0;n<len;n++)
  str+=getRandomChar(true, true, true);
return str;
}

function MyInputForm()
{
	this.addRow = MyInputFormAddRow;
	this.show = MyInputFormShow;
	this.hide = MyInputFormHide;
}

function MyInputFormAddRow(mylegend,formname)
{
	if(!mylegend) mylegend = '';
	if(!formname) formname = 'inputform';
	MyInputFormShow(mylegend,formname);
	if (document.forms[formname].reset) // IE pukes on this...
	{
		document.forms[formname].reset();
	}
	document.getElementById('it_key').value = '';
}

function MyInputFormShow(mylegend,formname)
{
	if(!mylegend) mylegend = '';
	if(!formname) formname = 'inputform';
	if(o = document.getElementById('inputformFieldSet'))
	{
//		$(o).slideDown();
		document.getElementById('inputformFieldSet').style.display = "block";
	}
	if(o = document.getElementById('inputformLegend')) o.innerHTML=mylegend;
	for(a=0;a<10;a++)
	{
		o = document.forms[formname][a];
		if(o && (o.tagName == 'INPUT') && (o.type != 'hidden')) { o.focus(); break; }
	}
}

function MyInputFormHide(formname)
{
	if(!formname) formname = 'inputform';
	if(o = document.getElementById('inputformFieldSet'))
	{
//		$(o).slideUp();
		document.getElementById('inputformFieldSet').style.display = "none";
	}
}

var MyInputForm = new MyInputForm();

function isElement(o)
{
  return o && o.nodeType == 1 && o.tagName != undefined
}

function ieMakeRowsClickable()
{
/*
  tds = document.getElementsByTagName('td');

  for(var a=0;tds.length>a;a++)
  {
    if(tds[a].getAttribute('it_field'))
      tds[a].attachEvent("onclick",rowClickedIe);
  }
/ *  if(document.getElementById('hoverBig'))
  {
    anchors = getElementsByTagName('a');
  }* /
*/
}

function rowClickedIe(e) {
	if (!e) var e = window.event;
        //e.srcElement = td, parentElement = tr
        // rowClicked verwacht de TD zoals in FF, vandaar parentElement
	rowClicked(e.srcElement.parentElement);
// 	if (e.target) targ = e.target;
}

var lastSelected;

function rowClicked(obj, redirectHere)
{
//	alert("rowClicked");
//	alert(obj);
	var f = document.forms['inputform'];
  if(!f)
    return false;
//   if(itKey = document.getElementById('it_key')) itKey.value = obj.id;
//   alert(document.getElementById('it_key').value);
  // alert(obj.innerHTML);
  if(obj.childNodes)
  {
  document.getElementById('it_key').value = obj.id;

  if(lastSelected)
  {
    if(lastSelected.className=='odd trselected')  lastSelected.className = 'odd';
    if(lastSelected.className=='trselected')  lastSelected.className = '';
  } if(lastSelected != obj)
  {
    if(obj.className=='odd') obj.className = 'odd trselected';
    else if(obj.className=='odd trselected')  obj.className = 'odd';
    else if(obj.className=='')  obj.className = 'trselected';
    else if(obj.className=='trselected')  obj.className = '';
    lastSelected = obj;
    if(document.getElementById('delRow')) document.getElementById('delRow').disabled = false;
//    alert("show");
		MyInputForm.show('Bewerken');
//     document.getElementById('action').value = 'delete';
  }
  else
  {
    lastSelected = null;
//    alert("hide");
    MyInputForm.hide();
    if(document.getElementById('delRow')) document.getElementById('delRow').disabled = true;
//     document.getElementById('action').value = 'insert/update';
  }

    for(var a=0;obj.childNodes.length>a;a+=1)
    {td=obj.childNodes[a];

      if(!isElement(obj.childNodes[a])) continue;
      if(fieldName = td.getAttribute('it_field')) // zonder primary key, die is vaak niet weergegeven...
      {
//         if(redirectHere)
//             { alert('Redirecting'); window.location = redirectHere + '/' + fieldName; }
        tds = document.getElementsByTagName('td');

        for(var b=0;f.length>b;b++)
        {
          if(f[b].name == fieldName)
          {
            if((f[b].type.toLowerCase() == 'text') || (f[b].type.toLowerCase() == 'hidden') || (f[b].type.toLowerCase() == 'textarea') )
            {
              f[b].value = td.innerHTML;
            }
            if((f[b].type.toLowerCase() == 'radio') && (f[b].value == td.innerHTML))
                  f[b].checked = true;
            if((f[b].tagName.toLowerCase() == 'select') && (f[b].name == fieldName))
              for(var c=0;f[b].options.length>c;c++)
                if(f[b].options[c].value==td.innerHTML)
                  f[b].selectedIndex = c;
          }
        }
      }
    }//for a
  }//if childnodes

	return false;
}

/* Dependencies: koppeltabel
*/
function getElementsByClassName( strClassName, obj ) {
    var ar = arguments[2] || new Array();
    var re = new RegExp("\\b" + strClassName + "\\b", "g");

    if ( re.test(obj.className) ) {
        ar.push( obj );
    }
    for ( var i = 0; i < obj.childNodes.length; i++ )
        getElementsByClassName( strClassName, obj.childNodes[i], ar );

    return ar;
}
/* Dependencies: koppeltabel
*/
function read_pairs()
{
  xx=document.getElementsByName('mypairs');
  pairlist=xx[0];
  pairlist.value='';
    var aryClassElements = getElementsByClassName( 'datacell', document.body );
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if(!(aryClassElements[i].getAttribute('mystatus'))) aryClassElements[i].setAttribute('mystatus','null');
        pairlist.value += aryClassElements[i].id+'='+aryClassElements[i].getAttribute('mystatus')+',';
  }
//  alert(pairlist.value);
}

/* Dependencies: koppeltabel
*/
function my_select(t1,t2)
{

  cellEl = document.getElementById('ll'+t1+'v'+t2);
  if(mystatus = (cellEl.getAttribute('mystatus')))
  {
    if (mystatus == 'basis')
    {
       cellEl.setAttribute('mystatus','gevorderd');
       cellEl.style.backgroundColor='#9f5600';// basis -> maak gevorderd
    }
    if (mystatus == 'gevorderd')
    {
       cellEl.setAttribute('mystatus','null');
       cellEl.style.backgroundColor='';// gevorderd -> maak unset (wis relatie)
    }
   if (mystatus == 'null')
   {
       cellEl.setAttribute('mystatus','basis');
       cellEl.style.backgroundColor='#4477ff';// 'null' -> maak basis
   }

  }else
  {
       cellEl.setAttribute('mystatus','basis');
       cellEl.style.backgroundColor='#4477ff';// unset -> maak basis
  }
  read_pairs();

}




function init() {
// tabjes = getElementsByClassName('t_anchor','tabjes');
  if(ul = document.getElementById('tabjes'))
  {
    for(a=0;ul.childNodes.length>a;a++)
    {
      if((ul.childNodes[a].tagName) && (ul.childNodes[a].tagName == 'LI'))
      {
        li = ul.childNodes[a];
        for(b=0;li.childNodes.length>b;b++)
        {
          if(li.childNodes[b].href==window.location)
          {
            li.className='tabactief';
          }
        }
      }
    }
  }
  if(o = document.getElementById('inputformFieldSet'))
      if($('.databel').length)
          $(o).hide();

  isIE = (navigator.appName=="Microsoft Internet Explorer");
  isOpera = (navigator.appName=="Opera");
  isSafari = (navigator.userAgent.indexOf('Safari')!=-1);
  if(isIE)
  {
    console = function(){};
    console.log = function(str){};
    document.body.className+='iefix';
    ieMakeRowsClickable();
  }
  if(isOpera)
    document.body.className+='operafix';
  if(isSafari)
    document.body.className+='safarifix';

	if(initKlas)initKlas();

}


var vlak_html = '\n<table id="nieuwVlak" class="vlak">\n'+
'    <tr class="tr1">\n'+
'        <td class="tda"></td>\n        <td class="tdb"></td>\n        <td class="tdc"></td>\n'+
'    </tr>\n'+
'    <tr class="tr2">\n'+
'        <td class="tda"></td>\n        <td class="tdb content"></td>\n        <td class="tdc"></td>\n'+
'    </tr>\n'+
'    <tr class="tr3">\n'+
'        <td class="tda"></td>\n        <td class="tdb"></td>\n        <td class="tdc"></td>\n'+
'    </tr>\n'+
'</table>';

$(document).ready(function(){
init();

/* add icon to external links */
$('a:not(:has(img))').filter(function() {
    return (this.hostname.substr(this.hostname.length-14)!='.digimaster.nl' && this.hostname != 'digimaster.local.roes.nl' && this.hostname != 'digimaster.roes.nl' && this.hostname != '');
  }).append(' <img src="'+GUI_URL+'/res/pic/external-link.gif" title="Externe link">').attr('target','_blank');

/* datepicker functionality */
    $(".dateField").datepicker({
        showOn: "button",
        buttonImage: "/res/pic/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1970,1,1),
        maxDate: new Date(2020,1,1)
    }).addClass("embed");

    $(".hideTip").click(function(e){
        $(".shadyDiv").filter(this).fadeOut("slow");
    });

/*TODO FINISH THIS FIX
 *    $('.databel > tbody > tr').each(function(){
    var anId=$(this).attr('id');
    $(this).filter('td').click(function(){
        rowClicked(anId);
    });
  });
*/

});

