function delProduct(id){
    if(confirm('Olete kindel?')){
        var params = {};

        params['id']=id;
        setWait();
        $.post(
            ajax_path + "lepingDelProduct",
            params
            ,
            function (result){
                if (result == "error"){
                    showNotice("error", true);
                } else {
                    clearWait();
                    //if(result.list){
                    $('#ajax_list').html('<center><span class="prod_ok">Toode kustutatud!</span></center>');
                    $('#ajax_added_items').html(result.list);
                    $('#total_'+jupid[1]).attr('value',result.item_total);
                    $('#stotal_'+jupid[1]).html(result.item_total);
                    $('#grand_total').html(result.grand_total+' &euro;');
                //}
                }
            },"json"
            );
    }
}

function AddProduct(see){
    var params = {};
    jupid = see.split('_');
    params['id']=jupid[1];
    params['vf']=jupid[2];
    params['volume']=jupid[3];
    params['amount']=$('#'+see).val();
    params['note']= $('#v_'+params['id']+'_comment').val();

    if(params['amount']>=0.5){
        setWait();
        $.post(
            ajax_path + "lepingAddProduct",
            params
            ,
            function (result){
                if (result == "error"){
                    showNotice("error", true);

                }
                else {
                    clearWait();
                    if(result.ok){
                        $('#ajax_list').html('<center><span class="prod_ok">Toode lisatud!</span></center>');
                        $('#infoprodbox').focus();
                        $('#ajax_added_items').html(result.list);
                        $('#total_'+jupid[1]).attr('value',result.item_total);
                        $('#stotal_'+jupid[1]).html(result.item_total);
                        $('#grand_total').html(result.grand_total+' &euro;');
                        $('#infoprodbox').focus();
                    }
                }
            },"json"
            );
    }
    else {
        showNotice("amounterror", true);
        return false;
    }

}
function searchProducts(code_field){

    var kood = $('#'+code_field).val();

    if (kood.length > 3){
        setWait();
        $.post(
            ajax_path + "lepingProductSearch",
            {
                code:kood
            }
            ,
            function (result){
                if (result == "error"){
                    showNotice("error", true);
                } else {
                    clearWait();
                    if(result.list){
                        $('#ajax_list').html(result.list)
                    }
                    else if (result.exists){
                        $('#ajax_list').html('<center><span class="prod_error">Toode on juba lisatud!</span></center>');
                    }
                }
            },"json"
            );
    }
}

function setlepingAmount(see){

            var params = {};
            setWait();
            var jid=$(see).attr('id');
            jupid = jid.split('_');
            params['id']=jupid[1];
            params['vf']=jupid[2];
            params['volume']=jupid[3];

            value = see.value;

            if(value.match(",")) {
                value = value.replace(',','.');
                see.value=value;
            }

            params['amount']=value;

            $.post(
                ajax_path + "slamount",
                params
                ,
                function (result){
                    //alert(result);
                    if (result == "error"){
                        showNotice("error", true);
                    }
                    else if(result.items || result.items==0 ) {
                        clearWait();
                        $('#total_'+jupid[1]).attr('value',result.item_total);
                        $('#stotal_'+jupid[1]).html(result.item_total);
                        $('#grand_total').html(result.grand_total);
                        $('#items_in_cart').html(result.items);
                    }
                    else if(value!='0' || value!='') {
                        alert('Tekkis probeem serveriga ühendamise, palun sisestage kogus uuesti!!!!');
                    }
                },"json"
                );
            see.focus();

}

function _step(step){
    $('#cstep').val(step);
}


var root_path = location.protocol + "//" + location.host;
var ajax_path = root_path + '/_ajax/';
var t;
var extra_selver;

(function( $ ){
    $.fn.dnkl_option = function(optionSettings) {
        /*
	NAME:	dnkl_option([visible, value, text])
	VERS:	1.0
	DESC:	Hide/Show option item in a select list
	USAGE:	$('#mySelectID').dnkl_option({ visible: false, value: '1' });
         */
        var settings = $.extend({
            visible: false,
            value: '',
            text: ''
        }, optionSettings || {});
        if (settings.value == '' && settings.text == '') {
            return $(this);
        }
        var os = $(this).data('options');
        if (typeof (os) === 'undefined') {
            $(this).data('options', $('#' + $(this).attr('id') + ' option'));
            os = $(this).data('options');
        }
        var o = null;
        var a = null;
        var b = null;
        for (var i = 0; o == null && i < $(os).length; i++) {
            if ($(os[i]).val() == settings.value || $(os[i]).text() == settings.text) {
                if (i - 1 >= 0) {
                    a = os[i - 1];
                }
                else if (i + 1 < $(os).length) {
                    b = os[i + 1];
                }
                o = os[i];
            }
        }
        if (settings.visible) {
            if (!$($('#' + $(this).attr('id') + ' option[value=' + $(o).val() + ']')).length) {
                if (a !== null) {
                    $(a).after(o);
                }
                else if (b !== null) {
                    $(b).before(o);
                }
                else {
                    $(this).append(o);
                }
            }
        }
        else {
            if ($(o).length) {
                $(o).remove();
            }
        }
        return $(this);
    }
})( jQuery );

