jQuery(document).ready(function() {

	/*
	 * update page events; used: surveyInstance page
	 */
	updatePageEvents();
	/*
	 * initialise LiveCentral buttons
	 */
	jQuery(".buttonChannel a[id$=details]").click(function() {
		jQuery(".buttonChannel").removeClass("labelSelected");
		jQuery(this).parent().addClass("labelSelected");
	});

	/*
	 * init channelManager
	 */
	jQuery(".dropdown .dropdownItem").hover(function() {
		jQuery(this).addClass("selected");
	}, function() {
		jQuery(this).removeClass("selected");
	});

	/*
	 * initialize actions for dashboard elements controls
	 */
	manageElementsControls();

	/*
	 * draw the matrix questions in Creator and surveyInstance
	 */
	drawMatrixSI("all");
});

function toggleOptions(wrapper) {
	/*
	 * toggles the answer options page: CREATOR
	 */
	wrapper.bind('mouseenter', function() {
		jQuery(this).find('.buttonDelete').removeClass("hidden");
		jQuery(this).find('.buttonLogic').removeClass("hidden");
	});

	wrapper.bind('mouseleave', function() {
		jQuery(this).find('.buttonDelete').addClass("hidden");
		var buttonLogic = jQuery(this).find('.buttonLogic');
		if (!buttonLogic.hasClass("logicOn")) {
			buttonLogic.addClass("hidden");
		}
	});
}
function manageElementsControls() {
	jQuery(".showhideControl").each(function() {
		var el = jQuery(this);
		var parent = el.parent().parent();
		el.click(function() {
			if (parent.hasClass('pageCellClosed')) {
				parent.removeClass('pageCellClosed');
				if (el.hasClass('buttonMax')) {
					el.removeClass('buttonMax').addClass('buttonMin');
				}
			} else {
				parent.addClass('pageCellClosed');
				if (el.hasClass('buttonMin')) {
					el.removeClass('buttonMin').addClass('buttonMax');
				}
			}
		});
	});

	jQuery(".buttonClose").each(function() {
		var el = jQuery(this);
		var parent = el.parent().parent();
		el.click(function() {
			parent.addClass('hidden');
		});
	});
}
var focusedInput = null;
function updatePageEvents() {
	readCurrentPage();
	jQuery('.answerCheckbox a').mouseover(function() {
		if (!jQuery(this).hasClass("siAnswerCheckOn")) {
			jQuery(this).addClass('siAnswerHoverCheckOn');
			jQuery(this).removeClass('siAnswerCheckOff');
		}
	}).mouseout(function() {
		if (!jQuery(this).hasClass("siAnswerCheckOn")) {
			jQuery(this).removeClass('siAnswerHoverCheckOn');
			jQuery(this).addClass('siAnswerCheckOff');
		}
	}).mouseup(function() {
		if (!jQuery(this).hasClass("siAnswerCheckOn")) {
			jQuery(this).addClass('siAnswerCheckOn');
			jQuery(this).removeClass('siAnswerHoverCheckOn');
			jQuery(this).removeClass('siAnswerCheckOff');
			jQuery(this).unbind("mouseover");
			jQuery(this).unbind("mouseout");
		} else {
			if (focusedInput != jQuery(this).attr('id')) {
				jQuery(this).removeClass('siAnswerCheckOn');
				jQuery(this).addClass('siAnswerCheckOff');
				jQuery(this).mouseover(function() {
					jQuery(this).addClass('siAnswerHoverCheckOn');
					jQuery(this).removeClass('siAnswerCheckOff');
				}).mouseout(function() {
					jQuery(this).removeClass('siAnswerHoverCheckOn');
					jQuery(this).addClass('siAnswerCheckOff');
				});
			}
		}
	});
	jQuery('.answerRadio a').mouseover(function() {
		if (!jQuery(this).hasClass("siAnswerRadioOn")) {
			jQuery(this).addClass('siAnswerHoverRadioOn');
			jQuery(this).removeClass('siAnswerRadioOff');
		}
	}).mouseout(function() {
		if (!jQuery(this).hasClass("siAnswerRadioOn")) {
			jQuery(this).removeClass('siAnswerHoverRadioOn');
			jQuery(this).addClass('siAnswerRadioOff');
		}
	}).mouseup(
			function() {
				jQuery(this).parents(".answerRadio").find('a').removeClass(
						'siAnswerRadioOn').removeClass('siAnswerHoverRadioOn')
						.addClass('siAnswerRadioOff').mouseover(function() {
							jQuery(this).addClass('siAnswerHoverRadioOn');
							jQuery(this).removeClass('siAnswerRadioOff');
						}).mouseout(function() {
							jQuery(this).removeClass('siAnswerHoverRadioOn');
							jQuery(this).addClass('siAnswerRadioOff');
						});

				jQuery(this).toggleClass('siAnswerRadioOn').toggleClass(
						'siAnswerRadioOff');

				jQuery(this).unbind("mouseover");
				jQuery(this).unbind("mouseout");
			});
	jQuery('.answerLikert a').mouseover(function() {
		if (!jQuery(this).hasClass("siAnswerLikertOn")) {
			jQuery(this).addClass('siAnswerHoverLikertOn');
			jQuery(this).removeClass('siAnswerLikertOff');
		}
	}).mouseout(function() {
		if (!jQuery(this).hasClass("siAnswerLikertOn")) {
			jQuery(this).removeClass('siAnswerHoverLikertOn');
			jQuery(this).addClass('siAnswerLikertOff');
		}
	}).mouseup(
			function() {
				jQuery(this).parents(".answerLikert").find('a').removeClass(
						'siAnswerLikertOn')
						.removeClass('siAnswerHoverLikertOn').addClass(
								'siAnswerLikertOff').mouseover(function() {
							jQuery(this).addClass('siAnswerHoverLikertOn');
							jQuery(this).removeClass('siAnswerLikertOff');
						}).mouseout(function() {
							jQuery(this).removeClass('siAnswerHoverLikertOn');
							jQuery(this).addClass('siAnswerLikertOff');
						});

				jQuery(this).toggleClass('siAnswerLikertOn').toggleClass(
						'siAnswerLikertOff');

				jQuery(this).unbind("mouseover");
				jQuery(this).unbind("mouseout");
			});
	jQuery('.siWrapperLikert a').mouseup(
			function() {
				jQuery(this).parents(".siWrapperLikert").find('a').removeClass(
						'siAnswerLikertOn').addClass('siAnswerLikertOff');

				jQuery(this).addClass('siAnswerLikertOn').removeClass(
						'siAnswerLikertOff');
			});
	jQuery('.answerRadioMatrix a').mouseover(function() {
		if (!jQuery(this).hasClass("siAnswerRadioOn")) {
			jQuery(this).addClass('siAnswerHoverRadioOn');
			jQuery(this).removeClass('siAnswerRadioOff');
		}
	}).mouseout(function() {
		if (!jQuery(this).hasClass("siAnswerRadioOn")) {
			jQuery(this).removeClass('siAnswerHoverRadioOn');
			jQuery(this).addClass('siAnswerRadioOff');
		}
	}).mouseup(
			function() {
				jQuery(this).parents(".matrix_sc_row").find('a').removeClass(
						'siAnswerRadioOn').removeClass('siAnswerHoverRadioOn')
						.addClass('siAnswerRadioOff').mouseover(function() {
							jQuery(this).addClass('siAnswerHoverRadioOn');
							jQuery(this).removeClass('siAnswerRadioOff');
						}).mouseout(function() {
							jQuery(this).removeClass('siAnswerHoverRadioOn');
							jQuery(this).addClass('siAnswerRadioOff');
						});

				jQuery(this).toggleClass('siAnswerRadioOn').toggleClass(
						'siAnswerRadioOff');

				jQuery(this).unbind("mouseover");
				jQuery(this).unbind("mouseout");
			});
	if (currentPage == "survey instance") {
		fillInAnswersSI();
		drawMatrixSI("all");
		generateQuestionNumbers();
	}
	setLikertValue('initialisation', '', '');
}

