/**
 * The KucoCourseData object is responseble for course data retrieval
 *
 * @author Strawberries (KS)
 */
var KucoCourseData = new Class({

	/**
	 * Options
	 * @type {Object}
	 */
	options: 	{
				action: 'GetCourse',
				url: '/sbeos/ajax/JsonCall.php',
				onStart: Class.empty,
				onData: Class.empty,
				onFail: Class.empty
				},
	
	/**
	 * @type {String}
	 */
	courseid: null,
	
	/**
	 * @type {String}
	 */
	courseData: null,
	
	/**
	 * Indicates if data is being retrieved
	 * @type {Boolean}
	 */
	pending: false,

	/**
	 * @constructor
	 * @param {String} courseid
	 * @param {Object} options
	 */
	initialize: function(courseid, options) {
		this.setOptions(this.options, options);
		this.courseid = courseid;
	},
	
	/**
	 * Returns the courseid of the object
	 * 
	 * @return {String}
	 */
	getCourseId: function() {
		return this.courseid;
	},
	
	/**
	 * Returns the courec html.
	 * If no html is set will return null
	 *
	 * @return {String}
	 */
	getCourseHTML: function() {
		
		if(this.courseData !== null) {
			return this.courseData.courseHtml;
		} 
		return null;

	},
	
	/**
	 * Retrieves the course data and calls the onData method
	 * when data is retrieved (or served from memory)
	 *
	 * @param {Function} onData
	 */
	retrieveCourseData: function() {

		if(this.pending === false) {
			this.fireEvent('onStart', this);
			this.doRetrieveCourseData();
		}
		
	},
	
	/**
	 * Will start the data retrieval
	 */
	doRetrieveCourseData: function() {
		
		this.pending = true;


		var postObject = JSON.encode({
			action:this.options.action, 
			Course: this.getCourseId()
		});
		var request = new Request.JSON({
			url: this.options.url,
			data: {json: postObject},
			onSuccess: 		this.courseDataSuccesHandler.bindWithEvent(this),
			onFailure: 		this.courseDataFailureHandler.bindWithEvent(this),
			onStateChange: 	this.courseDataStateChangeHandler.bindWithEvent(this)
		}).send();
	},
	
	/**
	 * Handles data xhr succes 
	 *
	 * @private
	 */
	courseDataSuccesHandler: function(response) {
		this.courseData = response;
		this.pending = false;
		this.fireEvent('onData', this);
	},
	
	/**
	 * Handles data xhr failure 
	 *
	 * @private
	 */
	courseDataFailureHandler: function(xhrObj) {
		this.pending = false;
		this.fireEvent('onFail', 'Error');	
	},
	
	/**
	 * Handles data xhr state change 
	 *
	 * @private
	 */
	courseDataStateChangeHandler: function(xhrObj) {
		/*
//		window.console.log(xhrObj);
		if($chk(xhrObj) && $chk(xhrObj.status)) {
			var msg = '';
			switch(xhrObj.status) {
				case 404:

					if($chk(xhrObj.statusText)) {
						msg = xhrObj.statusText;
					} else {
						msg = 'Data Not Found';
					}
					
					xhrObj.abort();

					this.fireEvent('onFail',msg);
					break;
			}
			
		}
		*/	
	}
	
});
KucoCourseData.implement(new Options);
KucoCourseData.implement(new Events);
KucoCourseData.implement(new Chain);
//End KucoCourseData

