/* MooFlow Viewer (extra JS MooFlowViewer.js)
 * v0.1dev useViewer:true
 */
MooFlow.implement({
	attachViewer: function(imageGroup){
	    this.imageGroup = imageGroup;
	    return this;
	},
	    
	flowComplete: function(){
	    this.createIconTip();
	},
	
	createIconTip: function(){
		var cur = this.getCurrent();
		if(!$chk(cur.rel)||!$chk(cur.href)) return;
		this.tipFx = new Fx({link:'cancel'});
		if(!$chk(this.icon)) { 
			this.icon = new Element('a', {html: 'Click to View'}).addClass('show').setStyles({'display':'none','opacity':'0'}).inject(this.MooFlow); 
		}
		this.icon.addEvent('click', this.onClickView.bind(this, cur));
		this.icon.addClass(cur.rel.toLowerCase());
		this.icon.setStyle('display','block').fade(0.6);
	},
	
	onClickView: function(cur){
		switch (cur.rel.toLowerCase()){
			case 'image':
				this.showImage('', cur.href, 'image', this.imageGroup);
			break;
			case 'link':
				window.open(cur.href, cur.target || '_blank');
				break;
			default:
		}
	},
	
	showImage: function(){
		var cur = this.getCurrent();
		TB_show('', cur.href, 'image', this.imageGroup);
	}
});


/*
 * The following codes are modified from smoothbox.js.
 */

var TB_doneOnce = 0;

// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel, imageGroup){

    // create iframe, overlay and box if non-existent
    
    if (!$("TB_overlay")) {
        new Element('iframe').setProperty('id', 'TB_HideSelect').injectInside(document.body);
        $('TB_HideSelect').setOpacity(0);
        new Element('div').setProperty('id', 'TB_overlay').injectInside(document.body);
        $('TB_overlay').setOpacity(0);
        TB_overlaySize();
        new Element('a').setProperty('id', 'TB_load').injectInside(document.body);
        $('TB_load').innerHTML = "<img src='../images/loader.gif' />";
        
        $('TB_overlay').set('tween', {
            duration: 400
        });
        $('TB_overlay').tween('opacity', 0, 0.6);        
    }
    
    if (!$("TB_load")) {
        new Element('div').setProperty('id', 'TB_load').injectInside(document.body);
        $('TB_load').innerHTML = "<img src='../images/loader.gif' />";
    }
    $("TB_overlay").onclick = TB_remove;   

    if (!$("TB_window")) {
		var left = parseInt(window.getScrollLeft() + (window.getWidth() ) / 2 - 226) + 'px';
		var top = '158px'; 
		var tbwindow = new Element('div').setProperty('id', 'TB_window');
		tbwindow.setStyles({'top': top, 'left': left});
		tbwindow.injectInside(document.body);
    }
   
	window.onscroll = TB_position;
    
    // check if a query string is involved
    var baseURL = url.match(/(.+)?/)[1] || url;
    
    // regex to check if a href refers to an image
    var imageURL = /\.(jpe?g|png|gif|bmp)/gi;
    
    // check for images
    if (baseURL.match(imageURL)) {
        var dummy = {
            caption: "",
			link: "",
            url: "",
            html: ""
        };
        
        var prev = dummy, next = dummy, imageCount = "";
        
        function getInfo(image, id){
			switch (id)
			{
				case 'prev':
					var label = "<a href='#'>Previous</a>";
					break;
				case 'next':
					var label = "<a href='#'>Next</a>";
					break;
				default :
					var label = "";
			}
			var html = "<span id='TB_" + id + "'>" + label + "</span>";

			return {
				caption: image.title,
				extlink: image.id,
                url: image.src,
                html: html
            }
        }
            
        var foundSelf = false;
            
        // loop through the anchors, looking for current clicked image, saving informatialon about previous and next image
        for (var i = 0; i < imageGroup.length; i++) {
                var image = imageGroup[i];
				
                // look for current clicked image
				if (image.src.match(/.*\/(.+)/)[1] == url.match(/.*\/(.+)/)[1])
				{
                    foundSelf = true;
					imageTitle = imageGroup[i].title;
					imageLink = imageGroup[i].id;
                    imageCount = "(" + (i + 1) + "/" + (imageGroup.length) + ")";
                }
                else {
                    // when we found current clicked image, the current is the next image
                    if (foundSelf) {
                        next = getInfo(image, "next");
                        // stop searching
                        break;
                    }
                    else {
                        // didn't find current clicked image yet, so this may be the one before current clicked image
                        prev = getInfo(image, "prev");
                    }
                }
        }
        
        imgPreloader = new Image();
        imgPreloader.onload = function(){
			imgPreloader.onload = null;
				
			// Resizing large images
			var x = window.getWidth() - 150;
			var y = window.getHeight() - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth);
				imageWidth = x;
				if (imageHeight > y) {
					imageWidth = imageWidth * (y / imageHeight);
					imageHeight = y;
				}
			}
			else if (imageHeight > y) {
				imageWidth = imageWidth * (y / imageHeight);
				imageHeight = y;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth);
					imageWidth = x;
				}
			}
			// End Resizing
				
			// TODO don't use globals
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
				
			// window contents

			var imageHtml = "<a href=" + imageLink + " target='_blank'><img id='TB_Image' src='" + url + "' alt='" + caption + "'/></a>";
			var imageTitleHtml = "<span id='TB_title'>" + imageTitle + imageCount + "</span>";
			var enlargeHtml = "<span id='TB_link'><a href='" + imageLink + "' target='_blank'>Click to Enlarge</a></span>";
			var closeHtml = "<span id='TB_close'><a href='#' id='TB_closeWindowButton' title='Close'>Close</a></span>";
			var controlHtml = "<span id='TB_control'>" + prev.html + next.html + closeHtml + "</span>";
			var captionHtml = "<span id='TB_caption'>" + imageTitleHtml + enlargeHtml + controlHtml + "</span>";
			$("TB_window").innerHTML =  imageHtml + captionHtml;
			$("TB_closeWindowButton").onclick = TB_remove;

			function buildClickHandler(image){
				return function(){
					$("TB_window").dispose();
					var left = parseInt(window.getScrollLeft() + (window.getWidth() - TB_WIDTH ) / 2 + 100) + 'px';
					var top = '158px'; 
					var tbwindow = new Element('div').setProperty('id', 'TB_window');
					tbwindow.setStyles({'top': top, 'left': left});
					tbwindow.injectInside(document.body);
						
					TB_show(image.caption, image.url, 'image', imageGroup);
					return false;
				};
			}
			var goPrev = buildClickHandler(prev);
			var goNext = buildClickHandler(next);
			if ($('TB_prev')) {
				$("TB_prev").onclick = goPrev;
			}
				
			if ($('TB_next')) {
				$("TB_next").onclick = goNext;
			}
				
			document.onkeydown = function(event){
				event = new Event(event);
				switch (event.code) {
					case 27:
						TB_remove();
						break;
					case 190:
						if ($('TB_next')) {
							document.onkeydown = null;
							goNext();
						}
						break;
					case 188:
						if ($('TB_prev')) {
							document.onkeydown = null;
							goPrev();
						}
						break;
				}
			}
				
			// TODO don't remove loader etc., just hide and show later
			//$("TB_ImageOff").onclick = TB_remove;
			TB_position();
			TB_showWindow();
		}
		imgPreloader.src = url;
	}
		
	window.onresize = function(){
		TB_position();
		TB_overlaySize();
	}
		
	document.onkeyup = function(event){
		event = new Event(event);
		if (event.code == 27) { // close
			TB_remove();
		}
	}
}

