$(document).ready(function() {
	pkg('website.dashboardActivityItem');
	/**
	 * TODO Combine text inputs, select, and textarea since the logic for these inputs is the same
	 */
	website.dashboardActivityItem.form = (function() {
		var nodes = {};
		var url = '';
		var timer;
		var saveInterval = 1500;
		var submitting = false;
		
		
		/**
		 * root param should be a jQuery object (eg $('#main'))
		 */
		function init(root) {
			if(!root || root.length < 1)
				return;
			
			/*
			 * Set nodes
			 */
			nodes.root = root;
			nodes.cTextInputs = $('input[type="text"]', nodes.root);
			nodes.cSelects = $('select', nodes.root);
			nodes.cCheckboxes = $('input[type="checkbox"]', nodes.root);
			nodes.cTextareas = $('textarea', nodes.root);
			nodes.which = $('input[name="which"]', nodes.root);
			nodes.submit = $('.submit', nodes.root);
			
			/*
			 * Set misc
			 */
			url = nodes.root.attr('action');
			
			/*
			 * Set events
			 */
			nodes.cTextInputs.bind('keydown', onKeyDownText).bind('focus', onFocusInput).bind('blur', onBlurInput);
			nodes.cTextareas.bind('keydown', onKeyDownText);
			nodes.submit.bind('click', onClickSubmit);
			
			for(var i = 0; i < nodes.cTextInputs.length; i++) {
				nodes.cTextInputs.get(i).savedValue = $(nodes.cTextInputs.get(i)).val();
			}
			
			for(var i = 0; i < nodes.cSelects.length; i++) {
				nodes.cSelects.get(i).savedValue = $(nodes.cSelects.get(i)).val();
			}
			
			for(var i = 0; i < nodes.cCheckboxes.length; i++) {
				nodes.cCheckboxes.get(i).savedValue = $(nodes.cCheckboxes.get(i)).prop('checked');
			}
			
			for(var i = 0; i < nodes.cTextareas.length; i++) {
				nodes.cTextareas.get(i).savedValue = $(nodes.cTextareas.get(i)).val();
			}
			
			checkboxlimit($('.objectives input[type="checkbox"]'), 3);
			
			// Set timer
			setTimer();
		}
		
		function hasChanged() {
			var change = false;
			
			for(var i = 0; i < nodes.cTextInputs.length; i++) {
				var compareVal = $(nodes.cTextInputs.get(i)).attr('m:defaultValue') == $(nodes.cTextInputs.get(i)).val() ? '' : $(nodes.cTextInputs.get(i)).val()
				
				if(compareVal != nodes.cTextInputs.get(i).savedValue) {
					change = true;
					nodes.cTextInputs.get(i).savedValue = compareVal;
				}
			}
			
			for(var i = 0; i < nodes.cSelects.length; i++) {
				if($(nodes.cSelects.get(i)).val() != nodes.cSelects.get(i).savedValue) {
					change = true;
					nodes.cSelects.get(i).savedValue = $(nodes.cSelects.get(i)).val();
				}
			}
			
			for(var i = 0; i < nodes.cCheckboxes.length; i++) {
				if($(nodes.cCheckboxes.get(i)).prop('checked') != nodes.cCheckboxes.get(i).savedValue) {
					change = true;
					nodes.cCheckboxes.get(i).savedValue = $(nodes.cCheckboxes.get(i)).prop('checked');
				}
			}
			
			for(var i = 0; i < nodes.cTextareas.length; i++) {
				if($(nodes.cTextareas.get(i)).val() != nodes.cTextareas.get(i).savedValue) {
					change = true;
					nodes.cTextareas.get(i).savedValue = $(nodes.cTextareas.get(i)).val();
				}
			}
			
			return change;
		}
		
		function save() {
			// Clear timer
			clearTimeout(timer);
			
			if(submitting || hasChanged()) {
				$.ajax({
					url: url,
					type: 'POST',
					data: nodes.root.serialize()+"&objectives="+getObjectives(),
					complete: onCompleteSubmit
				});
			}
			else {
				// Set new timer
				setTimer();
			}
		}
		
		function setTimer() {
			timer = setTimeout(onTimeout, saveInterval);
		}
		/***********************************************
		* Limit number of checked checkboxes script- by JavaScript Kit (www.javascriptkit.com)
		* This notice must stay intact for usage
		* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and 100s more
			***********************************************/
		function checkboxlimit(checkgroup, limit){
			var checkgroup=checkgroup;
			
			var limit=limit
			for (var i=0; i<checkgroup.length; i++){
				/*
				checkgroup[i].onclick=function(){
					var checkedcount=0
					for (var i=0; i<checkgroup.length; i++)
						checkedcount+=(checkgroup[i].checked)? 1 : 0
					if (checkedcount>limit){
						alert("You can only select a maximum of "+limit+" checkboxes")
						this.checked=false
					}
				}*/
				$(checkgroup[i]).bind('change', function() {
					var checkedCount = 0;
					for (var i=0; i<checkgroup.length; i++) {
						checkedCount+=(checkgroup[i].checked)? 1 : 0;
					}
					if (checkedCount>limit){
						//alert("You can only select a maximum of "+limit+" checkboxes")
						this.checked=false;
						this.update();
					}
					
					if (checkedCount>=limit) {
						disableCheckboxes();
					}
					
					if (checkedCount < limit) {
						enableCheckboxes();
					}
				});
			}
		}
		
		function disableCheckboxes() {
			var divs = $('.objectives>div>div', nodes.root);
			
			for(var i = 0; i < divs.length; i++) {
				var checkbox = $('input[type="checkbox"]', divs.get(i));
				
				if(!checkbox.get(0).checked) {
					$(divs.get(i)).addClass('grayedOut');
				}
			}
		}
		
		function enableCheckboxes() {
			var divs = $('.objectives>div>div', nodes.root);
			
			for(var i = 0; i < divs.length; i++) {
				$(divs.get(i)).removeClass('grayedOut');
			}
		}
		
		function getObjectives() {
			var objectives = "";
			
			//loop
			var divs = $('.objectives>div>div', nodes.root);
			
			for(var i = 0; i < divs.length; i++) {
				var checkbox = $('input[type="checkbox"]:checked', divs.get(i));

				if (!checkbox.val() == '') {
					objectives+= checkbox.val() + ",";
				}

			}
			
			// objectives+=","+input.value
			
			return objectives;
		}
		
		/*
		 * Don't send form while user is typing
		 */
		function onKeyDownText() {
			// Clear timer
			clearTimeout(timer);
			// Set new timer
			setTimer();
		}
		
		function onClickSubmit(event) {
			event.preventDefault();
			
			// Show popup
			if(website.dashboardActivityItem.location.hasLocations()) {
				var copy = window.staticCopy.submitActivityPopUp;
				var dialog = new DialogPopUp('Bevestig', copy, {ok: onOkSubmitDialog, cancel: onCancelSubmitDialog});
				dialog.show();
			}
			else {
				var copy = window.staticCopy.submitActivityLocationPopUp;
				var alertPopUp = new AlertPopUp('Locatie', copy);
				alertPopUp.show();
			}
			
		}
		
		function onOkSubmitDialog() {
			// Submit this activity
			
			// Clear timer
			clearTimeout(timer);
			
			submitting = true;
			
			nodes.which.val('submit');
			save();
			
			// Set value back
			nodes.which.val('edit');
		}
		
		function onCancelSubmitDialog() {
			// Do action is taken
		}
		
		function onTimeout() {
			save();
		}
		
		function onCompleteSubmit(jqXHR, textStatus) {
			if(submitting) {
				window.location = '/profiel/activiteiten.php';
				// This won't ever be executed
				submitting = false;
			}
			else {
				// Set new timer
				setTimer();
			}
		}
		
		function onFocusInput() {
			var $this = $(this);
			
			if($this.val() == $this.attr('m:defaultValue')) {
				$this.val('');
			}
		}
		
		function onBlurInput() {
			var $this = $(this);
			
			if($this.val() == '') {
				$this.val($this.attr('m:defaultValue'));
			}
		}
		
		init.apply(this, arguments);
	})($('#dashboardActivityItem-rowTop form'));
	
});
