/**
 * @desc: Get the selected date from the calendar
 *
 * @param: array $arr_input
 *
 * @global: object $oCalendar
 */
function get_date_from_calendar($arr_input)
{
	
	var $references = $oCalendar.getHtmlElementReferences(); // Get back reference to form field.

	$references.myDate.value = $arr_input.day + '.' + $arr_input.month + '.' + $arr_input.year;

	$oCalendar.hide();
	check_calenders($references.myDate.id);
}


/**
 * @desc: Call the calendar object en display the calendar
 *
 *
 * @param: object $object_button
 * @param: object $object_input
 *
 * @global: object $oCalendar
 */
function select_date($object_button , $object_input)
{	
	if (typeof($oCalendar) == "undefined"){
		$oCalendar = new DHTMLSuite.calendar({
			minuteDropDownInterval : 10 ,
			callbackFunctionOnDayClick : 'get_date_from_calendar' ,
			isDragable : false ,
			displayTimeBar : false ,
			calendarModelReference : new DHTMLSuite.calendarModel({
				languageCode : iso_lang // from site.tpl
			})
		}); 
	}
	$oCalendar.setCalendarPositionByHTMLElement($object_input , 0 , $object_input.offsetHeight + 2);
	$oCalendar.setInitialDateFromInput($object_input , 'dd.mm.yyyy');	
	$oCalendar.addHtmlElementReference('myDate' , $object_input);

	if ($oCalendar.isVisible())
	{
		$oCalendar.hide();
	}
	else
	{
		$oCalendar.resetViewDisplayedMonth();
		$oCalendar.display();
	}
	
}
function select_date2()
{
	
}

///####

var locations = Array();
var add_location;
var beforeChangePattern;
var afterChangePattern;
var changeData = Array();
Array.prototype.remove=function(s){
	var index = this.indexOf(s);
	if(this.indexOf(s) != -1)
		this.splice(this.indexOf(s), 1);
}

function get_locations($postal_code , $default_location_id,location,txt_location){
	var $length = $postal_code.length;

	/*
	console.log($postal_code);
	console.log($default_location_id);
	console.log(location);
	console.log(txt_location);
	*/
	
	//if (($length == 4 && $default_location_id == 1) || ($length == 4 && $default_location_id == 2))
	//{
		$('idLocationList_'+location).disabled = true;
		
		new Ajax.Request
		(
			'/ajax/get_locations_from_country.php' ,
			{
				method			: 'get' ,
				parameters		: {postal_code : $postal_code, country_id : $default_location_id} ,
				requestHeaders	: {Accept : 'application/json'} ,
				onSuccess		: function (transport)
				{
					
					var $arr_location = transport.responseText.evalJSON(true);
					var $total			= $arr_location.length;
					
					$('idLocationList_'+location).innerHTML = '';

					var $text			= document.createTextNode('Maak je keuze');
					var $new_option	= document.createElement('option');
					$new_option.value	= '';

					$new_option.appendChild($text);
					$('idLocationList_'+location).appendChild($new_option);
									

					for ($i = 0; $i < $total; $i++)
					{
						var $text			= document.createTextNode($arr_location[$i]['name']);
						var $new_option	= document.createElement('option');
						$new_option.value	= $arr_location[$i]['name'];						
						if (txt_location == $arr_location[$i]['name'])
						{
							$new_option.selected = "selected";
							
						}
						$new_option.appendChild($text);
						$('idLocationList_'+location).appendChild($new_option);
					}
					location_changed(null,location,txt_location);

					if ($total > 0)
					{
						//$oProfileHandler.approve('idHidLocation');
						//$objControl.check_element('idLocationList');
						
						$('idLocationList_'+location).style.display = '';
						if($('idLocation_'+location)){
							$('idLocation_'+location).style.display = 'none';
						}
						$('idHidLocation_'+location).value = $F('idLocationList_'+location);
						
						if($('txt_school_gemeente_'+location)){
							$('txt_school_gemeente_'+location).setStyle({display:'none'});
							$('txt_school_gemeente_'+location).setAttribute('disabled','disabled');
						}
					}
					
					else
					{						
						$('idLocationList_'+location).style.display = 'none';
						if($('idLocation_'+location)){
							$('idLocation_'+location).style.display = '';
						}
						$('idHidLocation_'+location).value = $F('idLocation_'+location);
						
						if($('txt_school_gemeente_'+location)){
							$('txt_school_gemeente_'+location).setStyle({display:'inline'});
							$('txt_school_gemeente_'+location).removeAttribute('disabled');
						}
					}
				}
			}
		);
		
		
		$('idLocationList_'+location).disabled = false;
		
		return true;
	//}
	
	return false;
}