//helper functions below

function TB_showWindow(){
    //$("TB_load").dispose();
    //$("TB_window").setStyles({display:"block",opacity:'0'});
    
    if (TB_doneOnce == 0) {
        TB_doneOnce = 1;
        
        $('TB_window').set('tween', {
            duration: 250,
            onComplete: function(){
                if ($('TB_load')) {
                    $('TB_load').dispose();
                }
            }
        });
        $('TB_window').tween('opacity', 0, 1);
        
    }
    else {
        $('TB_window').setStyle('opacity', 1);
        if ($('TB_load')) {
            $('TB_load').dispose();
        }
    }
}

function TB_remove(){
    $("TB_overlay").onclick = null;
    document.onkeyup = null;
    document.onkeydown = null;
    
    if ($('TB_imageOff')) 
        $("TB_imageOff").onclick = null;
    if ($('TB_closeWindowButton')) 
        $("TB_closeWindowButton").onclick = null;
    if ($('TB_prev')) {
        $("TB_prev").onclick = null;
    }
    if ($('TB_next')) {
        $("TB_next").onclick = null;
    }
    
    
    $('TB_window').set('tween', {
        duration: 250,
        onComplete: function(){
            $('TB_window').dispose();
        }
    });
    $('TB_window').tween('opacity', 1, 0);
    
    
    
    $('TB_overlay').set('tween', {
        duration: 400,
        onComplete: function(){
            $('TB_overlay').dispose();
        }
    });
    $('TB_overlay').tween('opacity', 0.6, 0);
    
    window.onscroll = null;
    window.onresize = null;
    
    $('TB_HideSelect').dispose();
    //TB_init();
    TB_doneOnce = 0;
    return false;
}

function TB_position(){
	$('TB_window').setStyles({
		left: parseInt(window.getScrollLeft() + (window.getWidth() - TB_WIDTH) / 2 + 100) + 'px',
		top: '158px'
	});	
}

function TB_overlaySize(){
    // we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
    $("TB_overlay").setStyles({
        "height": '0px',
        "width": '0px'
    });
    $("TB_HideSelect").setStyles({
        "height": '0px',
        "width": '0px'
    });
    $("TB_overlay").setStyles({
        "height": window.getScrollHeight() + 'px',
        "width": window.getScrollWidth() + 'px'
    });
    $("TB_HideSelect").setStyles({
        "height": window.getScrollHeight() + 'px',
        "width": window.getScrollWidth() + 'px'
    });
}

function TB_parseQuery(query){
    // return empty object
    if (!query) 
        return {};
    var params = {};
    
    // parse query
    var pairs = query.split(/[;&]/);
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        if (!pair || pair.length != 2) 
            continue;
        // unescape both key and value, replace "+" with spaces in value
        params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
    }
    return params;
}
