var stima = {
	html: {}
};

function expand(obj) {
	alert(obj);
}
stima.html.Events = 
{
	AttachEvent: function(ob, eventName, functionName, bNoBubble)
    {
        if (stima.html.Events.IsIE())
        {
            ob.detachEvent(eventName,functionName);
            ob.attachEvent(eventName,functionName);
        }
        else
        {
            eventName = eventName.replace("on", "");
            //alert(eventName);
            //alert(ob);
            ob.removeEventListener(eventName, functionName, false);
            ob.addEventListener(eventName, functionName, false);
        }
    },
    NewEvent: function(ob, eventName, functionName)
    {
        if (stima.html.Events.IsIE())
        {
            ob.attachEvent(eventName,functionName);
        }
        else
        {
            eventName = eventName.replace("on", "");
            ob.addEventListener(eventName, functionName, false);
        }
    },
    IsIE: function()
    {
        return navigator.appName == "Microsoft Internet Explorer";
    }
}

function InitPage()
{
	//no calendars are present
	if (typeof(general_calendars) == "undefined")
		return;
	//new calendar is used, so we have no need to assign old calendar behaviour
	if (typeof(Epoch) == null || typeof(Epoch) == 'undefined')
		return;
	var toEval = "";
	for(var i=0; i<general_calendars.length; i++)
	{
		var field = general_calendars[i];
		toEval = field+"_cal=new Epoch('"+field+"_cal','popup',document.getElementById('"+field+"'));"
		eval(toEval);
	}
}


function AddSelectChangeEvents(select_name, table){
		jQuery("select[name^='cx_" + select_name + "_']").each(function(i)
			{
				jQuery(this).change(function()
					{
						var span_loading = jQuery("span[id^='cx_" + select_name + "_loading_" + (i + 1) + "']");
						
						span_loading.css("visibility", "visible");
						
						var child_name = "cx_" + select_name.slice(0, select_name.length - 1) + "2_" + (i + 1);
						var sel_value = jQuery(this).attr("value");
						
						var ajax = new XHConn();
						if (!ajax)
							{
								alert("Ajax is not available. Try a better browser!");
							}
						
						var Done = function (response)
							{
								jQuery("div[id='ajax_js']").html(response.responseText);
								span_loading.css("visibility", "hidden");
							};
						
						ajax.connect("optionsList.php", "GET", "type=" + table + "&parent=" + sel_value + "&child=" + child_name, Done);
						
					});
			});
			
	}
	
	
function getSelectedIndexValue(selId)
{
    var selIndex = document.getElementById(selId).selectedIndex;
		return document.getElementById(selId).options[selIndex].value;
}
function disclaimed( ) {
  if( document.getElementById('disclaimerCheck').checked) {
    return true;
  }
  else {
    alert("Vergeet u a.u.b. niet 'Akkoord met deze voorwaarden' aan te kruisen.");
    return false;
  }
}


function add_sub(obj_name)
{
	var sibling_blocks = jQuery("div[name='" + obj_name + "'] > div");
	
	for (var i = 0; i < sibling_blocks.length; i++)
		{
			var sibling = sibling_blocks[i];
			if (jQuery(sibling).css("display") == "none")
				{
					jQuery(sibling).css("display", "block");
					break;
				}
		}
}


function remove_sub(obj_name, min_blocks)
{
	var counter_none = 0;
	var sibling_blocks = jQuery("div[name='" + obj_name + "'] > div");
	
	for (var i = sibling_blocks.length - 1; i >= 1; i--)
		{
			if (counter_none >= (sibling_blocks.length - min_blocks))
				{
					break;
				}
				
			var sibling = sibling_blocks[i];
			
			if (jQuery(sibling).css("display") == "block")
				{
					jQuery(sibling).css("display", "none");
					break;
				}
				
			counter_none++;
		}
}