function remove_required(step,id){
	objControl.$arr_required.remove(step+'|'+id);
	
	if ($(id + '_img')) {
		$(id + '_img').src = domain + "/" + template_dir + '/img/icons/empty.gif';
	}else{
		//console.log($(id + '_img'));
	}
	
	$(id + '_row') && $(id + '_row').removeClassName("required");
}


function add_required(step,id){
	//console.log(objControl.$arr_required);
	
	if (objControl.$arr_required.indexOf(step + '|' + id) == -1) {
		objControl.$arr_required.push(step + '|' + id);
		
		if ($(id + '_img')) {
			$(id + '_img').src = domain + "/" + template_dir + '/img/icons/required.gif';
		}else{
			//console.log('element met id: ' + id + '_img' + ' niet gevonden');
		}
		
		$(id + '_row') && $(id + '_row').addClassName("required");
	}
	//console.log(objControl.$arr_required);
}


function clear(){
	
	//console.log(locations);
	var table = $('step1_tbody');
	for(var i=0;i<locations.length;i++){
		
		remove_validation(locations[i]);
		
		if ($('date_' + locations[i])) {
			date = $('date_' + locations[i]);
			if(table.removeChild(date)){
				//console.log("$('date_'" + locations[i] + " removed");
			}
		}		
		
		if ($('location_' + locations[i])) {
			loc = $('location_' + locations[i]);
			if(table.removeChild(loc)){
				//console.log("$('location_'" + locations[i] + " removed");
			}
		}
		if ($('remove_' + locations[i] + '_row')) {
			rem = $('remove_' + locations[i] + '_row');
			if(table.removeChild(rem)){
				//console.log("$('remove_'" + locations[i] + " removed");
			}
		}
		//locations.remove(i);			
	}
	locations = Array();
	
}

function new_location($location){
	
	var loading_tr  = new Element('tr', {id: 'loading'});
	var loading_td  = new Element('td', {colspan: '3'}).setStyle({textAlign: 'center'});
	var loading_img = new Element('img', {src: '/template/default/img/icons/updating.gif'});
	
	loading_tr.appendChild(loading_td);
	loading_td.appendChild(loading_img);
	
	var table = $('step1_tbody');
	table.appendChild(loading_tr);
	
	var id = locations.length;
	locations[locations.length] = id;
	new Ajax.Request('/ajax/add_location.xml.php',{
		
		method: 'get',
		parameters: {'id':id},
		onSuccess: function(transport){
			var table = $('step1_tbody');
			
			if($('loading')){
				$('loading').remove();
			}
			
			var response = transport.responseXML.documentElement;
			
			$A(response.childNodes).each(function(childNode) {
				table.appendChild(XMLtoHTML(childNode));
			});
			
			id = transport.request.parameters.id;

			add_validation(id);

			if (add_location != null) {
				table.appendChild(add_location);
			}
			
			if($location != undefined){
				$('calendar_from_'+id).value = $location.agenda_from;
				$('calendar_until_'+id).value = $location.agenda_until;
				$$('#location_'+id+'_hour_from_h option').each(function(o){
					if(o.value == $location.hour_from_h)
						o.selected = true;
				});
				$$('#location_'+id+'_hour_from_m option').each(function(o){
					if(o.value == $location.hour_from_m)
						o.selected = true;
				});
				$$('#location_'+id+'_hour_until_h option').each(function(o){
					if(o.value == $location.hour_until_h)
						o.selected = true;
				});
				$$('#location_'+id+'_hour_until_m option').each(function(o){
					if(o.value == $location.hour_until_m)
						o.selected = true;
				});
				$$('#step1_country_'+id+' option').each(function(o){
					$location.country.each(function(c){
						if(o.value == c){
							o.selected= true;
							country_changed(null,id);
						}
					});
				});
				$location.country.each(function(c){
					switch(c){
						case "1": 
							$$('#step1_provincie_be_'+id+' option').each(function(o){
								$location.province.each(function(p){
									if(o.value == p){
										o.selected = true;
									}
								});
							});
							$is_be = true;
							break;
					}
					$('step1_postalCode_'+id).value = $location.postalcode[0];
					get_locations($location.postalcode[0],c,id,$location.city[0]);
				});
			}
			
			
			
		}
	});
}

