/**
 * @package 120.com.ua
 * @filename main.js
 * @contents frontend javascripts
 * @author Bartelby Acceptic <nlantinov@acceptic.com>
 * @version 1.2
 * @created 08.04.2009
 * @LastUpdate 22.04.2009 13:15 by @author
 *
 */

function sendOrderData()
{
	var errors = false;
	var name = $F('name');
	var shipping_method = $F('shipping_method');
	var paying_method = $F('paying_method');
    var code_discount = $F('code_discount');
	var city = $F('city');
	var phone = $F('phone');
	var email = $F('email');
	var emailValidator = new RegExp("[0-9a-z_]+@[0-9a-z_^\.]+.[a-z]{2,3}");
	var adres = $F('adres');         
	var comment = $F('comment');
	var source = $F('source');
	if (name == '')
	{
		$('name_error').show();
		errors = true;
	}
	else
		$('name_error').hide();
	
	if (phone == '')
	{
		errors = true;
		$('phone_error').show();
	}
	else
		$('phone_error').hide();
	
	if (email != '' && !emailValidator.test(email))
	{
		errors = true;
		$('email_error').show();
	}
	else
		$('email_error').hide();
	
	if (adres == '')
	{
		errors = true;
		$('adres_error').show();
	}
	else
		$('adres_error').hide();
	
	if (errors)
		return 0;
	else
	{
		new Ajax.Request("/order", {
			method: "post",
			parameters:{
				name: name,
				phone: phone,
				email: email,
				adres: adres,
				shipping_method: shipping_method,
				paying_method: paying_method,
				code_discount: code_discount,
				city: city,
				comment: comment,
				source: source,
				formOrder: 1
			},
			onSuccess: function(trans){
				alert("Ваш заказ успешно сформирован.\nНомер заказа - " + trans.responseText + "\nНаш менеджер свяжется с Вами в ближайшее время.\n\nСпасибо за покупку");
				location.href = '/';
			}
		});
	}
}

function sendPreOrderData()
{
	var errors = false;
	var name = $F('name');
	var product = $F('product');
	var city = $F('city');
	var phone = $F('phone');
	var adres = $F('adres');         
	var comment = $F('comment');
	
	if (product == '')
	{
		$('product_error').show();
		errors = true;
	}
	else
		$('product_error').hide();
	
    if (name == '')
	{
		$('name_error').show();
		errors = true;
	}
	else
		$('name_error').hide();
	
	if (phone == '')
	{
		errors = true;
		$('phone_error').show();
	}
	else
		$('phone_error').hide();
	if (adres == '')
	{
		errors = true;
		$('adres_error').show();
	}
	else
		$('adres_error').hide();
	
	if (errors)
		return 0;
	else
	{
		new Ajax.Request("/contacts", {
			method: "post",
			parameters:{
				name: name,
                product: product,
				phone: phone,
				adres: adres,
				city: city,
				comment: comment,
				formPreOrder: 1
			},
			onSuccess: function(trans){
				alert("Ваш предзаказ отправлен админу.");
				location.href = '/';
			}
		});
	}
}

function displayPict(pict, head)
{
	var productWindow = open("", "product_window","resizable=yes, scrollbars=yes, titlebar=no, location=no, menubar=no, toolbar=no, width=600, height=600");
	productWindow.document.writeln('<html><head><TITLE>' + head + '</TITLE>');
    productWindow.document.writeln("</head><body>");
	productWindow.document.writeln('<div class="box"><img src="' + pict + '" /></div>');
    productWindow.document.writeln('</body></html>');
    productWindow.document.close();
    productWindow.focus();
    productWindow.scroll(0,0);
}

function deleteProduct(id)
{
	new Ajax.Request("/cart.html", {
		method: "get",
		parameters: {
			deleteFromCart: 1,
			id: id
		},
		onSuccess: function(trans){
			location.href = "/cart.html";
			}
	});
}

function refresh(id)
{
	var price = $('price_' + id).innerHTML;
	var orderTotal = $('orderTotal').innerHTML;
	var count = $F('qty_' + id);
	var total = $('total_' + id).innerHTML;
	orderTotal = orderTotal - total;
	total = price * count;	
	orderTotal = orderTotal + total;
	new Ajax.Request("/cart.html", {
		method: "get",
		parameters:{
			id: id,
			qty: count
		},
		onSuccess: function(trans){
			$('orderTotal').innerHTML = orderTotal;
			$('total_' + id).innerHTML = total;
		}
	})
}

function DeleteCookie(name, path, domain)
{
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function SetCookieForNDays(name, value, days, path, domain, secure)
{
    var today = new Date();
    expires = new Date(today.getTime() + days*24*60*60*1000);
    document.cookie = name + "=" + escape(value) +
                    "; expires=" + expires.toGMTString() +
                    ((path) ? "; path=" + path : "") +
                    ((domain) ? "; domain=" + domain : "") +
                    ((secure) ? "; secure" : "");
}

function open_close (category)
{
     DeleteCookie(category, '/', '');
    if ($('case_'+category).getStyle("display") == 'none')
    {
        SetCookieForNDays(category, "1", 10, '/', '', '')
        $(''+category).setAttribute('class', 'selected');
        $('case_'+category).show();
    }
    else
    {
        $(''+category).setAttribute('class', '');
        $('case_'+category).hide();
    }
}

function add2cart(id, count, type)
{
    new Ajax.Request("/add2cart",
        {
            method: 'get',
            parameters:{
                id: id,
                count: count,
                type: type
            },
            onSuccess: function(trans)
            {
                if (trans.responseText)
                {
                    $('shopping_cart').innerHTML = trans.responseText;
                    location.href = "/cart.html";
                    //alert('Товар успешно добавлен в корзину!\n\nВы можете продолжить просмотр каталога либо перейти к оформлению покупки, для этого нажмите на Корзину вверху страницы.');
                }
                else
                {
                    alert("Вы пытаетесь добавить в корзину товар, отсутствующий на нашем складе.\n\nУточните, пожалуйста его наличие у менеджера.");
                }
            },
            onFailure: function(){alert("Нет цены")}
        }
    )
}
