function roundNumber(num,delimiter){
    if(!delimiter){
        delimiter = ".";

    }
    num = Math.round(num*100)/100;
    num = num.toString();
    if(num.indexOf('.') === false){
        split_simbol = ',';
    } else {
        split_simbol = '.';
    }
    var split = num.split(split_simbol);
    if(!split[1]){
        split[1] = '00';
    } else {
        if(split[1].length  < 2){
            split[1] = split[1]*10;
        }
    }
    num = split[0]+delimiter+split[1];
    return num;
}


$(document).ready(function(){
	
	
    //last-child for MSIE
    if ( $.browser.msie ) {
        $(".listMenys div:last-child, .cartTop li:last-child").addClass('last');
    }
	
    $(function() {
        if (window.PIE) {
            $('#wraper, ul.productList, .roundBox, .pinkButton,.greyRounded, .greenButton, .silverTab').each(function() {
                PIE.attach(this);
            });
		
        }

        $('#addon_dialog').dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            title: "Please select product for you addon",
            width: 640,
            buttons: {
                "Ok": function() {
                    $('#add_addon_form').submit();
                },

                "Close": function() {
                    $(this).dialog('close');
                }

            }
        });

        // add addon to product link
        $('.add_addon').bind('click', function(e) {
            e.preventDefault();
            addon_slug = $(this).attr('rel');
            price_option = $('input[name="pricing"]:checked').val();
            $('#addon_dialog').dialog('open');
            dialog_html = '<div style="float:left;">';
            $.getJSON(base_url + 'shop/ajax_GetCartList', '', function(response_text){
                if(response_text.item_list.length > 0) {
                    dialog_html += '<form id="add_addon_form" action="' + base_url + 'shop/process_add_addon/' + addon_slug + '/' + price_option + '" method="POST">';
                    dialog_html += "<input type='hidden' name='addon_data' value='" + $('input[name="product_data"]').val() + "' />";
                    $.each(response_text.item_list, function(key,val){
                        dialog_html += '<div class="addon_product_box_item">';
                        dialog_html += '<input style="float: left;"type="checkbox" name="addto_list[]" value="' + val.slug + '::' + val.price_type +'" />'
                        dialog_html += '<div style="float: left;"><img src="' + image_srv + val.img + '_80_80.jpg" alt="' + val.name + '" /></div>';
                        dialog_html += '<span style="line-height: 80px; float: left;">' + val.name + ' ( ' + val.price_type + ' )</span>';
                        dialog_html += '</div>';
                    });
                } else {
                    dialog_html += 'There is no products in your cart! Please select one first.';
                }
                dialog_html += '</form></div>';
                $('#addon_dialog').html(dialog_html);
            });

            return false;
        });

        //*** auto add addon if single product in cart
        $('.add_addon_auto').bind('click', function(e) {
            e.preventDefault();
            addon_slug = $(this).attr('rel');

            $('input[name="pricing"]').each(function(index, object) {
                if($(object).attr('checked') === 'checked' || $(object).attr('checked') === true){
                    price_option = $(object).val();
                }
            });
            action_link = base_url + 'shop/process_add_addon/' + addon_slug + '/' + price_option;
            $('#add_form').attr('action', action_link);
            $('#add_form').submit();
            return false;
        });

        // clear search field when needed
        $('.searchField input[type="text"]').focus(function(){
            if($(this).val() == 'Type your search...') {
                $(this).val('');
            }
        });

        $('.searchField input[type="text"]').blur(function(){
            if(jQuery.trim($(this).val()) == '') {
                $(this).val('Type your search...');
            }
        });

        //*** add to cart

        $('#add_to_cart').bind('click', function(e){
            e.preventDefault();
            if(product_data != undefined && product_data.url_slug != undefined) {
                $('#add_notification').fadeIn(300);
                $('#add_notification').html('Processing your request...');
                price_option = $('input[name="pricing"]:checked').attr('value');
                ajax_url = base_url + 'shop/ajax_add_to_cart/' + price_option;
                $.ajax({
                    url: ajax_url,
                    dataType: 'json',
                    type: 'POST',
                    data: product_data,
                    success: function(response) {
                        //*** show notification and change number in header
                        if(response.add_result == true) {
                            $('#add_notification').fadeIn(300);
                            $('#add_notification').html('This product has been added to your <a href="/shop">cart</a>.')
                            $('#cart_count').html('('+response.cart_items+')');
                        } else {
                            $('#add_notification').html('There was an error while adding item to cart. Please refresh page').fadeIn(300);
                        }
                    }
                });
            }

            return false;
        });

        $('.removeItem').bind('click', function(e) {
            e.preventDefault();

            product_slug = e.currentTarget.id;
            price_opt    = e.currentTarget.rel;
            prod_type    = e.currentTarget.rev;
            parent_data  = '';
            if(prod_type == 'addon') {
                parent_data = $(this).attr('data-parent');
            }
            ajax_url     = base_url + 'shop/ajax_remove_from_cart/'
            ajax_param   = 'product_slug='+encodeURI(product_slug)+'&price_opt='+encodeURI(price_opt)+'&prod_type='+encodeURI(prod_type)+'&parent_data='+encodeURI(parent_data);

            //*** ask for confirmation
            result = confirm("Please confirm removal of " + product_slug);

            if(result === false) {
                return false;
            }

            //*** send ajax request
            $.ajax({
                url: ajax_url,
                dataType: 'json',
                type: 'POST',
                data: ajax_param,
                success: function(response) {
                    //console.log(response);
                    if(response.remove_result == true) {
                        main_holder = $('#'+product_slug+'-'+price_opt);
                        child_addons = product_slug + '|' + price_opt;
                        if(response.items_left == 0) {
                            $('tr[data-parent="' + child_addons + '"]').fadeOut(500);
                            $(main_holder).fadeOut(500, function() {
                                main_holder.html('');
                            });
                        } else {
                            $('.quantity', main_holder).html(response.items_left);
                            curr_price = parseFloat($('.item_tot_price', main_holder).html());
                            new_price = curr_price - response.single_price;
                            $('.item_tot_price', main_holder).html(roundNumber(new_price));
                        }
                        curr_total = parseFloat($('#total_amount').html());
                        new_total = curr_total - response.total_diff;
                        $('#total_amount').html(roundNumber(new_total));
                        $('#cart_count').html('(' + response.cart_items + ')');

                        if(response.cart_items == 0) {
                            window.location = base_url;
                        }

                    } else {
                //                    console.log(response.remove_message);
                }
                }
            });
        });


        var minDate = new Date();
        var maxDate = new Date();
        if(shop_closed_dates != undefined && shop_closed_dates != null) {
            minDate = $.datepicker.parseDate('M d yy', shop_closed_dates.min_day);
            maxDate = $.datepicker.parseDate('M d yy', shop_closed_dates.max_day);

        //        minDate = new Date(shop_closed_dates.min_day);
        //        maxDate = new Date(shop_closed_dates.max_day);
        }

        //*** delivery date datapicker
        $('#delivery_date').datepicker({
            dateFormat: 'dd MM yy',
            minDate: minDate,
            maxDate: maxDate,
            firstDay: 1,
            numberOfMonths: 2,
            beforeShowDay: function(date) {
                date_php_format = date.getDate() + " " + (date.getMonth()+1) + " " + date.getFullYear();
                if($.inArray(date_php_format, shop_closed_dates.closed_days) == -1) {
                    result = true;
                } else {
                    result = false;
                }

                return [result, '', ''];
            }
        });

        //*** disable billing_fields
        $('.billing_fields').attr('disabled', 'disabled');
        $('.customer_fields').bind('change', function() {
            elem_id = $(this).attr('id');
            target_id = elem_id.replace('customer_', 'billing_');
            field_type = 'input';
            if(elem_id == 'customer_title' || elem_id == 'customer_country') {
                field_type = 'select';
            }
            $('#'+target_id).val($(this).val());
        });

        //*** enable binding fields
        $('#use_customer').bind('change', function(e){
            state = $(this).attr('checked');
            console.log(state);
            switch(state) {
                case 'checked':
                case true:
                    $('#billing-box').show();
                    $('.billing_fields').removeAttr('disabled');
                    $('.customer_fields').unbind('change');
                    break;
                default:
                case false:
                    $('#billing-box').hide();
                    $('.billing_fields').attr('disabled', 'disabled');
                    $('.customer_fields').bind('change', function() {
                        elem_id = $(this).attr('id');
                        target_id = elem_id.replace('customer_', 'billing_');
                        field_type = 'input';
                        if(elem_id == 'customer_title' || elem_id == 'customer_country') {
                            field_type = 'select';
                        }
                        $('#'+target_id).val($(this).val());
                    });
                    $('#billing_title').val($('#customer_title').val());
                    $('#billing_name').val($('#customer_name').val());
                    $('#billing_lastname').val($('#customer_lastname').val());
                    $('#billing_address_1').val($('#customer_address_1').val());
                    $('#billing_address_2').val($('#customer_address_2').val());
                    $('#billing_city').val($('#customer_city').val());
                    $('#billing_county').val($('#customer_county').val());
                    $('#billing_postcode').val($('#customer_postcode').val());
                    $('#billing_country').val($('#customer_country').val());
                    $('#billing_phone').val($('#customer_phone').val());
                    $('#billing_email').val($('#customer_email').val());
                    break;
            }
        });
    });
	
});
 

