/** 
 * @version $Id: v 0.1 26.04.2010 - 16:45:41 Exp $
 *
 * Project:     golden
 * File:        cart.js *
 *
 * This library is commercial distributed software; you can't
 * redistribute it and/or modify it without owner (or author) approval.
 *
 * @link http://bestartdesign.com
 * @copyright (C) 2009
 *
 * @author Seyar Chapuh <seyarchapuh@gmail.com>, <sc@bestitsolutions.biz>
 */

$('document').ready(function()
{
    
    $('#sample8').attr('disabled', 'disabled');
    var paymentId = $('[name=payment] option:selected').val();
    getShipments( paymentId );
//    var shipmentId = $('select[name=shipment] option:selected').val();
//    if( shipmentId != 0 && shipmentId != undefined)
//        getShipmentCost(shipmentId);
    
});

function showPreloader()
{
    mytop = $(window).height()/2;
    $('.preloader').css('top', parseInt(mytop) + 'px').removeClass('hidden');
}

function deleteFromCart(id, thisObj)
{
    showPreloader();
    $.getJSON(
        '/shop/cart/'+id+'/delete_item',
        function(data)
        {
            $('.preloader').addClass('hidden');            
            if(data){
                if( data.total_sum != 0 )
                {
                    $(thisObj).parent().parent().remove();
                    $('.total_sum_price').text(data.total_sum.toFixed(2));
                    $('#cart_global_sum').text(data.total_sum.toFixed(2));
                    $('#cart_global_amount').text( data.count );
                    $('.preloader').addClass('hidden');
                }else{
                    document.location.reload();
                    $('.cart').html('<div class="cart"><p class="tCenter">Ваша корзина пуста.</p></div>');
                }
            }
            else
                myAlert('server error', 'err');
        }
    );
}

function change_amount(id, thisObj)
{
    var res = check(thisObj);
    if( res != 'noerror' )
        return false;
    else
    {
        change_amount_ajax(id, thisObj);
        return true;
    }
}

function change_amount_ajax(id, thisObj)
{    
    showPreloader();
    shipmentMethodId = $('#shipment').length != 0 ? $('#shipment').val()*1 : 0;
    $.getJSON(
        '/shop/cart/'+id+'/change_amount?amount='+$(thisObj).val()+'&shipmentMethodId='+shipmentMethodId,
        function(data)
        {
            $('.preloader').addClass('hidden');
            if(data.errors == 0){
                $(thisObj).parents('tr').find('.good_price').text(data.good_sum.toFixed(2));
                $('.total_sum_price').text(data.total_sum.toFixed(2));
                $('#cart_global_sum').text(data.total_sum.toFixed(2));
                $('#cart_global_amount').text(data.total_amount);
                $('#shipmentCost').text( data.shipmentCost );
                $('#shipmentCostInput').val( data.shipmentCost );
                $('.preloader').addClass('hidden');
            }
            else
                myAlert('server error', 'err');
        }
    );
}

function check(field)
{
  var val;

  if (field.value == '')
      return 'Не введено значение....';

  if (field.value.indexOf('.') != -1 )
      return 'Не введено значение....';

  val = parseInt(field.value);
  if (isNaN(val))
      return 'Не целое число....';

  if (val != field.value)
      return 'Не число.......';

  if (val <= 0)
      return 'Пожалуйста введите положительно число...';

  return 'noerror';
}

function checkCartForm(form)
{
	total_amount = 0;
	$(form).find('input.amount').each(function(){total_amount+= parseInt($(this).val());});
        
	if ( total_amount && $('[name=shipment]').val() && parseInt($('[name=payment]').val()) )
	{
		form.submit();
	}
	else 
	{
		err='\n';
		if (!total_amount) err+='В корзине нет товаров.\n';
		if (!parseInt($('[name=shipment]').val())) err+='Выберите метод доставки.<br />';
		if (!parseInt($('[name=payment]').val())) err+='Выберите метод оплаты.<br />';
		
		if (err) myAlert(err, "err");
	}
}

