/* - - - - - - - - - - - - - - - - - - - - -
Version info
$Id: forms.js 2079 2011-11-22 09:25:05Z jtangelder $
$Rev: 2079 $
$Author: jtangelder $
$LastChangedDate: 2011-11-22 10:25:05 +0100 (Tue, 22 Nov 2011) $
- - - - - - - - - - - - - - - - - - - - - */
Event.observe(window, 'load', function() {
	
	if($('id_course_type')) {
		Event.observe($('id_course_type'), 'change', function(event)
        {
			var courseType = $('id_course_type').getValue();

			// update the selectbox with courses
			updateCourses($('id_course'), $("container_course"), courseType, true);
		});

        var type = $('id_course_type').getValue();
        if(type)
        {
            updateCourses($('id_course'), $("container_course"), type, true);
        }

	}

    if($('id_course_type_after')) {
		Event.observe($('id_course_type_after'), 'change', function(event){

            var courseType = $('id_course_type_after').getValue();

			// update the selectbox with courses
			updateCourses($('id_course_after'), $("container_course_after"), courseType, false);
		});
	}


	if($('id_course')){
		Event.observe($('id_course'), 'change', function(event){
            toggleCourseInformation($('id_course_type').getValue(), $('id_course').getValue());
        });
	}


    // form validation
    if($('apfform'))    {
        Event.observe($('apfform'), 'submit', function(event)
        {


            if(
                ($('id_course').getValue() == '' || $('id_course_type').getValue() == '') ||
                ($('id_course_type').getValue() == 'preparatory' && (
                    $('id_course_after').getValue() == '' || $('id_course_type_after').getValue() == '')
                )
            )
            {
                alert('Please select a course.');
                event.preventDefault();
                return false;
            }
        });
    }

    
    // if the url has an course_id we load the options and set everything in its place
    selectCourseByUrl();



    toggleCourseInformation();
});




/* ========	 getCourseByType ======== */
function updateCourses(select_courses, courseContainer, courseType, toggleInfo)
{
    if(toggleInfo) {
        toggleCourseInformation(courseType, 0);
    }


    if(courseType == '') {
        courseContainer.hide();
        return;
    }

	// first remove previous options
	select_courses.options.length = 0;

	new Ajax.Request('/ajax/courses/' + courseType,{
		method: "get",
		parameters: '',
		onFailure: function(ajaxRequest){
			//console.log('There was an error with your request: '+ajaxRequest.responseText);
		},
		onSuccess: function(xhr) {
			var jsonObject = eval('(' + xhr.responseText + ')');
			
			var options = jsonObject.options;
			
			for (i=0; i<options.length; i++) {
				var optn 	= document.createElement("OPTION");
				optn.text 	    = options[i]['label'];
				optn.value 	    = options[i]['value'];
                optn.studielink = options[i]['text'];
				select_courses.options.add(optn, i);
			}

            courseContainer.show();

            if(toggleInfo) {
                toggleCourseInformation(courseType, 0);
            }
		},
		onComplete: function(ajaxRequest){
			//console.log('onComplete');
		}
	});
}

/* ========	set class and hide it ======== */
function toggleCourseInformation(courseType, courseId)
{
    if(!courseType || !courseId)
    {
        return;
    }

    // search for a value in an array
    function in_array(needle, array)
    {
        for(var i=0,len=array.length; i<len; i++)
        {
            if(array[i] == needle)
                return true;
        }

        return false;
    }

    var studielink_info = $("info_studielink").removeClassName("hide");
    var studielink_text_info = $("info_studielink_text");
    var preparatory_info = $("info_preparatory").removeClassName("hide");
    var form_submit = $("form_submit").removeClassName("hide");

    
    if(!courseType || !courseId)
    {
        studielink_info.hide();
        preparatory_info.hide();
        form_submit.hide();
    }

    // is croho course
    // show studielink info and hide submit and preparatory
    else if(in_array(courseId, croho_courses))
    {
        studielink_info.show();

        preparatory_info.hide();
        form_submit.hide();

        studielink_text_info.hide().update("");

        var options = $('id_course').options;
        for(var o=0; o<options.length; o++)
        {
            if(options[o].value == courseId && options[o].studielink)
            {
                studielink_text_info.show().update(options[o].studielink);

                // weird ie9 bug with OL tags
                studielink_text_info.select("ol").each(function(ol) {
                    ol.hide();
                    setTimeout(function() { ol.show(); }, 1);
                });
            }
        }

    }

    // is preparatory course
    else if(courseType == 'preparatory' && !in_array(courseId, croho_courses))
    {
        studielink_info.hide();
        preparatory_info.show();
        form_submit.show();
    }

    else
    {
        studielink_info.hide();
        preparatory_info.hide();
        form_submit.show();
    }
};



function selectCourseByUrl()
{
    // get url parameters
    var request = {};
    var groups = location.search.replace(/^\?/, '').split("&");
    for(var i=0,len=groups.length; i<len; i++)
    {
        var parts = groups[i].split("=");
        request[ parts[0] ] = parts[1];
    }


    // when course_id is set
    if(request.course_id)
    {
        // fetch all courses
        new Ajax.Request('/ajax/courses/',{
            method: "get",
            parameters: '',
            onFailure: function(ajaxRequest)
            {
                //console.log('There was an error with your request: '+ajaxRequest.responseText);
            },
            onSuccess: function(xhr)
            {
                var jsonObject = eval('(' + xhr.responseText + ')');
                var options = jsonObject.options;


                // search for the type of the course id
                var type = '';
                for(var i=0,len=options.length; i<len; i++)
                {
                    if(options[i].value == request.course_id)
                    {
                        type = options[i].type;
                        $('id_course_type').setValue(type);
                    }
                }


                // fill the courses
                var select_courses = $('id_course');
                for(var i=0,len=options.length; i<len; i++)
                {
                    if(options[i].type == type)
                    {
                        var optn 	    = document.createElement("OPTION");
                        optn.text 	    = options[i]['label'];
                        optn.value 	    = options[i]['value'];
                        optn.studielink = options[i]['text'];
                        select_courses.options.add(optn, i);

                        if(options[i].value == request.course_id)
                        {
                            optn.selected = true;
                            toggleCourseInformation( type, optn.value );
                        }
                    }
                }


            }
        });
    }

}
