function steps(selector) {
    var tInp = $(selector).parent().prev();
    var cprice = $(selector).parent().parent().prev().children('.SSprice');
    var cpriceval = parseInt(tInp.attr('rel'));
    var full = 0;
    var tVal =  parseInt(tInp.val());
    var tStep = parseInt(tInp.attr('step'));
    if ($(selector).hasClass('stepUp')){
        tInp.val(tVal ? tVal+tStep : tStep);
        //$(cprice).text(cpriceval*(tVal+tStep));
    } else if(tInp.val() != 0) {
        tInp.val(tVal ? (tVal == '0' ? '0' : tVal-tStep) : 0);
        //if(tInp.val() > 0) $(cprice).text(cpriceval*(tVal-tStep));
    }
    buyItem();
    $('.allitems input.step55').each(function(){
        if(parseInt($(this).attr('rel')) > 0) {
            full += parseInt($(this).val()) * parseInt($(this).attr('rel'));
        }
    });
    $('#fprice').text(full);
    $('#amount').val(full);
}

function submitform(elem) {
    var form = $(elem).parent().parent().parent().parent().parent().parent();
    if(inquiryvalidate(form)) {
        $('.cfio').text($('.fio').val());
        $('.ctel').text($('.tel').val());
        $('.cmail').text($('.mail').val());
        $.facebox({div: '#userresult'}, 'my-groovy-style');
    }
}

function paystep() {
    var form = jQuery('#generalform');
    jQuery.post("http://aquapark-terminal.com.ua/index.php", jQuery(form).serialize(), function(data){ resultajax(data) } );
}

function resultajax(resultdata) {
    if(resultdata) {
        jQuery('#orderid').val(resultdata);
        jQuery('#generalform').submit();
    }
}

$(document).ready(function(){
	/*$('.items input').each(function() {
       if(!$(this).val() || $(this).val() == 0) $(this).hide();
    });*/
    $('.selectCount img').click(function(){steps(this);});
    $(".tel").inputmask("+38 (999) 999-99-99");
    $('.owervr').click(function() {
        submitform(this);
    });
    $('.canc').click(function() {
        $.facebox.close();
    });
    $('.submit').click(function() {
        paystep();
    });
	/*$('.items').hover(
		function(){
			$(this).find('input').show();
		},
		function() {
			if($(this).find('input').val() && $(this).find('input').val() != 0) {
				$(this).addClass('active');
			} else {
				$(this).find('input').hide();
			}
		}
	);*/
});
function buyItem(){
    var html = '';
    $('.allitems input.step55').each(function(){
        if(parseInt($(this).attr('rel')) > 0 && $(this).val() > 0) {
            html += '<tr><td>'+$(this).prev().children().text()+'</td><td>'+$(this).val()+' шт</td><td style="text-align: right; padding: 0pt 13px 0pt 0pt;">'+$(this).attr('rel')+' грн</td></tr>';
        }
    });
    $('#basket').html(html);
}
function changeBasket() {
    var coo = '';
    $('.basket').toggle('slow');
    $('.top_basket').animate({
    opacity: 'toggle',
    //left: 'toggle',
    height: 'toggle'
  }, 1000, function() {
    if($(this).css('display') == "none") coo = 1; else coo = 2;
    $.cookie("coo", coo);
  });
}

function reCountBasket(){
    var tcount = 0;
    var tprice = 0;
    var cookie = '';
    $('.top_basket').hide('slow');
    $('.basket table tbody tr').each(function(){
        tprice+=parseFloat($(this).children('td:eq(3)').text());
        tcount+=parseFloat($(this).children('td:eq(2)').text());
        cookie += $(this).attr('data-id') + '|' + $(this).children('td:eq(2)').text() /*+ '|' + $(this).children('td:eq(0)').text() + '|' + $(this).children('td:eq(1)').text()*/ + ';';
    });
    $('.basket table tfoot tr th:eq(1)').text(tcount);
    $('.bascount').text(tcount);
    $('#coptice').text(tprice+' грн');
    $('#coall').text(30 + tprice+' грн');
    $('.basket table tfoot tr th:eq(2)').text(tprice);
    if($('.basket table tbody tr').length) $('#cprname').text('Ст-ть');
    $.cookie("basket", cookie);
}

/*$("#userresult").dialog({
    width: 550,
    modal: true,
    autoOpen: false,
    open: function(event, ui) {
            window.setTimeout(function() {
                $(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay');
            }, 10);
        }

});*/

function deleteItem(itemRow, allFlag){
    if (!allFlag ? confirm('Удалить товар из корзины?') : true){
        $(itemRow).remove();
        if(!$('.basket table tbody tr').length) {
            $('.basket').hide('slow');
        }
        reCountBasket();
    }
}
function emptyBasket(){
	if (confirm('Очистить корзину?')){
		$('.basket table tbody tr').each(function(){
			deleteItem(this, true);
		})
        $.cookie("basket", null);
        $('.basket').hide('slow');
	}
}
function inquiryvalidate(elem) {
    var form = $(elem);
    //var form =elem;
    var ok = true;
    var fields = new Array();
    var ereg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    var nreg = /[0-9]/ ;
    var lreg = /^([а-яa-zёїійє \-]+)$/i ;
    $(form).find('input').each(function() {
        if($(this).attr('type') != 'hidden' && $(this).attr('rel') && !$(this).hasClass('step55')) {
            $(this).css('border', '1px solid #F0F0F0');
            if($(this).val() == '' || $(this).val() == ' ') {
                ok = false;
                $(this).css('border', '1px solid #ff0000');
                fields.push($(this).attr('rel'));
            } else if ($(this).hasClass('mail') && !$(this).val().match(ereg)) {
                ok = false;
                $(this).css('border', '1px solid #ff0000');
                alert('Введенный Вами E-mail некорректный');
                return false;
            } else if ($(this).hasClass('numeric') && !$(this).val().match(nreg)) {
                ok = false;
                $(this).css('border', '1px solid #ff0000');
                alert('Введите в поле "'+$(this).attr('rel')+'" только цифры');
                return false;
            } else if ($(this).hasClass('literal') && !$(this).val().match(lreg)) {
                ok = false;
                $(this).css('border', '1px solid #ff0000');
                alert('Введите в поле "'+$(this).attr('rel')+'" только буквы');
                return false;
            } else if ($(this).attr('lcount')) {
                if(Number($(this).val().replace(/\D+/g,"")).toString().length != $(this).attr('lcount')) {
                    ok = false;
                    $(this).css('border', '1px solid #ff0000');
                    alert('Введите в поле "'+$(this).attr('rel')+'" '+$(this).attr('lcount')+' символов');
                    return false;
                }
            }
        }
    });
    if(ok) {
        if(parseInt($('#fprice').text()) > 0) {
            return true;
        } else {
            alert('Для оформления заказа кликните на плюсик возле необходимой услуги.');
            return false;
        }
    } else if(fields != '') {
        alert('Заполните, пожалуста, поле(я) "' + fields.join('", "') + '".');
        return false;
    }
}
