//helpers
Event.observe(window, 'load', function() {
	$$('body')[0].addClassName('js');
});

/* FUNCTIONS */
/*Extending the fireClose function of dbnLayer with a callback*/
if (typeof(fireClose) != 'undefined') {
	extendedFireClose = fireClose;
	
	fireClose = function(callback) {
		extendedFireClose(callback);
		//adding extended functionality here
		//callbacks for the registration form
		if(callback == 'resetRegistrationForm') {
			$('registrationForm').reset();
			
			//deprecated
			//			$('registrationForm').removeClassName('formHasChanges');
			//
			//			//iterate over all fields that are not prefilled and clear them
			//			var notPrefilledInputs = $$('#registrationForm input[value=""]');
			//			notPrefilledInputs.each(function(inputToClear){
			//				inputToClear.clear();
			//			});
		}
		if(callback == 'resetTimetableForm') {
			$('timetableForm').reset();
			
			//deprecated
			//			$('timetableForm').removeClassName('formHasChanges');
			//			
			//			//see above code
			//			var notPrefilledInputs = $$('#timetableForm input[value=""]');
			//			notPrefilledInputs.each(function(inputToClear){
			//				inputToClear.clear();
			//			});
		}
	}
}


var fx;
var counter = 0;
var slider;
var tab;
var faq;

/**
 *	@Descr: Tabs
 */
var Tab = Class.create();
Object.extend(Tab.prototype, {
	initialize: function(id) {
		this.id = id;
		var tabs = $$('ul#' + this.id + ' li a')
		tabs.each(function(tab) {
			Event.observe(tab, 'click', function(event) {
				event.stop();
				tabs.invoke("toggleClassName", 'active');
				$$('div.tab').each(function(tabContent) {
					tabContent.toggle();
					sIFR.replace(din, {
						selector: '.violetBox .tabContent h3',
						css: '.sIFR-root { color: #292371; font-size: 17px; }',
						wmode: 'transparent',
						ratios: [8, 1.41, 11, 1.31, 15, 1.29, 16, 1.28, 24, 1.26, 27, 1.24, 33, 1.23, 44, 1.22, 47, 1.21, 48, 1.22, 73, 1.21, 74, 1.2, 75, 1.21, 76, 1.2, 78, 1.21, 79, 1.2, 80, 1.21, 84, 1.2, 85, 1.21, 1.2]
					});
				});
				return false;
			});
		});
	}
});


/**
 *	@Descr: Accordion
 */
var Faq = Class.create();
Object.extend(Faq.prototype, {
	initialize: function(id) {
		this.id = id;
		this.isDisabled == false;  //css class 'disabledFaqBox', set if an accordion element is disabled, e.g. if a user is not logged in
		this.toggleBox = this.toggleBox.bindAsEventListener(this);
		this.button = $$('#' + this.id + ' h5')[0];
		
		if (!$(this.id).hasClassName('disabledFaqBox')) {//just a primitive check, if the element is disabled
			this.button.observe('click', this.toggleBox);
		}
		else {
			this.isDisabled = true;
		}
		
		this.content = $(this.id).down('.faqContent');
	},
	toggleBox: function(event) {
		if (!this.isDisabled == true) {
			this.button.stopObserving('click', this.toggleBox);
			if (this.content.style.display == "none") {
				this.openBox(this.id, this.content);
			}
			else {
				this.closeBox(this.id, this.content);
			}
		}
	},
	openBox: function(id, content) {
		fx = new Effect.BlindDown(content, {
			duration: 0.5,
			beforeStart: function() {
				$(id).toggleClassName('activeFaqBox');
			}.bind(this),
			afterFinish: function() {
				this.button.observe('click', this.toggleBox);
				content.style.height = "";//this cleans up after the function call
			}.bind(this)
		});
	},
	closeBox: function(id, content) {
		fx = new Effect.BlindUp(content, {
			duration: 0.5,
			afterFinish: function() {
				$(id).toggleClassName('activeFaqBox');
				this.button.observe('click', this.toggleBox);
			}.bind(this)
		});
	}
});

Event.observe(window, 'load', function() {
	$$('ul.slides').each(function(slides) {
		slides.id = "slides_" + counter++;
		slider = new Slider(slides.id, 1, true, true);
	});
	counter = 0;
	$$('ul.tabs').each(function(tabs) {
		tabs.id = "tabs_" + counter++;
		tab = new Tab(tabs.id);
	});
	counter = 0;
	$$('.faqBox').each(function(faqBox) {
		faqBox.id = "faq_" + counter++;
		faqBox.down('.faqContent').style.display = "none";
		faq = new Faq(faqBox.id);
	});
});


