﻿jrcHandleForm = function (req, status, xhttp) {
    if (req.gelukt) {
        if (req.message) {
            alert(req.message);
        }
        if (req.redirect) {
            location.href = req.redirect;
        }
        if (req.refresh) {
            location.reload();
        }
    } else {
        if (req.exception) {
            $('div.exception', this.context).html(req.exception.message).show();

            if (req.exception.fields) {
                var that = this.context;
                for (var i = 0; i < req.exception.fields.length; i++) {
                    var n = req.exception.fields[i];
                    $('input[name=' + n + ']', this.context).css({ backgroundColor: '#FFCCCC' }).click(function () {
                        $(this).css('backgroundColor', null);
                    });
                }
            }
        }
    }
}

$(document).ready(function () {


    $('div.Breadcrumbs div.Breadcrumb:first > a').each(function () {
        var t = $('<img src="/Content/logo_small_gray.jpg" class="logo" />').hover(function () {
            $(this).attr('src', '/Content/logo_small.jpg');
        }, function () {
            $(this).attr('src', '/Content/logo_small_gray.jpg');
        });
        $(this).html('');
        $(this).append(t);
    });

    $('ul.JrcMenu li[haschild=true] > ul.Sub').each(function () {
        var that = this;

        //var c = $('<div class="crn tl"></div><div class="crn tr"></div><div class="crn bl"></div><div class="crn br"></div></div>');
        //c.prependTo($(this));



    if (!$(this).parent().parent().is('.JrcMenu')) {
        $(that).css({
            top: 0,
            right: -132
        });
    }

    var subconfig = {
        sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
        interval: 150, // number = milliseconds for onMouseOver polling interval    
        over: function () { $(that).show(); }, // function = onMouseOver callback (REQUIRED)    
        timeout: 250, // number = milliseconds delay before onMouseOut    
        out: function () { $(that).hide(); } // function = onMouseOut callback (REQUIRED)    
    };
    $(that).parent().hoverIntent(subconfig);

    //        $(that).parent().hover(function() {
    //            $(that).show();
    //        }, function() {
    //            $(that).hide();
    //        });
});

$('#search').autocomplete('/Ajax/Search', {
    mustMatch: false,
    width: 225,
    scrollHeight: 250,
    selectFirst: false,
    formatItem: function (data) {
        var name = data[0];
        var catname = data[1];

        var prd = data[2];
        var imageurl = data[3];
        return name + '|' + catname + '|' + prd + '|' + imageurl;
    },
    highlight: function (item, q) {
        var data = item.split('|');
        var name = data[0].replace(q, '<strong>' + q + '</strong>');
        var catname = data[1].replace(q, '<strong>' + q + '</strong>');

        var fname = name.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + q.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong><u>$1</u></strong>");
        var fcatname = catname.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + q.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong><u>$1</u></strong>");
        var prd = data[2];
        var imageurl = data[3];
        return '<span class="product">' + fname + '</span> <span class="productcategory">' + fcatname + '</span> <span class="productid">' + prd + '</span> <span class="productimage"><img src="' + imageurl + '" /></span>';
        return data;
    },
    formatResult: function (data) {
        return data[0];
    }
})
    .result(function (event, data, formatted) {
        if (data) {
            var name = data[0];
            var catname = data[1];
            var prd = data[2];
            var imageurl = data[3];
            $('#search_prd').val(prd)[0].form.submit();
        }
    });
});





/**
 BASKET
 **/