KucoCourse = new Class({
	
	/**
	 * @type {Object}
	 */
	options: {},
	
	/**
	 * @type {NUmber}
	 */
	courseid: null,
	
	/**
	 * @type {Element}
	 */
	knob: null,

	/**
	 * @type {Element}
	 */
	indicator: null,
	
	/**
	 * @type {Element}
	 */
	container: null,
	
	/**
	 * @type {KucoCourseData}
	 */
	courseData: null,
	
	/**
	 * @type {Fx.Slide}
	 */
	fxObj: null,
	
	/**
	 * @type {Boolean}
	 */
	htmlIsSet: false,
	
	/**
	 * @type {Boolean}
	 */
	opened: false,
	
	/**
	 * @constructor
	 * @param {Element} knob The trigger button
	 * @param {Element} container The course data display container
	 * @param {KucoCourseData} courseData The course data controller
	 * @param {Object} options
	 */
	initialize: function(courseid, knob, container, indicator, options) {
		
		this.setOptions(this.options, options);
		
		this.courseid = courseid;
		this.knob = knob;
		this.container = container;
		this.indicator = indicator;
		
		this.initCourse();
		
	},
	
	/**
	 * @private
	 */
	initCourse: function() {
		
		this.fxObj = new Fx.Slide(this.container, {duration: 500});
		this.fxObj.hide();
		this.courseData = new KucoCourseData(
											this.courseid, 
											{
												onData: this.displayCourseData.bind(this),
												onFail: this.courseDataFailed.bind(this)
											});
		this.knob.addEvent('click', this.toggleCourseData.bind(this));
		this.knob.addEvent('mouseover', this.setOverState.bind(this));
		this.knob.addEvent('mouseout', this.setOutState.bind(this));
		
	},
	
	setOverState : function() {
		if(this.opened === false) {
			this.knob.removeClass('voor-alle-row2');
			this.knob.addClass('voor-alle-row2-sel');	
		}
	},
	
	setOutState: function() {
		if(this.opened === false) {
			this.knob.removeClass('voor-alle-row2-sel');
			this.knob.addClass('voor-alle-row2');
		}
	},
	
	toggleCourseData: function() {
		
		if(this.htmlIsSet) {
			
			if(this.opened === true) {
				this.knob.removeClass('voor-alle-row2-sel');
				this.knob.addClass('voor-alle-row2');				
				this.fxObj.slideOut();
				this.opened = false;
			} else {
				this.knob.removeClass('voor-alle-row2');
				this.knob.addClass('voor-alle-row2-sel');
				this.fxObj.slideIn();
				this.opened = true;
			}
			
			
		} else {
			this.indicator.setStyle('visibility', 'visible');
			this.courseData.retrieveCourseData();
		}
		
	},
	
	/**
	 * Called by courseData's onData
	 *
	 * @private
	 * @param {KucoCourseData} courseData
	 */
	displayCourseData: function(courseData) {

		if(!this.htmlIsSet) { // Need to set the html inside the container
			var courseHTML = courseData.getCourseHTML();
			if(courseHTML !== null) {
				var tmpContainer = new Element('div').set('html', courseHTML);
				tmpContainer.injectTop(this.container);
				this.htmlIsSet = true;
				this.fxObj.slideIn();
				this.opened = true;
				this.knob.removeClass('voor-alle-row2');
				this.knob.addClass('voor-alle-row2-sel');
			} else {
				this.courseDataFailed(courseData);
			}
			this.indicator.setStyle('visibility', 'hidden');	
		}

	},
	
	/**
	 * Called by courseData's onFail
	 *
	 * @private
	 * @param {KucoCourseData} courseData
	 * @param {XHR} The failing request
	 */
	courseDataFailed: function(reason) {
		this.indicator.setStyle('visibility', 'hidden');
	}
	
	
	
});
KucoCourse.implement(new Options);
KucoCourse.implement(new Events);
KucoCourse.implement(new Chain);
//End KucoCourseData


var courseObjects = new Hash();