function XMLtoHTML(xml) {
	
	switch(xml.nodeType) {
		case 1: // Element Node
			var elemAttr = {}, elemClass = '', elemStyle = {};
			var hasev = false;
			$A(xml.attributes).each(function(attr) {
				switch (attr.name) {
					case 'class':
						elemClass = attr.value;
						break;
					case 'style':
						attr.value.scan(/([^:;]+):([^;]+)/, function(styleRule) {
							elemStyle[styleRule[1].strip().camelize()] = styleRule[2].strip();
						});
						break;
					default:
						elemAttr[attr.name] = attr.value;
				}
			});
			
			var html = new Element(xml.nodeName, elemAttr).addClassName(elemClass).setStyle(elemStyle);
			//console.log(html);
			
			$A(xml.childNodes).each(function(childNode) {
				html.appendChild(XMLtoHTML(childNode));
			});
			
			return html;
		case 3: // Text Node
			// IE7 whitespace woes call for the strip() and extra spaces
			return document.createTextNode(' '+xml.nodeValue.strip()+' ');
	}
}

function remove_validation(location){
	remove_required(1,'calendar_from_'+location);
	remove_required(1,'calendar_until_'+location);
	remove_required(1,'step1_country_'+location)
	remove_required(1,'step1_provincie_be_'+location);
	remove_required(1,'step1_provincie_nl_'+location);
	remove_required(1,'step1_postalCode_'+location);
	remove_required(1,'idLocation_'+location);
	remove_required(1,'idLocationList_'+location);
	remove_required(1,'idHidLocation_'+location);
}

function add_validation(location){
	/* datum validatie */
	add_required('1','calendar_from_'+location);
	add_required('1','calendar_until_'+location);
	add_required('1','step1_country_'+location);
	
	if($('remove_' + location + '_row')){
		$('remove_' + location + '_row').setStyle({
			display: 'table-row'
		});
	}
	if($('step1_country_'+location)){
		Event.observe($('step1_country_'+location),'change',country_changed.bindAsEventListener(this,location));
	}
	if($('step1_postalCode_'+location)){
		Event.observe($('step1_postalCode_'+location),'change',postalcode_changed.bindAsEventListener(this,location));
	}
	if($('idLocationList_'+location)){
		Event.observe($('idLocationList_'+location),'change',location_changed.bindAsEventListener(this,location));
	}
	if($('remove_'+location)){
		Event.observe($('remove_'+location),'click',remove_location.bindAsEventListener(this,location));
	}
}

function check_calenders(date){
	if ($(date)) {
		if(typeof(objControl) != "undefined"){
			if ($(date).value != '') {
				objControl.approve_element(date);
			}else{
				objControl.reject_element(date);
			}
		}
	}
}

function location_changed(e,location,txt_location){
	txt_location = (txt_location == undefined || txt_location == null) ? "" : txt_location;
	
	var id = 'idLocation_'+location;

	for (var i=0; i < $('idLocationList_'+location).options.length; i++){
		if ($('idLocationList_'+location).options[i].selected) {
			 sel_location = $('idLocationList_'+location).options[i].value;
		}
	}
	sel_location = sel_location == "" ? txt_location : sel_location;
	
	if($('idLocation_'+location)){
		$('idLocation_'+location).value = sel_location;
	}
	if($('idHidLocation_'+location)){
		$('idHidLocation_'+location).value = sel_location;
	}
	
}

function postalcode_changed(e,location,txt_location){
	var element = $('step1_postalCode_'+location);
	var zip = element.value;
	if (zip != '') {
		if ($('step1_country_'+location).options[1].selected) {
			get_locations(zip, 1,location,txt_location);
		}else if ($('step1_country_'+location).options[2].selected) {
			get_locations(zip, 2,location,txt_location);
		}
	}
}

function country_changed(e,location){

	if($('step1_country_'+location).options[1].selected){ //belgie geselecteerd
		$('step1_provincie_be_'+location+'_row').setStyle({display:"table-row"});
		//add_required('1','step1_provincie_be_'+location);
		//Event.observe($('step1_provincie_be_'+location),'change',province_changed.bindAsEventListener(this,'step1_provincie_be_'+location));
	}else{
		$('step1_provincie_be_'+location+'_row').setStyle({display:"none"});
		//remove_required('1','step1_provincie_be_'+location);
	}
		
	//bij het laden van de pagina provincies selectie niet verwijderen.
	//load : e=null
	//klikken : e=change
	if(e != null){
		options = $('step1_provincie_be_'+location).options;
		for(i=0;i<options.length-1;i++){
			options[i].selected = false;
		}	
	}						
	
	if($('step1_country_'+location).options[2].selected){ //nederland geselecteerd
		$('step1_provincie_nl_'+location+'_row').setStyle({display:"table-row"});
		//add_required('1','step1_provincie_nl_'+location);
		//Event.observe($('step1_provincie_nl_'+location),'change',province_changed.bindAsEventListener(this,'step1_provincie_nl_'+location));
	}else{
		$('step1_provincie_nl_'+location+'_row').setStyle({display:"none"});
		//remove_required('1','step1_provincie_nl_'+location);
	}
	
	if(e != null){
		options = $('step1_provincie_nl_'+location).options;
		for(i=0;i<options.length-1;i++){
			options[i].selected = false;
		}
	}				
	
	$('step1_postalCode_'+location+'_row').setStyle({display:"table-row"});
	$('idLocation_'+location+'_row').setStyle({display:"table-row"});
		
	/*
	 * geen validatie zie kalender testdossier 5 puntje 11
	 */
	//add_required('1','step1_postalCode_'+location);
	//add_required('1','idLocation_'+location);
	
	//console.log(objControl.$arr_required);
	
	objControl.check_element('step1_country_'+location);
}

