//http://seadragon.com/ajax/0.8/doc/index.html

//globale configuratie:
seadragonConfig=function(){with(Seadragon.Config){
	animationTime=.8;
	//blendTime=0;//DIT GAAT MIS IN FIREFOX!
	wrapHorizontal=!w.CimpleEditModus;//in Cimple niet herhalen anders worden hotspots wellicht verkeerd ingevoerd
	wrapOverlays=true;
	alwaysBlend=false;
	immediateRender=true;
	maxZoomPixelRatio=1;
	//imageLoaderLimit=4;
	zoomPerClick=0;//anders resulteert klik op hotspot in zoom
	zoomPerScroll=1.1;
}};

PMI = X(function(id, xmlUrl, hotspots, hotspotouderID) {
    //alert('id: '+id+' hotspotsouderID: '+ hotspotouderID +' hotspots: '+Deval(hotspots));
    var t = this;
    t.Hotspot = {};
    t._backup = {};
    t._panDiffPoint = new Seadragon.Point(.05, 0);
    var scrollIncPoint = new Seadragon.Point(.0003, 0);
    t._scrollMove = function() { t.viewer.viewport.panBy(scrollIncPoint, true) };
    t.div = CimpleProxy.bewaarTag(bouw('div#' + id+'.pmi'));
    var placeholder = d.E('tmp' + id);
    placeholder.parentElement.replaceChild(t.div, placeholder);
    t.div.onmousedown = function() {
        t.div.style.cursor = 'move';
    }
    d.body.onmouseup = function() {
        t.div.style.cursor = 'default';
    }
    t.viewer = new Seadragon.Viewer(t.div, true, false);
    //tbv stylesheet:
    //var nav = t.viewer.getNavControl();
    //nav.style.display = 'auto';
    //nav.style.border = '3px solid green';
    //nav.id = 'nav';
    t.viewer.clearControls();
    t.viewer.openDzi(xmlUrl);
    t.viewer.addControl(bouw(['div#pmiZoomtool', _, [
			['div.zoomin', { title: 'klik om in te zoomen.\nU kunt ook uw scrollwiel\n gebruiken om in te zoomen', onclick: function() { t.viewer.viewport.zoomBy(1.1) } }],
			['div.zoom'],
			['div.zoomout', { title: 'klik om uit te zoomen.\nU kunt ook uw scrollwiel\n gebruiken om uit te zoomen', onclick: function() { t.viewer.viewport.zoomBy(.9, t.viewer.viewport.getCenter()) } }],
			['div.fullscreen', { title: 'schakel volledig scherm in/uit', onclick: function() { t.viewer.setFullPage(!t.viewer.isFullPage()) } }]
		]]), Seadragon.ControlAnchor.BOTTOM_RIGHT);
    //t.viewer.addControl(bouw(['div#fullscreen', _, 'test']), Seadragon.ControlAnchor.BOTTOM_RIGHT);
    t.viewer.addEventListener('open', function() {
        if (Lokatie.Args.pagina == 2337) t.viewer.setFullPage(true); //rechtstreekse link voor fullscreen weergave
        //t.autoScroll(t.isScrolling);
        t._overruleViewportMethods();
        t._backup.panTo = t.viewer.viewport.panTo;
        //hotspots renderen
        for (var id in hotspots) {
            var info = hotspots[id];
            var rectdata = eval('[' + info[3] + ']');
            var inhoudtekst;
            info[4] ? inhoudtekst = info[4] : inhoudtekst = '';
            t.Hotspot[id] = new PMIHotspot(t, id, info[0], info[1], info[2], rectdata[0], rectdata[1], rectdata[2], rectdata[3], inhoudtekst);
        };
        t.handleNavigation(t._activeHotspotId, hotspotouderID);
    });
    var point1, point2;
    t.editTracker = new Seadragon.MouseTracker(t.div);
    t.editTracker.pressHandler = function(tracker, position) {
        point1 = t.viewer.viewport.pointFromPixel(position);
        with (t.activeHotspot) {
            moveTo(point1.x, point1.y);
            resizeTo(.001, .001);
            render();
        }
    };
    t.editTracker.dragHandler = function(tracker, position) {
        point2 = t.viewer.viewport.pointFromPixel(position);
        with (t.activeHotspot) {
            moveTo(Math.min(point1.x, point2.x), Math.min(point1.y, point2.y));
            resizeTo(Math.abs(point1.x - point2.x), Math.abs(point1.y - point2.y));
            render();
        }
    };
    t.editTracker.releaseHandler = function(tracker, position) {
        with (new HTTPVerzoek) {
            URL.Args.Verzoek = 'positie';
            URL.Args.waarde = t.activeHotspot;
            Reactie = function() { if (this.Respons) alert(this.Respons) };
            Start();
        }
    };
    t.chkEdit = bouw('input#switchInvoer', { type: 'checkbox', onclick: function() { t._setEditable(this.checked) } });
    t.controls = CimpleProxy.bewaarTag(bouw('div', _, [
		['div#pmiControls', _, [
			['div#pmiMarkerOpties', _, [
				['input#switchMarkers', { type: 'checkbox', onclick: function() { toggleClass(t.div, 'noMarkers') } }],
				['label', { 'htmlFor': 'switchMarkers' }, ' Verberg markeringen']
			]],
    //via CSS deze optie verbergen indien niet in cimple:
			['div#pmiEditOpties', _, [
				t.chkEdit,
				['label', { 'htmlFor': 'switchInvoer' }, ' invoer modus']
			]]
		]]
	]));
}, {
    hotspotsParentId: 1092,
    firstKeyIn: function(o) { for (var r in o) return r },
    prototype: {
        //Seadragon.Config is niet toerijkend voor alle benodigde beperkingen, vandaar deze functie:
        _overruleViewportMethods: function() {
            var viewer = this.viewer;
            var heightPts = 1 / viewer.source.aspectRatio;
            var centerBounds = new Seadragon.Rect(.5, 0, .1, heightPts);
            //viewer.drawer.addOverlay(createMarker(),centerBounds);//centerBounds zichtbaar maken
            var viewport = viewer.viewport;
            viewport.fitBounds(centerBounds, true);
            var defaultZoom = viewport.getZoom(), defaultCenterY = viewport.getCenter().y;
            viewport.maxZoom = 21.45;
            //corrigeert het center point zoomTo en panTo:
            var fixCenter = function(point, level) {
                if (!level) level = viewport.getZoom();
                var minY = defaultCenterY * (defaultZoom / level);
                if (point.y < minY) point.y = minY;
                else if (point.y > heightPts - minY) point.y = heightPts - minY;
                return point;
            };
            //uitzoombeperking en corrigeren orientatiepunt:
            var zoomTo = viewport.zoomTo;
            viewport.zoomTo = function(level, center) {
                //document.title=level;
                if (level > viewport.maxZoom) level = viewport.maxZoom;
                if (level > defaultZoom) {
                    if (center) {
                        var y = center.y;
                        center = fixCenter(center, level);
                        if (center.y != y) this.panTo(center, true);
                    }
                    zoomTo.apply(this, arguments);
                }
            };
            //panning beperken tot de randen van de afbeelding:
            var panTo = viewport.panTo;
            viewport.panTo = function(center) {
                fixCenter(center);
                panTo.apply(this, arguments);
            };
            //viewport.goHome=function(){this.fitBounds(centerBounds)};
        },

        //zorgt ervoor dat hotspots kunnen worden aangepast:
        _setEditable: function(b) {
            this.viewer.viewport.panTo = b ? Nix : this._backup.panTo;
            this.editTracker.setTracking(b);
            this.chkEdit.checked = b;
        },

        _setActive: function(activeHotspotId) {
            if (this.activeHotspot) this.activeHotspot.setActive(false);
            this.activeHotspot = this.Hotspot[activeHotspotId];
            if (this.activeHotspot) this.activeHotspot.setActive(true);
        },
        /*
        autoScroll:function(b){
        this.isScrolling=b;
        if (!this.viewer.isOpen()) return;
        clearInterval(this.autoScroll.interval);
        if (b&&!this.autoScroll.interval) this.autoScroll.interval=setInterval(this._scrollMove,20);
        else{
        delete this.autoScroll.interval;
        }
        },
        */

        //wordt uitgevoerd nadat naar een andere pagina wordt genavigeerd:
        handleNavigation: function(pageId, hotspotouderID) {
            this._activeHotspotId = pageId;
            if (this.viewer.isOpen()) {
                var placeholder = d.E('tmp' + this.div.id);
                if (placeholder) placeholder.parentElement.replaceChild(this.div, placeholder);
                var isHotspot = cimple.route[Route[pageId] - 1] == hotspotouderID; //PMI.hotspotsParentId;
                if (isHotspot && !this.Hotspot[pageId]) this.Hotspot[pageId] = new PMIHotspot(this, pageId, PaginaTitel);
                this.editOptionAvailable = !!this._activeHotspotId;
                zetStatus(this.chkEdit, this.editOptionAvailable);
                this._setActive(this._activeHotspotId);
            }
        }
    }
});

