﻿/*
	CONSTANTS
*/

var choise = "- выберите формат -";
var help = "Выберите из предлагаемого списка формат сайта. В блоках «Дизайн» и «Функционал» будут отмечены соответствующие формату элементы."

var note = '* Данный расчет предварителен и не является публичной офертой.'

// price list
var category = new Array('design', 'functional');
var coefficient = 1.6;
var priceList = {
	'design': [
		{
			'title': 'Создание логотипа',
			'shortname': 'Логотип',
			'price': [
				{'count': 1, 'cost': 4000 * coefficient},
				{'count': 2, 'cost': 7000 * coefficient},
				{'count': 3, 'cost': 9500 * coefficient},
				{'count': 4, 'cost': 11000 * coefficient}
			]
		},
		{
			'title': 'Создание гаммы фирменных цветов',
			'shortname': 'Фирменные цвета', 
			'price': [
				{'count': 1, 'cost': 2000 * coefficient},
				{'count': 2, 'cost': 3500 * coefficient},
				{'count': 3, 'cost': 4700 * coefficient},
				{'count': 4, 'cost': 5700 * coefficient}
			]
		},
		{
			'title': 'Создание эксклюзивных иллюстраций',
			'shortname': 'Иллюстрации',
			'price': [
				{'count': 1, 'cost': 4000 * coefficient}
			]
		},
		{
			'title': 'Создание уникальных графических элементов (иконки, кнопки)',
			'shortname': 'Иконки, кнопки',
			'price': [
				{'count': 1, 'cost': 300 * coefficient}
			]
		},
		{
			'title': 'Создание структуры страницы',
			'shortname': 'Структура страницы',
			'price': [
				{'count': 1, 'cost': 1000 * coefficient}
			]
		}
	],
	'functional': [
		{
			'title': 'Форум',
			'shortname': 'Форум',
			'description': 'Традиционный сервис для общения пользователей сайта с тематическими обсуждениями и возможностью отправки личных сообщений',
			'price': [{'count': 1, 'cost': 3000 * coefficient},]
		},
		{
			'title': 'Каталог',
			'shortname': 'Каталог',
			'description': 'Разбитый на категории перечень товаров и услуг с описаниями, фотографиями, ценами и пр.',
			'price': [{'count': 1, 'cost': 10000 * coefficient},]
		},
		{
			'title': 'Почтовая рассылка',
			'shortname': 'Почтовая рассылка',
			'description': 'Сервис рассылки новостей сайта по электронной почте',
			'price': [{'count': 1, 'cost': 2000 * coefficient},]
		},
		{
			'title': 'Формирование и ведение заказа',
			'shortname': 'Заказ товара',
			'description': 'Функции выбора пользователем товара, способа оплаты и доставки; включает возможности расчёта, отображения информации о статусе заказа (принят, оплачен, отменён, выполнен и т.п.), хранения истории заказов',
			'price': [{'count': 1, 'cost': 3500 * coefficient},]
		},
		{
			'title': 'Поиск по сайту',
			'shortname': 'Поиск',
			'description': 'Быстрый поиск информации на сайте',
			'price': [{'count': 1, 'cost': 2000 * coefficient},]
		},
		{
			'title': 'Импорт каталогов',
			'shortname': 'Импорт каталогов',
			'description': 'Импорт данных из  из электронных таблиц формата XLS или аналогичных форматов',
			'price': [{'count': 1, 'cost': 1500 * coefficient},]
		},
		{
			'title': 'Блог',
			'shortname': 'Блог',
			'description': 'Сетевой журнал с комментируемыми записями, с возможностью добавлять в записи изображения, аудио- и видеофайлы',
			'price': [{'count': 1, 'cost': 3000 * coefficient},]
		},
		{
			'title': 'Интеграция платёжных систем',
			'shortname': 'Платежные системы',
			'description': 'Настройка систем оплаты товаров и услуг через интернет (Яндекс.Деньги, WebMoney, RUpay и др.)',
			'price': [{'count': 1, 'cost': 12000 * coefficient},]
		},
		{
			'title': 'Новостная лента',
			'shortname': 'Новостная лента',
			'description': 'Сервис для размещения на сайте обновляемой информации (новости компании, пресс-релизы и пр.)',
			'price': [{'count': 1, 'cost': 2500 * coefficient},]
		},
		{
			'title': 'Комментарии пользователей',
			'shortname': 'Комментарии',
			'description': 'Возможность для пользователей оставлять комментарии на сайте (к записям в блоге, картинкам в галерее и т.п.)',
			'price': [{'count': 1, 'cost': 2000 * coefficient},]
		},
		{
			'title': 'Обратная связь',
			'shortname': 'Обратная связь',
			'description': 'Возможность для посетителей задать вопрос администрации сайта и получить ответ на электронную почту или на сайте',
			'price': [{'count': 1, 'cost': 1500 * coefficient},]
		},
		{
			'title': 'Счетчик посетителей',
			'shortname': 'Счетчик посетителей',
			'description': 'Индикатор посещаемости сайта',
			'price': [{'count': 1, 'cost': 500 * coefficient},]
		},
		{
			'title': 'Голосование',
			'shortname': 'Голосование',
			'description': 'Сервис для опроса посетителей сайта',
			'price': [{'count': 1, 'cost': 1500 * coefficient},]
		},
		{
			'title': 'Базовая поисковая оптимизация',
			'shortname': 'Поисковая оптимизация',
			'description': 'Мета-теги каждой страницы сайта (описание и ключевые слова)',
			'price': [{'count': 1, 'cost': 1500 * coefficient},]
		},
		{
			'title': 'Фотогалерея',
			'shortname': 'Фотогалерея',
			'description': 'Возможность размещения на сайте фотографий и других изображений',
			'price': [{'count': 1, 'cost': 4000 * coefficient},]
		}
	]
};

