<?php
    // ini_set("display_errors", 1);
    include_once(PATH_TO_ROOT."/webcati/_plugins/dragandrop/class/class.dragandrop.plugin.php");
    $data = new Dragandrop($db);
    $data->load($projectId, $q->id);
	
	$config = $data->getData();
	$config['inverse'] = ($q->les_sql == "5") ? 1 : 0;
	
	$dragValues = array();
	
	// added by Soulskiner #15.6.2014
	// preparing array for must asnwer conditions.
	$pluginMustCondition = array();
	$pluginNoGoCondition = array();
	
	// legend array
	$legArr = $q->answerToArray($q->display->readRequiredQuestionVariables($q->leg_sql));
	
	$qName = $q->q_name;
	
	$ansArrBasic = array();
	$ansArrNoGo = array();
	
	$cleanValues = array();
	
	$noGoSelected = FALSE;
	
	$noGo = preg_replace('/\s+/', '', $config['noGoAnswers']);	// trim whitespaces
	$noGo = explode(",", $noGo);
	
	foreach ($ansArr as $value) {
		if (in_array($value[0], $noGo)) $ansArrNoGo[] = $value;
		else $ansArrBasic[] = $value;
	}
	
	$legArrBasic = $legArr;
	if (!empty($ansArrNoGo)) array_splice($legArrBasic, count($legArr) - 1, 1);
	
	// reverse answers array (start at first item)
	// $ansArrBasic = array_reverse($ansArrBasic);
	
	// feldValues .. question already answered, but back button clicked
	$fields = $q->getStructureFields();
	
	if ($config['openAnswerEnabled'] == 1) $fields[] = $config['openAnswerRelQuestion'] . "_1";
	
	$fieldsValues = $q->display->readStructureVariables($fields,'');
	
	/*echo "Leg: " . json_encode($legArrBasic) . "<hr>";
	echo "Ans: " . json_encode($ansArrBasic) . "<hr>";*/
	
	/*echo "Answers: " . json_encode($_POST['answers']) . "<br>";
	echo "Values: " . json_encode($fieldsValues) . "<br>";
	echo "Fields: " . json_encode($fields) . "<br><hr>";*/
	
	// partial answers (requirements for next question not satisfied)
	if (isset($_POST['answers'])) {
		foreach ($fieldsValues as $key => &$value) {
			if (isset($_POST['answers'][$key])) $value = $_POST['answers'][$key];
		}
	}
	
	// echo json_encode($fieldsValues) . "<hr>";
	$captionHidden = ($config['boxCaptionHidden']) ? " display:none;" : "";
	$boxMargin = ($config['boxMargin'] == 0) ? "margin: 0;" : ($config['boxCaptionHidden']) ? "margin:" . $config['boxMargin'] . "px 0;" : "margin:".$config['cardPaddingInBox']."px 0";
	$minHeight = ($config['cardsType'] == 4) ? "/*min-height:300px;*/display:block !important;" : "";
	$cardBoxMargin = ($config['cardsType'] == 4 and $config['itemsAlignVertical'] == 'middle') ? 'display:table;height:'.$config['cardHeight'].'px;' : '';// "margin-top:".(($config['cardHeight'] - $config['cardFontSize']) / 2)."px;" : "";
	$containerHeight = ($config['cardsType'] == 4) ? "display:none;visibility:hidden;" : "";
	$mp = ($config['cardAllVisible'] == 1) ? count($ansArrBasic) : 1;
	$marginBoxInCards = ($config['cardAllVisible'] == 1) ? "" : "margin-left:-".($config['cardWidth']+2)."px;";
	
	$tbl = '<script src='.PATH_TO_ROOT.'_support/jquery.ui.touch-punch.min.js></script>
	<style>
		.caption { height:'.($config['cardHeight'] > 40 ? ($config['cardHeight']/2) : "20").'px;'.$captionHidden.' font-size:'.$config['captionFontSize'].'px; overflow: hidden; padding-bottom:2px;padding-top:4px; position: absolute; bottom:0; left:0; width:100%; background-color:'.$config['boxBaseColor'].';-webkit-border-bottom-right-radius: '.$config['boxRoundCorners'].'px;-webkit-border-bottom-left-radius: '.$config['boxRoundCorners'].'px;-moz-border-radius-bottomright: '.$config['boxRoundCorners'].'px;-moz-border-radius-bottomleft: '.$config['boxRoundCorners'].'px;border-bottom-right-radius: '.$config['boxRoundCorners'].'px;border-bottom-left-radius: '.$config['boxRoundCorners'].'px; }
		ul#app li { list-style: none;float:left;'.(($config['cardsType'] == "3") ? 'margin: 5px;' : '').' }
		#app { padding:0;height:'.($config['cardHeight'] + 5).'px;margin: '.(($config['itemsAlignHorizontal'] == 'center') ? '0 auto' : '0 0 0 5px;').';margin-top:20px;/*background:url('.$BasketImage.');background-repeat: no-repeat; background-size: 100% 50px; background-position: left bottom;*/ }
		.outer { width:'.$topWidth.'px;height:'.$topHeight.'px; }
		.inner { float: left;width: '.$config['cardWidth'].'px;height:'.$config['cardHeight'].'px;margin-right: 5px;margin-bottom: 5px; }
		.inner li { list-style: none; }
		.item { list-style:none; font-size:'.$config['cardFontSize'].'px;width:'.$config['cardWidth'].'px;height:'.$config['cardHeight'].'px;border:1px solid '.$config['cardBorderColor'].';background-color:'.$config['cardBaseColor'].';overflow:hidden;cursor:move;box-shadow: '.$config['cardShadow'].'px '.$config['cardShadow'].'px '.$config['cardShadow'].'px '.$config['cardShadowColor'].';-moz-border-radius:'.$config['cardRoundCorners'].'px;-webkit-border-radius:'.$config['cardRoundCorners'].'px;border-radius:'.$config['cardRoundCorners'].'px; }
		#openAnswer { margin-left:2px; }
		.labelText { font-size:'.$config['cardFontSize'].'px;margin-bottom:10px; }
		.box { padding:2px;padding-left:6px;width:92%;height:100%;text-align:'.$config['textAlign'].';'.$cardBoxMargin.'; }
		.container { position: relative;'.$containerHeight.'width:'.($config['cardWidth']+($config['cardPaddingInBox'] * 2)+5).'px; float:left;/*margin:'.$config['cardPaddingInBox'].'px;*/padding:0px; }
		.cart { height:'.((($config['cardHeight']+2)*$mp)+10).'px;padding:4px 2px;'.$boxMargin.'-moz-border-radius:'.$config['boxRoundCorners'].'px;-webkit-border-radius:'.$config['boxRoundCorners'].'px;border-radius:'.$config['boxRoundCorners'].'px;border:1px solid '.$config['boxBorderColor'].';background-color:'.$config['boxBgColor'].'; }
		ul.neutral { list-style:none;padding:4px 8px; }
		ul.neutral li + li { margin-left:-'.($config['cardWidth']+2).'px;}
		ul.neutral li { float:left; }
		ul.cart li { float:left; }
		ul.app { list-style:none; }
		ul.cart{ list-style:none;padding: 0 '.$config['cardPaddingInBox'].'px; }
		ul.cart li + li { '.$marginBoxInCards.' }
		.delete { /*width:24px; height:24px;*/ left: '.$config['resetOffsetLeft'].'px; top: '.$config['resetOffsetTop'].'px; position: absolute;}
		.active { border: 1px solid #AAAAAA; }
		.test { position: absolute; }
		li.placeholder { list-style:none; }
		.ui-custom-highlight { background-color:#0b4da2; }
		.ui-small-highlight { background-color:#eeeeee; }
		#cartdiv {'.(($config['itemsAlignHorizontal'] == 'center') ? 'margin:0 auto;' : '').$minHeight.'}
	</style>
	<!--[if lte IE 8]>
	<style>
		#app { background-image: none !important;float:left;margin: 10px auto 0;height:'.($config['cardHeight'] + 35).'px;background:url('.$BasketImage.');background-repeat: no-repeat; background-size: 100% 50px; background-position: left bottom; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src="'.$BasketImageIE.'", sizingMethod="scale"); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\"'.$BasketImageIE.'\", sizingMethod=\"scale\")"; font-size: 1px; }
	</style>
	<![endif]-->
	<script>
		var App = {};
		App.count = '.count($ansArrBasic).';
		App.items = [];
		App.cardType = "'.$config['cardsType'].'";
		App.inverse = '.$config['inverse'].';
		App.width = "';
		
		$cnt = 50 + $config['cardWidth'];
		
		if (count($ansArrBasic) > 10) {
			$cnt += (count($q->ansArr)-11) *2;
			$cnt += 10 * 7;
		}
		else {
			$cnt += (count($ansArrBasic)-1) * 7;
		}
		
		$tbl .= $cnt .'px";';
		
		// If type == 2 limit number of rows and columns
		if ($config['cardsType'] == 2) {
			$tbl .= 'App.dimX=' . $config['cardColumns'] . ';App.dimY='.$config['cardRows'].';';
		}
		
		$tbl .= '$(document).ready(function(){
			var w = '.$config['cardWidth'].';
			if (App.cardType == "3" || App.cardType == "4") {
				$(".first").width(w);
				$(".second").width(w);
				
				$("#app").css("padding", "0").css("margin", "0");
				
				$(".tableCenter").width('.$config['centerOffset'].');
			} else {
				$(".tableCenter").height('.$config['centerOffset'].');
			}
		});
	</script>';
	
	// Main table for dragandrop
	$tbl .= '<table '.(($config['fullScreenWidth']) ? 'style="width:100%;"' : '').'>
		<tr align="center" style="text-align:center;">
			<td class="first" '.(($config['itemsAlignVertical'] == 'middle' or $config['cardsType'] != "3" or $config['cardsType'] != "4") ? 'valign="middle" style="vertical-align:middle;"' : '').'>';
			
			if ($config['resetEnabled']) $tbl .= '<div id="resetDiv" style="position:relative;"><div id="delete" class="delete"><div style="float:left;">' . $q->display->readRequiredQuestionVariables($config['resetIcon']) . '</div><div style="float:left;margin-left:5px;margin-top:10px;"><span>' . $config['resetText'] . '</span></div><div style="clear:both;"></div></div></div>';
			
			if ($config['cardsType'] == 2) {
				$tbl .= '<div class="outer">';
				
				for ($i=0; $i<$config['cardRows']; $i++) {
					for ($j=0; $j<$config['cardColumns']; $j++) {
						$tbl .= '<div id="row'.$i.'_'.$j.'" class="inner mesh"></div>';
					}
					
					$tbl .= '<div class="clear"></div>';
				}
				
				$tbl .= '</div>';
			} else {
				$tbl .= '<ul id="app"></ul>';
			}
				
			$tbl .= '</td>';
			
			$tbl .= ($config['layout'] != "horizontal") ? '<tr/><tr><td class="tableCenter" valign="middle" style="vertical-align:middle;"></td></tr><tr align="center" style="text-align:center;">' : '<td class="tableCenter" valign="middle" style="vertical-align:middle;"></td>';
			if ($config['cardsType'] == 4) {
				$tbl .= '<td style="width:100px;vertical-align:middle;valign:middle;"><div>';
					foreach ($legArrBasic as $i => $ans) {
						$label = $q->display->readRequiredQuestionVariables($ans[1]);
						$tbl .= '<div style="display:table;height:'.($config['cardHeight']+1).'px;width:100%;"><span style="vertical-align:middle;valign:middle;display:table-cell;text-align:right;padding-right:2px;">'.$label.'</span></div>';
					}
				$tbl .= '</div></td>';
			}
			
			$tbl .= '<td class="second" valign="'.$config['itemsAlignVertical'].'" style="vertical-align:'.$config['itemsAlignVertical'].';">';
			
			$cleanValues = array();
			
			foreach ($fieldsValues as $k => $v) {
				$nk = explode("_", $k);
				
				if ($nk[0] == $qName) $cleanValues[$nk[1]] = $v;
			}
			
			foreach ($ansArrBasic as $i => $ans) {
				
				$selected = false;
				
				$index = $ans[0];
				$label = $q->display->readRequiredQuestionVariables($ans[1]);
				
				foreach ($cleanValues as $a => $b) {
					
					if ($config['inverse']) {
						
						if ($b != "") {
							
							if ($b == $index) {
								$lab = ($config['cardsType'] == 4) ? '<span style="vertical-align:middle;valign:middle;display:table-cell;">'.$label.'</span>' : $label;
								
								$li = '<li id="app_'.$index.'" class="item"><div class="box">'.$lab.'</div>';
								$li .= '</li>';
								
								$dragValues[$a][] .= $li;
								
								$dragScript[] = '$("#input_'.$a.'").val("'.$index.'");';
								
								$selected = true;
							}
						}
						
					} else {
						
						if ($b != "") {
							
							if ($a == $index) {
								
								$li = '<li id="app_'.$index.'" class="item"><div class="box">'.$label.'</div>';
								$li .= '<input id="input_'.$index.'" type="hidden" name="answers['.$qName.'_'.$index.']" value="'.$b.'" />';
								$li .= '</li>';
								
								$dragValues[$b][] .= $li;
								
								$selected = true;
							}
						}
					}
					
				}
				
				if (!$selected)	$tbl .= "<script>App.items.push(['" . $index . "', \"" . $label . "\", '".$qName."_".$index."']);</script>";
				
			}

			$color = ($config['cardsType'] == 4) ? "border:1px solid #aaaaaa;padding:10px;" : "";
			
			$tbl .= '<div style="clear:both;"></div>
				<div id="cartdiv" style=" '.$BasketPosition.$color.' display: table; text-align: center;">';
				
				$break = false; $offset = false;
				//array_reverse($legArrBasic,true)
				
				$neutral = explode(",", $config['boxNeutralColor']);
				$first = true;
				$tbls = array();
				$vals = array();
				
				//$pluginMustCondition[] = $qName.'_'.$kIndex.' > 0 ';
				foreach ($legArrBasic as $legInd => $leg) {
					$index = $legInd+1;
					
					// added by Soulskiner #15.6.2014
					// here we define condition in case for must asnwer condition
					$pluginMustCondition[] = '$'.$qName.'_'.$index.' > 0 ';
					
					$ddName= "answers[$fields[$legInd]]";	// answers[q1_1..q1_n]
					
					$style = "";
					$margin = "";
					
					if ($legInd > (count($legArrBasic) - count($neutral) - 1)) {
						$style = "style=\"background-color: " . $neutral[count($legArrBasic) - $legInd - 1] . "\";";
						
						if ($first) {
							$margin = ($config['layout'] == "vertical") ? "style=\"margin-left:".$config['neutralMargin']."px;\"" : "style=\"margin-top:".$config['neutralMargin']."px;\"";
							$first = false;
						} elseif ($config['horizontal_card_margin']) {
							$margin = "style=\"margin-left:".$config['horizontal_card_margin']."px;\"";
						}
					}
					
					if ($first && $config['horizontal_card_margin']) {
						$margin = "style=\"margin-left:".$config['horizontal_card_margin']."px;\"";
					} 
					// Added carts
					$tbl .= '<div class="container" '.$margin.'>';
					if ($config['cardsType'] != 4) {
						$tbl .= '<ul id="dropContainer_'.$index.'" class="cart">'.(isset($dragValues[$index]) ? implode(" ", $dragValues[$index]) : '').'</ul>
						<div class="caption" '.$style.'>'.$leg[1];
					
						if ($config['inverse']) {
							$tbl .= '<input id="input_'.$index.'" type="hidden" value="" name="answers['.$qName.'_'.$index.']" />';
						}
					
						$tbl .= '</div>';
					} else {
						$tbls[] = '<input id="input_'.$index.'" type="hidden" value="" name="answers['.$qName.'_'.$index.']" />';
						if (isset($dragValues[$index])) $vals[] .= implode("", $dragValues[$index]);
					}
						
					$tbl .= '</div>';
				}
				
				if ($config['cardsType'] == 4) {
					$tbl .= implode("", $tbls);
					$tbl .= implode("", $vals);
					if (!count($vals)) $tbl .= '<li class="placeholder"></li>';
				}
			
			$tbl .= '</td>
		</tr>
		<tr>
			<td>';
			
			$tbl .= '<div style="margin:15px;">';
			$indexx = count($legArrBasic) + 1;
			$pluginNoGoCondition[] = '$'.$qName.'_'.$indexx.' > 0 ';
			
			if ($cleanValues[$indexx] != "") $noGoSelected = $cleanValues[$indexx];
			
			foreach ($ansArrNoGo as $value) {
				// answers['.$qName.'_'.$index.']
				$selected = $noGoSelected == $value[0] ? " checked=checked" : "";
				$tbl .= '<input id="app_' . $value[0] . '" type="radio" name="answers['.$qName.'_'.$indexx.']" value="' . $value[0] . '"' . $selected . '></input>' . $value[1] . '<br>';
			}
			$tbl .= '</div>';
			
			$tbl .= '</td>
		</tr>';
		
	
	$tbl .= '</table></div>';

	$tbl .= '<div id="openAnswer">';
	
	if ($config['openAnswerEnabled'] == 1) {
		$tbl .= '<label class="labelText">'.$config['openAnswerText'].'</label>'.($config['openAnswerTextArea'] == 1 ? '<textarea rows="4" columns="50" name="answers['.$config['openAnswerRelQuestion'].'_1]">'.$fieldsValues[$config['openAnswerRelQuestion']."_1"].'</textarea>' : '<input type="text" value="'.$fieldsValues[$config['openAnswerRelQuestion']."_1"].'" name="answers['.$config['openAnswerRelQuestion'].'_1]"></input>');
	}
	
	$tbl .= '</div>';
	
	if (!empty($dragScript)) {
		$tbl .= '<script>'.implode(" ", $dragScript).'</script>';
	}
	
	$tbl .= '
	<script>
		function setItemDraggable(item) {
			item.dblclick(function() {
		    	if (App.cardType == 4) {
		    		$(this).appendTo("#cartdiv");
					
					var productOrder = $("#cartdiv").sortable("toArray");
				   var input = 1;
				   
				   for (var i=0; i<productOrder.length; i++) {
				   	
				   	if (productOrder[i].substr(0,4) === "app_") {
				   		
				   		$("#cartdiv > #input_"+input).val(productOrder[i].substr(4)+"");
				   		input++;
				   	}
				   }
		    	}
				
		    }).draggable({
		    	connectToSortable: "#cartdiv .item",
		        appendTo: "#cartdiv",
		        revert: "invalid",
		        scroll: true,
		        refreshPositions: true,
		        cursorAt: {
		            top: '.($config['cardHeight'] / 2).',
		            left: '.(($config['cardsType'] == 1) ? ($config['cardWidth']) : ($config['cardWidth']/2)).'
		        },
		        drag: function(event, ui) {
		        	var st = parseInt($(this).data("startingScrollTop"));
					ui.position.top -= $(this).parent().scrollTop() + st;
		        },
			    start: function() {
			    	$(this).data("startingScrollTop", $(this).parent().scrollTop());
			    	if (App.cardType == 1) {
				    	if ($(this).is(":last-child")) {
				        	$(this).hide();
						} else {
							return false;
						}
					}
			    },
			    stop: function(event, ui) {
			        $(this).show();
					if (App.cardType == 3) {
						
						var inner = ('.$config['cardHeight'].'+12) * $("#app li").size();
						var height = (('.$config['cardHeight'].'+12) * App.count);
						
						var diff = height - inner;
						
						$("#app").css("padding-top", diff/2);
						$("#app").css("height", height-(diff/2));
					} else if (App.cardType == 4) {
						var inner = ('.$config['cardHeight'].') * $("#app li").size();
						var height = (('.$config['cardHeight'].') * App.count);
						
						var diff = height - inner;
						
						$("#app").css("padding-top", diff/2);
						$("#app").css("height", height-(diff/2));
					} else if (App.cardType == 2) {
						/* TODO: move all to start
						$(".outer").find(".mesh:empty:first");
						$(".outer").find(".mesh:not(empty):last")*/
					}
			    },
		        helper: function (event, ui) {
		        	if (App.cardType == 1) {
			            if ($(event.currentTarget).is("li:first-child")) {
			                return $("<div class=\"test\"></div>").append($(this).clone().css("list-style", "none"));
			            } else {
			                return $("<div class=\"test\"></div>").append($(this).clone().css("margin-left", "-30px").css("list-style", "none"));
			            }
					} else {
						return $("<div class=\"test\"></div>").append($(this).clone().css("list-style", "none"));
					}
		        }
		    });
		};
		
		$("input[name=\"answers['.$qName.'_'.(count($legArrBasic) + 1).']\"]").mouseup(function(a){
		    if ($(this).is(":checked")) {
		    	setTimeout(function() { $("input[name=\"answers['.$qName.'_'.(count($legArrBasic) + 1).']\"]").prop("checked", false); }, 100);
				
				toggleDrag("enable");
			}
			
			else {
				$("#delete").click();
				toggleDrag("disable");
			}
		});
		
		function toggleDrag(status) {
			$(".item").each(function(index, item) {
				$(item).draggable(status);
			});
			refreshAnswersLocation();
		};
		
		function refreshAnswersLocation() {
			var inner = ('.$config['cardHeight'].') * $("#app li").size();
			var height = (('.$config['cardHeight'].') * App.count);
			
			var diff = height - inner;
			
			$("#app").css("padding-top", diff/2);
			$("#app").css("height", height-(diff/2));
		};
		
		$(function () {
			for (var i = 0; i < App.items.length; i++) {
				var li = (App.inverse) ? (App.cardType == 4) ? "<li class=\"item\" id=app_" + App.items[i][0] + "><div class=\"box\"><span style=\"vertical-align:middle;valign:middle;display:table-cell;\">" + App.items[i][1] + "</span></div></li>" : "<li class=\"item\" id=app_" + App.items[i][0] + "><div class=\"box\">" + App.items[i][1] + "</div></li>" : "<li class=\"item\" id=app_" + App.items[i][0] + "><div class=\"box\">" + App.items[i][1] + "</div><input id=\"input_" + App.items[i][0] + "\" type=\"hidden\" value=\"\" name=\"answers[" + App.items[i][2] + "]\" /></li>";';
				
				if (intval($config['centerLineWidth']) > 0 and $config['layout'] == 'vertical') {						
					$tbl .= '$(".tableCenter").append("<div style=\"height:'.$config['centerLineWidth'].'px;background-color:'.$config['centerLineColor'].';\"></div>");';
				}
				
				$tbl .= 'if (App.cardType == 1) {
				    $("#app").append(li);
				    if (i !== 0) {
				        if (i >= (App.items.length - 10)) $("#app_" + App.items[i][0]).css("margin-left", "-'.($config['cardWidth']-5).'px");
				        else $("#app_" + App.items[i][0]).css("margin-left", "-'.$config['cardWidth'].'px");
				    }
				}
				
				else if (App.cardType == 2) {
					var x = Math.floor(i / App.dimX);
					var y = i % App.dimX;
						
					$("#row"+x+"_"+y).append(li);
				}
				
				else if (App.cardType == 3 || App.cardType == 4) {
				    $("#app").append(li);
				}
			}
	
			if (App.cardType == 2) {
				for (var i = 0; i < App.items.length; i++) {
					if (typeof App.items[i][3] !== "undefined") {
						$("#app_"+App.items[i][3]).appendTo($("#dropContainer_"+App.items[i][0]));
						$("#input_"+App.items[i][0]).val(App.items[i][3]);
					}
				}
			}
			
			if (App.cardType == 1) {
		    	$("#app").width(App.width);
			}
			
			else if (App.cardType == 3) {
				var height = (('.$config['cardHeight'].'+12) * App.count);
				$("#app").height(height);
			} else if (App.cardType == 4) {
				var height = (('.$config['cardHeight'].') * App.count);
				$("#app").height(height);
			}
		
		    setItemDraggable($(".item"));
		
		    $(".cart,.neutral").droppable({
		        accept: ".item",
		        hoverClass: "active",
		        drop: function (event, ui) {
		        	
		            var dropped = ui.draggable;
		            var droppedOn = $(this);
					
		        	var name = dropped.attr("id");
		                name = name.split("_");
		                name = name.pop();
					
					if (App.inverse) {
						$.each($("#cartdiv :input"), function(i,v) {
							if (!isNaN($(v).val())) {
								if ($(v).val() == name) {
									$(v).val("");
								}
							}
						});
					}
					
					if (App.inverse && droppedOn.children(".item").length) {
						
						if (App.cardType == 2) {
							for (var i=0; i<App.dimY; i++) {
								for (var j=0; j<App.dimX; j++) {
									if ($("#row"+i+"_"+j).children(".item").length == 0) {
										droppedOn.children(".item").first().appendTo($("#row"+i+"_"+j));
									}
								}
							}
						}
						
						else if (App.cardType == 1 || App.cardType == 3 || App.cardType == 4) {
							droppedOn.children(".item").first().appendTo("#app");
							
							if (App.cardType == 1) {
								$("#app").children(".item").each(function (index) {
					                var id = $(this).attr("id");
									if (index !== 0){
						                if (index >= (App.len - 10) || App.len <= 10) {
						                    $("#" + id).css("margin-left", "-'.($config['cardWidth']-5).'px");
						                } else if (index !== 0) {
						                    $("#" + id).css("margin-left", "-'.$config['cardWidth'].'px");
						                }
									} else {
										$("#" + id).css("margin-left", "");
									}
									$("#" + id).css("top", "10px");
					            });
							}
						}
					}
		
		            if (dropped.parent()[0] !== droppedOn[0]) {
		                $(dropped).detach().css({
		                    top: 0,
		                    left: 0
		                }).css("margin-left", "").appendTo(droppedOn);
		
						if (App.cardType == 1) {
			                App.len = $("#app").children(".item").length;
			                $("#app").children(".item").each(function (index) {
			                    if (index >= (App.len - 11) && App.len > 10 && index !== 0) {
			                        var id = $(this).attr("id");
			                        $("#" + id).css("margin-left", "-'.($config['cardWidth']-5).'px");
			                    }
			                });
						}
		
		                var item = droppedOn.attr("id");
		                item = item.split("_");
		                item = item.pop();
		
		                var name = dropped.attr("id");
		                name = name.split("_");
		                name = name.pop();
		
		                if (!App.inverse) {
		                	$("#input_" + name).val(item);
						} else {
							$("#input_" + item).val(name);
						}
						
						setItemDraggable($(dropped));
		            }
		        }
		    });
		
		    $("#app,.mesh").droppable({
		    	hoverClass : "ui-small-highlight",
		        accept: ".item",
		        drop: function (event, ui) {
		            var dropped = ui.draggable;
		            var droppedOn = $(this);
		
					if (App.cardType == 1) {
			            App.len = $("#app").children(".item").length;
			            var margin = (App.len > 0) ? "-'.$config['cardWidth'].'px" : "";
					}
		
		            var name = dropped.attr("id");
		            name = name.split("_");
		            name = name.pop();
					
		            $("#input_" + name).val("");
					
					if (App.inverse) {
						$.each($("#cartdiv :input"), function(i,v) {
							if (!isNaN($(v).val())) {
								if ($(v).val() == name) {
									$(v).val("");
								}
							}
						});
					}
		
		            $(dropped).detach().css({
		                top: 0,
		                left: 0,
		                "margin-left": margin
		            }).appendTo(droppedOn);
		
					if (App.cardType == 1) {
			            $("#app").children(".item").each(function (index) {
			                var id = $(this).attr("id");
							if (index !== 0){
				                if (index >= (App.len - 10) || App.len <= 10) {
				                    $("#" + id).css("margin-left", "-'.($config['cardWidth']-5).'px");
				                } else if (index !== 0) {
				                    $("#" + id).css("margin-left", "-'.$config['cardWidth'].'px");
				                }
							} else {
								$("#" + id).css("margin-left", "");
							}
							$("#" + id).css("top", "10px");
			            });
					}
					
					setItemDraggable($(dropped));
		        }
		    })';
		    
			if ($config['cardsType'] == 3 or $config['cardsType'] == 4) $tbl .= '.sortable({
				revert: true
			})';
			
		    $tbl .= ';';
		
		if ($noGoSelected !== FALSE) {
			$tbl .= 'toggleDrag("disable");';
		}

		if (!empty($ansArrNoGo)) {
			$tbl .= 'setTimeout(function() { refreshAnswersLocation(); }, 100);';
		}

		$tbl .= '});';
		
		if ($config['cardsType'] == 4)
			$tbl .= '$("#cartdiv").sortable({
				connectWith: "li",
				/*cursorAt: { top: 0, left: 0 },*/
				update: function(event, ui) {
	               var productOrder = $(this).sortable("toArray");
	               
				   var input = 1;
				   
				   for (var i=0; i<productOrder.length; i++) {
				   	
				   	if (productOrder[i].substr(0,4) === "app_") {
				   		
				   		$("#cartdiv > #input_"+input).val(productOrder[i].substr(4)+"");
				   		input++;
				   	}
				   }
	            },
	            sort: function () {
	            	$(this).removeClass("ui-state-default");
				}
			});
			
			$("#cartdiv").disableSelection();
			
			$("#cartdiv").droppable({
				hoverClass : "ui-custom-highlight",
		        accept: ":not(.ui-sortable-helper)",
		        /*activeClass: "ui-custom-highlight",*/
				drop : function(ev, ui) {
					
					if ($(this).find(".placeholder").length > 0) {
                 		$(this).find(".placeholder").remove();
			 		
						$(ui.draggable).clone().appendTo(this);
					} else {
						var i = 0;
                 		$(this).children(".item").each(function () {
	                     	if ($(this).offset().top >= ui.offset.top) {
	                         	$(ui.draggable).clone().insertBefore($(this));
	                         	i = 1;
	                         	return false;
	                     	}
                 		})

                 		if (i != 1) {
                 			$(ui.draggable).clone().appendTo(this);
                 		}
					}
					$(ui.draggable).remove();
					
					var children = $("#cartdiv").children(".item");
					var input = 1;
					
					for (var i=0; i<children.length; i++) {
				   	
				   	if (children[i].id.substr(0,4) === "app_") {
				   		
				   		$("#cartdiv > #input_"+input).val(children[i].id.substr(4)+"");
				   		input++;
				   	}
				   }
					
					
					/*var productOrder = $(this).sortable("toArray");
	               
				   var input = 1;
				   
				   for (var i=0; i<productOrder.length; i++) {
				   	
				   	if (productOrder[i].substr(0,4) === "app_") {
				   		
				   		$("#cartdiv > #input_"+input).val(productOrder[i].substr(4)+"");
				   		input++;
				   	}
				   }*/
				}
			}).sortable({
         		items: "li:not(.placeholder)",
         		/*cursorAt: { top: 0, left: 0 },*/
         		sort: function () {
             		$(this).removeClass("ui-state-default");
         		}
     		});
			
			$("#cartdiv").width("'.$config['cardWidth'].'px");
			$("#cartdiv").height("'.(($config['cardHeight']+2)*count($legArrBasic)).'px");
			$("#cartdiv").css("padding-top", "0px");
			$("#cartdiv").css("padding-bottom", "0px");
			';
		
		$tbl .= '$("#delete").bind("click", function () {
	
			$("#cartdiv > .item").each(function(index, item) {
				if ($(item).parent().attr("id") !== "app") {
					
					if (App.cardType == 2) {
						for (var a=0; a<App.dimY; a++) {
							for (var b=0; b<App.dimX; b++) {
								if ($("#row"+a+"_"+b).children(".item").length == 0) {
									$(item).appendTo($("#row"+a+"_"+b));
								}
							}
						}
					} else {
					
		            	var droppedOn = $("#app");
						var margin = (App.cardType == 1) ? (!droppedOn.children().length) ? "" : "-115px" : "0px";
					
						$(item).detach().css({
							top: 0,
							left: 0,
							"margin-left": margin
						}).hide().appendTo(droppedOn).show("fast");
		
						if (App.inverse) {
							try {
								$("input[id^=\"input_\"]").each(function(index, item) {
									$(item).val("");
								});
							} catch (ignore) {}
						}
						
						else {
			            	var name = $(item).attr("id");
			            	name = name.split("_");
			            	name = name.pop();
							
							$("#input_" + name).val("");
						}
		
			            try {
			                var a = $("#app").length - 10;
			                if (a > 1) {
		    	                var id = $("#app").children().eq(i).attr("id");
								if (App.cardType == 1) $("#" + id).css("margin-left", "-120px");
		        	        }
		            	} catch (err) {
		            	}
		            	
		            	setItemDraggable($(item));
					}
	        	}
			});
	
			if (App.cardType == 1) {
				setTimeout(function() {
				
					App.len = $("#app").children(".item").length + 1;
		    		$("#app").children(".item").each(function (index) {
						var id = $(this).attr("id");
						if (index !== 0){
							if (index >= (App.len - 10) || App.len <= 10) {
								$("#" + id).css("margin-left", "-115px");
							} else if (index !== 0) {
								$("#" + id).css("margin-left", "-120px");
							}
						} else {
							$("#" + id).css("margin-left", "");
						}
						$("#" + id).css("top", "10px");
					});
				}, 200);
			}
		
			refreshAnswersLocation();
		});
	</script>';

$html .= $tbl;	

//added by Soulskiner #15.6.2014
// we check if question has must answer checked and if their is must answer condition.
// if yes it is defined in session variable.
if ($q->must_answer && $pluginMustCondition) {
	$operator = ($config['requireAllAnswers']) ? " AND " : " OR ";
	
	if (!empty($ansArrNoGo)) {
		$_SESSION['mustAnswerCondition'] = "(" . implode(" OR ", $pluginNoGoCondition) . ") OR (" . implode($operator, $pluginMustCondition) . ")";
	}
	
	else {
		$_SESSION['mustAnswerCondition'] = implode($operator, $pluginMustCondition);
	}
}

// echo "Must answer: " . $_SESSION['mustAnswerCondition'] . "<br><hr>";
/*echo "<pre>";
	var_dump($_POST);

var_dump($_POST['answers']);
var_dump($dragScript);*./
echo "<pre>";
var_dump($_POST);
echo "<hr>";
var_dump($fieldsValues);
echo "</pre>";*/

?>