/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
(function ($) {

	// Detect touch support
	$.support.touch = 'ontouchend' in document;

	// Ignore browsers without touch support
	if (!$.support.touch) {
		return;
	}

	var mouseProto = $.ui.mouse.prototype,
		_mouseInit = mouseProto._mouseInit,
		_mouseDestroy = mouseProto._mouseDestroy,
		touchHandled;

	/**
	 * Simulate a mouse event based on a corresponding touch event
	 * @param {Object} event A touch event
	 * @param {String} simulatedType The corresponding mouse event
	 */
	function simulateMouseEvent (event, simulatedType) {

		// Ignore multi-touch events
		if (event.originalEvent.touches.length > 1) {
			return;
		}

		event.preventDefault();

		var touch = event.originalEvent.changedTouches[0],
			simulatedEvent = document.createEvent('MouseEvents');

		// Initialize the simulated mouse event using the touch event's coordinates
		simulatedEvent.initMouseEvent(
			simulatedType,    // type
			true,             // bubbles
			true,             // cancelable
			window,           // view
			1,                // detail
			touch.screenX,    // screenX
			touch.screenY,    // screenY
			touch.clientX,    // clientX
			touch.clientY,    // clientY
			false,            // ctrlKey
			false,            // altKey
			false,            // shiftKey
			false,            // metaKey
			0,                // button
			null              // relatedTarget
		);

		// Dispatch the simulated event to the target element
		event.target.dispatchEvent(simulatedEvent);
	}

	/**
	 * Handle the jQuery UI widget's touchstart events
	 * @param {Object} event The widget element's touchstart event
	 */
	mouseProto._touchStart = function (event) {

		var self = this;

		// Ignore the event if another widget is already being handled
		if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
			return;
		}

		// Set the flag to prevent other widgets from inheriting the touch event
		touchHandled = true;

		// Track movement to determine if interaction was a click
		self._touchMoved = false;

		// Simulate the mouseover event
		simulateMouseEvent(event, 'mouseover');

		// Simulate the mousemove event
		simulateMouseEvent(event, 'mousemove');

		// Simulate the mousedown event
		simulateMouseEvent(event, 'mousedown');
	};

	/**
	 * Handle the jQuery UI widget's touchmove events
	 * @param {Object} event The document's touchmove event
	 */
	mouseProto._touchMove = function (event) {

		// Ignore event if not handled
		if (!touchHandled) {
			return;
		}

		// Interaction was not a click
		this._touchMoved = true;

		// Simulate the mousemove event
		simulateMouseEvent(event, 'mousemove');
	};

	/**
	 * Handle the jQuery UI widget's touchend events
	 * @param {Object} event The document's touchend event
	 */
	mouseProto._touchEnd = function (event) {

		// Ignore event if not handled
		if (!touchHandled) {
			return;
		}

		// Simulate the mouseup event
		simulateMouseEvent(event, 'mouseup');

		// Simulate the mouseout event
		simulateMouseEvent(event, 'mouseout');

		// If the touch interaction did not move, it should trigger a click
		if (!this._touchMoved) {

			// Simulate the click event
			simulateMouseEvent(event, 'click');
		}

		// Unset the flag to allow other widgets to inherit the touch event
		touchHandled = false;
	};

	/**
	 * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
	 * This method extends the widget with bound touch event handlers that
	 * translate touch events to mouse events and pass them to the widget's
	 * original mouse event handling methods.
	 */
	mouseProto._mouseInit = function () {

		var self = this;

		// Delegate the touch handlers to the widget's element
		self.element.bind({
			touchstart: $.proxy(self, '_touchStart'),
			touchmove: $.proxy(self, '_touchMove'),
			touchend: $.proxy(self, '_touchEnd')
		});

		// Call the original $.ui.mouse init method
		_mouseInit.call(self);
	};

	/**
	 * Remove the touch event handlers
	 */
	mouseProto._mouseDestroy = function () {

		var self = this;

		// Delegate the touch handlers to the widget's element
		self.element.unbind({
			touchstart: $.proxy(self, '_touchStart'),
			touchmove: $.proxy(self, '_touchMove'),
			touchend: $.proxy(self, '_touchEnd')
		});

		// Call the original $.ui.mouse destroy method
		_mouseDestroy.call(self);
	};

})(jQuery);