var sortableStatus = false;
var sorting = "bullshit";
var sortOptions = {
	start : function(e, ui) {

	},
	stop : function() {
		var sorting = "aiurea";
		sortingValue(sorting);
	},
	handle : 'div[id^=questionHeader]',
	placeholder : 'questionPlaceholder',
	axis : 'y'
};

var counterQuestions = 1;
function generateQuestionNumbers() {
	/*
	 * Generates the questions numbers dynamically
	 */
	c = counterQuestions;
	l = counterQuestions + 96;
	jQuery(".questionNumber, .siQuestionNumber").each(function() {
		if (jQuery(this).attr("title") != "TEXT") {
			var requiredLink = jQuery(this).find("span");

			jQuery(this).empty().append("" + c + ".");
			if (requiredLink.length > 0) {
				jQuery(this).append(requiredLink);
			}

			jQuery(this).attr("title", "");
			c++;
			if (jQuery(this).hasClass("hidden")) {
				jQuery(this).removeClass("hidden");
			}
		} else {
			if (currentPage != "survey instance") {
				jQuery(this).empty().append("" + String.fromCharCode(l) + ".");
				l++;
				jQuery(this).attr("title", "");
				if (jQuery(this).hasClass("hidden")) {
					jQuery(this).removeClass("hidden");
				}
			} else {
				jQuery(this).empty().css( {
					'display' : 'none'
				});
			}
		}
	});
}
function sendSortable(entity, prefix, hash, pageHash) {
	if (entity == "dashboardElement") {
		var nr1 = jQuery("#dashboardColumn1").sortable('toArray');
		var newOrderColumn1 = "";
		for ( var i = 0; i < nr1.length; i++) {
			if (newOrderColumn1 == "") {
				newOrderColumn1 = newOrderColumn1 + '' + nr1[i];
			} else {
				newOrderColumn1 = newOrderColumn1 + ',' + nr1[i];
			}
		}
		var nr2 = jQuery("#dashboardColumn2").sortable('toArray');
		var newOrderColumn2 = "";
		for ( var i = 0; i < nr2.length; i++) {
			if (newOrderColumn2 == "") {
				newOrderColumn2 = newOrderColumn2 + '' + nr2[i];
			} else {
				newOrderColumn2 = newOrderColumn2 + ',' + nr2[i];
			}
		}
		sortingDashboardElements(newOrderColumn1, newOrderColumn2,
				'dashboardElement_');
	} else {
		var nr = jQuery('#' + prefix + '' + hash).sortable('toArray');

		var newOrder = "";
		for ( var i = 0; i < nr.length; i++) {
			if (newOrder == "") {
				newOrder = newOrder + '' + nr[i];
			} else {
				newOrder = newOrder + ',' + nr[i];
			}
		}
		// callSortable(entity, pageHash, hash, newOrder);
		sortingItems(entity, pageHash, hash, newOrder);
	}
}

