/*
 *	developer: Воронков Виктор Александрович
 *	skype: kreexus
 *	e-meil: kreexus@gmail.com
 *	icq: 370992749
 */

jQuery.fn.calculator = function(options) {
	function initialize(object, subobject) {
		object
			.find(subobject)
			.eq(0)
			.addClass(options.clFirst)
			.addClass(options.clThis);
		return object;
	};

	function validate(value) {
		if(value > indexCount) {
			return indexCount;
		};
		if(value < 0) {
			return 0;
		};
		return value;
	};

	function changeIndex(value) {
		if(move == true) {
			move = false;
			for(var i = 0; i < value; i++) {
				jQuery(options.elNavigateLine)
					.eq(i)
					.addClass(options.clSuccess);
				jQuery(options.elCaption)
					.eq(i)
					.addClass(options.clSuccess);
			};
			for(var i = value; i <= indexCount; i++) {
				jQuery(options.elNavigateLine)
					.eq(i)
					.removeClass(options.clSuccess)
					.removeClass(options.clThis);
				jQuery(options.elCaption)
					.eq(i)
					.removeClass(options.clSuccess)
					.removeClass(options.clThis);
			};
			jQuery(options.elNavigateLine)
				.eq(value)
				.addClass(options.clThis);
			jQuery(options.elCaption)
				.eq(value)
				.addClass(options.clThis);
			jQuery(options.elNavigatePlace).animate({
				'left' : '-' + (value * parseInt(jQuery(options.elNavigateLinePlace).css('width'))) + 'px'
			}, time, 'swing', function() {
				move = true;
			});
			return true;
		} else {
			return false;
		};
	};

	function checkSelect(value) {
		var element = jQuery('select[name=step' + value + '] option:selected').val();
		if(element != 'default') {
			return true;
		} else {
			return false;
		};
	};

	function getSelectDataToJSON() {
		var object = jQuery(options.elNavigatePlace).find('select');
		var strJSON = '{';
		jQuery.each(object, function() {
			strJSON = strJSON + '"' + jQuery(this).attr('name') + '":"' + jQuery(this).find('option:selected').val() + '",';
		});
		strJSON = strJSON.slice(0, (strJSON.length - 1)) + '}';
		return strJSON;
	};

	function getFormToJSON(form) {
		var input = jQuery(form).find('input');
		var textarea = jQuery(form).find('textarea');
		var strJSON = '{';
		jQuery.each(input, function() {
			strJSON = strJSON + '"' + jQuery(this).attr('name') + '":"' + jQuery(this).attr('value') + '",';
		});
		strJSON = strJSON + '"' + jQuery(textarea).attr('name') + '":"' + jQuery(textarea).attr('value') + '", "json":' + getSelectDataToJSON() + '}';
		return strJSON;
	}

	function valideForm(form) {
		var inputValide = ['firstName', 'e-mail', 'phone'];
		var input = jQuery(form).find('input');
		var patternMail = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		var patternPhone = new RegExp(/^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/i);
//	+79261234567
//	89261234567
//	79261234567
//	+7 926 123 45 67
//	8(926)123-45-67
//	123-45-67
//	9261234567
//	79261234567
//	(495)1234567
//	(495) 123 45 67
//	89261234567
//	8-926-123-45-67
//	8 927 1234 234
//	8 927 12 12 888
//	8 927 12 555 12
//	8 927 123 8 123
		var valideStat = true;
		for(var i = 0; i < inputValide.length; i++) {
			jQuery(form).find('input[name=' + inputValide[i] + ']');
			if(jQuery(form).find('input[name=' + inputValide[i] + ']').attr('value') == '') {
				valideStat = false;
			} else {
				if(inputValide[i] == 'e-mail') {
					if(!patternMail.test(jQuery(form).find('input[name=' + inputValide[i] + ']').attr('value'))) {
						valideStat = false;
					};
				};
				if(inputValide[i] == 'phone') {
					if(!patternPhone.test(jQuery(form).find('input[name=' + inputValide[i] + ']').attr('value'))) {
						valideStat = false;
					};
				};
			};
		};
		if(valideStat) {
			return true;
		} else {
			return false;
		};
	};

	function indexState(value) {
		switch (value) {
			case 4:
				jQuery(options.mvNext).attr({
					'value' : 'Далее'
				});
				jQuery('div#calcWrapper #navigateLinePlace #navigatePlace .step#step4 #print').fadeIn(time);
				jQuery('div#calcWrapper #navigateLinePlace #navigatePlace .step#step5 #descript').fadeOut(time);
				jQuery('div#calcWrapper #navigateLinePlace #navigatePlace .step#step4 a#print').attr({
					'href' : options.fScriptPath + '?set=print&data=' + getSelectDataToJSON()
				});
				goAjax(options.fScriptPath, 'setJSON', getSelectDataToJSON(), options.elResponceContent);
				jQuery(options.elResponceContent).fadeIn(time);
				jQuery(options.elSendFormPlace).fadeOut(time);
				return true;
				break;
			case 5:
				jQuery(options.mvNext).attr({
					'value' : 'Отправить'
				});
				jQuery('div#calcWrapper #navigateLinePlace #navigatePlace .step#step5 #descript').fadeIn(time);
				jQuery(options.elResponceContent).fadeOut(time);
				jQuery(options.elSendFormPlace).fadeIn(time);
				return true;
				break;
			default:
				jQuery(options.mvNext).attr({
					'value' : 'Далее'
				});
				jQuery('div#calcWrapper #navigateLinePlace #navigatePlace .step#step4 #print').fadeOut(time);
				jQuery('div#calcWrapper #navigateLinePlace #navigatePlace .step#step5 #descript').fadeOut(time);
				jQuery(options.elResponceContent).fadeOut(time);
				jQuery(options.elSendFormPlace).fadeOut(time);
				return false;
				break;
		};
	};

	function isonToArray(object) {
		var item = new Array();
		jQuery.each(object, function(key, value) {
			if(typeof(value) == 'object') {
				item[key] = isonToArray(value);
			} else {
				item[key] = value;
			};
		});
		return item;
	};

	function goAjax(urlPath, set, data, object) {
		jQuery.ajax({
			type: 'POST',
			url: urlPath,
			data: 'set=' + set + '&data=' + data,
			success: function(result) {
				jQuery(object).html(result);
			}
		});
	};

	function sendMail(sendSet) {
		var str;
		switch(sendSet) {
			case 'ok':
				str = '<div id="status" class="ok"></div>Ваше сообщение успешно отправлено.<br />Вы можете вновь воспользоваться нашим калькулятором.';
				break;
			case 'no':
				str = '<div id="status" class="no"></div>К сожалению сообщение не удалось отправить.<br /> Вероятнее всего, Вы не заполнили поля, отмеченные звёздочкой (<strong>*</strong>) как обязательные.';
				break;
			default:
				break;
		};
		return str;
	};

	var options = jQuery.extend({
		elNavigate : '#navigate',
		elNavigateLine : '.navigateLine',
		elNavigateLinePlace : '#navigateLinePlace',
		elNavigatePlace : '#navigatePlace',
		elSteps : '#steps',
		elCaption : '.caption',
		elResponceContent : '#responceContent',
		elResponceMail : '#responceMail',
		elResponceMailContent : '#responceMailContent',
		elSendFormPlace : '#sendFormPlace',
		elSendForm : '#sendForm',
		clStep : 'step',
		clFirst : 'first',
		clLast : 'last',
		clSuccess : 'success',
		clThis : 'this',
		mvNext : '#next',
		mvPrev : '#prev',
		fParamPath : '/calculator/data/param.json',
		fScriptPath : '/calculator/calc.php',
		redirect : '/'
	}, options);

	var index = 0;
	var indexCount = (jQuery(this).find(options.elNavigateLine).length) - 1;
	var time = 500;
	var move = true;
	var redirect = false;

	initialize(jQuery(this), options.elNavigateLine);
	initialize(jQuery(options.elSteps), options.elCaption);

	jQuery(options.elCaption)
		.eq(indexCount)
		.addClass(options.clLast);

	jQuery(options.mvNext).click(function() {
		if(move == true) {
			var set = checkSelect(index);
			if(set) {
				index = validate(index + 1);
				changeIndex(index);
				if(jQuery(options.mvNext).attr('value') == 'Отправить') {
					if(valideForm(options.elSendForm)) {
						goAjax(options.fScriptPath, 'sendMail', getFormToJSON(options.elSendForm));
						$(options.elResponceMail).fadeIn(time).find(options.elResponceMailContent).html(sendMail('ok'));
						redirect = true;
					} else {
						$(options.elResponceMail).fadeIn(time).find(options.elResponceMailContent).html(sendMail('no'));
					};
					
				};
				indexState(index);
			};
		};
	});

	jQuery(options.mvPrev).click(function() {
		if(move == true) {
			index = validate(index - 1);
			changeIndex(index);
			indexState(index);
		};
	});

	jQuery.getJSON(options.fParamPath, {}, function(json) {
		var tagGroup = '';
		jQuery.each(json, function(key, value) {
			if(typeof(value) == 'object') {
				tagGroup = tagGroup + '\n\t\t\t\t\t<div class="' + options.clStep + '" id="' + key + '">\n\t\t\t\t\t\t<select name="' + key + '">';
				jQuery.each(value, function(key, value) {
					tagGroup = tagGroup + '\n\t\t\t\t\t<option value="' + value.name + '">' + value.value + '</option>';
				});
				tagGroup = tagGroup + '\n\t\t\t\t\t\t<select>\n\t\t\t\t\t</div>';
			};
		});
		jQuery(options.elNavigatePlace).prepend(tagGroup);
	})
	.error(function() {})
	.complete(function() {});

	jQuery(options.elNavigatePlace).css({
		'width' : ((indexCount + 1) * parseInt(jQuery(options.elNavigateLinePlace).css('width'))) + 'px'
	});

	jQuery(options.elResponceMail).click(function() {
		jQuery(this).fadeOut(time);
		jQuery(this).animate({
			'z-index' : '5'
		}, 0, 'swing', function() {
			if(redirect) {
				window.location = options.redirect;
			};
		});
	});
};