var subType = {};
function addSub(type, sType)
{
  var count = document.getElementById ( "cx_count_sub_"+type+"_1").value;
  if( count < 5) {
    count++;
    var el = document.getElementById ( "sub_"+ type + "_" + count);
    el.style.display = sType != null ? sType : "block";
    document.getElementById( "cx_deleted_sub_"+type+"_"+count ).value = 0;
    //cx_count_sub_educations_1
    document.getElementById ("cx_count_sub_"+type+"_1").value = count;
    //create calendars
    //createCalendars(el);
  }
}


function removeSub(type)
{
  var count = document.getElementById ( "cx_count_sub_"+type+"_1").value;
  if( count > 1) {
    var el = document.getElementById (  "sub_"+ type + "_" + count);
    //clear fields
    clearFields(el, type, count);
    document.getElementById( "cx_deleted_sub_"+type+"_"+count ).value = "1";
    el.style.display = "none";
    count--;
    document.getElementById( "cx_count_sub_"+type+"_1").value = count;
  }
  //alert(document.getElementById( "cx_deleted_sub_"+type+"_"+(count+1) ).value);
}


function createCalendars(el)
{        
  var inputs = el.getElementsByTagName("input");
  for(i = 0; i < inputs.length; i++){
    var inp = inputs[i];children[i]
    //format_startDate_sub_workHistories_2
    if(inp.name.indexOf("format_") == 0 && inp.value == "date"){
      var nm = inp.name.substr(7);
      new Epoch('epoch_popup_'+nm,'popup',document.getElementById('cx_'+nm));
    }
  }
}
function clearFields(el, type, count) {
  //alert (el +"\r\n" + type + "\r\n" + count);
  var inputs = el.getElementsByTagName("input");
  //alert(1);
  var selects = el.getElementsByTagName("select");
  //alert(2);
  var textareas = el.getElementsByTagName("textarea");
  for(i = 0; i < textareas.length; i++){
    textareas[i].innerHTML = "";
  }
  for(i = 0; i < selects.length; i++){
    selects[i].selectedIndex = 0;
  }
  for(i = 0; i < inputs.length; i++) {
    inp = inputs[i];
    //DO NOT CLEAR THE ID
    if(inp.name != "cx_id_sub_"+type+"_"+count){
      inp.value = "";
    }
  }
}

function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="' + jsFile + '"></script>'); 
}
IncludeJavaScript('js/datetimepicker.js');
IncludeJavaScript('js/prototype.js');

/*textarea maxlength*/
/***********************************************
* Textarea Maxlength script- � Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

/*create dynamic tr and td in table*/
 var element_no =1; // we will use i variable just for names 'sample 4', 'sample 5', ...
  function AddEndRow(tid) {
  	//get the needed type for coverletter
  	var arr = document.getElementsByName('filetype_cover_1');
  	var typeCovverLetter = -1; //this should never be the case. we always should have a first type
  	try{
	  	if (arr!=null || arr.length==1)
	  		typeCovverLetter = arr[0].value;
//  	alert(typeCovverLetter);
	}
	catch(ex){ typeCovverLetter = -1;}
  
  // first we create <tr> element
  var myTR=document.createElement('tr');
  // now we create first cell (<td> element)
  var myTD=document.createElement('td');
  // it will have one child - text node
  myTD.appendChild(document.createTextNode('Extra document '+(++element_no)));
  // create second cell, and append the child text node 'sample text here 2...'
  var myTD2=document.createElement('td');
  myTD2.appendChild(document.createTextNode(""));
  myTD2.innerHTML = 
  	'<input id="cx_cover_'+element_no+'" class="cx_applyAttachment" type="file" name="cx_cover_'+element_no+'"/>'+
  	'<input type="hidden" value="cover_'+element_no+'" name="filenames[]"/><span class=""/>'+
  	'<input type="hidden" name="filetype_cover_'+element_no+'" value="1459" />'
  	' PDF, DOC, DOCX';
  //<input type="hidden" name="filetype_cover_1" value="1459" />
  
 myTD.setAttribute("class", "cx_applyLeft");
 myTD.className = "cx_applyLeft";
 myTD2.setAttribute("class", "cx_applyRight");
 myTD2.className = "cx_applyRight";
 
  // now we append our 2 cells to our table row.
  myTR.appendChild(myTD);
  myTR.appendChild(myTD2);
  
  // after that we add our row (tr) to tbody
  document.getElementById(tid).appendChild(myTR);
  }
  
  function DelLastRow(tid) {
      // myTbl -> reference to our Tbody
      var myTbl=document.getElementById(tid);
      // go to the last child of tbody - i.e. the last row
      var deltr=myTbl.lastChild;
      // remove the last row.
      myTbl.removeChild(deltr);
  }





