$(document).ready(function(){
    $(document).pngFix();
    $("#nav li").hover(
        function () {
            $(this).css('backgroundColor','#81ca07');
        },
        function () {
            $(this).css('backgroundColor','transparent');
        }
        );
        
    $("#loginmenu li").hover(
        function () {
            $(this).css('backgroundColor','#81ca07');
        },
        function () {
            $(this).css('backgroundColor','transparent');
        }
        );
    initProductieSlider();
    initPromoSlider();
});

function initProductieSlider() {
    if($('#productie_menu')!=null) {
        $('#productie_menu li').hover(
            function () {
                $(this).css('backgroundColor','#81ca07');
            },
            function () {
                $(this).css('backgroundColor','#252525');
            }
            );
        activeSlide = 1;
    }
}

var promoSliderCounter = 1;
function initPromoSlider() {
    if($('#promo_slider').length) {
        $('#promo_slider').stop();
        promoSliderCounter = 1;
        var itemLength = $("#promo_slider > li").length;
        var dir = 1;

        var setSlide = function() {
            if(itemLength == promoSliderCounter-1)
                dir = 0;
            if(promoSliderCounter==0)
                dir = 1;
        
            $('#promo_slider').scrollTo({
                top: 220 * promoSliderCounter,
                left:0
            }, 500);
        
            if(dir==1)
                promoSliderCounter++;
            else
                promoSliderCounter--;
        }
    
        setInterval(setSlide, 5000);
    }
}

function setProductieBackground(i) {
    if($('#productie_slider').length) {
        $('#productie_slider').stop();
        $('#productie_slider').scrollTo('#slider_'+i+' img',700);

        $('#productie_info div').css('display','none');
        $('#info_'+i).css('display','block');
    }
}

function addDefaultText(element) {
    if(element.value == element.defaultValue)
        element.value = '';
    element.onblur = function() {
        if(element.value == '')
            element.value = element.defaultValue;
    }
}

function checkInputForm(ele) {
    var td = ele.parentNode;
    if(ele.value!='' && ele.value.length >= 3) {
        showMark(td, true);
    }
    else
        showMark(td, false);
}

function checkInputEmail(ele){
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if (pattern.test(ele.value))
        showMark(ele.parentNode, true);
    else
        showMark(ele.parentNode, false);
}

function showMark(td, correct) {
    var img = null;
    if(td.innerHTML.indexOf('img') >= 0) {
        var elements = td.getElementsByTagName('img');
        img = elements[0];
    }
    else {
        img = document.createElement('img');
        img.marginTop = '5px';
        td.appendChild(img);
    }

    if(correct) {
        img.alt = 'Ok';
        img.src = '../../img/icons/ok.jpg';
    }
    else {
        img.alt = 'Not Ok';
        img.src = '../../img/icons/cancel.jpg';
    }
}

function setTabActive(li, ele, ele2) {
    $('.zoekdiv').animate({
        color:"white"
    }, 300, function() {
        document.getElementById(ele2).style.display = 'none';
        document.getElementById(ele).style.display = 'block';

        $('#zoek_top').find('li>a').attr('class','');
        $('#'+li).find('a').attr('class','selected');

        $('#results').hide(350, function() {
            $(this).attr('innerHTML','');
        });
        
        $('.zoekdiv').animate({
            color:"black"
        }, 300 );

        var childs = document.getElementById(ele).getElementsByTagName('input')
        for(var i = 0; i < childs.length; i++) {
            if(childs[i].type=='text') {
                childs[i].focus();
                childs[i].select();
                childs[i].value = '';
            }
        }
    } );
}

function setActiveTab(li, ele) {
    $('.zoekdiv').stop(true,true);
    $('#menu_tabbed').find('li>a').attr('class','');
    $('.zoekdiv').css('display', 'none')
    $('#'+li).find('a').attr('class','selected');
    $('#'+ele).css('display', 'block')
}