$(document).ready(function() {
    extra_selver = {
        id : $("#js_selver option[class=is_extra]").val() ,
        txt : $("#js_selver option[class=is_extra]").text()
    }
    var pay_type = $("input[@name=paytype]:checked").val();
    if(pay_type=="1"){

    }
    else {
        $("#js_selver option[class=is_extra]").remove();
    }
    UpdateTime();

    $('#infoprodbox').keypress(function (event){
        if(event.keyCode == 13){
            searchProducts('infoprodbox');
            $('#infoprodbox').val('');
            return false;
        }
        else {
            return true;
        }

    });

});

function setOfferCode(){
    setWait();
    var offercode = $('#offercode').val();
    $.post(

        ajax_path + "setoffercode/cartview/true",
        {
            offercode: offercode
        },
        function (result){

            if (result == "error"){
                showNotice("error", true);
            } else {
                if (offercode){
                    clearWait();
                    $("#js_ajax_cart").html(result);
                }
            }
        }
        );

}

function UpdateTime(){
    /*
    var where = $('#js_selver option:selected').attr('rel');
    if (where=="not_tallinn"){
        jQuery.each($('#js_deliverytime option[class=morning],#js_deliverytime2 option[class=morning]'), function() {

            $(this).attr('disabled','disabled');
            if($(this).attr('selected')){
                $(this).removeAttr('selected');
            }
        });
    } else {
        jQuery.each($('#js_deliverytime option[class=morning],#js_deliverytime2 option[class=morning]'), function() {
            $(this).removeAttr('disabled');
        });
    }

     */
    return true;
}


function CopyAddress(){
    //  $('input[name=deliveryaddress1]').attr('value',$('input[name=companyaddress1]').attr('value'));
    $('input[name=deliveryaddress2]').attr('value',$('input[name=companyaddress1]').attr('value'));
    $('input[name=deliveryaddress3]').attr('value',$('input[name=companyaddress3]').attr('value'));
    $('input[name=copy]').attr('checked', false);

}

function SetBillType(billtype){
    //setWait();
    if(billtype=="2"){
        $('tr[rel=company]').show();
    }
    else {
        $('tr[rel=company]').hide();
    }

}

function SetPayType(paytype,year, month, day){


    setWait();

    if(paytype==""){
        paytype = ("input[@name=paytype]:checked").val();
    }



    if(paytype=="1"){
        $('#js_selver').append($("<option class=\"is_extra\"></option>").attr("value",extra_selver.id).text(extra_selver.txt));
        $("#selver_choose").show();
        $('#js_deliverytime').show();
        $('#js_deliverytime2').hide();
    }
    else if(paytype=="3"){
        $("#js_selver").attr('selectedIndex', '-1');

        $("#js_selver option[class=is_extra]").remove();
        $("#selver_choose").hide();
        $('[rel=calendar_cont]').show();
        $('#js_deliverytime').hide();
        $('#js_deliverytime2').show();

        d = new Date(year, month, day);
        calendar(d, 2);

        $('[rel=calendar_cont]').show();
    }
    else {
        $("#js_selver option[class=is_extra]").remove();
        $("#selver_choose").show();
        $('#js_deliverytime').show();
        $('#js_deliverytime2').hide();
    }

    $.post(

        ajax_path + "setpaytype/" + (paytype ? "cartview/true" : null),
        {
            paytype: paytype
        },
        function (result){

            if (result == "error"){
                showNotice("error", true);
            } else {
                if (paytype){
                    clearWait();
                    $("#js_ajax_cart").html(result);
                }
            }
        }
        );
}

function showCart()
{

    if ( $("#js_cartinfo").length > 0 ) {
        $.ajax({
            url: ajax_path + "showcart/",
            cache: false,
            success: function(html){
                $("#js_cartinfo").html(html);
            }
        });
        $.ajax({
            url: ajax_path + "showcart/footer/true",
            cache: false,
            success: function(html){
                $("#js_cartinfo_footer").html(html);
            }
        });
    }

}