/**
 * ===================================================
 *  Library agnostic methods (the app includes random
 *  js libraries like prototype.js or jQuery, and we
 *  don't want to rely on a specific library for
 *  certain functionalities).
 * ===================================================
 */

 // old browsers compatibility (IE5.0)
 if(typeof Array.prototype.push == 'undefined') {
	Array.prototype.push = function(item){
		this[this.length] = item;
	}
 }
 if(typeof Array.prototype.pop == 'undefined') {
	Array.prototype.pop = function(){
		item = this[this.length-1];
		this.length -= 1;
		return item;
	}
 }
 
 
 // sanity checks
 if(typeof stima == 'undefined') stima = {};
 if(typeof stima['util'] == 'undefined') stima.util = {};
 if(typeof stima['html'] == 'undefined') stima.html = {};
 
 // trim
 stima.util.trim = function(str){
	return str.replace(/^\s+/gi,'').replace(/\s+$/,'');
 }
 
 /**
 * sets/gets the text content of a DOM element
 * 
 * @param element {string} the DOM element to get/set the text content
 * @param id {string} the id to look for in the DOM
 * @returns {object} the DOM node on success or null
 */
stima.html.text = function(element, newtext){
	var ret = null;
	var prop = null;

	// default, IE behavior, use innerText
	if(stima.html.isNode(element, 'innerText')) prop = 'innerText';

	// do we have the textContent property ? (W3C DOM)
	else if(stima.html.isNode(element, 'textContent')) prop = 'textContent';

	// fallback to innerHTML
	else if(stima.html.isNode(element, 'innerHTML')) prop = 'innerHTML';

	ret = element[prop];
	if(typeof newtext != 'undefined') element[prop] = newtext;

	return ret;
}

 /**
 * document.getElementById wrapper
 * 
 * @param id {string} the id to look for in the DOM
 * @returns {object} the DOM node on success or null
 */
stima.html.byId = function(id){
	if(!id) return null;
	// we already have an object, return it
	if(typeof id == 'object') return id;
	// find element in the DOM
	return document.getElementById(id);
}


/**
 * constructs a native array (with all the Array methods) from a NodesList type
 * @see https://developer.mozilla.org/En/DOM/NodeList
 
 * @param tagName {string} the tag of the elements to look for in the DOM
 * @param context {object} the context to search in
 * @returns {mixed} a DOM nodes array on success or an empty array on failure
 */
stima.html.nodeListToArray = function(nodeList){
	// we can't loop through whatever came as nodeList
	if(typeof nodeList.length == 'undefined') return [];
	
	// construct native array with nodeList contents
	var result = [];
	for(var i=0;i<nodeList.length;i++) result.push(nodeList[i]);
	return result;
}

/**
 * document.getElementByTagName wrapper;
 * this version returns a real javascript array of nodes, as opposed to the native
 * NodeList returned by the native method
 * @see stima#html#byTag
 * 
 * @param tagName {string} the tag of the elements to look for in the DOM
 * @param context {object} the context to search in
 * @returns {mixed} a DOM nodes array on success or an empty array on failure
 */

