﻿$(function () {
    EM.modelDetailUrlPrefix = 'details-';
    if ($.History) {
        //start disable history support
        $.History.navigateTo = $.noop;
        //$.History.bind = $.noop;
        //$.History.unbind = $.noop;
        //end disable history support


        //enable google analytics:
        var navigateToProxy = $.History.navigateTo;
        $.History.navigateTo = function (url) {
            if (url.indexOf('/') !== 0) {
                url = '/' + url;
            }
            //push url to analytics 
            _gaq.push(['_trackPageview', url]);
            navigateToProxy.apply(this, arguments);
        };

        $.History.alwaysMonitorHashChanges = true;
        //catch the "initial" hashchange for html5 browsers
        $.History.bind('hashchange', function (url, relativeUrl) {
            if (relativeUrl) {
                //remove listener
                $.History.unbind('hashchange', arguments.callee);
                //handle
                handleUrl(relativeUrl);
            }
        });
        $.History.bind('change', function (url, relativeUrl) {
            if (relativeUrl) {
                //handle 
                handleUrl(relativeUrl);
            }
        });

        function handleUrl(url) {
            var hashbang = url.indexOf('#!');
            if (hashbang > 0) {
                url = url.substr(hashbang + 2);
            }


            if (url.indexOf(EM.modelDetailUrlPrefix) === 0) {
                var modelId = url.substring(EM.modelDetailUrlPrefix.length, url.indexOf('.'));
                EM.Lightbox.showModelDetailsImpl({}, modelId);
            } else if (url == 'default.aspx' || url == 'Default.aspx') {
                if (EM.closeDetailOverlay) {
                    EM.closeDetailOverlay();
                }
            }
        }
        //bootstrap
        $('<div />').history();
    }
});
EM.Lightbox = {
    models: [],
    modelDetailHandler: 'pages/v2/ModelDetailHandler.ashx',
    mailHandler: 'pages/v2/MailModelHandler.ashx',
    lightboxHandler: 'pages/v2/LightboxHandler.ashx',
    pdfUrl: 'pages/v2/LightboxPdf.aspx',
    offerteUrl: 'Offerte.aspx',

    containsModel: function (modelId) {
        var models = this.models;
        for (var i = 0; i < models.length; i++) {
            if (models[i].id === modelId) {
                return true;
            }
        }
        return false;
    },
    init: function () {
        EM.tooltipCache = {};
        var lightboxContainer = $('.mylightbox');
        this.enabled = (lightboxContainer.length > 0);
        if (EM.msie) {
            lightboxContainer.addClass('msie ie' + EM.msieVersion);
        }
        if (this.enabled) {
            this.setupLightboxButtons();
            this.repaintLightbox();
        }
    },
    onLightboxChanged: function () {
        var right = $('#main > .right');
        var h1 = parseInt($('#main > .left').height(), 10);
        var h2 = parseInt(right.height(), 10); ;
        if (h2 < h1) {
            right.css('min-height', h1 + 'px');

        }
    },
    refreshDetailFont: function (controlLabelOnly) {
        if (controlLabelOnly) {
            Cufon.refresh('.model_detail .control_label');
        } else {
            //Cufon.replace('.model_detail .md_detail');
            //Cufon.replace('.md_detail div.name, .md_detail div.info, .md_detail ul span.label, .md_detail ul span.value');
            Cufon.replace('.md_detail div.name, .md_detail div.info, .md_detail li, .model_detail .control_label');
            Cufon.replace('.model_detail .control_label');
        }
    },
    refreshTooltipFonts: function () {
        //Cufon.replace('.modelTooltip h3,.modelTooltip .details span');
        Cufon.replace('.modelTooltip');
    },
    downloadModels: function () {
        var modelIds = [];
        for (var i = 0; i < this.models.length; i++) {
            modelIds.push(this.models[i].id);
        }
        document.location.href = EM.root + this.pdfUrl + "?download=1&models=" + encodeURIComponent(modelIds.join(','));
    },
    downloadModel: function (modelId) {
        document.location.href = EM.root + this.pdfUrl + "?download=1&models=" + encodeURIComponent(modelId);
    },
    makeOfferte: function (optionalModelId) {
        var url = EM.root + this.offerteUrl;

        if (optionalModelId) {
            url += '?modelId=' + encodeURIComponent(optionalModelId);
        } else if (this.models.length == 0) {
            //no models, cancel
            return;
        }
        document.location.href = url;
    },
    /** Add a model to the lightbox */
    addModel: function (modelId) {
        //store
        if (this.containsModel(modelId)) {
            return;
        }

        EM.ajaxPost(this.lightboxHandler, { action: 'add', modelId: modelId });

        this.models.push({ id: modelId });
        this.repaintLightbox();

    },
    /** Remove a model from the lightbox */
    removeModel: function (modelId) {
        EM.ajaxPost(this.lightboxHandler, { action: 'remove', modelId: modelId });

        var models = this.models,
            m = [];
        for (var i = 0; i < models.length; i++) {
            if (models[i].id !== modelId) {
                m.push(models[i]);
            }
        }
        this.models = m;
        this.repaintLightbox();
    },
    /** 
    * Search by modelId. Use the specifications of the selected model to find simular matches
    * @param modelId
    */
    searchByModel: function (modelId) {
        var me = this;
        EM.ModelSearch.searchByModel(modelId);
        //if we search because a model is placed in the searchbox, then make sure
        //the match "line" is updated to reflect a complete match
        setTimeout(function () {
            //        $('.modellist .first .match').css({
            //            'background-position': '0px top',
            //            display: 'block'
            //        }).show();
            $('.modellist .first .match').css({
                'background-position': '0px top',
                display: 'block'
            }).hide();
            $('.modellist .first .modelFrame').click(function (e) {
                var x = (e.layerX || e.offsetX);
                var y = (e.layerY || e.offsetY);
                if (x < 100 || y > 22) {
                    var modelId = $(this).parents('.model').find('.modelimg').attr('data-modelid');
                    me.showModelDetails(e, modelId);
                    return;
                }

                setTimeout(function () {
                    EM.ModelSearch.searchByFilters();
                }, 0);
                $('.modellist .first *').remove();
                return false;
            });
        }, 0);


    },

    /* sets up the lightbox for use on any normal page 
    * render the selected items
    */
    repaintLightbox: function () {
        var lb = $('div.mylightbox');
        var modelContainer = lb.find('.models');

        if (this.models.length == 0) {
            lb.addClass('lightbox_empty');
        } else {
            lb.removeClass('lightbox_empty');
        }


        //remove old
        modelContainer.find('.model').remove();

        var models = EM.Lightbox.models;
        //add entries
        if (models.length > 0) {
            $('#lb_model_tmpl').tmpl({ root: EM.root, models: models })
                .appendTo(modelContainer);
        }
        //fill the remaining spaces with empty boxes
        var remaining = (models.length < 4) ? (4 - models.length) : (models.length % 2);
        if (models.length > 3 && remaining == 0) { remaining = 2; }
        if (remaining > 0) {
            var empty = [];
            for (var i = 0; i < remaining; i++) { empty.push({}); }

            $('#lb_model_empty_tmpl').tmpl({ root: this.root, startCounter: models.length, models: empty }).appendTo(modelContainer); ;
        }
        if (EM.ModelSearch && EM.ModelSearch.DND) {
            EM.ModelSearch.DND.refreshLightbox();
        }
        this.onLightboxChanged();
    },
    setupRolloverButtons: function (selector, scope, handler) {
        var me = this;
        /* buttons with the class "rollover" store the hover image in the data-rolloverimg attribute */
        if (!handler) {
            handler = function () {
                var parents = $(this).parents('div.mylightbox');
                if (parents.length > 0 && parents.hasClass('lightbox_empty')) {
                    return;
                }

                var lnk = $(this).attr('href');
                if (lnk) {
                    document.location.href = lnk;
                    return false;
                }
                var action = $(this).attr('data-action');
                switch (action) {
                    case 'offerte':
                        me.makeOfferte();
                        break;
                    case 'download':
                        me.downloadModels();
                        break;
                    default:
                        break;
                }
            };
        }
        $(selector, scope).hover(function () {
            var newImg = $(this).attr('data-rolloverimg');
            if (newImg) {
                if (!this.origSrc) { this.origSrc = this.src; };
                this.src = $(this).attr('data-rolloverimg');
            }
        }, function () {
            if (this.origSrc) {
                this.src = this.origSrc;
            }
        }).css('cursor', 'pointer')
          .click(handler);
    },
    /** handle clicks, add/remove buttons etc */
    setupLightboxButtons: function () {
        var self = this;
        //make sure the 'tooltip' element is attached directly to the body
        $('div.modelTooltip').detach().appendTo('body');
        //setup buttons
        this.setupRolloverButtons('.mylightbox .rollover');

        /* add hover listener to the models in the lightbox
        and also for the main page
        */
        var tooltipActive = false;
        $('.modellist')
            .delegate('.model', 'mousemove', function (e) {
                if (!tooltipActive) { return; }
                var x = e.pageX;
                var y = e.pageY;
                x += 10; y += 10;
                var tt = $('div.modelTooltip');

                var ttWidth = parseInt(tt.width(), 10);
                var maxX = parseInt($(window).width(), 10) - ttWidth;
                if (x > maxX) {
                    //snap to the other side of th mouse button
                    x -= 40;
                    x -= ttWidth;
                }


                tt.css({
                    left: x + 'px',
                    top: y + 'px'
                });
            })
            .delegate('.model', 'mouseenter', function (e) {
                //show tooltip 
                var me = $(this);
                var tt = $('div.modelTooltip');
                var loc = me.offsetParent();
                var id = me.find('.modelimg').attr('data-modelid');
                if (!id) {
                    return;
                }

                tooltipActive = true;

                if (tt.data('modelId') == id) {
                    //we already have the correct data                    
                    tt.show();
                    return;
                }


                var bgPos = 0;
                try {
                    var bgMatchElement = me.find('.match');
                    var tmp = bgMatchElement.css('background-position');
                    if (!tmp && bgMatchElement.length > 0) {
                        //work around an IE issue:
                        tmp = '' + bgMatchElement[0].style.backgroundPosition;
                    }
                    bgPos = parseInt(tmp.split(' ')[0], 10);


                } catch (ex) { }
                var score = Math.round((130 + bgPos) / 1.3);

                tt.data('modelId', id);
                function handleTooltip(data) {
                    if (tt.data('modelId') == id) {
                        tt.html(data);

                        var x = e.pageX;
                        var y = e.pageY;
                        x += 10; y += 10;

                        var ttWidth = parseInt(tt.width(), 10);
                        var maxX = parseInt($(window).width(), 10) - ttWidth;
                        if (x > maxX) {
                            //snap to the other side of th mouse button
                            x -= 40;
                            x -= ttWidth;
                        }


                        tt.css({
                            left: x + 'px',
                            top: y + 'px'
                        });
                        tt.show();

                        self.refreshTooltipFonts();
                    }
                }

                if (EM.tooltipCache && EM.tooltipCache[id]) {
                    handleTooltip(EM.tooltipCache[id]);
                } else {
                    EM.loadText('pages/v2/ModelTooltip.ashx', { id: id, score: score, version: EM.siteVersion }, function (data) {
                        EM.tooltipCache[id] = data;
                        handleTooltip(data);
                    });
                }
            })
            .delegate('.model', 'mouseleave', function (e) {
                ///hide tooltip
                tooltipActive = false;
                $('div.modelTooltip').data('modelId', '').hide();
            });
        $('.mylightbox .models,.modellist')
            .delegate('.model', 'mouseenter', function () {
                var me = $(this);
                if (!me.hasClass('empty')) {
                    me.find('.overlay').show();
                    me.find('.match').hide();
                }

            })
            .delegate('.model', 'mouseleave', function () {
                var me = $(this);
                if (!me.hasClass('empty')) {
                    me.find('.overlay').hide();
                    me.find('.match').show();
                }
            })
            .delegate('.overlay img, .modelimg', 'click', function (e) {
                var me = $(this);
                var model = me.parents('.model');
                var id = model.find('.modelimg').attr('data-modelid');
                var action = me.attr('data-action');

                if (!id) {
                    return;
                }
                switch (action) {
                    case 'del':
                        self.removeModel(id);
                        break;
                    case 'add':
                        self.addModel(id);
                        //EM.Lightbox.addModel(id);
                        var info = model.find('.modelFrame');
                        info.html('<div class="mf_infotext">Dit model is in uw selectie geplaatst</div>').css('background-image', 'none !important').show();
                        Cufon.replace(info);
                        setTimeout(function () {
                            info.hide().html('').css('background-image', '');
                        }, 2000);
                        break;
                    case 'search':
                        $('.modellist').get(0).scrollIntoView();
                        self.searchByModel(id);
                        //place the model in the first box:
                        $('.modellist .first').html(me.parents('.model').html()).find('.modelimg').attr('data-modelid', id);


                        break;
                    case 'info':
                        self.showModelDetails(e, id);
                        break;
                    case 'mail':
                        //self.downloadModel(id);
                        self.showEmailForm(e, id);
                        break;
                    default:
                        break;
                }

            });

    },
    /**
    * Show an overlay with the details for the specified model
    */
    showModelDetails: function (e, modelId) {
        if (EM.Lightbox.dragBusy) {
            return;
        }
        this.showModelDetailsImpl(e, modelId);
        $.History.navigateTo(EM.modelDetailUrlPrefix + modelId + '.aspx');
    },
    showModelDetailsImpl: function (e, modelId) {
        var me = this;
        //model_detail_template
        if (me.showModelDetailsModelId == modelId) {
            //make sure we don't do this twice (the url change event should also call this function)
            return;
        }
        me.showModelDetailsModelId = modelId;
        EM.loadJson(this.modelDetailHandler, { 'action': 'load', modelId: modelId, version: EM.siteVersion }, function (data, status, xhr) {
            if (me.showModelDetailsModelId != modelId) {
                //another model was clicked while we loaded the data
                return;
            }
            //$('#model_detail_template');  
            if (!data.success) {
                return;
            }
            var args = data.data;
            args.root = EM.root;
            if (!args.modelId) { args.modelId = modelId; }

            //remove old overlay if it exists
            if (me.modelDetailOverlay) {
                me.modelDetailOverlay.remove();
            }

            var doc = $(document);
            var docWH = { w: parseInt(doc.width(), 10), h: parseInt(doc.height(), 10) }
            var overlay = $('#model_detail_template').tmpl(args);
            me.modelDetailOverlay = overlay;

            overlay.appendTo("body");



            function closeOverlay() {
                //close and remove the overlay
                $(window).unbind('keydown', EM.Lightbox.keyDownHandler);
                EM.Lightbox.keyDownHandler = null;

                overlay.hide();
                overlay.remove();
                me.showModelDetailsModelId = null;
                me.modelDetailOverlay = null;
                EM.closeDetailOverlay = null;
                //go to default
                $.History.navigateTo('default.aspx');
            }
            EM.closeDetailOverlay = closeOverlay;
            //setup handlers
            if (EM.Lightbox.keyDownHandler) {
                $(window).unbind('keydown', EM.Lightbox.keyDownHandler);
            }
            EM.Lightbox.keyDownHandler = function (e1) {
                if (e1.which == 27) {
                    //escape
                    closeOverlay();
                }
            };
            $(window).bind('keydown', EM.Lightbox.keyDownHandler);
            //clicking anywhere on the page closes the overlay
            overlay.find('.model_detail_modal_bg')
                .css({
                    width: docWH.w,
                    height: docWH.h
                })
                .click(closeOverlay);

            var detail = overlay.find('.model_detail');

            var win = $(window);
            var detailY = Math.round(parseInt(win.scrollTop(), 10) + ((parseInt(win.height(), 10) - parseInt(detail.height(), 10)) / 2));

            me.setupRolloverButtons('.bottom_bar .rollover', detail);

            detail.css({
                //top: Math.round((docWH.h - parseInt(detail.height(), 10))/2) + 'px' ,
                top: detailY + 'px',
                left: Math.round((docWH.w - parseInt(detail.width(), 10)) / 2) + 'px'
            })
                .delegate('.button', 'click', function () {
                    var action = $(this).attr('data-action');
                    switch (action) {
                        case 'close':
                            closeOverlay();
                            break;
                        case 'offerte':
                            me.makeOfferte(modelId);
                            break;
                        case 'add':
                            closeOverlay();
                            me.addModel(modelId);
                            break;
                        default:
                            break;
                    }
                });
            me.initModelDetailImages();
            me.refreshDetailFont();


            //            
            //            $('#model_detail_template').tmpl(args)
            //                .appendTo(modelContainer);
        });

    },

    initModelDetailImages: function () {
        var me = this;
        var parent = $('.model_detail .md_media');
        var controller = parent.find('.controls');
        var items = parent.find('.md_m');
        if (items.length > 1) {
            //hide all but the first
            items.not(":first").hide();
            var activeImage = 0;
            controller.delegate('.button', 'click', function () {
                var action = $(this).attr('data-action');
                switch (action) {
                    case 'next':
                        $(items.get(activeImage)).hide();
                        activeImage++;
                        if (activeImage >= items.length) {
                            activeImage = 0;
                        }
                        $(items.get(activeImage)).show();
                        break;
                    case 'prev':
                        $(items.get(activeImage)).hide();
                        activeImage--;
                        if (activeImage < 0) {
                            activeImage = items.length - 1;
                        }
                        $(items.get(activeImage)).show();
                        break;
                    default:
                        break;
                }
                controller.children('.control_label').text((activeImage + 1) + '/' + items.length);
                me.refreshDetailFont(true);

            });

            controller.children('.control_label').text((activeImage + 1) + '/' + items.length);
        } else {
            controller.hide();
        }

    },

    _hideOldInfoWindows: function () {
        $('body > .infowindow').remove();
    },
    showEmailForm: function (e, modelId) {
        this._hideOldInfoWindows();
        var me = this;
        var base = $('<div />', {
            'class': 'infowindow'
        });
        base.html([
            '<div class="close-button button"></div>',
            '<div class="iw_lbl">Vul het e-mail adres in van de ontvanger</div>',
            '<div class="iw_frm">',
                '<input type="text" class="iw_input" />',
                '<br />',
                '<div class="button send-button">Verstuur</div>',
            '</div>'
        ].join(''));

        base.css({
            position: 'absolute',
            top: e.pageY,
            left: e.pageX
        });

        base.appendTo('body').show();
        Cufon.replace(base);

        base.find('.send-button').click(function (ev) {
            var v = base.find('.iw_input').val();
            if (!/[^@]+\@[^@]+\.[^@]{2}[^@]*/.test(v)) {
                var win = me.showInfoWindow(e, "Ongeldig e-mail adres", 'iw_err');
                win.width(base.width());
                win.height(base.height());
                return;
            }
            base.remove();
            base = null;
            //send e-mail 
            setTimeout(function () {
                jQuery.ajax({
                    type: 'POST',
                    async: true,
                    url: EM.root + me.mailHandler,
                    data: {
                        modelId: modelId,
                        email: v
                    },
                    success: function (d) {
                        me.showInfoWindow(e, "E-mail is verstuurd");
                    },
                    error: function () {
                        me.showInfoWindow(e, "Er is iets mis gegaan tijdens het versturen");
                    }

                });
            }, 0);

        });
        base.find('.close-button').click(function (ev) {
            base.remove();
            base = null;
        });
    },
    showInfoWindow: function (e, txt, cssClass) {
        var clz = 'infowindow ' + cssClass;
        var base = $('<div />', {
            'class': clz
        });
        base.html([
            '<div class="close-button button"></div>',
            '<div class="iw_lbl">', txt, '</div>',
            '<div class="iw_frm">',
            '</div>'
        ].join(''));
        if (e) {
            base.css({
                position: 'absolute',
                top: e.pageY,
                left: e.pageX
            });
        }

        base.appendTo('body').show();

        base.click(function (ev) {
            base.remove();
            base = null;
        });
        Cufon.replace(base);
        return base;
    },

    noop: EM.noop
};

if(window.EM_Lightbox_models) {
    EM.Lightbox.models = window.EM_Lightbox_models;
    window.EM_Lightbox_models =null;
}