function addToOfferteNoKlant(ele, urls, vrij, art_id, print_id) {
    var gotourl = urls+"index.php/site/addtocart";
    var postdata = {
        addtoofferte: true,
        vrijveld: vrij,
        artikelen_id: art_id,
        printer_id: print_id
    };
    
    $.ajax({
        type: "POST",
        url: gotourl,
        data: postdata,
        success: function(html) {
            $("#prijsaanvraag_small").html(html);
            $(ele.parentNode.parentNode.parentNode).effect("bounce", {
                times:4,
                direction: 'down',
                distance: 20
            }, 300);
            $(ele.parentNode).css('font-size','12px');
            $(ele.parentNode).html('<strong>'+$("#addedtoorder").val()+'</strong>').animate({
                "color" : "green"
            },500).animate({
                "color" : "#121212"
            },500);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Error adding product to basket, please try again.');
        }
    });
}

function addToIntroductionOrder(ele, urls, vrij, art_id) {
    var gotourl = urls+"index.php/introduction/addtoorder";
    var postdata = {
        addtoofferte: true,
        vrijveld: vrij,
        artikelen_id: art_id
    };
    
    $.ajax({
        type: "POST",
        url: gotourl,
        data: postdata,
        success: function(html) {
            $("#prijsaanvraag_small").html(html);
            $(ele.parentNode.parentNode.parentNode).effect("bounce", {
                times:4,
                direction: 'down',
                distance: 20
            }, 300);
            $(ele.parentNode).css('font-size','12px');
            $(ele.parentNode).html('<strong>'+$("#addedtoorder").val()+'</strong>').animate({
                "color" : "green"
            },500).animate({
                "color" : "#121212"
            },500);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Error adding product to basket, please try again.');
        }
    });
}

function cartRemove(ele, urls, rowid) {
    var tr = ele.parentNode.parentNode;
    var tablebody = tr.parentNode;
    var urlstring = urls+'index.php/site/removefromcart/'+rowid;
    
    $.ajax({
        type: "POST",
        url: urlstring,
        data: "id="+rowid,
        success: function() {
            $(tr).animate( {
                backgroundColor:"darkorange"
            }, 500 ).fadeOut(300, function() {
                $(tr).remove();
                for(var i = 0; i < tablebody.rows.length; i++) {
                    if(i%2==0)
                        $(tablebody.rows[i]).attr("class","even");
                    else
                        $(tablebody.rows[i]).attr("class","oneven");
                }
            });
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Could not remove..');
        }
    });
}

function removeFromIntroduction(ele, urls, rowid) {
    var tr = ele.parentNode.parentNode;
    var tablebody = tr.parentNode;
    var urlstring = urls+'index.php/introduction/removefromorder/'+rowid;
    
    $.ajax({
        type: "POST",
        url: urlstring,
        data: "id="+rowid,
        success: function() {
            $(tr).animate( {
                backgroundColor:"darkorange"
            }, 500 ).fadeOut(300, function() {
                $(tr).remove();
                for(var i = 0; i < tablebody.rows.length; i++) {
                    if(i%2==0)
                        $(tablebody.rows[i]).attr("class","even");
                    else
                        $(tablebody.rows[i]).attr("class","oneven");
                }
            });
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Could not remove..');
        }
    });
}

function addToOfferte(ele, urls, vrij, art_id, print_id)
{
    var gotourl = urls+"index.php/shop/addtoofferte";
    var postdata = {
        addtoofferte: true,
        vrijveld: vrij,
        artikelen_id: art_id,
        printer_id: print_id
    };

    $.ajax({
        type: "POST",
        url: gotourl,
        data: postdata,
        success: function(html) {
            $("#prijsaanvraag_small").html(html);
            $(ele).attr('disabled','disabled');
            $(ele).blur();
        },
        error: function(xhr, ajaxOptions, thrownError) {
            $(ele).css('background-color','red');
        }
    });
}

function removeFromOfferte(ele, urls, rowid) {
    var tr = ele.parentNode.parentNode;
    var tablebody = tr.parentNode;
    var urlstring = urls+'index.php/shop/removefromofferte/'+rowid;
    var postdata = {
        removefromofferte: true,
        id: rowid
    };

    $.ajax({
        type: "POST",
        url: urlstring,
        data: postdata,
        success: function() {
            $(tr).animate( {
                backgroundColor:"darkorange"
            }, 500 ).fadeOut(300, function() {
                $(tr).remove();
                for(var i = 0; i < tablebody.rows.length; i++) {
                    if(i%2==0)
                        $(tablebody.rows[i]).attr("class","even");
                    else
                        $(tablebody.rows[i]).attr("class","oneven");
                }
            });
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Could not remove..');
        }
    });
}