stima.html.byTag = function(tagName, context){
	// sanitize the tagname
	tagName = stima.util.trim(tagName.toLowerCase());
	
	// sanity check for empty tagname
	if(tagName == '') return [];
	
	if(typeof context == 'undefined') context = document;

	// we only check the existence of getElementsByTagName, not the type,
	// as IE sets the type to object, not function
	if(!stima.html.isNode(context, 'getElementsByTagName')) return [];

	// find the elements in the DOM and return them
	return stima.html.nodeListToArray(context.getElementsByTagName(tagName));
}

/**
 * get elements by class name
 * 
 * @param className {string} the css classname of the elements to look for in the DOM
 * @param context {object} the context to search in
 * @returns {mixed} a DOM nodes array on success or an empty array on failure
 */
stima.html.byClass = function(className, context){
	// sanitize the classname
	tagName = stima.util.trim(className);
	
	// sanity check for empty tagname
	if(className == '') return [];
	
	if(typeof context == 'undefined') context = document;
	
	// we only check the existence of getElementsByTagName, not the type,
	// as IE sets the type to object, not function
	if(!stima.html.isNode(context, 'getElementsByTagName')) return [];

	// find the elements in the DOM and return them
	var results = [];
	var children = stima.html.byTag('*', context);
	
	for(var i=0;i<children.length;i++) {
		// skip array methods injected by prototypejs (if include in page)
		if(!stima.html.isNode(children[i])) continue;
		
		// skip if no classname match
		if(!stima.html.hasClass(className, children[i])) continue;
		
		// add element to result array
		results.push(children[i]);
	}
	return results;
}

/**
 * DOM node cloner
 * 
 * @param node {object} the DOM node to clone
 * @returns {object} a clone of the DOM element, or null if node not found
 */
stima.html.clone = function(node){
	// sanity check
	if(!stima.html.isNode(node, 'cloneNode')) return false;
	
	// clone the node and return the clone
	return node.cloneNode(true);
}

/**
 * DOM node checker, checks if an object is a DOM node, and optionally,
 * if it has a specific property or if that property is of a specific
 * type
 * 
 * @param node {object} the object to test if it is a DOM node, 
 * @param prop {string} optional, the property to check if exists
 * @param type {string} optional, the type of the property if it exists
 * @returns {boolean} true if param is a DOM node
 */
stima.html.isNode = function(obj, prop, type){
	// sanity check
	if(typeof obj != 'object' || typeof obj['tagName'] == 'undefined') return false;
	
	// check if property is presentr
	if(typeof prop != 'undefined' && typeof obj[prop] == 'undefined') return false; 
	
	// check if property is of specific type
	if(typeof type != 'undefined' && typeof obj[prop] != type) return false; 

	// it's a DOM Node alright	
	return true;
}

/**
 * checks if a specified node has a specific css classname
 * 
 * @param classname {satring} the class to test the node against
 * @param node {object} the subject DOM node
 * @returns {boolean} true if node has specified class, false otherwise
 */
stima.html.hasClass = function(classname, node){
	// sanity check
	if(!stima.html.isNode(node)) return false;
	
	// find all classnames for the node
	var rawClass = node.className.split(' ');
	
	// test classname components
	for(var i=0;i<rawClass.length;i++) {
		// if found, return true
		if(classname == rawClass[i]) return true;
	}
	
	// didn't find the classname
	return false;
}

/**
 * adds a specified classname to the specified DOM node
 *
 * @param classname {string} the class to be added to the DOM node
 * @param node {object} the DOM node to process
 * @returns {boolean} if the class was added, or was already there
 */
stima.html.addClass = function(classname, node) {
	
	// no need to re-add the class
	if(stima.html.hasClass(classname, node)) return false;
	
	// add the separator if className not empty
	if(node.className != '') classname = ' ' + classname;
	
	// add the new class
	node.className = node.className + classname;
	
	// done
	return true;
}