function sendSortableMatrix(container, hash, pageHash) {
	/*
	 * TODO: make this work for both rows and columns
	 * 
	 */
	var entity = "answer";
	var nr = jQuery('#' + container).sortable('toArray');

	var newOrder = "";
	for ( var i = 0; i < nr.length; i++) {
		if (newOrder == "") {
			newOrder = newOrder + '' + nr[i];
		} else {
			newOrder = newOrder + ',' + nr[i];
		}
	}
	// callSortable(entity, pageHash, hash, newOrder);
	sortingItems(entity, pageHash, hash, newOrder);
}

function chooseAnswer(id) {
	var name = "radioButton";
	var entity = jQuery('#' + id + ' .answerHead');
	if (entity.hasClass("checkBoxOff") || entity.hasClass("checkBoxOn")) {
		name = "checkBox";
	}
	if (entity.hasClass("lsBoxOff") || entity.hasClass("lsBoxOn")) {
		name = "lsBox";
	}
	entity.toggleClass(name + 'On').toggleClass(name + 'Off');
}

function drawProgress() {
	var progress = jQuery(".surveyProgressWrapperIphone");
	if (progress.length == 0) {
		var pageCurrent = jQuery(".surveyProgress_highlight").length - 1;
		var pageTotal = jQuery(".surveyProgress").length - 1;
		var target = jQuery(".surveyProgress_highlight").parent();
		target.append('<div class="surveyProgress_label">page <b>'
				+ pageCurrent + '</b> of <b>' + pageTotal + '</b></div>');
	} else {
		var pageCurrent = jQuery(".surveyProgressIphone_highlight").length;
		var pageTotal = jQuery(".surveyProgressIphone").length;
		var target = jQuery(".surveyProgressIphone_highlight").parent();
		target.append('<div class="surveyProgressIphone_label">page <b>'
				+ pageCurrent + '</b> of <b>' + pageTotal + '</b></div>');
	}
}
function setLikertValue(action, wrapperId, data) {
	if (action == "setSlider") {
		var c = 0;
		var found = false;
		jQuery("#" + wrapperId + " .siAnswerLikert").each(function() {
			if ((jQuery(this).attr("id") != data.id) && (!found)) {
				c++;
			} else {
				found = true;
			}
		});
		var sliderValue = +c + 1;
		if (sliderValue != 0) {
			jQuery("#" + wrapperId).siblings(".progressbar").slider('value',
					sliderValue);
		}
	}

	if (action == "callAction") {
		if (data == 0) {
			jQuery("#" + wrapperId).siblings(".progressbar").slider('value', 1);
		} else {
			var c = 1;
			jQuery("#" + wrapperId + " .siAnswerLikert").each(
					function() {
						jQuery(this).removeClass("siAnswerLikertOn").addClass(
								"siAnswerLikertOff");
						if (c == data) {
							// jQuery(this).trigger("click");
							jQuery(this).removeClass("siAnswerLikertOff")
									.addClass("siAnswerLikertOn");
							var parent = jQuery(this).parents(
									"[id^='questionWrapper_']");
							siRecordAnswer(parent.attr('id').substring(16),
									'siAnswerLikert', 'simple');
						}
						c++;
					});
		}
	}

	if (action == "initialisation") {
		jQuery(".siWrapperLikert").each(function() {
			var c = 0;
			jQuery(this).find(".siAnswerLikert").each(function(i, val) {
				if (jQuery(this).hasClass("siAnswerLikertOn")) {
					jQuery(".progressbar").slider('value', i + 1);
				}
			});
		});
	}
}
function initSurveyBoard() {
	jQuery("#surveyBoardSwitcher").click(function() {
		var container = jQuery("#surveyBoardElements");
		var wrapperMenu = container.find("[id$='surveyFilter']").height();
		var wrapperContent = container.find("#surveyBoardInner").height();
		var newHeight = wrapperMenu + 24;
		if (wrapperContent > wrapperMenu) {
			newHeight = wrapperContent;
		}
		var wrapper = jQuery(this).parent();
		if (wrapper.hasClass("pullDown")) {
			wrapper.addClass("pullUp");
			wrapper.removeClass("pullDown");
			container.animate( {
				height : newHeight
			}, 500, function() {
				jQuery(this).css( {
					height : "auto"
				});
				debug(newHeight + "-" + jQuery(this).height(), false);
			});

		} else {
			newHeight = 3;
			wrapper.addClass("pullDown");
			wrapper.removeClass("pullUp");
			container.animate( {
				height : newHeight
			}, 500);
		}
	});

	// var currentName=jQuery(".surveyBoardInnerHeader input:text").val();
	var currentName = jQuery("#initialSurvey").html();
	jQuery(".surveyBoardMenu a").each(function() {
		if (jQuery(this).text() == currentName) {
			jQuery(this).addClass("selected");
		}
	});

	var parentId = jQuery(".surveyBoardMenu").find(".selected").parent().attr(
			"id");
	if (parentId != null) {
		parentId = parentId.substring(9);
		var entity = jQuery("[id$='button_" + parentId + "']").click();
		// chooseSurveyBoardCategory(entity);
	}
}