function province_changed(e,id){
	objControl.check_element(id);
}

function add_new_location(e,$location_data){
	new_location($location_data);
}

function remove_location(e,location){
	remove_validation(location);
	
	var table = $('step1_tbody');
	if ($('date_' + location)) {
		date = $('date_' + location);
		table.removeChild(date);
	}		
	
	if ($('location_' + location)) {
		loc = $('location_' + location);
		table.removeChild(loc);
	}
	
	if ($('remove_' + location + '_row')) {
		rem = $('remove_' + location + '_row');
		table.removeChild(rem);
	}
	locations.remove(location);
}

function init_return_pattern(e,mode,iso_lang){

	$oCalendar = new DHTMLSuite.calendar(
			{
				minuteDropDownInterval		: 10 ,
				callbackFunctionOnDayClick	: 'get_date_from_calendar' ,
				isDragable						: false ,
				displayTimeBar					: false ,
				calendarModelReference		: new DHTMLSuite.calendarModel(
				{
					languageCode : iso_lang
				})
			});
	Event.observe($('btn_add_location'),'click',add_new_location.bindAsEventListener(this));
	
	if($('return_pattern_serie_date')){
		var rem_element = $('return_pattern_serie_date');
		var table = rem_element.parentNode;
		add_location = table.removeChild(rem_element);
	}

	table.appendChild(add_location);

	if(mode == 'add'){
		new_location();
	}
}

function convert(data,new_id){
	//console.log(data);
	$('calendar_from_'+new_id).value = data[0]; // datum from
	check_calenders('calendar_from_'+new_id);
	
	from_hour = document.getElementsByName("location["+new_id+"][calendar_hour_from_h]");
	from_minutes = document.getElementsByName("location["+new_id+"][calendar_hour_from_m]");
	until_hour = document.getElementsByName("location["+new_id+"][calendar_hour_until_h]");
	until_minutes = document.getElementsByName("location["+new_id+"][calendar_hour_until_m]");
	
	data[2][0] = data[2][0].length == 1 ? "0"+data[2][0] : data[2][0];
	data[2][1] = data[2][1].length == 1 ? "0"+data[2][1] : data[2][1];
	data[2][2] = data[2][2].length == 1 ? "0"+data[2][2] : data[2][2];
	data[2][3] = data[2][3].length == 1 ? "0"+data[2][3] : data[2][3];
	
	for(i=0; i < from_hour[0].options.length; i++){
		val = from_hour[0].options[i].value;
		if(val == data[2][0]){
			from_hour[0].options[i].selected = "selected";
		}
	}
	for(i=0; i < from_minutes[0].options.length; i++){
		val = from_minutes[0].options[i].value;
		if(val == data[2][1]){
			from_minutes[0].options[i].selected = "selected";
		}
	}
	for(i=0; i < until_hour[0].options.length; i++){
		val = until_hour[0].options[i].value;
		if(val == data[2][2]){
			until_hour[0].options[i].selected = "selected";
		}
	}
	for(i=0; i < until_minutes[0].options.length; i++){
		val = until_minutes[0].options[i].value;
		if(val == data[2][3]){
			until_minutes[0].options[i].selected = "selected";
		}
	}									
	
	
	for(i=0; i<$('step1_country_'+new_id).options.length; i++){ // land
		if($('step1_country_'+new_id).options[i].value == data[3]){
			$('step1_country_'+new_id).options[i].selected = "selected";
		}
	}
	for(i=0; i<$('step1_provincie_be_'+new_id).options.length; i++){ // province
		data[4].each(function(s){
			if($('step1_provincie_be_'+new_id).options[i].value == s){
				$('step1_provincie_be_'+new_id).options[i].selected = "selected";
			}
		});
	}
	$('step1_postalCode_'+new_id).value = data[5];
	get_locations(data[5],data[3],new_id,data[6]);
}	