function getShipments()
{
    var id = $('#sample7').val();
    $('#sample8').attr('disabled','disabled');
    
    if( $('.basketTable').length == 0 && $('.cartTab').length == 0)
    {
        $('.preloader').addClass('hidden');
       // return;
    }
    
    if(id == 0)
    {
        $('#sample8').html('').attr('disabled','disabled');
        return;
    }
    $('#shipmentBlock').html('');
    $.getJSON(
        '/shop/cart/'+id+'/getShipments', 
        {},
        function(data)
        {
            
            var selectoptions = '<select id="sample8" name="shipment">';
            for(i in data)
            {
                selectoptions += '<option value="'+data[i]['id']+'">'+data[i]['name']+'</option>';
            }
            selectoptions += '</select>';
            $('#shipmentBlock').html(selectoptions);
            $('#sample8').SelectCustomizer();
//            $('#sample8_holder').html(selectoptions).attr('disabled','');
            var shipmentId = $('select[name=shipment] option:selected').val();
            if( shipmentId != 0 && shipmentId != undefined)
                getShipmentCost(shipmentId);
        }
    );
}

function getInstructions()
{
    $('.instruction').addClass('hidden');
    var paymentId = $('select[name=payment] option:selected').val();
    var shipmentId = $('select[name=shipment] option:selected').val();
    $.getJSON(
        '/shop/cart/1/getInstructions', 
        {paymentId:paymentId, shipmentId:shipmentId},
        function(data)
        {
            if(data['paymethods'] && $('#paymentInstruction').length > 0 )
            {
                $('#paymentInstruction').html(data['paymethods']);
                $('#paymentInstruction').parent().removeClass('hidden');
            }
            if(data['shipmethods'] && $('#shipmentInstruction').length > 0)
            {
                $('#shipmentInstruction').html(data['shipmethods']);
                $('#shipmentInstruction').parent().removeClass('hidden');
            }
            rebuildPrices();
        }
    );
}

function getShipmentCost( shipment_id )
{
    showPreloader();
    var goodsCount = {};
    
    
    if( $('.cartTab').length != 0)
    {
        $('.cartTab input').each(
            function()
            {                
                id = $(this).attr('name').replace(/.+\[/, '');
                id = id.replace(']', '');
                goodsCount[id] = $(this).val();
            }
        );
    }
    else if( $('.basketTable').length != 0 )
    {
        $('.basketTable input').each(
            function()
            {                
                id = $(this).attr('name').replace(/.+\[/, '');
                id = parseInt(id.replace(']', ''));
                goodsCount[id] = $(this).val();
            }
        );
    }
        
    
    if( $('.basketTable').length == 0 && $('.cartTab').length == 0)
    {
        $('.preloader').addClass('hidden');
        return;
    } 
        
    $.getJSON(
        '/shop/cart/'+shipment_id+'/getShipmentCost',
        {goodsCount:goodsCount},
        function(data)
        {            
            if( data.errors == 0)
            {
                if( $('.cartTabBottom:visible').length == 0 ) $('.cartTabBottom').removeClass('hidden');
                
                $('.total_sum_price').text(data.total_sum.toFixed(2));
                $('#cart_global_sum').text(data.total_sum.toFixed(2));
                $('#cart_global_amount').text(data.total_amount);
                $('#shipmentCost').text( data.shipmentCost );
                
            }
            else
                myAlert('server error', 'err');
            getInstructions();
        }
    );
    $('.preloader').addClass('hidden');
}

function rebuildPrices()
{
    showPreloader();
    var paymentId = $('select[name=payment] option:selected').val();
    var shipmentId = $('select[name=shipment] option:selected').val();
    
    $.getJSON(
        '/shop/cart/1/rebuildPrices', 
        {paymentId:paymentId, shipmentId:shipmentId}, 
        function(data)
        {
            if(typeof data == 'object')
            {
                $('.total_sum_price').text(data.total_sum);
                $('#cart_global_sum').text( data['total_sum'] );
                
                for( i in data.items )
                {
                    var block = $('tr.i_'+i);
                    var sum = data.items[i][0] * $(block).find('input.amount').val();
                    block.children('td:last-child').children('.good_price').text( sum.toFixed(2) )
                }
            }
            $('.preloader').addClass('hidden');
        }
    );
}
