/*
Lightbox JS: Fullsize Image Overlays 
by Lokesh Dhakar - http://www.huddletogether.com

For more information on this script, visit:
http://huddletogether.com/projects/lightbox/

Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
*/

var loadingImage = '/drupal5/sites/all/modules/imgdb/images/loading.gif';
var nextButton = '/drupal5/sites/all/modules/imgdb/images/next_grey.gif';		
var prevButton = '/drupal5/sites/all/modules/imgdb/images/prev_grey.gif';		
var closeButton = '/drupal5/sites/all/modules/imgdb/images/close_grey.png';		
var smallSizeX = 400;
var smallSizeY = smallSizeX*2/3;

// global XMLHTTP-Object
var http = null;
// global GoogleMap Object
var gmap = null;
var marker = null;
var enablemap = true;
var baseUrl = null;
var imgPreload = null;
var latlong = [0,0];

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){

    var xScroll, yScroll;
	
    if (window.innerHeight && window.scrollMaxY) {	
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
	
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }	
	
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else { 
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){	
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }


    arrayPageSize = [pageWidth,pageHeight,windowWidth,windowHeight];
    return arrayPageSize;
}


//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime) {
            return;
        }
    }
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){
    if (e === null) { // ie
        keycode = event.keyCode;
    } else { // mozilla
        keycode = e.which;
    }
    key = String.fromCharCode(keycode).toLowerCase();

    if(key == 'x'){ hideLightbox(); }
    if(enablemap && key == 'm'){ toggleMap(); }
}

function centerLightbox() 
{
    var arrayPageSize = getPageSize();

    var lightboxLeft;
    var lightboxTop = ((arrayPageSize[3] - 35 - 44 - imgPreload.height) / 2);
    lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);

    $('#lightbox').css({'top': (lightboxTop < 0) ? "0px" : lightboxTop + "px",
        'left': (lightboxLeft < 0) ? "0px" : lightboxLeft + "px"});
}


//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
    // prep objects
    var objLoadingImage = $('#loadingImage');

    var arrayPageSize = getPageSize();

    if (baseUrl === null) {
        baseUrl = objLink.match(/(.*\/)([a-zA-Z0-9_]+)(\_big.jpg)/);
    }

    // center loadingImg if it exists
    if (objLoadingImage.length) {
        objLoadingImage.css({'top': Math.round((arrayPageSize[3] - 35 - objLoadingImage.height()) / 2) + 'px',
            'left': Math.round((arrayPageSize[0] - 20 - objLoadingImage.width()) / 2) + 'px'}).show();
    }

    // set height of Overlay to take up whole page and show
    $('#overlay').css({"height": (arrayPageSize[1] + 'px'), "display": "block"});

    // preload image
    if (imgPreload === null) {
        imgPreload = new Image();
        $('#lightboxCaption').css({'display': 'none', 'overflow': 'hidden'});
    }

    imgPreload.onload=function(){
        var id = objLink.match(/\/([a-zA-Z0-9_]+)\_big.jpg/);
        $.ajax({type:'GET', 
            url:'/drupal5/sites/all/modules/imgdb/ajax.php?id='+id[1], 
            success:function(dataObj) { 
                $('#lightboxImage').attr('src', objLink);
                centerLightbox();
                $('#lightboxDetails').css('display', 'block');

                if (dataObj.lat) {
                    latlong = [dataObj.lat, dataObj.long];
                    maplink = ' <a href="javascript:toggleMap();"><img src="/drupal5/files/ImgDB/res/path3242.png" width="13" height="13" title="Karte zeigen"/></a><a href="/drupal5/files/ImgDB/kml/'+id[1]+'.kml"><img src="/drupal5/files/ImgDB/res/path3241.png" width="13" height="13" title="In Google Earth zeigen"/></a>';
                } else {
                    latlong = null;
                    maplink = '';
                }
                data = '<p><span class="desc"><img src="/drupal5/sites/all/modules/imgdb/images/description.png" />'+dataObj.desc+'</span><span class="loc"><img src="/drupal5/sites/all/modules/imgdb/images/location.png" />'+dataObj.loc+maplink+'</span><span class="date"><img src="/drupal5/sites/all/modules/imgdb/images/clock.png"/>'+dataObj.date+'</span></p>';
                $("#lightboxCaption").html(data);
                if ($("#lightboxCaption").css("display") == "none") {
                    $("#lightboxCaption").slideDown("normal"); 
                }
                if (dataObj.lat) {
                    $("#mapkey").show();
                    centerMap();
                } else {
                    hideMap();
                    $("#mapkey").hide();
                }
                var a = $("#lightboxNextImgDiv");
                if (dataObj.next) {
                    a.unbind('click');
                    a.unbind('hover');
                    a.click(function(){changeImage(dataObj.next); return false;});
                    a.show();
                    a.hover(
                            function() {
                                $(this).find('img').fadeIn('fast');
                                return false;
                            }, function() {
                                $(this).find('img').fadeOut('fast');
                                return false;
                            });
                } else {
                    a.unbind('click');
                    a.unbind('hover');
                    a.hide();
                }
                a = $("#lightboxPrevImgDiv");
                if (dataObj.prev) {
                    a.unbind("click");
                    a.unbind('hover');
                    a.click(function(){changeImage(dataObj.prev); return false;});
                    a.show();
                    a.hover(
                            function() {
                                $(this).find('img').fadeIn('fast');
                                return false;
                            }, function() {
                                $(this).find('img').fadeOut('fast');
                                return false;
                            });
                } else {
                    a.unbind('click');
                    a.unbind('hover');
                    a.hide();
                }

            },
            error:function(req, textStatus, errorThrown){
                alert(textStatus);
            },
            dataType:'json'
        });
                
        // A small pause between the image loading and displaying is required with IE,
        // this prevents the previous image displaying for a short burst causing flicker.
        if (navigator.appVersion.indexOf("MSIE")!=-1){
            pause(250);
        } 

        $("#loadingImage").hide();

        // Hide select boxes as they will 'peek' through the image in IE
        $("select").hide();
        
        $("#lightbox").css('display','block');

        // After image is loaded, update the overlay height as the new image might have
        // increased the overall page height.
        arrayPageSize = getPageSize();
        $('#overlay').css('height', arrayPageSize[1] + 'px');
                
        // Check for 'x' keypress
        document.onkeypress = getKey;

        return false;
    };

    imgPreload.src = objLink;

}