PMIHotspot = X(function(pmi, id, name, statusId, categoryId, x, y, width, height, inhoudtekst) {
    this.pmi = pmi;
    this.id = id;
    this.name = name;
    this.statusId = statusId || PMI.firstKeyIn(PMIHotspot.Status);
    this.categoryId = categoryId || PMI.firstKeyIn(PMIHotspot.Category);
    this._rect = new Seadragon.Rect(x || 0, y || 0, width || 0, height || 0);
    var prijsLabel = 'prijs: ' + String.fromCharCode(8364) + ' '; //vanwege de timestamp in de querystring wordt de UTF-8 encoding header niet doorgegeven en dus wordt het euro-karakter niet herkend
    var titel
    if (statusId != categoryId) {
        titel = [
		    this.name,
		    prijsLabel + PMIHotspot.Category[this.categoryId],
		    'status: ' + PMIHotspot.Status[this.statusId]
	    ]
    }
    else { titel = [this.name] }

    inhoudtekst ? '' : inhoudtekst = '';
    this._elm = bouw('a.status_' + statusId, { href: '/?pagina=' + id, onclick: function(e) { openPagina(id) }, title: titel.join(' \n')
    }, [
		['span', _, [//ivm IE quirks tbv active class
			['div.kader'],
			['div.marker'],
			['div.tekst', { innerText: inhoudtekst}]
		]]
	]);
    this._viewer = pmi.viewer;
    this._viewer.drawer.addOverlay(this._elm, this._rect);
}, {
    Category: {},
    Status: {},
    prototype: {
        render: function() {
            this._viewer.drawer.updateOverlay(this._elm, this._rect);
        },
        moveTo: function(x, y) {
            this._rect.x = x;
            this._rect.y = y;
        },
        resizeTo: function(width, height) {
            this._rect.width = width;
            this._rect.height = height;
        },
        toString: function() { with (this._rect) return [x, y, width, height].join(',') },
        setActive: function(b) {
            toggleClass(this._elm.firstChild, 'active', b);
            if (!b) return;
            var t = this;
            setTimeout(function() {
                var vp = t._viewer.viewport;
                vp.zoomTo(vp.maxZoom, null, true);
                if (t._rect.getSize().y > vp.getBounds().getSize().y) {//hotspot hoger dan viewport
                    vp.fitBounds(t._rect, true);
                    vp.zoomBy(.8); //stukkie uitzoomen
                }
                vp.panTo(t._rect.getTopLeft().plus(vp.getBounds().getSize().divide(3)), true);
            }, 100);
        }
    }
});