jQuery.fn.basket = function (p) {
    return this.each(function () {
        var that = $(this);
        var tthat = this;

        this.basketType = 'default';

        if (p.basketType) this.basketType = p.basketType; // 'default or items

        this.jb_items = [];
        this.jb_total = 0;
        this.jb_ic = $('<div />');
        this.jb_tcc = $('<div />').css({ display: 'none' });
        this.jb_tc = $('<span />');
        this.jb_cc = $('<div />').attr('class', 'content');
        this.jb_ac = $('<div />').css({
            position: 'absolute',
            display: 'none',
            backgroundColor: '#ffffff',
            border: 'solid 1px #4f4f4f',
            padding: '8px'
        }).append($('<input />').attr({
            type: 'text',
            value: 0
        })).append($('<input />').click(function () {
            $(this).prev().val('0');
            tthat.jb_p = null;
            $(this).parent().parent().hide();
        }).attr({
            type: 'button',
            value: 'cancel'
        })).append($('<input />').click(function () {
            var o = tthat.jb_p;
            var t = $(this).prev().prev();
            o.amount = parseInt(t.val());
            that.addToBasket(o);
            tthat.jb_p = null;
            $(this).parent().parent().hide();
            t.val('0');
        }).attr({
            type: 'button',
            value: 'add'
        }))
        .append($('<div />')
            .addClass('message')
            .css({
                backgroundColor: '#fff',
                position: 'absolute',
                bottom: '-36px',
                left: '0px',
                border: 'solid 1px black',
                borderTopColor: 'white'
            }))
            .append($('<div />').addClass('clear'));

        var settings = {
            tl: { radius: 4 },
            tr: { radius: 4 },
            bl: { radius: 4 },
            br: { radius: 4 },
            antiAlias: true
        }
        $('body').append(this.jb_ac);

        curvyCorners(settings, this.jb_ac[0]);


        this.jb_cc.append(this.jb_ic);
        this.jb_cc.append(this.jb_tcc);

        if (p && p.message) {
            this.jb_cc.append($('<div />').attr('class', 'submessage').html(p.message));
        }

        switch (this.basketType) {
            case 'default':
                {
                    this.jb_tcc.append('Total: &euro;');
                    this.jb_tcc.append(this.jb_tc);

                    this.jb_cc.append($('<a />').click(function () {
                        $('html,body').animate({ scrollTop: $("#order").offset().top }, 'slow', 'easeInOutQuint');
                    }).attr({
                        href: 'javascript:;'
                    }).html('scroll down'));

                    this.jb_refresh = function () {
                        tthat.jb_ic.html('');
                        var t = 0;
                        for (var i in tthat.jb_items) {
                            var item = tthat.jb_items[i];

                            t += item.amount * item.price;
                            var removelink = $('<a />').css({ float: 'right', cursor: 'pointer' }).click(function () {
                                that.removeFromBasket(item.id);
                            }).html('x');
                            var idiv = $('<div>' + item.amount + 'x ' + item.name + '</div>');
                            idiv.append(removelink);
                            tthat.jb_ic.append(idiv);
                        }
                        if (t == 0) {
                            tthat.jb_tcc.hide();
                        } else {
                            tthat.jb_tc.html(t);
                            tthat.jb_tcc.show();
                        }

                    }

                    var to = that.offset().top;
                    var cur = 0;

                    $(window).scroll(function () {
                        var s = $(window).scrollTop();
                        var m = 0;

                        if (s > to) {
                            m = s - to + 50;
                        }
                        if (cur != m) {
                            var dif = Math.abs(cur - m);
                            cur = m;
                            that.stop().animate({
                                top: m
                            }, dif + 1000, 'easeOutExpo');
                        }
                    });

                    break;
                }
            case 'calendar':
                {
                    this.jb_refresh = function () {
                        tthat.jb_ic.html('');
                        for (var i in tthat.jb_items) {
                            var item = tthat.jb_items[i];
                            var idiv = $('<div>' + item.name + '</div>').attr('jb_id', item.id);
                            var removelink = $('<a />').css({ float: 'right', cursor: 'pointer' }).click(function () {
                                that.removeFromBasket($(this).parent().attr('jb_id'));
                            }).html('x');

                            idiv.append(removelink);
                            tthat.jb_ic.append(idiv);
                        }
                    }
                    break;
                }
        }

        that.append($('<div />').attr('class', 'header'));
        that.append(this.jb_cc);
        that.append($('<div />').attr('class', 'bottom'));
        that.attr('class', 'JrcBasket');


    });
};

jQuery.fn.getBasketInfo = function () {
    var that = this[0];
    var ret = {
        keys: [],
        amounts: []
    }

    for (var i in that.jb_items) {
        if (that.jb_items[i].amount > 0) {
            ret.keys[ret.keys.length] = that.jb_items[i].id;
            ret.amounts[ret.amounts.length] = that.jb_items[i].amount;
        }
    }

    return ret;
}

jQuery.fn.getBasketAmount = function (p) {
    return this.each(function () {
        if (!p) return;
        var b = $('#' + p.basket)[0];
        b.jb_p = p;

        var top, left;
        if (this.pageX && this.pageY) {
            top = this.pageY;
            left = this.pageX;
        } else {
            top = $(this).offset().top;
            left = $(this).offset().left;
        }

        top -= 10;

        if (typeof p.available != "undefined") {
            if (p.available <= 0) {
                $('.message', b.jb_ac).html(
                'Please check your order acknowledgement for delivery date.').show();
            } else {
                $('.message', b.jb_ac).hide();
            }
        } else {
            $('.message', b.jb_ac).hide();
        }


        b.jb_ac.css({
            top: top,
            left: left
        }).show();
        $('input:first', b.jb_ac).focus();


    });
}

var traineeCounter = 0;
function refreshTrainees() {
    traineeCounter = 0;
    var tru = new RegExp("trainees\[[0-9]+\]","g");

    $('#trainees div.ttrainees div').each(function () {
        var old = $(this).html();
        var replaced = old.replace(tru, "trainees[" + traineeCounter + "]");
        $(this).html(replaced);
        traineeCounter++;
    });
}