/**
 * @Descr: timetable_location form
 * DEPRECATED
 */
Event.observe(window, 'load', function() {
	var location_name = $('timetable_location_name');
	var location_range = $('timetable_location_range');
	var radio1 = $('timetable_location_id_1');
	var radio2 = $('timetable_location_id_2');
	var rangeLabel = $$('label[for=timetable_location_range]')[0];
	if (location_name) {
		location_name.writeAttribute("disabled", "disabled");
		location_range.writeAttribute("disabled", "disabled");
		
		location_name.up().setOpacity(0.5);
		location_range.up().setOpacity(0.5);
		rangeLabel.setOpacity(0.5);
		
		radio1.observe('click', (function() {
			location_name.value = " ";
			location_name.writeAttribute("disabled", "disabled");
			location_range.removeAttribute("disabled");
			
			location_name.up().setOpacity(0.5);
			location_range.up().setOpacity(1);
			rangeLabel.setOpacity(1);
		}));
		radio2.observe('click', (function() {
			location_range.value = " ";
			location_range.writeAttribute("disabled", "disabled");
			location_name.removeAttribute("disabled");
			
			location_name.up().setOpacity(1);
			location_range.up().setOpacity(0.5);
			rangeLabel.setOpacity(0.5);
		}));
	}
	
	
	
	/* MULTIPICMODUL HOME */
	var multipicmod = $('multipictureProfileWrapper');
	
	if (multipicmod) {
		$$("div.multipictureProfile").each(function(item) {
			item.observe('mouseover', function() {
				var test = this.childElements()[0].addClassName("hideIt");
				//console.log("mouseover", test);
			});
		});
		$$("div.multipictureProfile").each(function(item) {
			item.observe('mouseout', function() {
				var test = this.childElements()[0].removeClassName("hideIt");
				//console.log("mouseout");
			});
		});
	}
});