function addCart(id, amount, cartview)
{

    if (!id || !amount){
        return false;
    }
    if(amount < 0.5){
    //alert(amount);
    //showNotice("amounterror", true);
    //return false;
    }

    if (cartview){
        setWait();
    } else {
        showNotice("wait");
    }

    $.post(
        ajax_path + "addcart/" + (cartview ? "cartview/true" : null),
        {
            id: id,
            amount: amount
        },
        function (result){
            if (result == "error"){
                showNotice("error", true);
            }
            else if(result == "amounterror"){
                showNotice("amounterror", true);
            } else {
                if (cartview){
                    clearWait();
                    $("#js_ajax_cart").html(result);
                } else {
                    showNotice("success", true);
                    showCart();
                }

            }
        }
        );
}


function changeCart(id, amount)
{

    if (!id || !amount || amount<=0){
        return false;
    }
    setWait();

    $.post(
        ajax_path + "changecart/",
        {
            id: id,
            amount: amount
        },
        function (result){
            if (result == "error"){
                showNotice("changeerror", true);
            } else {
                $("#js_helper").val("wait");
                clearWait();
                $("#js_ajax_cart").html(result);
                setTimeout( function() {
                    $("#product_" + id).focus().val($("#product_" + id).val());
                    $("#js_helper").val(" ");
                    $('input.js_cart_amount_input').bind('keypress', function(e) {
                        allowed = ( e.which!=8 && e.which!=0 && e.which!=44 && e.which!=46 && (e.which<48 || e.which>57)) ? false : true ;
                        if (allowed){
                            if (checkAmount($(this).val(), $(this).hasClass("js_kg") )) {
                                $("#" + this.id + "_lastvalue").val($(this).val());
                            } else {
                                $("#" + this.id + "_lastvalue").val("");
                            }
                            return true;
                        } else {
                            return false;
                        }
                    });
                } , 500);
            }
        }
        );

}



function removeCart(id)
{

    if (!id){
        return false;
    }
    setWait();

    $.post(
        ajax_path + "removecart/",
        {
            id: id
        },
        function (result){
            if (result == "error"){
                showNotice("error", true);
            } else {
                clearWait();
                $("#js_ajax_cart").html(result);
            }
        }
        );
}



function chooseSelver(year, month, day)
{
    //$(".calendar_cont").fadeOut("fast");
    $('[rel=calendar_cont]').hide();
    if ($("#js_selver").val())
    {
        $.post(
            ajax_path + "chooseselver/",
            {
                id: $("#js_selver").val()
            },
            function (result){
                if (result == "selvererror"){
                    showNotice("selvererror", true);
                } else {

                    initCalendar("", day+'/'+month+'/'+year);

                    d = new Date(year, month, day);
                    calendar(d, result);
                    //$(".calendar_cont").fadeIn("fast");

                    $('[rel=calendar_cont]').show();

                }
            }
            );
        UpdateTime();
    }

}


function chooseTime(tt)
{

    if ($("#js_deliverytime"+tt).val())
    {
        $.post(
            ajax_path + "choosedeliverytime/",
            {
                time: $("#js_deliverytime"+tt).val(),
                time2 : $("#js_deliverytime"+tt).val()
            },
            function (result){
                if (result == "error"){
                    showNotice("timeerror", true);
                }
            }
            );
    }



}



function calendar(d, days)
{
    $('#js_datepick').dpSetStartDate(d.addDays(days).asString());
    selected = $('#js_datepick').dpGetSelected();
    if (typeof(selected.length) != "undefined" && selected.length>0 && selected[0] < d){
        setDeliverDate(0);
    }
}



function initCalendar(selecteddate, startdate)
{




    $('#js_datepick')
    .datePicker({
        createButton:false
    })
    .bind('click',
        function()
        {
            $(this).dpDisplay();
            this.blur();

            return false;
        }
        )
    .bind(
        'dateSelected',
        function(e, selectedDate, $td)
        {
            setDeliverDate(selectedDate);
        }
        );
    $('#js_datepick').dpSetOffset(-50, 80);
    if (selecteddate){
        $('#js_datepick').dpSetSelected(selecteddate);
    }
    if (startdate)
    {
        $('#js_datepick').dpSetStartDate(startdate);
    }



}



function setDeliverDate(date)
{
    if (typeof(date) != "object"){
        $("#js_deliver_date").html(' ');
    } else {
        $.post(
            ajax_path + "setdeliverdate/",
            {
                date: date.getDate() + '.' + (date.getMonth()+1) + '.' + date.getFullYear()
            },
            function (result){
                if (result == "dateerror"){
                    showNotice("error", true);
                } else {
                    $("#js_deliver_date").html(result);
                }
            }
            );
    }
}