jQuery.fn.addToBasket = function (p, ce) {
    return this.each(function () {
        if (!p) return;

        if (p.amount <= 0) {
            $(this).removeFromBasket(p.id);
        } else {
            var pid = 'jb_' + p.id;

            if (!(pid in this.jb_items) && this.basketType == 'calendar') {
                var template = $('#trainingtemplate').html();

                template = template.replace("{pid}", pid);
                template = template.replace("{trainingid}", p.id);
                template = template.replace("{trainingid}", p.id); //double required

                template = template.replace("{from}", $.format.date(ce.start, 'dd-MM-yyyy'));
                if (ce.end) {
                    template = template.replace("{to}", $.format.date(ce.end, ' - dd-MM-yyyy'));
                } else {
                    template = template.replace("{to}", '');
                }

                template = template.replace("{name}", p.name);


                $training = $(template);
                $('#trainees').append($training);
            }
            this.jb_items[pid] = p;
            this.jb_refresh();
        }
    });
}

jQuery.fn.removeFromBasket = function (id) {
    return this.each(function () {
        var pid = 'jb_' + id;

        //Calendar helper
        if (pid in this.jb_items && this.basketType == 'calendar') {
            $('#trainees div[pid=' + pid + ']').remove();
            refreshTrainees();
        }


        delete this.jb_items[pid];
        this.jb_refresh();
    });
}

$.fn.jrcClearFilters = function() {
    return this.each(function() {
        var that = this;
        
        $('div.Filters div.Filter', this.jFilterContainer).each(function() {
            if($(this).hasClass('FilterSelected')) $(that).jrcRemoveFilter(this);
            that.jFilterCount = 0;
        });
        
        $('div.Filters div.FilterMultiple div.Values div.Value', this.jFilterContainer).each(function() {
            if($(this).hasClass('FilterSelected')) $(that).jrcRemoveFilter(this);
            that.jFilterCount = [];
        });
        
        
        $('div.ClearAll div.Filter', this.jFilterContainer).addClass('FilterSelected');
    });
}

$.fn.jrcAddFilter = function(filter) {
    return this.each(function() {
        $(filter).addClass('FilterSelected');
        switch(this.jFilterType) {
            case 'single' : {
                this.jFilterCount++;
                this.jFilters[$(filter).attr('jrcfiltername')] = true;
                $('div.ClearAll div.Filter', this.jFilterContainer).removeClass('FilterSelected');
                break;
            }
            case 'multiple' : {
                var filterName = '';
                if(this.jCurvy) {                    
                    filterName = $(filter).parent().parent().parent().attr('jrcfiltername');
                } else {
                    filterName = $(filter).parent().parent().attr('jrcfiltername');
                }
                
                var filterValue = $(filter).attr('jrcfiltervalue');
                if(!this.jFilters[filterName]) {
                    this.jFilters[filterName] = '';
                    if(!this.jFilterCount) this.jFilterCount = [];
                    this.jFilterCount[filterName] = 0;
                }
                this.jFilterCount[filterName]++;
                this.jFilters[filterName] += filterValue + '|';
                $('div.ClearAll div.Filter', this.jFilterContainer).removeClass('FilterSelected');
                
                if(this.jCurvy) {                    
                    $(filter).parent().parent().parent().addClass('FilterMultipleSelected');
                } else {
                    $(filter).parent().parent().addClass('FilterMultipleSelected');
                }
                
                
                break;
            }
        }
        
        
        $(this).jrcUpdateFilterList();
    });
}

$.fn.jrcRemoveFilter = function(filter) {
    return this.each(function() {
        $(filter).removeClass('FilterSelected');
        
        switch(this.jFilterType) {
            case 'single' : {
                this.jFilterCount--;
                delete this.jFilters[$(filter).attr('jrcfiltername')];
                $(filter).removeClass('FilterActive');
                if(this.jFilterCount <= 0) {
                    $(this).jrcClearFilters();
                }
                break;
            }
            case 'multiple' : {
                var filterName = '';
                filterName = $(filter).parent().parent().parent().attr('jrcfiltername');
           
                var filterValue = $(filter).attr('jrcfiltervalue');
                var totalvalues = this.jFilters[filterName];
                
                this.jFilters[filterName] = totalvalues.replace(filterValue + '|', '');
                
                if(totalvalues.length != this.jFilters[filterName].length) {
                    this.jFilterCount[filterName]--;
                }
                
                if(this.jFilters[filterName].length == 0) {
                    delete this.jFilters[filterName];
                    $(filter).parent().parent().parent().removeClass('FilterMultipleSelected');
                }
                
                var fcount = 0;
                for(var fname in this.jFilterCount) {
                    fcount += this.jFilterCount[fname];
                }
                
                if(fcount == 0) {
                    $(this).jrcClearFilters();
                }
                
                break;
            }
        }
        
        
        $(this).jrcUpdateFilterList();
    });
}