var compare = new Array('Сайт-визитка', 'Промо-сайт', 'Интернет-магазин');
var templates = {
	'Сайт-визитка' : {
		'design' : [
			{'title': 'Создание логотипа', 'count': 1}, 
			{'title': 'Создание гаммы фирменных цветов', 'count': 1}, 
			{'title': 'Создание структуры страницы', 'count': 1}
		], 
		'functional' : [],
		'information' : 'Информационный сайт, содержащий основные сведения о компании, о её деятельности, товарах и услугах, контактные данные.',
		'layout' : 30,
		'testing' : 30
	},
	'Промо-сайт' : {
		'design' : [
			{'title': 'Создание эксклюзивных иллюстраций', 'count': 4},
			{'title': 'Создание уникальных графических элементов (иконки, кнопки)', 'count': 5}, 
			{'title': 'Создание структуры страницы', 'count': 2}
		], 
		'functional' : [],
		'information' : 'Сайт, нацеленный на привлечение внимания к товару, товарной марке или событию; часто используется в рамках проведения оффлайновой рекламной кампании. Как правило, имеет яркий, с особой тщательностью проработанный, запоминающийся дизайн.',
		'layout' : 30,
		'testing' : 30
	},
	'Интернет-магазин' : {
		'design' : [
			{'title': 'Создание логотипа', 'count': 1},
			{'title': 'Создание гаммы фирменных цветов', 'count': 1},
			{'title': 'Создание уникальных графических элементов (иконки, кнопки)', 'count': 10}, 
			{'title': 'Создание структуры страницы', 'count': 5}
		],
		'functional' : [
			{'title': 'Каталог'},
			{'title': 'Поиск по сайту'},
			{'title': 'Формирование и ведение заказа'}
		],
		'information' : 'Сайт, предоставляющий посетителю возможность зарезервировать для покупки товары из каталога. Часто оснащён рядом вспомогательных сервисов, направленных на оптимизацию продаж (онлайн-оплата, учёт продукции на складе).',
		'layout' : 30,
		'testing' : 40
	},
	'- выберите формат -' : {
		'layout' : 30,
		'testing' : 30
	}	
};

/*
	FUNCTIONAL
*/

// illustration
window.step = 0
addPercentPrice(4000 * coefficient, 4000 * coefficient, 5, 4, 'design', 2);

// page map
window.step = 0
addPercentPrice(1000 * coefficient, 1000 * coefficient, 5, 9, 'design', 4);

// icon/button
addSimplePrice(300 * coefficient, 19, 'design', 3);

/*
	This function push new element in price with two parameters
	count and cost. You can chose, how much elements add.
	Next price is cheaper on X percent.
	
	sum: starting sum
	percet: how much percents
	stepCount: how much element what to add
	category: design or functional
	number: number of element in category
*/
function addPercentPrice(sum, finalResult, percent, stepCount, category, number) {
	var x = 0;
	window.step++;
	while (window.step <= stepCount) {
		result = (sum * percent)/100;
		result = sum - Math.round(result);
		
		finalResult += result;
		
		priceList[category][number].price.push({'count': window.step + 1, 'cost': finalResult})
		
		addPercentPrice(result, finalResult, percent, stepCount, category, number);
	};
};

