﻿/* mod of mootools-based slimbox1.6 for dmag modal forms */

var ModalBox = (function() {
    jQuery.noConflict(); 
	
	// Global variables, accessible to Slimbox only
	var win = window, ie6 = Browser.Engine.trident4, options, formElement,
	            compatibleOverlay, middle, centerWidth, centerHeight,
	// Preloader
	//preload = {},

	// DOM elements
	overlay, center, formArea, sizer, bottomContainer, bottom, formid, 
	            
	// Effects
	fxOverlay, fxResize, fxImage, fxBottom;

	/* Initialization */
	win.addEvent("domready", function() {
		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "lbOverlay", events: {click: close}}),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			).setStyle("display", "none")
		);

		formArea = new Element("div", {id: "lbModalForm"}).injectInside(center) /*.adopt(
			sizer = new Element("div", {styles: {position: "relative"} } )
		);*/

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			new Element("a", {id: "lbCloseLink", href: "javascript:void(0);", events: {click: close}}),
			new Element("div", {styles: {clear: "both"}})
		);
	});


	/* Internal functions */

	function position() {
		jQuery.noConflict(); 
	
	    var scroll = win.getScroll(), size = win.getSize();
		$$(center, bottomContainer).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	}

	function setup(open) {
	    jQuery.noConflict(); 
	
	    // disable/enable all objects and embeds and on ie6, any selected 
	    // this is so the modal box is always on top
		["object", "iframe", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});
        // show/hide overlay
		overlay.style.display = open ? "" : "none";
        //  
		var fn = open ? "addEvent" : "removeEvent";
		win[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		jQuery.noConflict(); 
	
	    var code = event.code;
		// Prevent default keyboard action (like navigating inside the page)
//		return options.closeKeys.contains(code) ? close()
////			: options.nextKeys.contains(code) ? next()
////			: options.previousKeys.contains(code) ? previous()
//			: false;
	}


	function loadForm(el) {
            
			jQuery.noConflict(); 
	
	        stop();
			center.className = "lbLoading";
            animateBox(el);
            
		return false;
	}

	function animateBox(el) {
		jQuery.noConflict(); 
	
	    center.className = "";
		fxImage.set(0);
		
		el.setStyles({ display: ""});
		el.inject(formArea);
		formArea.setStyles({ display: ""});
		
//		sizer.setStyle("width", el.width);
//		$$(sizer).setStyle("height", el.height);

		
		centerWidth = formArea.offsetWidth;
		centerHeight = formArea.offsetHeight;
		var top = Math.max(0, middle - (centerHeight / 2)), fn;
		if (center.offsetHeight != centerHeight) {
			fxResize.start({height: centerHeight, top: top});
		}
		if (center.offsetWidth != centerWidth) {
			fxResize.start({width: centerWidth, marginLeft: -centerWidth/2});
		}
		fn = function() {
			bottomContainer.setStyles({width: centerWidth, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			bottomContainer.setStyles({top: center.getCoordinates().top - bottomContainer.getCoordinates().height});
			fxImage.start(1);
		};
		if (fxResize.check(fn)) fn();
	}

	function animateCaption() {

		jQuery.noConflict(); 
	
	    fxBottom.set(-bottom.offsetHeight).start(0);
		bottomContainer.style.visibility = "";
		if ($$("#lbCenter input")[0] != null)
		     $$("#lbCenter input")[0].focus();
	}

	function stop() {
		jQuery.noConflict(); 
	
	    fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		$$( formArea, bottomContainer).setStyle("display", "none");
	}

	function close() {
		jQuery.noConflict(); 
	
	    stop();
		center.style.display = "none";
		fxOverlayClose.cancel().chain(setup).start(0).chain();
		//fxOverlay.cancel().chain(setup).start(0).chain();        
		//alert('on close');
	
	    $(document.body).grab($(formid));
	    $(formid).setStyle('display', 'none');
	
		return false;
	}
	
	function onClose() { /* placeholder function */
	}


	/*  API  */
	return {
		open: function(formElement, _options) {
		    if (formElement==null)
                return;
            else
                formid = formElement.id;
                
			options = $extend({
				loop: false,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				overlayFadeDuration: 200,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 200,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// false uses the mootools default transition
				initialWidth: 250,			// Initial width of the box (in pixels)
				initialHeight: 250,			// Initial height of the box (in pixels)
				imageFadeDuration: 200,			// Duration of the formArea fade-in animation (in milliseconds)
				captionAnimationDuration: 200,		// Duration of the caption animation (in milliseconds)
				//counterText: "Image {x} of {y}",	// Translate or change as you wish, or set it to false to disable counter text for formArea groups
				closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
				//previousKeys: [37, 80],			// Array of keycodes to navigate to the previous formArea, default: Left arrow (37), 'p' (80)
				//nextKeys: [39, 78]			// Array of keycodes to navigate to the next formArea, default: Right arrow (39), 'n' (78)
				onCloseFunction: onClose
			}, _options || {});

			// Setup effects
			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});
			fxOverlayClose = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration, onComplete: options.onCloseFunction});
			fxResize = new Fx.Morph(center, $extend({duration: options.resizeDuration, link: "chain"}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			fxImage = new Fx.Tween(formArea, {property: "opacity", duration: options.imageFadeDuration, onComplete: animateCaption});
			fxBottom = new Fx.Tween(bottom, {property: "margin-bottom", duration: options.captionAnimationDuration});

			// The function is called for a single formArea, with URL and Title as first two arguments
//			if (typeof formElement == "string") {
//				formElement = [[formElement, startImage]];
//				startImage = 0;
//			}

			middle = win.getScrollTop() + (win.getHeight() / 2);
			centerWidth = options.initialWidth;
			centerHeight = options.initialHeight;
			center.setStyles({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2, display: ""});
			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			fxOverlay.set(0).start(options.overlayOpacity);
			position();
			setup(1);

			//images = formElement;
			//options.loop = options.loop && (images.length > 1);
			return loadForm(formElement);
		}
	};

})();

/* SCROLL FUNCTION FOR MODAL POPUPS */
function makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse){
    jQuery.noConflict(); 
	
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
    var slider = new Slider(scrollbar, handle, {	
        steps: steps,
        mode: (horizontal?'horizontal':'vertical'),
        onChange: function(step){
            // Scrolls the content element in x or y direction.
            var x = (horizontal?step:0);
            var y = (horizontal?0:step);
            content.scrollTo(x,y);
        }
    }).set(0);
    if( !(ignoreMouse) ){
        // Scroll the content element when the mousewheel is used within the 
        // content or the scrollbar element.
        $$(content, scrollbar).addEvent('mousewheel', function(e){	
            e = new Event(e).stop();
            var step = slider.step - e.wheel * 30;	
            slider.set(step);					
        });
    }
    // Stops the handle dragging process when the mouse leaves the document body.
    $(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}