function addToOrder(ele, urls, vrij, art_id, price)
{
    var nodes = ele.parentNode.childNodes;
    var number = 0;
    for(var x = 0; x < nodes.length; x++) {
        var node = nodes[x];
        if(node.className=='add_aantal') {
            number = node.value;
        }
    }
    
    if(price==null)
        price = 0;
    var gotourl = urls+"index.php/shop/addtoorder";
    var postdata = {
        addtoorder: true,
        vrijveld: vrij,
        artikelen_id: art_id,
        prijs: price,
        aantal: number
    };
    
    $.ajax({
        type: "POST",
        url: gotourl,
        data: postdata,
        success: function(html) {
            $("#order_small").html(html);
            $(ele).attr('disabled','disabled');
            $(ele).blur();

            $("#webshop_sum").animate({
                "backgroundColor" : "rgb(199,249,150)"
            },600).animate({
                "backgroundColor" : "#FFF"
            },250);
            $("#countorderrows").animate({
                "fontSize" : "26px"
            },500).animate({
                "fontSize" : "16px",
                "color" : "#222"
            },300);
            $(ele.parentNode).css('color','green');
            $(ele.parentNode).animate({
                "fontSize" : "20px"
            },500).animate({
                "fontSize" : "14px",
                "color" : "#222"
            },300);
            $(ele.parentNode).html('<strong>'+$("#addedtoorder").val()+'</strong>');
            
        //ele.parentNode.innerHTML = ele.parentNode.innerHTML + ' <strong>Artikel toegevoegd.</strong>';
            
        },
        error: function(xhr, ajaxOptions, thrownError) {
            $(ele).css('background-color','red');
        }
    });
}

//FILTERS
function resetCheckBoxFilter(ele, id) {
    if(ele!=null) {
        var isChecked = ele.checked;
        $("#product_group input[type='checkbox']").attr('checked', false);
        ele.checked = isChecked;
    }
    else {
        $("#product_group input[type='checkbox']").attr('checked', false);
    }
}

function showAanbevelingen() {
    $('#consult_printers').hide();
    $('#consult_grid').hide();
    $('#aanbeveling_grid').show();
}

function searchWithMerkConsultFilter(ele) {
    resetCheckBoxFilter(ele, 'consult_filter');
    $('#consult_printers').hide();
    $('#aanbeveling_grid').hide();
    $('#consult_grid').show();

    $('#consult_grid .grid_item').hide();
    $('#consult_filter input:checkbox:checked').each(function() {
        var filter = $(this).val();
        $('#consult_grid .grid_item input:hidden[name=item_merk[]]').each(function() {
            if($(this).val()==filter)
                $(this).parent().show();
        });
    });
}

function searchWithMerkPrinterFilter(ele) {
    resetCheckBoxFilter(ele, 'printer_filter');
    $('#consult_grid').hide();
    $('#aanbeveling_grid').hide();
    $('#consult_printers').show();

    $('#consult_printers .printer_line').hide();
    $('#printer_filter input:checkbox:checked').each(function() {
        var filter = $(this).val();
        $('#consult_printers .printer_line input:hidden[name=item_merk[]]').each(function() {
            if($(this).val()==filter)
                $(this).parent().show();
        });
    });
}

function showConsultGroup(id) {
    $('#consult_grid').hide();
    $('#consult_printers').hide();
    $(id).show();
}

function filterProductTable(id,searchValue) {
    searchValue = searchValue.toUpperCase();

    var totaantal = 0;
    var totbedrag = 0;

    $('#'+ id + ' tbody tr').each(function() {
        var td = $(this).children('td:eq(0)');
        var text = td.children().first().html().toUpperCase();
        if(text.indexOf(searchValue) >= 0) {
            $(this).show();

            totaantal += parseInt($(this).find('.qty').first().val());
            totbedrag += parseFloat($(this).find('.bedrag').first().val());
        }
        else {
            $(this).hide();
        }
    });

    $('#tot_aantal').html(Math.round(totaantal));
    $('#tot_bedrag').html('&euro; ' + (Math.round(totbedrag * 100, 2) / 100).toFixed(2));
}