Event.observe(window, 'load', function() {
	/**
	 * @Descr:
	 * Handle the registration (accordion)
	 * observe forms and store state (when there are changes) in class name "formHasChanges"
	 */
	//registration form
	if ($('registrationForm')) {
		//		var registrationObserve = new Form.Observer('registrationForm', 0.33, function(form, value) {
		//			$(form).addClassName('formHasChanges');
		//		});
	
		//serialize the form in its original state and save the value
		var registrationFormOldValue = $('registrationForm').serialize();
		//console.log('registrationFormOldValue is: ' + registrationFormOldValue);
		//var registrationFormActualValue;
	}
	
	//timetable form
	if ($('timetableForm')) {
		//		var uploadsObserve = new Form.Observer('timetableForm', 0.33, function(form, value) {
		//			$(form).addClassName('formHasChanges');
		//		});
		
		//serialize the form in its original state and save the value
		var timetableFormOldValue = $('timetableForm').serialize();
		//console.log('timetableFormOldValue is: ' + timetableFormOldValue);
		//var timetableFormActualValue;
	}
	
	/**
	 * @Descr:
	 * 	This supports trigger native events such as 'onchange'
	 * 	whereas prototype.js Event.fire only supports custom events
	 * @See:
	 * 	-	http://stackoverflow.com/questions/460644/trigger-an-event-with-prototype
	 * 	-	http://stackoverflow.com/questions/590289/javascript-event-that-fires-without-user-interaction/590339#590339
	 */
	function triggerEvent(element, eventName) {
		// safari, webkit, gecko
		if (document.createEvent) {
			var evt = document.createEvent('HTMLEvents');
			evt.initEvent(eventName, true, true);
			return element.dispatchEvent(evt);
		}
		// Internet Explorer
		if (element.fireEvent) {
			return element.fireEvent('on' + eventName);
		}
	}
	
	
	/**
	 * @Descr:
	 * -	Handle the forms for registration consisting of:
	 * -	Accordion handling
	 * -	Confirmation dialog
	 * -	form handling
	 */
	
	if ($('registrationForm')) {	
		
		//check, if a form has changes
		//DEPRECATED
		function checkForm(form, changeClass) {
			if (form.hasClassName(changeClass)) {
				return true;
			}
			else {
				return false;
			}
		}
		
		
		//if a form has changes and the user navigates to another accordion element
		//show a confirmation
		openConfirmationDialog = function(target) {
			var link = new Layer(target, {
				width: 300,
				topOffset: 100,
				leftOffset: null,
				overlay: true,
				objBody: $$('body')[0],
				centerOffset: true,
				select: true
			});
		}
		
	
		//the accordion triggers
		var personalAccordionTrigger = $$('.box_personal')[0];
		var profileAccordionTrigger = $$('.box_profile')[0];
		var uploadsAccordionTrigger = $$('.box_uploads')[0];
		var timetableAccordionTrigger = $$('.box_timetable')[0];
		
		//stop observing disabled accordion elements
		if(timetableAccordionTrigger.hasClassName('disabledFaqBox')) {
			timetableAccordionTrigger.stopObserving('click');
		}
	
		//open an array of accordion elements
		//e.g. openAccordionElements([personalAccordionTrigger]);
		openAccordionElements = function(items) {
			//@ToDo: each accordion element mustn't fire its own 'click', use it's method instead!
			
			for (var i = 0; i < items.length; i++) {
				if ($(items[i]).hasClassName('activeFaqBox') == false) {
					faq.openBox($(items[i]).id, $(items[i]).down('.faqContent'));
				}
				else {}
			}
		}
		
		//close an array of accordion elements
		//e.g. closeAccordionElements([personalAccordionTrigger,profileAccordionTrigger,uploadsAccordionTrigger]);
		closeAccordionElements = function(items) {
			//@ToDo: each accordion element mustn't fire its own 'click', use it's method instead!
			
			for (var i = 0; i < items.length; i++) {
				if ($(items[i]).hasClassName('activeFaqBox') == true) {
					faq.closeBox($(items[i]).id, $(items[i]).down('.faqContent'));
				}
				else {}
			}
		}
		
		//open "Angaben zu Ihrer Person" and "Profil festlegen" if there are errors in the form
		if ($('registrationForm').hasClassName('formHasErrors') == true) {
			openAccordionElements([personalAccordionTrigger, profileAccordionTrigger, uploadsAccordionTrigger]);
		}
		
		//button inside the form must open "Profil festlegen" 
		var initiateStepProfile = $('proceedToProfile');
		Event.observe(initiateStepProfile, 'click', function(event) {
			openAccordionElements([profileAccordionTrigger]);
		});
		
		
		//if there are changes inside the timetable, open layer and close other accordion elements
		Event.observe(personalAccordionTrigger, 'click', function(event) {
			if ($('timetableForm')) {
				var timetableFormActualValue = $('timetableForm').serialize();
				
				//if (checkForm($('timetableForm'), 'formHasChanges') === true) {//deprecated
				if(timetableFormActualValue != timetableFormOldValue) {
					//console.log('timetableFormActualValue != timetableFormOldValue');
					openConfirmationDialog('/layer/save-confirmation/timetableForm');
					closeAccordionElements([personalAccordionTrigger, profileAccordionTrigger, uploadsAccordionTrigger]);
				}
			}
			else {
				closeAccordionElements([timetableAccordionTrigger]);
			}
		});
		Event.observe(profileAccordionTrigger, 'click', function(event) {			
			if ($('timetableForm')) {
				var timetableFormActualValue = $('timetableForm').serialize();
				
				//if (checkForm($('timetableForm'), 'formHasChanges') === true) {//deprecated
				if(timetableFormActualValue != timetableFormOldValue) {
					//console.log('timetableFormActualValue != timetableFormOldValue');
					openConfirmationDialog('/layer/save-confirmation/timetableForm');
					closeAccordionElements([personalAccordionTrigger, profileAccordionTrigger, uploadsAccordionTrigger]);
				}
			}
			else {
				closeAccordionElements([timetableAccordionTrigger]);
			}
		});
		Event.observe(uploadsAccordionTrigger, 'click', function(event) {
			closeAccordionElements([timetableAccordionTrigger]);
		});
		
		//if there are changes inside the registration, open layer and close other accordion elements
		//only if trigger isn't deactivated
		if (!timetableAccordionTrigger.hasClassName('disabledFaqBox') == true) {
				Event.observe(timetableAccordionTrigger, 'click', function(event) {

					var registrationFormActualValue = $('registrationForm').serialize();

					if(registrationFormActualValue != registrationFormOldValue) {
					//if (checkForm($('registrationForm'), 'formHasChanges') === true) {//deprecated
						//console.log('registrationFormActualValue != registrationFormOldValue');
						
						openConfirmationDialog('/layer/save-confirmation/registrationForm');
						closeAccordionElements([timetableAccordionTrigger]);
					}
					else {
						closeAccordionElements([personalAccordionTrigger, profileAccordionTrigger, uploadsAccordionTrigger]);
					}
				});
			}
	}
	
	
	//submit upload forms via script
	//@TODO: Add video support
	if ($$('.uploadForm')) {
		$$('.uploadForm').each(function(uploadForm) {
			Event.observe(uploadForm, 'submit', function(event) {
				var formID = this.id;
				//console.log(formID);
				
				event.stop();
				uploadForm.submit();
				
				//specify the iframe
				var uploadsIFrameElement = this.down('.uploadsIFrame');
				
				//get the iframe's window object				
				var uploadsIFrameWindow = (uploadsIFrameElement.contentWindow || uploadsIFrameElement.contentDocument);
				
				Event.observe(uploadsIFrameElement, 'load', function(event) {
					//check if there is a document inside the iframe
					if (uploadsIFrameWindow.document) {
						uploadsIFrameDocument = uploadsIFrameWindow.document;
						uploadsIFrameBodyContent = uploadsIFrameDocument.body.innerHTML;
						
						//convert the string to a json object
						var json = uploadsIFrameBodyContent.evalJSON(true);
						
						//{"errors":[],"upload_success":false}
						if (!json.errors) {
							uploadsIFrameElement.stopObserving('load');
							//reset the upload form
							uploadForm.reset();
							uploadForm.down('span').removeClassName('error');
							
							//reset fake input field if present
							if (formID == 'uploadFileForm') {
								this.up('.uploadForm').down('.fakeFileInput').innerHTML = '';
								this.up('.uploadForm').down('.fakeFileInput').removeClassName('error');
								this.up('.uploadForm').down('#file_name').up('span').removeClassName('error');
							}
							if (formID == 'uploadYoutubeForm') {
								this.up('.uploadForm').down('#user_profile_video_video_code').up('span').removeClassName('error');
								this.up('.uploadForm').down('#video_name').up('span').removeClassName('error');
							}
							
							//convert json to html
							if (formID == 'uploadFileForm') {
								var jsonToHTML = '<li><span class="uploadName">' + json.file.original_filename + '<\/span><a title="Klicken Sie hier, um diese Datei zu löschen!" class="uploadDelete" href="/registrieren/datei/loeschen/' + json.file.lookup + '">löschen<\/a><\/li>';
								this.up('.uploadForm').down('.uploadedFiles').insert({
									'bottom': jsonToHTML
								});
							}
							//convert json to html
							//{"upload_success":true,"video":{"lookup":"6adb910122939656d3d2e779186b087f","name":"dds","video_code":"dsd"}}
							if (formID == 'uploadYoutubeForm') {
								var jsonToHTML = '<li><span class="uploadName">' + json.video.name + '<\/span><a title="Klicken Sie hier, um dieses Video zu löschen!" class="uploadDelete" href="/registrieren/video/loeschen/' + json.video.lookup + '">löschen<\/a><\/li>';
								this.up('.uploadForm').down('.uploadedFiles').insert({
									'bottom': jsonToHTML
								});
							}
							
						}
						else {
							if (formID == 'uploadFileForm') {
									if (json.errors.file) {
										this.up('.uploadForm').down('.fakeFileInput').addClassName('error');
										this.up('.uploadForm').down('#file_name').up('span').removeClassName('error');
									}
									if (json.errors.name) {
										this.up('.uploadForm').down('#file_name').up('span').addClassName('error');
										this.up('.uploadForm').down('.fakeFileInput').removeClassName('error');
									}
									if ((json.errors.file) && (json.errors.name)) {
										this.up('.uploadForm').down('#file_name').up('span').addClassName('error');
										this.up('.uploadForm').down('.fakeFileInput').addClassName('error');
									}
							}
							else {
								if (formID == 'uploadYoutubeForm') {
									if(json.errors.name) {
										this.up('.uploadForm').down('#video_name').up('span').addClassName('error');
										this.up('.uploadForm').down('#user_profile_video_video_code').up('span').removeClassName('error');
									}
									if(json.errors.video_code) {
										this.up('.uploadForm').down('#user_profile_video_video_code').up('span').addClassName('error');
										this.up('.uploadForm').down('#video_name').up('span').removeClassName('error');
									}
									if((json.errors.name) && (json.errors.video_code)) {
										this.up('.uploadForm').down('#video_name').up('span').addClassName('error');
										this.up('.uploadForm').down('#user_profile_video_video_code').up('span').addClassName('error');
									}
								}
							}
						}
					}
				});
			});
		});
		//observe delete links
		//we need to observe links that have been added via ajax
		
		document.observe('click', function(event, element) {
			if (element = event.findElement('.uploadDelete')) {
				callDelete(element);
				event.preventDefault();
			}
		});
		
		
		var deleteLinks = $$('.uploadDelete');
		
		function callDelete(deleteLink) {
			var jsonData = new Ajax.Request(deleteLink.href, {
				onSuccess: function(response) {
				
					var responseData = response.responseText;
					var responseJson = responseData.evalJSON();
					
					deleteLink.up('li').remove();
				},
				onFailure: function(failureResponse) {
					//							var failureResponseData = failureResponse.responseJSON;
					//							failureResponseData = failureResponseData.evalJSON(true);
					//							alert(failureResponseData.delete_success);
				}
			});
		}
		
	}
	
	//registration form, observe range selectors
	//if school == 1, enabled
	if ($('timetableForm')) {
		var rangeSelectorObj = $('hasRangeSelectorForLocation');
		var rangeSelectorObjItems = $$('#hasRangeSelectorForLocation input[type=radio]');
		var rangeSelectorLabels = $$('#hasRangeSelectorForLocation label');
		
		var locationSchool = $('timetable_location_id_1');
		var locationSchoolLabel = $('timetable_location_id_1').up('li').down('label');
		var locationInstitution = $('timetable_location_id_2');
		var locationInstitutionLabel = $('timetable_location_id_2').up('li').down('label');
		
		locationSchool.addClassName('test');
		//console.log(typeof(rangeSelectorObjItems));
		
		function disableRangeSelectorLabels(labels) {
			for(var label = 0;label < labels.length;label++) {
				labels[label].setOpacity(0.5);
			}
		}
		function enableRangeSelectorLabels(labels) {
			for(var label = 0;label < labels.length;label++) {
				labels[label].setOpacity(1);
			}
		}
		
		function disableRangeSelectorObjItems(items) {
			if (!$F(locationSchool) == 1) {
				for (var item = 0; item < items.length; item++) {
					items[item].writeAttribute("disabled", "disabled");
					//console.log(items[item]);
					disableRangeSelectorLabels(rangeSelectorLabels);
				}
			}
		}
		function enableRangeSelectorObjItems(items) {
			for(var item = 0;item < items.length;item++) {
				items[item].removeAttribute('disabled');
				//console.log(items[item]);
				enableRangeSelectorLabels(rangeSelectorLabels);
			}
		}
		//disable range selectors initially
		disableRangeSelectorObjItems(rangeSelectorObjItems);
		
		//observe click on "school"
		//->enable
		Event.observe(locationSchool,'click',function() {
				enableRangeSelectorObjItems(rangeSelectorObjItems);
		});
		Event.observe(locationSchoolLabel,'click',function() {
				enableRangeSelectorObjItems(rangeSelectorObjItems);
		});
		
		//observe click on "institution"
		//->disable
		Event.observe(locationInstitution,'click',function(){
				disableRangeSelectorObjItems(rangeSelectorObjItems);
		});
		Event.observe(locationInstitutionLabel,'click',function() {
					disableRangeSelectorObjItems(rangeSelectorObjItems);
		});
		
		timetableFormOldValue = $('timetableForm').serialize();
		//console.log('timetableFormOldValue adpated to match location settings: ' + timetableFormOldValue);
	}
});


/*
 * @Descr: Autocomplete for the searchbox
 */
Event.observe(window, 'load', function() {
	new Autocomplete('teaser_field_of_research_tags', {
		serviceUrl: '/autocomplete/tags',
		minChars: 3,
		maxHeight: 400,
		width: 276,
		deferRequestBy: 100,
		// callback function:
		onSelect: function(value, data) {
			//console.log('You selected: ' + value + ', ' + data);
		}
	});
});