function changeImage(imgsrc)
{
    showLightbox(baseUrl[1]+imgsrc+baseUrl[3]);
}


//
// hideLightbox()
//
function hideLightbox()
{
    // hide lightbox and overlay
    $("#overlay").hide();
    $("#lightbox").hide();
//    $('#lightboxMap').hide();

    // make select boxes visible
    $('select').css('visibility','visible');

    // disable keypress listener
    document.onkeypress = '';
}




//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{

    // loop through all anchor tags
    $('a[rel="lytebox"]').click(function() {showLightbox(this.href); return false;});

    var objBody = document.getElementsByTagName("body").item(0);

    // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id','overlay');
    objOverlay.onclick = function () {hideLightbox(); return false;};
    $(objOverlay).css({'display': 'none', 'position':'absolute', 'top':'0px',
        'left':'0px', 'zIndex': '90', 'width':'100%'});
    objBody.insertBefore(objOverlay, objBody.firstChild);
	
    var arrayPageSize = getPageSize();

    // create loader image
    var objLoadingImageLink = document.createElement("a");
    $(objLoadingImageLink).click(function() {hideLightbox(); return false;});
    objOverlay.appendChild(objLoadingImageLink);
            
    var objLoadingImage = document.createElement("img");
    objLoadingImage.src = loadingImage;
    $(objLoadingImage).attr('id','loadingImage').css({'position':'fixed', 'zIndex':'150'});
    objLoadingImageLink.appendChild(objLoadingImage);

    // create lightbox div, same note about styles as above
    var objLightbox = document.createElement("div");
    $(objLightbox).attr('id','lightbox').css({'display':'none', 'position':'fixed', 'zIndex':'100'});
    objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
    // create box for image, close button
    var objImgDiv = document.createElement("div");
    $(objImgDiv).attr('id','lightboxImgDiv');
    objLightbox.appendChild(objImgDiv);
        
    // create link for prev button
    var objPrevImgDiv = document.createElement("div");
    $(objPrevImgDiv)
        .attr('id','lightboxPrevImgDiv')
        .css({
            'position':'absolute', 'display':'none', 
            'top':'10px', 'left':'10px', 'width':'150px', 'height':'600px',
            'cursor':'pointer', 'zIndex':'200'});
    objImgDiv.appendChild(objPrevImgDiv);

    // create prev button image
    var imgPrevButton = document.createElement('img');
    imgPrevButton.src = prevButton;
    $(imgPrevButton).css({'position':'absolute', 'top':'350px', 'left':'0px', 
        'zIndex':'200', 'display':'none'});
    objPrevImgDiv.appendChild(imgPrevButton);
    $(objPrevImgDiv).hover(
            function() {
                $(this).find('img').show();
                return false;
            }, function() {
                $(this).find('img').hide();
                return false;
            });
        

    // create link for next button
    var objNextImgDiv = document.createElement("div");
    $(objNextImgDiv)
        .attr('id','lightboxNextImgDiv')
        .css({
            'position':'absolute', 'display':'none', 
            'top':'10px', 'right':'10px', 'width':'150px', 'height':'600px',
            'cursor':'pointer', 'zIndex':'200'});
    objImgDiv.appendChild(objNextImgDiv);

    // create next button image
    var imgNextButton = document.createElement('img');
    imgNextButton.src = nextButton;
    $(imgNextButton).css({'position':'absolute', 'top':'350px', 'right':'0px', 
        'zIndex':'200', 'display':'none'});
    objNextImgDiv.appendChild(imgNextButton);
    $(objNextImgDiv).hover(
            function() {
                $(this).find('img').show();
                return false;
            }, function() {
                $(this).find('img').hide();
                return false;
            });

    // create close button
    var objCloseButton = document.createElement("img");
    objCloseButton.src = closeButton;
    $(objCloseButton).attr({'id':'closeButton', 'title':'Click to close'}
        ).css({'position':'absolute', 'zIndex':'200'}).click(
            function(){hideLightbox(); return false;});
    objImgDiv.appendChild(objCloseButton);

   // create image
    var objImage = document.createElement("img");
    objImage.setAttribute('id','lightboxImage');
    objImgDiv.appendChild(objImage);
	
    // create google maps div
    var objLightboxMap = document.createElement("div");
    $(objLightboxMap).attr('id','lightboxMap');
    $(objLightboxMap).hover(function() {
        $(this).css({opacity:1});}, function() {
            $(this).css({opacity:0.5});});
    objImgDiv.appendChild(objLightboxMap);
        
     // create details div, a container for the caption and keyboard message
    var objLightboxDetails = document.createElement("div");
    objLightboxDetails.setAttribute('id','lightboxDetails');
    objLightbox.appendChild(objLightboxDetails);

    // create caption
    var objCaption = document.createElement("div");
    objCaption.setAttribute('id','lightboxCaption');
    objCaption.style.display = 'none';
    objLightboxDetails.appendChild(objCaption);

    // create keyboard message
    var objKeyboardMsg = document.createElement("div");
    objKeyboardMsg.setAttribute('id','keyboardMsg');
    objKeyboardMsg.innerHTML = '<span id="mapkey">press <a href="#" onclick="toggleMap(); return false;"><kbd>m</kbd></a> to show map. </span><span id="closekey">press <a href="#" onclick="hideLightbox(); return false;"><kbd>x</kbd></a> to close.</span>';
    objLightboxDetails.appendChild(objKeyboardMsg);

    if (GBrowserIsCompatible()) {
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	var point = new GLatLng(0, 0);
	var icon = new GIcon(baseIcon);
	icon.image = "http://www.google.com/mapfiles/marker.png";
	marker = new GMarker(point, icon);

        gmap = new GMap2(objLightboxMap,{size: new GSize(400,300)});
        gmap.setMapType(G_SATELLITE_MAP);
        gmap.addControl(new GSmallMapControl());
        gmap.addControl(new GMapTypeControl());
        gmap.addOverlay(marker);
        $(objLightboxMap).hide();
    }
}

var mapCentered = false;

function centerMap()
{
    if (GBrowserIsCompatible()) {
        var gll = new GLatLng(latlong[0], latlong[1]);
        marker.setLatLng(gll);
        if (mapCentered==false) {
            gmap.setCenter(gll, 13);
            mapCentered = true;
        } else {
            gmap.panTo(gll);
        }
    }

}


function hideMap()
{
    if ($('#lightboxMap').is(':visible')) {
        $('#lightboxMap').slideUp();
        return;
    }
}

function showMap()
{
    if (!$('#lightboxMap').is(':visible')) {
        $('#lightboxMap').slideDown();
        return;
    }
}

function toggleMap()
{
    if (latlong == null) {
        $('#lightboxMap').hide();
        return;
    }
    if ($('#lightboxMap').is(':visible')) {
        $('#lightboxMap').slideUp();
        return;
    } 

    $('#lightboxMap').slideDown();
    centerMap();
}

// drupal specific code
if (Drupal.jsEnabled) {
	$(document).ready(initLightbox);
}