function chooseSurveyBoardSurvey(entity) {
	jQuery(".surveyBoardMenu a").removeClass("selected");
	entity.addClass("selected");
	jQuery(".surveyBoardContent").append(
			'<div id="surveyBoardCurtain" class="surveyBoardCurtain"></div>');
	jQuery(".surveyBoardCurtain").width(jQuery(".surveyBoardContent").width())
			.height(jQuery(".surveyBoardContent").height()).fadeIn("fast");
}

function chooseSurveyBoardCategory(entity) {
	jQuery(".surveyBoardTabs a").removeClass("selected");
	entity.addClass("selected");
}
var openCount = 0;
var currentCurtainEntity = null;
var currentAnswerLogic = null;
var logicSourceId = null;
var skipLogicStatus = {};

function manageCurtain(action, entityId) {
	/*
	 * Manages the invisible curtain action: show, hide enityId: the element
	 * that gets additional management (bring to front, back)
	 */
	if ((action == "hide")) // end edit
	{
		if (this.openCount > 0) {
			this.openCount--;
		}
	}

	if (openCount == 0) {
		var entity = jQuery("#" + entityId);
		if (action == "show") {
			currentCurtainEntity = entityId;

			var curtain = createCurtain();
			entity
					.append('<div id="curtainError" class="curtainError" title="You have to finish editing, before choosing another entity. Click here to force editing finish." onclick="resetQuestionStatus();"></div>');

			// Set the CSS styles
			entity.css( {
				'z-index' : '9999',
				'position' : 'relative'
			});
			curtain.click(function() {
				var targetOffset = entity.offset().top - 50;
				jQuery('html,body').animate( {
					scrollTop : targetOffset
				}, 500);
				jQuery('#curtainError').css( {
					'top' : '4px',
					'left' : '-40px',
					'display' : 'block',
					'z-index' : '32000'
				});
			});
			manageEntityHighlight('highlight', entityId);
		} else {
			currentCurtainEntity = null;
			entity.css('z-index', 'inherit');
			jQuery('#curtainError').remove();
			closeCurtain();

			manageEntityHighlight('fade', entityId);
		}
	}
	if (action == "show") // start edit
	{
		this.openCount++;
	}
}
function createCurtain() {
	jQuery('body').append('<div id="curtain"></div>');
	var curtain = jQuery("#curtain");
	curtain.css( {
		'position' : 'fixed',
		'top' : '0px',
		'left' : '0px',
		'height' : '100%',
		'width' : '100%',
		'z-index' : '9998'
	});
	return curtain;
}
function closeCurtain() {
	jQuery('#curtain').remove();
}
function manageEntityHighlight(action, entityId) {
	/*
	 * 'bring to front' or 'bring to back' behaviour for an element
	 */
	var entity = jQuery("#" + entityId);
	if (action == "highlight") {
		entity.css( {
			'z-index' : '9999',
			'position' : 'relative'
		});
	} else {
		entity.css( {
			'z-index' : 'inherit'
		});
	}
}
function loadSavedSkipLogic() {
	jQuery("a.buttonLogic span").each(
			function() {
				var skipId = jQuery(this).html().strip();
				if (skipId != "") {
					var target = jQuery("#buttonLogicTarget_" + skipId);
					if (target.length > 0) {
						var targetId = target.siblings(".questionBox").find(
								".questionNumber").html();

						jQuery(this).html(targetId);
						var uid = jQuery(this).parent().attr('id');
						uid = uid.substring(uid.indexOf('_') + 1, uid.length);
						if (uid != "") {
							jQuery("#logicView_" + uid).html(targetId)
									.removeClass("hidden");
						}
						if (skipLogicStatus[uid] == null) {
							skipLogicStatus[uid] = {};
						}
						skipLogicStatus[uid].t = skipId;
						jQuery("#buttonLogicTarget_" + skipId).addClass(
								'buttonLogicTargetChecked');
					}
				}
			});
}
function manageQuestionLogic(action, reference, entityId, sourceId, targetId) {

	if (action == "start") {
		if (currentAnswerLogic != null) {
			clearCurrentLogic();
		}
		currentAnswerLogic = sourceId;
		var currentPage = jQuery("#answer_" + targetId).parents(
				"[id^='questionList']").attr("id");
		jQuery("#buttonLogic_" + currentAnswerLogic).css( {
			'visibility' : 'hidden'
		});
		jQuery("#answer_" + targetId)
				.append(
						'<a href="#" id="logicStart" title="' + skipMessageCancel + '"></a>');
		var logicStart = jQuery("#logicStart");

		jQuery('#logicStart').css( {
			'top' : '-3px',
			'left' : '-7px',
			'display' : 'block',
			'position' : 'absolute',
			'z-index' : '9999'
		}).click(function() {
			manageQuestionLogic('set', '', '', '', '-1');
			return false;
		});

		jQuery("[id^='buttonLogicTarget_']")
				.each(
						function() {
							//var page = jQuery(this).parents("ul.questionList:first").attr("id");
							var page = jQuery(this).parents("[id^='questionList']").attr("id");
							if (page != currentPage) {	
								var currentEntityId = jQuery(this).attr('id')
										.substring(18);
								if (currentEntityId != reference) {
									jQuery(this).fadeIn('fast');
									if (skipLogicStatus[sourceId] == null) {
										skipLogicStatus[sourceId] = {};
									}
									if ((skipLogicStatus[sourceId].t != "none")
											&& (skipLogicStatus[sourceId].t == currentEntityId)) {
										jQuery(this).addClass(
												'buttonLogicTargetChecked');
									} else {
										jQuery(this).removeClass(
												'buttonLogicTargetChecked');
									}
								}
							}
						});

		logicSourceId = sourceId;
	} else {
		if ((action == "set") && (logicSourceId != null)) {
			if (skipLogicStatus[logicSourceId] == null) {
				skipLogicStatus[logicSourceId] = {};
			}
			skipLogicStatus[logicSourceId].t = targetId;
			if (targetId != -1) {
				var currentAnswerLogicQuestion = entityId;
				if (currentAnswerLogicQuestion != null) {
					var questionNumber = jQuery(
							"#" + currentAnswerLogicQuestion).find(
							".questionNumber").html();
					jQuery("#buttonLogic_" + currentAnswerLogic).find('span')
							.html("" + questionNumber + "");
					jQuery("#logicView_" + currentAnswerLogic).html(
							"" + questionNumber + "").removeClass("hidden");
					currentAnswerLogicQuestion = null;
				}
			} else {
				jQuery("#buttonLogic_" + currentAnswerLogic).find('span').html(
						"");
				jQuery("#logicView_" + currentAnswerLogic).html("").addClass(
						"hidden");
			}
			Seam.Component.getInstance("surveyCreatorAction").setLogic(
					logicSourceId, targetId, setLogicCallback);
		}
		clearCurrentLogic();
	}
}
function clearCurrentLogic() {
	jQuery(".buttonLogicTarget").fadeOut("fast");
	jQuery('#logicStart').remove();
	logicSourceId = null;
	jQuery("#buttonLogic_" + currentAnswerLogic).css( {
		'visibility' : 'visible'
	});
	currentAnswerLogic = null;
}
function setLogicCallback(result) {
}
function resetInstance() {
	Seam.Component.getInstance("surveyInstanceAction").resetInstanceState(null);
}
function refreshResults() {
	Seam.Component.getInstance("resultDisplay").refreshResults(null);
}