/*
	This function add new element in price with two parameters
	count and cost. The next price in two is more previous.
	
	sum: starting sum
	count: how much element what to add
	category: design or functional
	number: number of element in category
*/
function addSimplePrice(sum, count, category, number) {
	for (var i = 1; i <= count; i++) {
		priceList[category][number].price.push({'count': i + 1, 'cost': (i + 1) * 300 * coefficient})
	};
};

/*
	Init price list
*/
function initPriceElements() {
	$('#siteFormatInfo').html('<p>' + help + '</p>');
	
	drawDesignElements();
	drawFunctionalElements();
	
	$('#checkOrderdesign').html('<dd>список пуст</dd>');
	$('#checkOrderfunctional').html('<dd>список пуст</dd>');
	$('#checkOrderlayout').html('<dd>список пуст</dd>');
	$('#checkOrdertesting').html('<dd>список пуст</dd>');
};

/*
	Create design elements in price list
*/
function drawDesignElements() {
	var category = 'design'
	var html = '';

	html += '<table border="0">';
	
	// column title
	html += '<tr>';
		html += '<td><div class="design-div"><b>Наименование<b></div></td>';
		html += '<td align="center"><div class="design-div"><b>Количество вариантов<b></div></td>';
	html += '</tr>';
	
	// make design elements
	for (var j = 0; j < priceList[category].length; j++) {
		html += '<tr>';
		
		// checkbox
		html += '<td width="60%">';
			html += '<div class="design-div">';
			html += '<label for="' + category + '-' + j + '" id="label_' + category + '-' + j + '">';
			html += '<input type="checkbox" id="' + category + '-' + j + '" name="' + category + '-' + j +
					'" onclick="disabledSelectBox(\'' + category + '\',' + j + '); onPriceElementClick(false);"/> ' + priceList[category][j].title;			
			html += '</label>';
			html += '</div>';
		html += '</td>';
		
		html += '<td align="center">';
		// selectbox
		html += '<div class="slider-div" id="slider_div' + j + '">';
		html += '<select id="select-' + category + '-' + j + '" onchange="onPriceElementClick(false)" style="display: none;">';
		for (var l = 0; l < priceList[category][j].price.length; l++)
			html += '<option>' + priceList[category][j].price[l].count + '</option>';
		html += '</select>';
		html += '</div>';
		html += '</td>';
		html += '</tr>';
		
	};
	html += '</table>';
	
	$('#' + category + 'Span').html(html);
	html = '';
	// slider
	for (var j = 0; j < priceList[category].length; j++) {
		$('select#select-' + category + '-' + j).selectToUISlider({tooltip: false});
		sliderOff(category + '-' + j, false);
		sliderBindClick(category + '-' + j);
	};
};

/*
	Create funcitonal elements in price list
*/
function drawFunctionalElements() {
	var category = 'functional';
	var html = '';
	
	// checkbox
	for (var j = 0; j < priceList[category].length; j++) {
		html += '<div class="design-div">';
		html += '<label class="design" for="' + category + '-' + j + '" id="label_' + category + '-' + j + '" title="' + priceList[category][j].description + '">';
		html += '<input type="checkbox" id="' + category + '-' + j + '" name="' + category + '-' + j + '" onclick="onPriceElementClick(false);"/> ' + priceList[category][j].title;			
		html += '</label>';
		html += '</div>';
		
		$('#' + category + 'Span').html(html);
	};
};

/*
	Calculate total sum, testing sum, layout sum
*/
function onPriceElementClick(needCompareTemplate) {
	var totalSum = 0;
	var percent;
	
	designSum = getSum('design');
	functionalSum = getSum('functional');
	totalSum = designSum + functionalSum;
	
	if (totalSum != 0) {
		percent = templates[$('#siteFormat').val()].layout;
		layoutSum = (designSum * percent)/100
		if (layoutSum != 0) {
			layout = '<dd>стоимость верстки составляет ' + percent + '% от стоимости разработки дизайна</dd>';
			layout += '<dd> Верстка дизайна <span> = ' + Math.round(layoutSum) + '</span></dd>';
			$('#checkOrderlayout').html(layout);
		} else
			$('#checkOrderlayout').html('<dd>список пуст</dd>');
		
		percent = templates[$('#siteFormat').val()].testing;
		testingSum = ((layoutSum * 20) + (functionalSum * percent))/100;
		if (testingSum != 0) {
			testing = '<dd>стоимость тестирования составляет ' + percent + '% от стоимости разработки функционала и 20% от стоимости верстки</dd>';
			testing += '<dd> Тестирование <span> = ' + Math.round(testingSum) + '</span></dd>';
			$('#checkOrdertesting').html(testing);
		} else
			$('#checkOrdertesting').html('<dd>список пуст</dd>');
			
		totalSum += layoutSum + testingSum;
		$('#sumSpan').html(Math.round(totalSum) + '*');
		$('.note').html(note);
	} else {
		$('#checkOrderlayout').html('<dd>список пуст</dd>');
		$('#checkOrdertesting').html('<dd>список пуст</dd>');
		
		$('#sumSpan').html('0');
		$('.note').html('');
	};
	
	if (needCompareTemplate)
		compareTemplates();
};