//Course init
var KucoInitCourseView = function() {
	
	//Get all course rows from dom
	var courseRows = $$('.cursus-row');
	
	//Activate all rows
	for(var i=0;i<courseRows.length;i++) {
		
		var currentRow = courseRows[i];
		
		//Get the three different elements
		var rowKnob			= currentRow.getElement('.voor-alle-row2');	//$ES('.voor-alle-row2', currentRow)[0];
		var courseContainer	= currentRow.getElement('.voor-alle-box');	//  $ES('.voor-alle-box', currentRow)[0];
		var clearObject		= currentRow.getElement('.clear5');			//  $ES('.clear5', currentRow)[0];
		
		//Get indicator and hide
		var indicator = currentRow.getElement('.indicator');			// $ES('.indicator', currentRow)[0];
		indicator.setStyle('visibility', 'hidden');
		
		//Get current rows course id
		var currentCourseId	= courseContainer.getProperty('id');
		
		// Create course object
		var courseObject = new KucoCourse(currentCourseId, rowKnob, courseContainer, indicator);
		
		//Add to courseObjects Hash for later use
		courseObjects.set(currentCourseId, courseObject);
		
	} // End for courseRows.length
	
	
	/**Old code needed for stuff**/
	P7_initPM(1,15,1,-4,1);
	//new Accordion($$('ul#subNavigation li.toggler'), $$('#subNavigation li.element'));


	new Accordion($$('.faqQuestion'), $$('.faqAnswer'), { alwaysHide: true });
	if($chk($('presentatiePager'))){
		presentationPager();
	}

	projectFilter = displayItem('filterfield');
	if(projectFilter != ""){
		$(projectFilter).selected = true;
	}
	artistFilter = displayItem('artistfilter');
	if(artistFilter != ""){
		art_filter_vals = artistFilter.split(";");
		art_filter_vals.each(function(item,index){
								$(item).selected = true;
							}
		)
	}
	
}

// DomReady Trigger
window.addEvent('domready', KucoInitCourseView)





/*
window.addEvent('load', function() {
	P7_initPM(1,15,1,-4,1);
	new Accordion($$('ul#subNavigation li.toggler'), $$('#subNavigation li.element'));

	if ($chk($E('.voor-alle-box'))) {
		cursusSlider();
	}

	new Accordion($$('.faqQuestion'), $$('.faqAnswer'), { alwaysHide: true });

	if($chk($('presentatiePager'))){
		presentationPager();
	}

	projectFilter = displayItem('filterfield');
	if(projectFilter != ""){
		$(projectFilter).selected = true;
	}
	artistFilter = displayItem('artistfilter');
	if(artistFilter != ""){
		art_filter_vals = artistFilter.split(";");
		art_filter_vals.each(function(item,index){
								$(item).selected = true;
							}
		)
	}
});
*/












/************ OLD ***************/





function handleCourse(returnvalue){
	//returnvalue = Json.evaluate(jsonObject);

	courseHtml = returnvalue.courseHtml;
	courseID = returnvalue.Course;
	
	selector = 'course' + courseID;
	currentHTML = $(selector).innerHTML; 
	$(selector).set('html', courseHtml + currentHTML);
}
	



/**
 * Slider functionality
 */
var sliderBehaviour = {
		hidden: false,
		currentFX: null,
		courses: new Array(),
		init: function() {
			this.collapse();
		},
		show: function() {
			this.hidden = false;
			this.getFX().slideIn();
			this.getParent().getPrevious().removeClass('voor-alle-row2');
			this.getParent().getPrevious().addClass('voor-alle-row2-sel');
            var children = this.getParent().getPrevious().getChildren();
            children[4].getFirst().innerHTML = 'Sluiten';
		},
		scroll: function() {
			var el = this.getParent().getPrevious();
			var posTop = 0;
			if (el.offsetParent) {
				posTop = el.offsetTop
				while (el = el.offsetParent) {
					posTop += el.offsetTop
				}
			}
			window.scrollTo(0, posTop);
		},
		hide: function() {
			this.hidden = true;
			this.getFX().slideOut();
			this.getParent().getPrevious().removeClass('voor-alle-row2-sel');
			this.getParent().getPrevious().addClass('voor-alle-row2');
            var children = this.getParent().getPrevious().getChildren();
            children[4].getFirst().innerHTML = 'Lees meer \>';
		},
		collapse: function() {
			this.hidden = true;
			this.getFX().hide();
		},
		expand: function() {
			this.hidden = false;
			this.getFX().show();
		},
		isHidden: function() {
			return this.hidden; //Or true
		},
		toggle: function() {
			if(this.isHidden()) {

				/* Get Course information */
				if (!contains(this.courses ,(this.id))) {
					loadCourseInfo(this.id);
					this.courses[this.courses.length] = this.id ;
				}

				this.scroll();
				this.show();
			} else {
				this.hide();				
			}
		},
		getFX: function() {
			if(this.currentFX == null) {
				this.currentFX = new Fx.Slide(this, {duration: 500});
			} 
			return this.currentFX;
		}
};