/**
 * adds a specified classname to the specified DOM node
 *
 * @param classname {string} the class to be added to the DOM node
 * @param node {object} the DOM node to process
 * @returns {boolean} if the class was added, or was already there
 */
stima.html.removeClass = function(classname, node) {
	
	// no need to re-add the class
	if(!stima.html.hasClass(classname, node)) return false;
	
	// find all classnames for the node
	var rawClass = node.className.split(' ');
	
	// find the classname to be removed
	var newClass = [];
	for(var i=0;i<rawClass.length;i++) {
		// if found, skip it
		if(classname == rawClass[i]) continue;
		newClass.push(rawClass[i]);
	}
	node.className = newClass.join(' ');
	
	// done
	return true;
}

/**
 * toggle a classname for a DOM element
 *
 * @param classname {string} the class to be toggled
 * @param node {object} the DOM node to process
 */
stima.html.toggleClass = function(classname, node) {
	
	// if it has the class, remove it
	if(!stima.html.hasClass(classname, node)) {
		stima.html.addClass(classname, node);
		return;
	}
	
	// add the class if element does not have it
	stima.html.removeClass(classname, node);
}



/**
 * remove part of a classname from a DOM element's children
 *
 * @param classname {string} the class to be toggled
 * @param node {object} the DOM node to process
 */
stima.html.filterClasses = function(node, string){
	// sanity checks 
	if(!stima.html.isNode(node)) return;
	string = stima.util.trim(string);
	if(string == '') return;

	// gett all nodes including parent
	var nodes = stima.html.byTag('*', node);
	nodes.push(node);
	
	// loop and process the classname
	for(var i=0;i<nodes.length;i++) {
		// get all classnames
		var classes = nodes[i].className.split(' ');
		
		// filter each classname
		var filtered = [];
		for(var j=0;j<classes.length;j++) {
			// remove the string from classname
			classes[j] = stima.util.trim(classes[j].replace(eval('/'+string+'/gi'),''));
			
			if(classes[j] == '') continue;
			filtered.push(classes[j]);
		}
		
		nodes[i].className = filtered.join(' ');
	}
	
}

/**
 * deletes a DOM node from it's context
 *
 * @param node {object} the DOM node to be removed from context;
 */
stima.html.removeNode = function(node) {
	// sanity check
	if(!stima.html.isNode(node)) return false;
	
	//don't remove toplevel nodes
	if(!node.parentNode) return false;
	//remove the node from it's parent
	node.parentNode.removeChild(node);
	return true;
}


/**
 * Clones a node containing a form field; it is mandatory that the parent element should not
 * contain more than one field (except for the hidden input field in the case of a mandatory field),
 * because it will get cloned also, and the results ill be unpredictable.
 * 
 * Use the increment_id, increment_name and increment_value classname to specify which attributes are
 * to be changed. Use the 'mandatory' classname to mark elements that are to be displayed when a
 * field is mandatory. Note that these elements will be removed from the cloned node if the mandatory
 * parameter is false
 * 
 * @param parentID {string} the id of the parent container
 * @param mandatory {boolean} if the cloned field is to be made mandatory, defaults to false
 * @returns {boolean} false on success (needed for onclick to block the default click action)
 */