/*
	Add price element in check, calculate design sum and functional sum
*/
function getSum(category) {
	var html = '';
	var sum = 0;
	var shortName;
	var cost;
	var selectIndex;

	for (var j = 0; j < priceList[category].length; j++) {
		if ($('#' + category + '-' + j).attr('checked')) {
			shortName = priceList[category][j].shortname;
			if (category == 'design') {
				selectIndex = $('#select-' + category + '-' + j).attr('selectedIndex');
				cost = priceList[category][j].price[selectIndex].cost;
				count = priceList[category][j].price[selectIndex].count;
				html += '<dd>' + shortName + ' <span>x' + count + ' = ' + cost + '</span></dd>';
			} else if (category == 'functional') {
				cost = priceList[category][j].price[0].cost;
				count = priceList[category][j].price[0].count;
				html += '<dd>' + shortName + ' <span> = ' + cost + '</span></dd>';
			};
			sum += cost;
		};
	};

	if (html == '')
		$('#checkOrder' + category).html('<dd>список пуст</dd>');
	else
		$('#checkOrder' + category).html(html);
	
	return sum;
};

/*
	Display information about template
*/
function onChangeSiteFormat() {
	var templateName = $('#siteFormat').val();
	
	if (templateName == choise) {
		clearAll();
	} else
		$('#siteFormatInfo').html('<p>' + templates[templateName].information + '</p>');
		
	$('#designBlock').show();
	$('#functionalBlock').show();
	
	substituteData();
};

/*
	Substitute data about template in price
*/
function substituteData() {
	checkboxOff();
	
	var find = false;
	var templateName = $('#siteFormat').val();

	if (templateName != choise) {
		// go by all category (design, functional)
		for (var i = 0; i < category.length; i++) {
			// go by all price list elements
			for (var j = 0; j < priceList[category[i]].length; j++) {
				// go by all site templates elements
				for (var l = 0; l < templates[templateName][category[i]].length; l++) {
					// if title are agree
					if (templates[templateName][category[i]][l].title == priceList[category[i]][j].title) {
						$('#' + category[i] + '-' + j).attr('checked', 'checked');
						if (category[i] == 'design') {
							// remove attribute 'disabled'
							disabledSelectBox(category[i], j);
							// set count of variants
							/*console.log('------------------');
							console.log(templates[templateName][category[i]][l].count);
							console.log(templateName);
							*/
							$('#select-' + category[i] + '-' + j).val(templates[templateName][category[i]][l].count);
							// call change
							$('#select-' + category[i] + '-' + j).change();
							sliderOff(category[i] + '-' + j, true);
							find = true;
						}
					}
				};
				// if not agree, disabled selectbox
				if (!find && category[i] == 'design') {
					// add attribute 'disabled'
					disabledSelectBox(category[i], j);
					sliderOff(category[i] + '-' + j, false);
				}
				find = false;
			};
		};
	};
	onPriceElementClick(false);
};

/*
	Pick all imformation about order and send 
*/
function pickInformationAboutOrder() {
	var i
	var labelListDesign = new Array();
	var selectListDesign = new Array();
	var labelListFunctional = new Array();

	var siteFormat = $('#siteFormat').val();
	if (siteFormat == '- выберите формат -')
		siteFormat = 'неопределен';
	
	var message = '';
	message += 'Формат сайта: ' + siteFormat + '\n';
	
	$('#designSpan input:checkbox:checked').each(function() {
		labelListDesign.push($('#label_' + $(this).attr('id')).text());
		selectListDesign.push($('#select-' + $(this).attr('id')).val());
	});
	if (labelListDesign.length != 0) {
		message += 'Дизайн: \n';
		for (i = 0; i < labelListDesign.length; i++) {
			message +=' - ' + labelListDesign[i] + '(количество вариантов: ' + selectListDesign[i] + ') \n';
		};
	};

	$('#functionalSpan input:checkbox:checked').each(function() {
		labelListFunctional.push($('#label_' + $(this).attr('id')).text());
	});
	if (labelListFunctional.length != 0) {
		message += 'Функционал: \n';
		for (i = 0; i < labelListFunctional.length; i++) {
			message +=' - ' + labelListFunctional[i] + '\n';
		};
	};
			
	$('#orderInfo').val(message);
	$('#column form').submit();
};