function postContactInfo()
{
    var params = {};
    $("#js_contact_data")
    .find("input[type='text'], textarea")
    .filter(":enabled")
    .each(function() {
        params[this.name] = this.value;
    });

    $("#js_contact_data")
    .find("input[type='radio']")
    .filter(":checked")
    .each(function() {
        params[this.name] = this.value;
    });
    
     $("#js_contact_data")
    .find("input[type='checkbox']")
    .filter(":checked")
    .each(function() {
        params[this.name] = this.value;        
    });

    $("#js_contact_data")
    .find("select")
    .each(function() {
        params[this.name] = this.value;
    });


    $.post(
        ajax_path + "postcontactinfo/",
        params,
        function (result){
            if (typeof(result) == "object"){
                success = true;
                $.each(result.status, function(field, status){
                    if (status == "ok"){
                        $("#js_input_" + field).removeClass("error");
                        $("#js_error_" + field).addClass("hidden");
                    } else {
                        success = false;
                        $("#js_input_" + field).addClass("error");
                        $("#js_error_" + field).removeClass("hidden");
                    }
                });
                if (success){
                    document.location.href = document.location.href.replace(2, 3);
                }
            }
        },
        "json"
        );
}

function bankLink(){
    $.ajax({
        url: ajax_path + "confirmorder/",
        cache: false,
        success: function(result){
            if (result == 'ok'){
                document.location.href = document.location.href.replace(3, 4);
            } else {
                showNotice("confirmerror", true);
            }
        }
    });
}

function confirmOrder()
{
    $.ajax({
        url: ajax_path + "confirmorder/",
        cache: false,
        success: function(result){
            if (result == 'ok'){
                document.location.href = document.location.href.replace(3, 5);
            } else {
                showNotice("confirmerror", true);
            }
        }
    });
}



function setWait()
{
    $(".bucket_cont a").css('cursor', 'wait');
}

function clearWait()
{
    $('.bucket_cont a').css('cursor', 'default');
}


function showNotice(type, timeout)
{

    $("#js_cart_notice_text").html($("#js_cart_notice_" + type).html());
    if (type.match(/error/)){
        $("#js_cart_notice_text").removeClass("info");
        $("#js_cart_notice_text").addClass("info_error");
    } else {
        $("#js_cart_notice_text").removeClass("info_error");
        $("#js_cart_notice_text").addClass("info");
    }
    if ($.browser.msie && parseInt($.browser.version) < 7){
        $("#js_cart_notice").css("top", $(window).scrollTop() + parseInt($(window).height() / 2) + "px");
        $("#js_cart_notice").show();
    } else {
        $("#js_cart_notice").center().show();
    }
    if (timeout){
        t = setTimeout(function() {
            $('#js_cart_notice').fadeOut("fast");
            clearTimeout(t);
        }, 1000);
    }

}


function closeNotice()
{
    clearTimeout(t);
    $('#js_cart_notice').fadeOut("fast");
}



function productMark(id, mark)
{

    $.post(
        ajax_path + "productmark/",
        {
            id: id,
            mark: mark
        },
        function (result){
            if (result == "error"){
                showNotice("markerror", true);
            } else {
                $("#js_stars_" + id).html(result);
                showNotice("marksuccess", true);
            }
        }
        );
}


function checkAmountCart(input, kg)
{

    if (checkAmount($(input).val(), kg, input))
    {
        newval = $(input).val().replace(/\,/, ".");
        // alert(newval+':'+$("#" + input.id + "_firstvalue").val());
        if (newval != $("#" + input.id + "_firstvalue").val()){
            if(newval >=0.5){
                changeCart(input.id.replace(/product_/, ""), newval);
            }
            else {
                $(input).val($("#" + input.id + "_firstvalue").val());
                showNotice("amounterror", true);
            }
        }
    }
}