function changeStyle(style){
	if ($('menu' + style)) {
		$('menu' + style).className = style+'-sel';
	}
};



function MM_showHideLayers() { //v9.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
};





function cursusSlider() {
	var elementsCursus = $$('.voor-alle-box');

	if (elementsCursus.length > 0) {
	    var knobs = $$('.voor-alle-row2');

	    for(var i=0;i<elementsCursus.length;i++) {
		    $(elementsCursus[i]).extend(sliderBehaviour);
		    $(elementsCursus[i]).init();
            $(knobs[i]).addEvent("click", $(elementsCursus[i]).toggle.bindAsEventListener($(elementsCursus[i])));
            $(knobs[i]).addEvent('mouseover', function() {
                this.addClass('voor-alle-row2-hover');
                this.removeClass('voor-alle-row2');
		    });
            $(knobs[i]).addEvent('mouseout', function() {
			    this.removeClass('voor-alle-row2-hover');
			    this.addClass('voor-alle-row2');
		    });
	    }
    }
    window.scrollTo(0, 0);
}

function presentationPager(){
	presentationDiv = $('presentatiePager');
	pageCounter = 0;
	artist = displayItem('kid');
	$$('#presentatiePager .pager').each(function(item){
		item.addEvent('click',function(){getPresentation(item.id)});
	});
	$$('#presentatiePager .pager-sel').each(function(item){
		item.addEvent('click',function(){getPresentation(item.id)});
	});
	if ($chk($('presentatieBox'))) {
		$('presentatieBox').addEvent('change',function (){ 
			$$('#presentatieBox option').each(function(item,index){
					if(item.id == $('presentatieBox').value){
						pageCounter = index;
						getPresentation(pageCounter+':'+artist);				
					}
				})		
		
		});
	}
					
	$$('#presentatiePager #prev').each(function(item){
		item.addEvent('click',function(){
				if(pageCounter > 0){
					$('prev').className = 'pager-prev';
					pageCounter = pageCounter - 1;
					getPresentation(pageCounter+':'+artist);
				}								
			
		});
	});
	
	$$('#presentatiePager #next').each(function(item){
		item.addEvent('click',function(){
					pageCounter = pageCounter + 1;
					if($chk($(pageCounter+':'+artist))){
						getPresentation(pageCounter+':'+artist);
					}else{
						pageCounter = pageCounter - 1;
					}
			});
	});

}
function getPresentation(item){
	if(!$chk($((pageCounter+1)+':'+artist))){
		$('next').removeEvent('click');	
		$('next').className = 'pager-next-disabled';
	}else{
		$('next').className = 'pager-next';	
	}
	if(pageCounter == 0){
		$('prev').className = 'pager-prev-disabled';
		$('prev').removeEvent('click');	
	}else{

		$('prev').className = 'pager-prev';
	}
	
	$$('#presentatiePager .pager-sel').each(function(item){
						item.className='pager';
					});

	$(item).className = 'pager-sel';

	var postObject = JSON.encode({
		'action':'GetPresentation',
		'Artist':item
	});
	var request = new Request.JSON({
	  url: '/sbeos/ajax/JsonCall.php',
	  data: {json: postObject},
	  onSuccess: handlePresentation.bindWithEvent(window)
	}).send();
}