/*
	If checkbox checked, remove attribute 'disabled'
*/
function disabledSelectBox(name, index) {
	if (!$('#' + name + '-' + index).attr('checked')) {
		$('#select-' + $('#' + name + '-' + index).attr('id')).val(1);
		$('#select-' + $('#' + name + '-' + index).attr('id')).change();
		$('#div-slider-select-' + $('#' + name + '-' + index).attr('id')).slider('disable');
	} else {
		$('#div-slider-select-' + $('#' + name + '-' + index).attr('id')).slider('enable');
	};
};

/*
	Off slider
*/
function sliderOff(id, flag) {
	if (flag)
		$('#div-slider-select-' + id).slider('enable');
	else {
		$('#div-slider-select-' + id).slider('disable');
	};
};

/*
	On slider click
*/
function sliderBindClick(id) {
	$('#div-slider-select-' + id).bind('click', function() {
		if (!$('#' + id).attr('checked')) {
			$('#div-slider-select-' + id).slider('enable');
			$('#' + id).attr('checked', 'checked');
			onPriceElementClick(false);
		};
	});
};

/*
	Set all checkbox in false
*/
function checkboxOff() {
	var allCheckbox = $('.design-div input:checkbox');
	allCheckbox.removeAttr('checked');
};

/*
	Button clear
*/
function clearAll() {
	checkboxOff();
	var designCkeckbox = $('#designSpan input:checkbox');
	for (var i = 0; i < designCkeckbox.length; i++) {
		$('#select-design-' + i).val(1);
		$('#select-design-' + i).change();
		$('#div-slider-select-design-' + i).slider('disable');
	};
	$('#siteFormat').val(choise);
	$('#siteFormatInfo').html('<p>' + help + '</p>');
	onPriceElementClick(false);

};

// --------------- old functional

/* 
	Set all checkbox in disabled
*/
/*
function disabledCheckbox(flag) {
	var allCheckbox = $('.design-div input:checkbox');
	if (flag)
		allCheckbox.attr('disabled', 'disabled');
	else
		allCheckbox.removeAttr('disabled');
};
*/
/*
	Sel all selectbox in disabled
*/
/*
function disabledSelectbox(flag) {
	var allSelectbox = $('.design-div select');
	if (flag)
		allSelectbox.attr('disabled', 'disabled');
	else
		allSelectbox.removeAttr('disabled');
};
*/
/*
	Define templates & compare templates allow the user 
	to return to the chosen format of a site.
	
	Define template: compare the template 
	with the list of checked checboxs.
	
	Compare template: get all checked checkbox, 
	define template and set information about template.
*/
/*
// Define template
function defineTemplate(templateName, design, functional) {
	var find = false;
	// check, that lengths of the array are agree
	if (templates[templateName].design.length == design.length && templates[templateName].functional.length == functional.length) {
		// if agree by design elements return true
		for (var i = 0; i < design.length; i++) {
			for (var j = 0; j < templates[templateName].design.length; j++) {
				if (design[i] == templates[templateName].design[j]) {
					find = true;
					break;
				}
			};
			
			if (!find) {
				return false;
			};
			find = false;
		};
		
		// if agree by functional elements return true
		for (var i = 0; i < functional.length; i++) {
			for (var j = 0; j < templates[templateName].functional.length; j++) {
				if (functional[i] == templates[templateName].functional[j]) {
					find = true;
					break;
				}
			};
			
			if (!find) {
				return false;
			};
			find = false;
		};
	} else {
		return false;
	}
	return true;
};
// Compare templates
function compareTemplates() {
	var list, category, id
	var design = new Array();
	var functional = new Array();
	
	// pick all checked checkbox
	var allCheckbox = $('.design-div input:checkbox:checked');
	allCheckbox.each(function () {
		list = $(this).attr('id').split('-');
		category = list[0];
		id = list[1];
		
		if (category == 'design')
			design.push(priceList[category][id].title);
		else if (category == 'functional')
			functional.push(priceList[category][id].title);
	});
	// define template
	for (var i = 0; i < compare.length; i++) {
		if (defineTemplate(compare[i], design, functional)) {
			$('#siteFormat').val(compare[i]);
			onChangeSiteFormat();
			return;
		};
	};
};
*/