(function($) {

	$.fn.shuffle = function() {
		var allElems = this.get(),
			getRandom = function(max) {
				return Math.floor(Math.random() * max);
			},
			shuffled = $.map(allElems, function() {
				var random = getRandom(allElems.length),
					randEl = $(allElems[random]).clone(true)[0];
				allElems.splice(random, 1);
				return randEl;
			});

		this.each(function(i) {
			$(this).replaceWith($(shuffled[i]));
		});

		return $(shuffled);
	};

})(jQuery);

$(document).ready(function() {
	var setFormHandlers = function() {
		// drag and drop
		var $eAnswerDragWraps = $('.answerDragWrap').shuffle(),
			iMaxHeight = Math.max.apply(Math, $eAnswerDragWraps.map(function() { return $(this).outerHeight(); }).get()),
			iMaxWidth = Math.max.apply(Math, $eAnswerDragWraps.map(function() { return $(this).outerWidth(); }).get());

		$eAnswerDragWraps.add('.answerDrop').outerHeight(iMaxHeight).outerWidth(iMaxWidth);

		$('.answerDrag').draggable({
			revert: 'invalid',
			helper: 'clone'
		}).each(function() {
			$(this).css({
				position: 'relative',
				width: $(this).outerWidth(),
				height: $(this).height()
			});
		});
		$('.answerDrop').droppable({
			over: function(event, ui) {
				$(this).addClass('ui-state-highlight');
			},
			out: function(event, ui) {
				$(this).removeClass('ui-state-highlight');
			},
			drop: function(event, ui) {
				var $eDroppable = $(this),
					$iAnswerDropID = $eDroppable.data('answer'),
					$iAnswerDragID = ui.draggable.data('answer');

				$(this).removeClass('ui-state-highlight');

				ui.draggable.prependTo($eDroppable);

				ui.draggable.css({
					position: 'absolute'
				}).css({
					/*top: ($eDroppable.outerHeight() - ui.draggable.outerHeight()) / 2,
					left: ($eDroppable.outerWidth() - ui.draggable.outerWidth()) / 2*/
				});


				// reset
                $('#answerDropWrap' + $iAnswerDragID + ' .answerDrop').removeClass('correctly');

                if($iAnswerDropID == $iAnswerDragID) {
                    $(this).addClass('correctly');
                }
                else {
                    $(this).removeClass('correctly');
                }

                /*
                if (typeof $iAnswerDropID === "undefined") {
                    $('#answerDropWrap' + $iAnswerDragID + ' .answerDrop').removeClass('correctly');
                } else {
                    if($iAnswerDropID == $iAnswerDragID) {
                        $(this).addClass('correctly');
                    }
                    else {
                        $(this).removeClass('correctly');
                    }
                }*/

			}
		});

		$('.complex').each(function() {
			var $eComplex = $(this),
				$eAnswers = $(this).find('.answer[data-grouped="1"][data-cycle="1"]');

			if($eComplex.is('.complex--checked')) {
				$eAnswers.addClass('active');
			}
			else {
				$eAnswers.click(function(e) {
					if(e.target == this && !$(this).is('.active')) { // clicked on header, open/close
						var $this = $(this);
						$this.toggleClass('active');

						setTimeout(function() {
							$('body').one('click', function() {
								$this.removeClass('active');
							});
						}, 100);
					}
				});

				$('.answer[data-grouped="1"] input[type="checkbox"], .answer[data-grouped="1"] input[type="radio"]').change(function() {
					if($(this).is(':checked')) {
						$(this).parents('.question').find('.answer').eq(0).attr('data-selected', $(this).next().text());
					}
				}).change();
			}
		});

		// Button Drag Drop Auswertung
		$('.questionType3 #check').click(function() {

			var iNotAnswered = 0,
				iCorrectlyAnswered = 0,
				$eAnswerDrop = $('.myAnswer');

			// check all answers
			$eAnswerDrop.each(function(index) {
				if($(this).hasClass('correctly')) {
					$(this).children('.iconCorrectAnswer').removeClass('hide');
					iCorrectlyAnswered++;
				}
				else if(!$(this).find('.answerDrag').length) {
					// in which way could we give the user the correct answers?
					iNotAnswered++;
				}
				else {
					$(this).children('.iconWrongAnswer').removeClass('hide');
				}
			});

            /*console.log('length:' + ($eAnswerDrop.length));
            console.log('correct:' + iCorrectlyAnswered);
            console.log('notanswered:' + iNotAnswered);*/

			if(iNotAnswered == ($eAnswerDrop.length)) {
				$('.solutionInfoText .noanswer').removeClass('hide');
			}
			else if(iCorrectlyAnswered == ($eAnswerDrop.length)) {
				$('.solutionInfoText .correct').removeClass('hide');
			}
			else {
				$('.solutionInfoText .incorrect').removeClass('hide');
			}

			$(this).hide();

			/*$('#skip').css({
				visibility: 'hidden',
				'pointer-events': 'none'
			});
            $('#restart').css({
                visibility: 'hidden',
                'pointer-events': 'none'
            });*/

            $('.complex').addClass('complex--checked');

			var $eContinue = $('#continue');

			if($eContinue.length) {
				$eContinue.show();
			}
			else {
				/*$(this).show().css({
					visibility: 'hidden',
					'pointer-events': 'none'
				});*/
			}

			return false;
		});

		$('.tx-htwkquestionnaire .complex.questionType1').each(function() {
			var $eQuestions = $(this).find('.question');

			if($eQuestions.length > 1) {
				var iAnswerCount = $eQuestions.map(function() {
					return $(this).find('input + label').map(function() {
						return $(this).text() || $(this).find('img').attr('src');
					}).get().join('||');
				}).get().filter(function(value, index, self) {
					return self.indexOf(value) === index;
				}).length;

				if(iAnswerCount == 1) {
					$(this).find('.question').addClass('question--combined');
				}
			}
		});

	};
	setFormHandlers();


    /* COOKIE
    --------------------------------------------- */

    var complexcount = $('.catalog').data('complexcount');
    var catalogindex = $('.catalog').data('index');

    var cookieSequence;

    var start = 2;
    var arr = [];
    while(start < complexcount+1){
        arr.push(start++);
    }
    shuffle(arr);
    var arraystring = '';
    arr.forEach(function(element) {
        arraystring = arraystring.concat('-'+ element);
    });

    arraystring = arraystring.substr(1);

    if (cookieSequence === undefined || catalogindex == 1) {
        Cookies.set('sequence',arraystring);
    }
    cookieSequence = Cookies.get('sequence');

    console.log(cookieSequence);

	$('.tx-htwkquestionnaire').on({
		submit: function() {
			var $eForm = $(this).addClass('questionnaire--loading');

			$.post($eForm.attr('action'), $eForm.serialize(), function(response) {
				$eForm.replaceWith($(response).find('.tx-htwkquestionnaire > form'));
				setFormHandlers();
			});

            /*clearTimeout(timeoutvar);*/


			return false;
		}
	}, 'form').on({
		click: function() {
			var $eForm = $('.tx-htwkquestionnaire > form').addClass('questionnaire--loading');

            var steps = cookieSequence.split('-');

            cookieSequence = cookieSequence.substr(steps[0].length+1);
            Cookies.set('sequence',cookieSequence);

            var counter = (complexcount-steps.length)+1;
            var islast;

            if (cookieSequence.length == 0) {
                islast = 1;
            } else {
                islast = 0;
            }

            var indexid = getUrlParam('id','Empty');


            if (indexid) {
                parameterText = 'id=' + indexid + '&';
            }

            var reference = '?' + parameterText + 'tx_htwkquestionnaire_pi1[index]='+steps[0]+'&tx_htwkquestionnaire_pi1[counter]='+counter+'&tx_htwkquestionnaire_pi1[islast]='+islast;

            console.log(reference);

            $.get(reference, function(response) {
				var $eNewForm = $(response).find('.tx-htwkquestionnaire > form');
				$eForm.replaceWith($eNewForm);
				setFormHandlers();
				var substract = window.matchMedia("screen and (min-width: 1024px)").matches ? 130 : 84;
				$(document).scrollTop($eNewForm.position().top - substract);

			});


            return false;
		}
	}, '#skip, #continue');


    var timeoutvar;
    /*$('.progressbar').show();*/
    /*nextslide();*/








});

function shuffle(array) {
    array.sort(() => Math.random() - 0.5);
}

function nextslide() {
    timeoutvar = setTimeout(function() { $('.footer .submit').click();}, 50000);
}
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}
function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
    }
    return urlparameter;
}
