//js functions

function get_cookies_array() {

	var cookies = { };

	if (document.cookie && document.cookie != '') {
		var split = document.cookie.split(';');
		for (var i = 0; i < split.length; i++) {
			var name_value = split[i].split("=");
			name_value[0] = name_value[0].replace(/^ /, '');
			cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
		}
	}

	return cookies;

}


function getTotalPrice() {
	var totalPrice = 0;
	var cookies = get_cookies_array();
	for(var cookieName in cookies) {
		if (cookieName.match(/mygoods_\d{1,2}/)) {
			totalPrice += parseFloat(aJSONGoods[cookieName].price);
		}
	}
	return totalPrice;
}

function showTotalPrice() {
	jQuery('#totalPrice').text(getTotalPrice());
}

//Onload event
jQuery(function(){
	if (jQuery("#totalPrice").length > 0) {
		showTotalPrice();
	}

	jQuery('#mainpict')
	.hover(function(){
			jQuery(this).fadeTo('normal', 0.2, function(){
				jQuery(this).attr({src: DIR_STATIC_SKIN + "/images/elephant.jpg"});
				jQuery(this).fadeTo('normal', 1);
			});
		}, function(){
			jQuery(this).fadeTo('normal', 0.2, function(){
				jQuery(this).attr({src: DIR_STATIC_SKIN + "/images/elephant_set.jpg"});
				jQuery(this).fadeTo('normal', 1);
			});
	})
	.click(function(){
		jQuery("#details").dialog('open');
	});


	jQuery("#details").dialog({
		buttons: { "Заказать": function() { jQuery(this).dialog("close"); jQuery('#orderform').dialog('open'); }, "Закрыть": function() { jQuery(this).dialog("close"); } },
		bgiframe: true,
		width: 600,
		maxHeight: 600,
		modal: true,
		autoOpen: false,
		show: 'slide'
	});
	jQuery("#orderform").dialog({
		buttons: {
			"Отправить": function() {
				$thisdiv = jQuery(this);
				JsHttpRequest.query(
					DIR_WEB_ROOT+'/include/ajax/orderGoods.php',
					{ params: jQuery(this).find('form')[0] },
					function(result, errors) {
						if (!result) {
							alert('Произошла ошибка при отправке заявки. Попробуйте ещё раз через некоторое время.');
						}
						if (result.bStateError) {
							alert('Произошла ошибка при отправке заявки. Заявка содержит ошибки.');
						} else {
							$thisdiv.html('<p>Заявка отправлена. Наш менеджер с Вами свяжется.</p>');
							$thisdiv.dialog('option', 'buttons', { "Закрыть" : function() { jQuery(this).dialog("close"); } });
						}
					},
					true
				);
			},
			"Закрыть": function() {
				jQuery(this).dialog("close");
			}
		},
		bgiframe: true,
		width: 600,
		maxHeight: 600,
		modal: true,
		autoOpen: false,
		show: 'slide'
	});

	//Cookie section

	jQuery('.buy-goods').each(function(){
		if (jQuery.cookie(jQuery(this).attr("id"))) {
			jQuery(this).remove();
		}
	});

	var options = { path: '/', expires: 10 };

	jQuery('.buy-goods').click(function(){
		jQuery.cookie(jQuery(this).attr("id"), 'true', options);
		jQuery.growl("Корзина", "Товар добавлен в корзину");
		jQuery(this).remove();
	});

	//Delete items

	jQuery('.delete-goods img').click(function(){
		jQuery.cookie('mygoods_' + jQuery(this).attr("id"), null, options);
		jQuery(this).parent().parent().empty();
		showTotalPrice();
	});

	//Order form call
	jQuery("#orderformcall").click(function(){
		var goodsList = "";
		var goodsListArray = new Array();
		var cookies = get_cookies_array();
		for(var name in cookies) {
			if (name.match(/mygoods_\d{1,2}/)) {
				goodsListArray.push(aJSONGoods[name].name);
			}
		}
		goodsList = goodsListArray.join(', ');
		jQuery('#orderDescription').text('Вы заказали следующие товары: ' + goodsList + ".");
		jQuery('#orderPrice').text('На общую сумму: ' + getTotalPrice() + " рублей.");
		jQuery('#goodsList').val(goodsList);
		jQuery('#orderform').dialog('open');
	});
});
//End of onload event