stima.html.addNewField = function(where, parentID, mandatory, mandatoryClass, desiredValue) {
//	alert(where);
	// sanitize the mandatory parameter
	if(typeof mandatory == 'undefined') mandatory = false;
	//else mandatory = !!mandatory;
	if(typeof mandatoryClass == 'undefined') mandatoryClass = 'mandatory';

	
	// try to find the parent
	var pNode = stima.html.byId(parentID);
	
	// store the number of copies in the DOM node itself
	if(typeof pNode.cx_fieldcount == 'undefined') pNode.cx_fieldcount = 1;
	
	// ok, we didn't find the parent node, nothing to do
	if(pNode == null) return;

	// make a clone of the parent node
	var clone = stima.html.clone(pNode);
	if(!clone) return;
	
	//this is the input fields
	//clone.children[1].children[1].value = '';
	//alert(clone.children[1].children[1].value);
	
//	alert(clone.innerHTML);
	// increment number of 
	pNode.cx_fieldcount++;
	
	// remove the elements that are present if the field is mandatory,
	// and the clone is not to be made mandatory
	if(!mandatory ) {
		var toBeRemoved = stima.html.byClass(mandatoryClass, clone);
		for(var i=0;i<toBeRemoved.length;i++) {
			stima.html.removeNode(toBeRemoved[i]);
		}
	
		// reset nodes textContent for non-mandatory
		var toBeReset = stima.html.byClass('reset_nonrequired', clone);

		for(var i=0;i<toBeReset.length;i++) {
			if(!stima.html.isNode(toBeReset[i])) continue;
			stima.html.text(toBeReset[i],'');
		}

		// filter classnames with the 'mandatory' field inside them
		stima.html.filterClasses(clone, 'mandatory');
	}
	
	// what to look for
	var tags = ['input', 'select', 'textarea'];
	
	// what to find and increment if necessary
	// ex 1:
	//		<span class="increment_id" id="field_1">something</span>
	// 		will become
	// 		<span class="increment_id" id="field_2">something</span>
	// ex 2:
	//		<span class="increment_name" name="name_1">something</span>
	// 		will become
	// 		<span class="increment_name" name="name_2">something</span>
	var incrementClasses = {
		'increment_id' 		: 'id',
		'increment_name'	: 'name',
		'increment_value'	: 'value'
	};
	
	// search for form fields in the cloned node
	var fields = [];
	for(i=0;i<tags.length;i++) {
		if(typeof tags[i] != 'string') continue;
		
		var tempnodes = stima.html.byTag(tags[i], clone);
		for(j=0;j<tempnodes.length;j++) {
			fields.push(tempnodes[j]);
		}
	}
	
	// take each classname
	for(cls in incrementClasses){
		// sanity check
		var crtcls = incrementClasses[cls];
		if(typeof crtcls != 'string') continue;
		
		// take each found elements and test
		for(j=0;j<fields.length;j++){
			
			// we found an element that has the current classname, so we modify the attribute
			if(stima.html.hasClass(cls, fields[j])){
				
				var oldAttributeValue = fields[j].getAttribute(crtcls);
				if(oldAttributeValue === null) continue;
				//console.log('old '+crtcls+' = '+oldAttributeValue);
				var newVal = oldAttributeValue;
				
				// find the fieldname, without the final _1
				var idx = oldAttributeValue.match(/[0-9]+$/gi);
				
				// reconstruct property value
				if(idx != '') newVal = oldAttributeValue.replace(/[0-9]+$/gi, pNode.cx_fieldcount );
				//console.log('new '+crtcls+' = '+newVal);
				
				// set the new attribute value
				fields[j].setAttribute(crtcls, newVal);
			}
		}
	}
	
	// increment content (if any)
	// ex: <span class="increment_content">Field 1</span>
	// will become <span class="increment_content">Field 2</span>
	var toIncrement = stima.html.byClass('increment_content',clone);
	for(var i=0; i<toIncrement.length;i++) {
		// skip non-dom nodes
		if(!stima.html.isNode(toIncrement[i])) continue;
		
		// get text value of the node
		var value = stima.html.text(toIncrement[i]);

		// find the fieldname, without the final _1
		var idx = value.match(/[0-9]+$/gi);
		
//		alert(value);
		// reconstruct property value
		if(idx != '') value = value.replace(/[0-9]+$/gi, pNode.cx_fieldcount );
		//alert(value);
		
		// assign new value
		stima.html.text(toIncrement[i], value);
		
	}

	// insert the node in the insertion point
	// go one level up and insert before the last element (the add more fields container)
	try{
		clone.children[1].children[0].value = desiredValue;
	}catch(ex){}
	pNode.parentNode.insertBefore(clone, where);
	
}