function manageUpload() {
	jQuery('#logoUpload').toggleClass('hidden');
}
function resetUploadComponent(id) {
	jQuery('#' + id).trigger('click');
}
function resetQuestionStatus() {
	// setCurrentEditor(null);
	selectQuestion(null);
	cleanup();
	// toggleEditor();
	this.openCount = 0;
	manageCurtain('hide', currentCurtainEntity);
}
var selectedQuestionHash = null;
function selectQuestion(hash) {
	var element = jQuery("#question" + hash);
	element.click(function(e) {
		e.stopPropagation();
	});
	if (hash != selectedQuestionHash) {
		if (selectedQuestionHash != null) {
			jQuery("#questionHeader" + selectedQuestionHash).removeClass(
					"questionHeaderHovered");
		}

		if (hash != null) {
			jQuery("#questionHeader" + hash).addClass(
					"questionHeaderHovered");
		}

		this.selectedQuestionHash = hash;
	}
}
function drawMatrix(prefix, questionId, pageId) {
	/*
	 * Makes changes to a matrix type questions: adjusts element width
	 */
	var container = prefix + '' + questionId;

	jQuery("#" + container + " tbody").sortable( {
		stop : function() {
			if (sortableStatus == true) {
				wait();
				sendSortableMatrix(container + " tbody", questionId, pageId);
			}
			// jQuery("#reRenderAnswersWrapper_"+questionId+" a").click(); //do
		// this for rerendering after resorting
		jQuery('body').enableSelection();
	},
	change : function() {
		sortableStatus = true;
	},
	start : function() {
		jQuery('body').disableSelection();
		sortableStatus = false;
	},
	forcePlaceholderSize : true,
	forceHelperSize : true,
	opacity : 0.6,
	handle : '.sortableHandler',
	placeholder : 'answerPlaceholder',
	delay : 100,
	helper : fixHelper,
	axis : 'y'
	});
	jQuery("#" + container + " tr").mouseover(function() {
		jQuery(this).addClass("active-row");
	});
	jQuery("#" + container + " tr").mouseout(function() {
		jQuery(this).removeClass("active-row");
	});

}
function drawMatrixSI(container) {
	if (container == "all") {
		container = "answersMatrixSI_";
	}
	jQuery("[id^='" + container + "']").each(function() {
		var matrixId = jQuery(this).attr('id');

		jQuery("#" + matrixId + " [id$='valueFromResponse']").each(function() {
			var value = jQuery(this).text();
			jQuery(this).siblings(".matrixTextarea").val(value);
		});

		jQuery("#" + matrixId + " tr:odd").addClass('odd-row');
		jQuery("#" + matrixId + " tr:even").addClass('even-row');
		jQuery("#" + matrixId + " tr").mouseover(function() {
			jQuery(this).addClass('active-row')
		});
		jQuery("#" + matrixId + " tr").mouseout(function() {
			jQuery(this).removeClass('active-row')
		});
	});
}
function updateFrameWithNewName() {

	var newName = jQuery("#surveyTitle input").val();
	parent.renameSurvey(newName);
}
function uiDeleteMatrixColumn(id, parent) {
	var uid = id.substring(id.indexOf("_") + 1, id.length);
	jQuery("#" + parent).find(".matrixInputCell").each(
			function() {
				var tmpId = jQuery(this).attr('id');
				if (tmpId != "") {
					var uidRow = tmpId.substring(tmpId.indexOf("_") + 1, tmpId
							.lastIndexOf("_"));
					var uidColumn = tmpId.substring(tmpId.lastIndexOf("_") + 1,
							tmpId.length);
					if ((uidRow == uid) || (uidColumn == uid)) {
						jQuery(this).remove();
					}
				}
			});
	jQuery("#" + id).remove();
}
function uiDeleteMatrixRow(id) {
	jQuery("#" + id).remove();
}
function deletePageFromBar(id) {
	jQuery("#page_" + id).remove();
}

