/* rxObject - RASAMAX Object Library
SIA RASAMAX - 2009

Requirements:
rxLib
jQuery - http://jquery.com
jQuery UI - http://jqueryui.com
jQuery.form - http://malsup.com/jquery/form/
jQuery.Livequery

*/

if (!rx) var rx = {};

rx.dataPathToModule = rx.settings.basePath+'modules/rxData/';

rx = $.extend(rx, {

	formLivequery : function (formId) {
		if(!formId){
			return false;
		}

		var thisForm = $(formId);

		if(!thisForm.length){
			return false;
		}

		$(thisForm).ajaxForm({
			dataType : 'json',
			beforeSerialize : function ($form, options) {
				// Trigger column type change to enable/disable different form elements
				$form.find('select[name=Type]').change();
				return true;
			},
			beforeSubmit: function (formData, $form, options) {
				// Validate form if validator is enabled
				if ($form.validate) {
					if ($form.valid()) {
						if(!rx.processRecaptcha(thisForm)){
							return false;
						}
						$form.find('button[type=submit]').attr('disabled', true).addClass('ui-state-disabled');
						return true;
					}
					else{
						return false;
					}
				}
				else {
					$form.find('button[type=submit]').attr('disabled', true).addClass('ui-state-disabled');
					return true;
				}
			},
			success: function(response,a,b,c,d,e) {
				if (response.error){
					// Reload captcha question if there are any errors (do it only in current form)
					if($(thisForm).find('.rx-recaptcha').length){
						Recaptcha.reload();
					}
					rx.alert(response.error);
					// Make submit button back workable
					$(thisForm).find('button[type=submit]').attr('disabled', false).removeClass('ui-state-disabled');
					return false;
				}
				else if (response.responseText) {
					// Destroy captcha in this form
					if($(thisForm).find('.rx-recaptcha').length){
						Recaptcha.destroy();
						$(thisForm).find('.rx-recaptcha').html('');
					}

					// If product found then submit product add to basket with new data record id, stop form reset and collapse
					var article = $(thisForm).closest('.rx-article');
					if (article.find('.rx-product').length) {
						var articleId = article.attr('articleId');
						var product_id = article.find('.rx-product').attr('prodId');
						rx.shopBuyProduct({product_id:product_id,units:$('#product_'+articleId+'_units').val(),articleId:articleId,dataId:response.dataId,dataIndex:response.dataIndex});
					} else {
						// If no product found then collapse and reset the form and show response message
						$.jGrowl(response.responseText);

						if ($(thisForm).is('.rx-data-postForm'))
							$(thisForm).find('.rx-data-form-response>span').text(response.responseText).parent().slideDown().end().end()
								.find('>div:first').slideUp(function(){
									// Hide article heading and text
									$(thisForm).parents('.rx-article:first').find('h1.article_heading').slideUp().end().find('div.article_text:first').slideUp();
								}).end();

						// If form reset was requested
						if (response.resetForm && !response.error) {
							$(thisForm).resetForm();
						}
					}
				}

				// If quiz answers are received
				if (response.answers) {
					//alert(response.answers);
					var correctAnswerCount = 0, answerCount = 0;
					$('button',$(thisForm).find('.rx-data-question').parent()).hide();
					$.each(response.answers, function(index, value) {

						var correct = false;
						// Check radio question
						if ($('#rxDataQuestion_'+index+' *[name="'+index+'"]',thisForm).is(':radio')) {
							$('#rxDataQuestion_'+index+' label[for='+$('#rxDataQuestion_'+index+' *[name="'+index+'"][value="'+value+'"]').attr('id')+']',thisForm).addClass('rx-correct-highlight');
							// Counting correct answers
							if ($('#rxDataQuestion_'+index+' input[name="'+index+'"]:checked',thisForm).val()==value)
								correct = true;
						}

						// Check checkbox question
						if ($('#rxDataQuestion_'+index+' *[name="'+index+'[]"]',thisForm).is(':checkbox')) {
							var valuesList = value.split(',');
							var oneValueNotFound = 0;
							$.each(valuesList, function(indexList, valueList) {
								$('#rxDataQuestion_'+index+' label[for="'+$('#rxDataQuestion_'+index+' *[name="'+index+'[]"][value="'+valueList+'"]',thisForm).attr('id')+'"]',thisForm).addClass('rx-correct-highlight');
								// Check if ALL correct answers are checked
								if (!oneValueNotFound && !$('#rxDataQuestion_'+index+' input[name="'+index+'[]"][value="'+valueList+'"]:checked',thisForm).size())
									oneValueNotFound = 1;
							});
							// Counting correct answers
							if (!oneValueNotFound)
								correct = true;
						}

						// Check text question
						if ($('#rxDataQuestion_'+index+' *[name="'+index+'"]',thisForm).is(':text')) {
							if ($('#rxDataQuestion_'+index+' input[name="'+index+'"]:first',thisForm).val()==value) {
								correct = true;
							} else {
								$('#rxDataQuestion_'+index+' *[name="'+index+'"]',thisForm).after($('<span></span>').html(value).addClass('rx-correct-highlight')).after('<br>');
							}
						}

						// Check image question
						if ($('#rxDataQuestion_'+index+' .quizImageAnswer',thisForm).size()>0) {
							// coordinates of the correct answers
							var correctCoords  = eval(value);
							// coordinates of where user clicked on the image
							var clickCoords  = eval($('#rxDataQuestion_'+index+' input[name="'+index+'"]:first',thisForm).val());
							var correct = false;
							$.each( correctCoords, function(i, val){
								var height = val.y2-val.y;
								var width = val.x2-val.x;
								var left = val.x;
								var top = val.y;
								// Check if user clicked in the area of an answer
  								if(clickCoords[0].x>=val.x && clickCoords[0].x<=val.x2 && clickCoords[0].y>=val.y && clickCoords[0].y<=val.y2){
									correct = true;
   								}
   								// Display correct click range on the image
   								$('#rxDataQuestion_'+index,thisForm).find('.quizClickPointer').after('<div class="quizCorrectClickRange"></div>').end().find('.quizCorrectClickRange:first').css({'left': left, 'top': top, 'width': width+'px', 'height': height+'px'});
 							});
 							// Disable clicks on the image and pointer - it's done just for beter UI, user still can't break anything if he clicks on the pointer or on the image
 							$('#rxDataQuestion_'+index,thisForm).find('.quizClickPointer').click(function(){return false;}).end().find('.quizImageAnswer').click(function(){return false;});
							if(correct){
								$('#rxDataQuestion_'+index,thisForm).find('.quizClickPointer').addClass('rx-correct');
							}
							else{
								$('#rxDataQuestion_'+index,thisForm).find('.quizClickPointer').addClass('rx-wrong');
							}
						}

						if(correct){
							correctAnswerCount++;
							$('#rxDataQuestion_'+index,thisForm).addClass('rx-correct');
						}
						else{
							$('#rxDataQuestion_'+index,thisForm).addClass('rx-wrong');
						}

						/*
							Multiple user answers (like set() - give all correct answers)
						*/

						// Total answers count
						answerCount++;
					});

					// Lock all fields
					$('input,textarea,select',thisForm).attr('disabled',1);

					// Show all answers on screen
					$('.rx-data-question',thisForm).slideDown();

					// Quiz results
					$(thisForm).prepend('<div class="article_text" style="padding-bottom:15px;">'+rx.translate('result')+': '+correctAnswerCount+'/'+answerCount+'('+(Math.round(correctAnswerCount / answerCount * 10000)/100)+'%)</div>');
				}

				// Change column name if functional type was changed (imagename, columnImage)
				if (response.newColumnName) {
					$('input[name=column][value='+response.oldColumnName+']').val(response.newColumnName).parents('.rx-data-settings').attr('column',response.newColumnName);
				}

				// Make submit button back workable
				$(thisForm).find('button[type=submit]').attr('disabled', false).removeClass('ui-state-disabled');
			}
		});

		return false;
	}

});