function handlePresentation(returnvalue){
	//returnvalue = Json.evaluate(jsonObject);
	presentation = returnvalue.presentationObject;
	
	if(presentation.image != null){
		$('presentatieImage').innerHTML = presentation.image;
	}else{
		$('presentatieImage').innerHTML = '&nbsp;';
	}
	
	if(presentation.material != null){
		$('itemMateriaal').innerHTML = presentation.material;
	}else{
		$('itemMateriaal').innerHTML = '&nbsp;';
	}
	if(presentation.website != null){
		$('itemLink').innerHTML = presentation.website;
	}else{
		$('itemLink').innerHTML = '&nbsp;';
	}
	if(presentation.description != null){
		$('presentatieDescr').innerHTML = presentation.description;
	}else{
		$('presentatieDescr').innerHTML = '&nbsp;';
	}
	
	$('pres:'+presentation.id).selected = true;
}

function doArtistFilter(startNode){
	nodeid = startNode;
	var filter1 = '';
	var filter2 = '';
	if($('sel_specialisme').value != '') filter1 = $('sel_specialisme').value;	
	if($('sel_achterletter').value != ''){
		filter2 = $('sel_achterletter').value;
		if(filter1 != '')	filter2 = ';'+filter2;
	}
	
	window.location.href='?node_id='+nodeid+'&pager=0&artistfilter='+filter1+filter2;
}

function doFilter(filtervalue){
	
	nodeid = displayItem('node_id');
	window.location.href='?node_id='+nodeid+'&pager=0&filterfield='+filtervalue;
}

function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
			}
			return false;
		}
		this.getParameters = function() {
			var a = new Array(this.getLength());
			for(var j=0; j < this.keyValuePairs.length; j++) {
				a[j] = this.keyValuePairs[j].split("=")[0];
			}
			return a;
		}
		this.getLength = function() { return this.keyValuePairs.length; } 
}
function queryString(key){
		var page = new PageQuery(window.location.search); 
		return unescape(page.getValue(key)); 
}
function displayItem(key){
		if(queryString(key)=='false'){
			if ($chk($(key))) {
				return $(key).value;
			}
			return ('');
		}else{
			return (queryString(key));
		}
}

function loadCourseInfo(courseid) {
	var postObject = JSON.encode({
		'action':'GetCourse',
		'Course':courseid
	});
	var request = new Request.JSON({
		url: '/sbeos/ajax/JsonCall.php',
  		data: {json: postObject},
  		onSuccess: handleCourse.bindWithEvent(window)
	}).send();
	

//	var request = new Json.Remote('../ajax/JsonCall.php' ,{async: false, onSuccess: handleCourse.bindAsEventListener(window)});
//	request.send({'action':'GetCourse','Course':courseid});
}

function handleCourse(jsonObject){
	returnvalue = Json.evaluate(jsonObject);

	courseHtml = returnvalue.courseHtml;
	courseID = returnvalue.Course;
	
	selector = 'course' + courseID;
	currentHTML = $(selector).innerHTML; 
	$(selector).set('html', courseHtml + currentHTML);
}

/* Array functions */
contains = function(array, item, from){
	return array.indexOf(item, from) != -1;
}


var searchBlur = function() {
	if(this.value=='') {
		this.value='Typ uw zoekterm';
	};
};

var searchFocus = function() {
	if(this.value=='Typ uw zoekterm') {
		this.value='';
	};
};



window.addEvent('domready', function() {
	var searchForm = $('searchForm');
	var searchField = $('Typuwzoekterm');
	var searchSubmitButton = $('zoeken-button');
	
	var searchFormSubmit = function() {
		searchFocus.run([], this);
		$('searchForm').submit();
		return true;
	};
	
	if ($chk(searchField) ){
		searchField.addEvents({
			'blur': searchBlur.bind(searchField),
			'focus': searchFocus.bind(searchField)
		});

		searchForm.addEvent('submit', searchFormSubmit.bind(searchField));
		searchSubmitButton.addEvent('click', searchFormSubmit.bind(searchField));
	}
	
});