$.fn.jrcUpdateFilterList = function () {
    return this.each(function () {
        var that = this;
        var values = [];
        var visible = 0;


        switch (that.jFilterType) {
            case 'single':
                {
                    for (var fname in that.jFilters) {
                        if (that.jFilters[fname]) {
                            values.push($('div.Filter[jrcfiltername=' + fname + ']', that.filterContainer).attr('jrcfiltervalue'));
                        }
                    }

                    $(this.jSelector, this).each(function () {
                        var val = $(this).attr('jrcfilter').toString();
                        var show = false;
                        if (that.jFilterCount <= 0) {
                            show = true;
                        } else {
                            for (var i in values) {
                                if (val == values[i]) show = true;
                            }
                        }

                        if (show) {
                            visible++;
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                    break;
                }
            case 'multiple':
                {
                    for (var fname in that.jFilters) {
                        if (that.jFilters[fname]) {
                            values[fname] = that.jFilters[fname].split('|');
                        }
                    }

                    $(this.jSelector, this).each(function () {
                        var showme = true;
                        for (var fname in values) {
                            var fcount = that.jFilterCount[fname];
                            var subshow;

                            if (!fcount) {
                                subshow = true;
                            } else {
                                var valmini = $(this).attr('jrcfilter_' + fname);

                                if (!valmini) {
                                    subshow = false;
                                } else {
                                    subshow = false;
                                    for (var i in values) {
                                        for (var ii = 0; ii < values[i].length; ii++) {
                                            if (values[i][ii] == valmini.replace('|', '')) {
                                                subshow = true;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!subshow) {
                                showme = false;
                            }
                        }

                        if (showme) {
                            visible++;
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                    break;
                }
        }

        if (visible == 0) {
            $(that).next('div.no-results').show();
        } else {
            $(that).next('div.no-results').hide();
        }

    });
}

$.fn.jrcToggleFilter = function(filter) {
    return this.each(function() {
        $(filter).hasClass('FilterSelected') ? $(this).jrcRemoveFilter(filter) : $(this).jrcAddFilter(filter);
    });
}

$.fn.jrcFilter = function(o) {
    return this.each(function() {
        settings = jQuery.extend({
            selector: '.JrcFilterable',
            filterSelector : '#newsfilter',
            filterType : 'single'
        }, o);
        
        var container = this;
        
        container.jSelector = settings.selector;
        container.jFilters = [];
        container.jFilterType = settings.filterType;
        
        
        switch(container.jFiltertype) {
            case 'single' : {
                container.jFilterCount = 0;
                break;
            }
            case 'multiple' : {
                container.jFilterCount = [];
                break;
            }
        }

        $(settings.filterSelector).each(function() {
            var that = this;
            container.jFilterContainer = this;
            
            $('div.Filter', this).each(function() {
                $(this).hover(function() {
                    $(this).addClass('FilterActive');
                },function() {
                    $(this).removeClass('FilterActive');
                });
            });
            
            $('div.FilterMultiple', this).each(function() {
                this.val = $('div.Values',this)[0];
                container.jCurvy = $(this.val).hasClass('curvy');
 
                
                $(this).hover(function() {
                    $(this).addClass('FilterMultipleActive');
                },function() {
                    $(this).removeClass('FilterMultipleActive');
                });
            });
            
            $('div.ClearAll div.Filter', this).click(function(){ 
                $(container).jrcClearFilters(this);
            });
            
            $('div.Filters div.Filter', this).click(function() {
                $(container).jrcToggleFilter(this);
            });
            
            $('div.Filters div.FilterMultiple div.Values div.Value').click(function() {
                $(container).jrcToggleFilter(this);
            });
        });
    });
}


$.fn.watermark = function (css, text) {
    return this.each(function () {
        var i = $(this), w;
        i.focus(function () {
            w && !(w = 0) && i.removeClass(css).data('w', 0).val('');
        })
		.blur(function () {
			!i.val() && (w = 1) && i.addClass(css).data('w', 1).val(text);
		})
		.closest('form').submit(function () {
			w && i.val('');
		});
        i.blur();
    });
};
$.fn.removeWatermark = function () {
    return this.each(function () {
        $(this).data('w') && $(this).val('');
    });
};

slug = function (str) {
    str = str.replace(/^\s+|\s+$/g, ''); // trim

    str = str.replace(/ /g, '-');
    str = str.replace(/[^a-zA-Z0-9\s]/g, '-');
    //str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars

    //.replace(/-+/g, '-'); // collapse dashes
    return str;
}