function checkAmount(input, kg, cart)
{


    if (!kg && typeof(input) == "object" && ($(input).hasClass("js_kg"))){
        kg = true;
    }

    inputval = (typeof(input) == "object") ?  $(input).val() : input;
    inputlength = inputval.length;
    if (!inputlength)
    {
        return false;

    } else if (!kg && inputval.charAt(0) == "0") {
        if (typeof(input) == "object"){
            $(input).val($("#" + input.id + "_lastvalue").val());
        } else if (cart){
            $(cart).val($("#" + cart.id + "_firstvalue").val());
        }
    } else {

        comma = 0;
        commaplace = 0;
        for (i=0;i<inputlength;i++){
            if (inputval.charAt(i) == '.' || inputval.charAt(i) == ','){
                comma++;
                commaplace = i;
                if (i == (inputlength - 1))
                {
                    if (comma > 1 || !kg){
                        if (typeof(input) == "object"){
                            $(input).val($("#" + input.id + "_lastvalue").val());
                        } else if (cart){
                            $(cart).val($("#" + cart.id + "_firstvalue").val());
                        }
                        return false;
                    }
                    return false;
                }
                if (comma>1 || i==0 || commaplace == 0){
                    if (typeof(input) == "object"){
                        $(input).val($("#" + input.id + "_lastvalue").val());
                    } else if (cart){
                        $(cart).val($("#" + cart.id + "_firstvalue").val());
                    }
                    return false;
                }
                if (!kg){
                    if (typeof(input) == "object"){
                        $(input).val($("#" + input.id + "_lastvalue").val());
                    } else if (cart){
                        $(cart).val($("#" + cart.id + "_firstvalue").val());
                    }
                    return false;
                }
            }
            if (commaplace>0 && (i-commaplace)>1)
            {
                if (typeof(input) == "object"){
                    $(input).val($("#" + input.id + "_lastvalue").val());
                } else if (cart){
                    $(cart).val($("#" + cart.id + "_firstvalue").val());
                }
                return false;
            }
        }
    }
    return true;
}


function backtofirst()
{
    var params = {};
    $("#js_contact_data")
    .find("input[type='text'], textarea")
    .filter(":enabled")
    .each(function() {
        params[this.name] = this.value;
    });

    $.post(
        ajax_path + "backtofirst/",
        params,
        function (result){
            document.location.href = document.location.href.replace(2, 1);
        }
        );
}



$(function(){

    $('.ingredientsWrap a').mouseover(function() {
        $(this).next('.ingredientsPopup').show('fast');
        return false;
    });
    $('.ingredientsWrap a').mouseout(function() {
        $(this).next('.ingredientsPopup').hide('fast');
        return false;
    });

    $('input.js_cart_amount_input').bind('keypress', function(e) {
        allowed = ( e.which!=8 && e.which!=0 && e.which!=44 && e.which!=46 && (e.which<48 || e.which>57)) ? false : true ;
        if (allowed){
            if (checkAmount($(this).val(), $(this).hasClass("js_kg") )) {
                $("#" + this.id + "_lastvalue").val($(this).val());
            } else {
                $("#" + this.id + "_lastvalue").val("1");
            }
            return true;
        } else {
            return false;
        }
    });

    $(".productmark").hover(
        function() {
            nr = this.id.charAt(this.id.length-1);
            i = 0;
            $(this).parent().children().each(function() {
                i++;
                if (i<=nr){
                    $(this).attr("src", root_path + '/gfx/star_active.png');
                }
            });

        },
        function() {
            $(this).parent().children().each(function() {
                if ($(this).hasClass ("half")) {
                    $(this).attr("src", root_path + '/gfx/star_half.png');
                } else if ($(this).hasClass ("empty")){
                    $(this).attr("src", root_path + '/gfx/star_empty.png');
                } else {
                    $(this).attr("src", root_path + '/gfx/star_complete.png');
                }
            });

        }
        );

    $(document).keydown(function (eh){
        if ((eh.which) == 8 && $("#js_helper").val() == 'wait'){
            return false;
        }
    });


});

function numbersonly(myfield, e, dec)
{

    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8)||
        (key==9) || (key==13) || (key==27) )
        return true;
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;
    else if (dec==1 && (key==46 || key==44))   {

        //myfield.value = parseFloat(myfield.value);
        return true;
    }
    else
        return false;
}

function MakePrint(urla,PrintDiv){
    var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
    disp_setting+="scrollbars=yes,width=950, height=600, left=50, top=50";
    var content_vlue = jQuery('#'+PrintDiv).html();
    var docprint=window.open("","",disp_setting);
    docprint.document.open();
    docprint.document.write('<html><head><title>Selver<\/title>');
    docprint.document.write('<link href="' + urla+ 'gfx\/print.css" rel="stylesheet" type="text\/css">');
    docprint.document.write('<\/head><body onload="window.print(); " style="padding:15px;">');
    docprint.document.write('<div class="MainContentArea">'+content_vlue+'</div>');
    docprint.document.write('<\/body><\/html>');
    docprint.document.close();
    docprint.focus();
}