var currentDevice = null;
var devices = new Array();
function Device(name, read, width, code) {

	this.name = name;
	this.read = read;
	this.width = width;
	this.code = code;

	this.updateUI = function() {
		if (this.width != 925) {
			jQuery(".resizableContent").css( {
				"width" : this.width + "px"
			});
		} else {
			jQuery(".resizableContent").css( {
				"width" : "auto"
			});
		}
	};
	this.toString = function() {
	};
}

function addDevice(name, read, width, code) {
	var device = new Device(name, read, width, code);
	devices.push(device);

}
function changeDevice(select) {
	var selectedCode = select.val();
	for ( var i = 0; i < devices.length; i++) {
		if (devices[i].code == selectedCode) {
			currentDevice = devices[i];
			currentDevice.updateUI();
		}
	}
	Seam.Component.getInstance("surveyHome").setCurrentDevice(selectedCode,
			changeDeviceCallback);
}
function changeDeviceCallback() {

}
function selectDevice(code) {
	for ( var i = 0; i < devices.length; i++) {
		if (devices[i].code == code) {
			currentDevice = devices[i];
			currentDevice.updateUI();
		}
	}
	jQuery("#selectDevice").val(code);
}

var b = null;
var e = null;
var f = null;
var i = null;
var m = null;
var s = null;
var q = null;
var newLocation = null;