// Live queries
// onchange of <select> (field type selector)
$(function() {
	$('body')
	.on('click','.rx-data-crossTable a',function(){
		$(this).parents('.rx-data').find('.rx-data-loader')
			.load(rx.dataPathToModule + 'controller.php' + this.search + '&action=get').end()
			.find('.rx-data-crossTable').prev().find('div.ptogtitle').click();
		return false;
	})
	.on('click','.rx-data-question button:even',function(){
		// OK & NEXT button in the quiz
		// Do nothing if user haven't specified an answer
		if ($('*',$(this).parents('.rx-data-question:first')).fieldValue()!='') $(this).parents('.rx-data-question:first').slideUp().next().slideDown();
	})
	.on('click','.rx-data-question button:odd',function(){
		// SKIP button in the quiz
		var button = $(this);
		var question = button.parents('.rx-data-question:first');
		if (!question.next().is(':last-child')){
			question.slideUp(500,function(){
				button.parents('form:first').find('.rx-data-question:last').after(question).end();
			}).next().slideDown();
		}
	})
	.on('click','.quizImageAnswer',function(e){
		var image = $(this);
		var posX = image.offset().left;
		var posY = image.offset().top;
		$(image).next().attr('value','[{"x":'+(e.pageX - posX)+',"y":'+(e.pageY - posY)+'}]');
		var pointer = $(image).parent().find('.quizClickPointer');
		// show circle on the image where user clicked
		if($(pointer).size()>0){
			$(pointer).css({'left': e.pageX-posX-$(pointer).width()/2, 'top': e.pageY-posY-$(pointer).height()/2});
		}
		else{
			$(image).next().after('<div class="quizClickPointer"></div>');
			pointer = $(image).parent().find('.quizClickPointer');
			$(pointer).css({'left': e.pageX-posX-$(pointer).width()/2, 'top': e.pageY-posY-$(pointer).height()/2}).show();
		}
	})
	// remove circle which shows where user clicked if user click on it again
	.on('click','.quizClickPointer',function(){
		$(this).parent().find('input:hidden').val('').end().find('.quizClickPointer').remove();
	});
});; 