function updateFilter(id, page, cc, token) {
	var calendarStart = $('mainForm:filterStartDate').component;
	var filterStartDate = calendarStart.getSelectedDateString("MMddyyyyHHmm");
	var calendarEnd = $('mainForm:filterEndDate').component;
	var filterEndDate = calendarEnd.getSelectedDateString("MMddyyyyHHmm");
	var root = "" + window.location;

	if (root != null) {
		root = root.substring(0, root.indexOf("?") + 1);
	}
	var apply = jQuery(".applyFilters");
	var params = "cc=" + cc;
	if (id != null) {
		params = params + "&id=" + id;
	}
	if (page != null) {
		params = params + "&page=" + page;
	}
	if (token != null) {
		params = params + "&token=" + token;
	}

	jQuery("#filtersList .filterItem").each(
			function() {
				var type = jQuery(this).attr("type");
				var tagName = jQuery(this).attr("tagName");
				var checked = jQuery(this).attr("checked");
				var value = jQuery(this).val();
				if (type == "checkbox") {
					if (checked) {
						value = "true";
					} else {
						value = "false";
					}
				}
				if ((tagName == "SPAN") || (tagName == "span")) {
					value = jQuery(this).html();
				}
				var param = jQuery(this).parents("li").find(".param").val();
				if ((param != null) && (param != "undefined") && (param != "")
						&& (value != "") && (value != null)) {
					params = params + "&" + param + "=" + value;
					if (param == "f") {
						f = value;
					}
					if (param == "i") {
						i = value;
					}
					if (param == "m") {
						m = value;
					}
					if (param == "s") {
						s = value;
					}
				}

			});
	if ((filterStartDate != null) && (filterStartDate != "")) {
		params = params + "&b=" + filterStartDate;
		b = filterStartDate;
	}
	if ((filterEndDate != null) && (filterEndDate != "")) {
		params = params + "&e=" + filterEndDate;
		e = filterEndDate;
	}
	params = params + "&conversationPropagation=join";
	apply.attr("href", root + params);
	newLocation = root + params;
	if (apply.hasClass('buttonNormalDisabled')) {
		apply.removeClass("buttonNormalDisabled").addClass("buttonNormalForm");
	}
}
function updateFilter2(link,lb,le,lf,li,lm,ls)
{
	b=lb;
	e=le;
	f=lf;
	i=li;
	m=lm;
	s=ls;
	newLocation=link.attr("href");
	applyFiltersResults();
}
function updateColumns()
{
	jQuery("#updateColumnsLink").removeClass("hidden");
}

function applyFiltersDataCenter() {
	wait();
	Seam.Component.getInstance("dataCenterAction").updateFilters(b, e, f, i, m, applyFiltersCallback);
}
function applyFiltersResults() {
	wait();
	Seam.Component.getInstance("resultDisplay").updateFilters(b, e, f, i, m, s, applyFiltersCallback);
}

function applyFiltersCallback() {
	window.location = newLocation;
}
function adjustPageDisplay(page)
{
	if ((page=="exportData")||(page=="channelManager")){
		jQuery(".contentWrapper").css({"maxWidth":"none","padding":"10px"});
		jQuery(".frameToolbarDropdownWrapper").css({"maxWidth":"925px"});
	}
}
function updateSearch(el)
{
	var buttonOn=jQuery("[id$='searchButtonOn']");
	var buttonOff=jQuery("#searchButtonOff");
	//if (el.val()!="")
	//{
		buttonOff.addClass("hidden");
		buttonOn.removeClass("hidden");
	/*}
	else
	{
		buttonOn.addClass("hidden");
		buttonOff.removeClass("hidden");
	}*/
}
