
var ImageFrame = Class.create();

ImageFrame.prototype = {

initialize: function(images) {
    this.currentimg = 0;   
    this.id = 'imageframe';
    this.infoID = 'imagecaption';
    this.images = images;
    this.leftID = 'imageLeft';
    this.rightID = 'imageRight';    

    Object.extend(this, arguments[1] || {});

    this.container = $(this.id);
    this.infoBar = $(this.infoID);
    
    if( !this.container ) return;
    this.mainimg = $$('#'+this.id+' .mainimg')[0];
    if( !this.mainimg) return;
    
    this.left = $(this.leftID);
    this.right = $(this.rightID);

    if( this.images.length < 2 ){
        Element.hide(this.left);
        Element.hide(this.right);
    }

    // Events //////////////////////////////////////////////
    Event.observe(this.left, 'click', function(){this.switchImage(-1)}.bind(this));
    Event.observe(this.right, 'click', function(){this.switchImage(1)}.bind(this));
    Event.observe(Element.down(this.container), 'click', function(e){this.fullScreen(this.currentimg);Event.stop(e);}.bind(this));
       
    this.thumbloading = document.createElement('img');
    Element.addClassName(this.thumbloading, 'thumbloading');
    this.thumbloading.src = '/img/loading.gif';
    Element.hide(this.thumbloading);
    this.container.appendChild(this.thumbloading);
    
    var overlay = $('overlay');
    if( !overlay ) {
        overlay = document.createElement('div');
        overlay.setAttribute('id','overlay');
        Element.setStyle(overlay,{'display':'none','position':'absolute'});
        document.body.appendChild(overlay);
    }
    this.switchImage(0);
},

switchImage: function(direction) {
    this.currentimg = ((direction + this.currentimg) + this.images.length)%this.images.length;
    var img = this.mainimg;
    var dim = Element.getDimensions(this.container);
    var src = this.createImgSrc(img, {img:this.images[this.currentimg]['filename']});
    var preloader = new Image();
    Element.hide(img);
    Element.hide(this.infoBar);
    var loadingEffect = new Effect.Appear(this.thumbloading, {duration: 4.0});
    preloader.onload = function(){
        img.src = src;
        this.setCaption(this.images[this.currentimg]['caption']);  
        loadingEffect.cancel();
        Element.hide(this.thumbloading);
        //Element.setStyle(img, {marginTop: parseInt((dim['height']-preloader.height)/2)+'px'});
        new Effect.Parallel( [
            new Effect.Appear(img),
            new Effect.Appear(this.infoBar)
        ], {duration:0.4});
    }.bind(this);
    preloader.src = src;    

    var anchor = Element.down(this.container);
    anchor.href = '/img/gallery/'+this.images[this.currentimg]['filename'];

    if (this.images[this.currentimg]['audio_file']) { 
        if (!this.audioPlayer){
            var div = document.createElement('div');
            var player_id = this.id + 'AudioPlayer';
            div.setAttribute('id', player_id);
            this.container.parentNode.appendChild(div);
            this.audioPlayer = new MediaPlayer('/mediaplayer/mediaplayer.swf', {
                swf_id: this.id + '_swf',
                container: player_id
            });
        }
        this.audioPlayer.loadTrack({
            file: '/files/audio/' + this.images[this.currentimg]['audio_file']
        });
        Element.show(this.audioPlayer.container);
    }
    else {
        if (this.audioPlayer) {
            this.audioPlayer.stop();
            Element.hide(this.audioPlayer.container);
        }
    }
},

fullScreen: function(index) {
    if (this.images[index].video_embed) {
        this.fullScreenVideo(index);
    } else {
        this.fullScreenImage(index);
    }
},

fullScreenVideo: function(index) {
    var embed = unescape(this.images[index].video_embed);
    var overlay = $('overlay');
    Element.setStyle(overlay, {width:'100%',height:'100%','top':'0px',left:'0px',zIndex:100});
    new Effect.Appear(overlay, {duration:0,from:0,to:0.9});
    Event.observe(overlay, 'click',this.closeFullScreen.bind(this));

    var load = document.createElement('img');
    load.setAttribute('id','fullscreenLoad');
    load.src = '/img/loading.gif';
    Element.setStyle(load, {position:'absolute','top':'48%','left':'48%',zIndex:'1000',display:'none'});
    document.body.appendChild(load);
    Element.hide(load);

    
    var pad = 20;
    var fsContainer = document.createElement('div');
    fsContainer.setAttribute('id', 'fullscreenContainer');
    
    var img = document.createElement('div');
    img.setAttribute('id','fullscreenImage');
    img.innerHTML = embed;
    fsContainer.appendChild(img);
    
    var imgData = document.createElement('div');
    imgData.setAttribute('id','fullscreenImageData');
    Element.addClassName(imgData, 'clearfix');
    fsContainer.appendChild(imgData);

    var caption = document.createElement('div');
    caption.setAttribute('id','fullscreenCaption');
    imgData.appendChild(caption);
    
    var fsButtons = document.createElement('div');
    fsButtons.setAttribute('id', 'fullscreenButtons');
    imgData.appendChild(fsButtons);


    var closeButton = document.createElement('a');
    closeButton.setAttribute('id', 'fullscreenCloseButton');
    closeButton.href = 'javascript:void(0)';
    closeButton.appendChild( document.createTextNode('close') );
    Event.observe(closeButton, 'click', function(){this.closeFullScreen(); return false;}.bind(this) );
    fsButtons.appendChild(closeButton);

    document.body.appendChild(fsContainer);

    // Set up Data
    Element.hide(fsContainer);
    caption.innerHTML = unescape(this.images[index]['caption']) + '&nbsp;';

    Element.setStyle(fsContainer, {left: '50%', top: '50%'});
    var w = jQuery(fsContainer).width(),
        h = jQuery(fsContainer).height();
    window.setTimeout(function() {
        Element.setStyle(fsContainer, {
            marginLeft: '-' + w/2 + 'px',
            marginTop: '-' + h/2 + 'px'
        });
        Element.show(fsContainer);
    }, 100);
   
},

fullScreenImage: function(index){
    var overlay = $('overlay');
    Element.setStyle(overlay, {width:'100%',height:'100%','top':'0px',left:'0px',zIndex:100});
    new Effect.Appear(overlay, {duration:0,from:0,to:0.9});
    Event.observe(overlay, 'click',this.closeFullScreen.bind(this));
    
    var load = document.createElement('img');
    load.setAttribute('id','fullscreenLoad');
    load.src = '/img/loading.gif';
    Element.setStyle(load, {position:'absolute','top':'48%','left':'48%',zIndex:'1000',display:'none'});
    document.body.appendChild(load);

    var loadingEffect = new Effect.Appear(load, {duration: 4.0});
    
    // Build DOM nodes 
    var pad = 20;
    var fsContainer = document.createElement('div');
    fsContainer.setAttribute('id','fullscreenContainer');
    
    var img = document.createElement('img');
    img.setAttribute('id','fullscreenImage');
    fsContainer.appendChild(img);

    var imgData = document.createElement('div');
    imgData.setAttribute('id','fullscreenImageData');
    Element.addClassName(imgData, 'clearfix');
    fsContainer.appendChild(imgData);

    var caption = document.createElement('div');
    caption.setAttribute('id','fullscreenCaption');
    imgData.appendChild(caption);
    
    var fsButtons = document.createElement('div');
    fsButtons.setAttribute('id', 'fullscreenButtons');
    imgData.appendChild(fsButtons);

    
    var fsPrintFrame = document.createElement("iframe"); 
    fsPrintFrame.setAttribute('id', 'printFrame');
    fsPrintFrame.setAttribute('name', 'printFrame');
    fsPrintFrame.setAttribute('src', 'about:blank');
    fsPrintFrame.style.width = "0px";
    fsPrintFrame.style.height = "0px";
    fsPrintFrame.style.border = "none";
    fsPrintFrame.style.position = "absolute";
    imgData.appendChild(fsPrintFrame);

    var printButton = document.createElement('a');
    printButton.setAttribute('id', 'fullscreenPrintButton');
    printButton.href = 'javascript:void(0)';
    printButton.appendChild( document.createTextNode('print') );
    fsButtons.appendChild(printButton);
    Event.observe(printButton, 'click', function(){
        frm = $('printFrame');
        frm.setAttribute('src', '/files/print.php?path=/img/gallery/' + encodeURIComponent(this.images[index]['filename']) + 
                    '&caption=' + (this.images[index]['caption']));
        return false;
    }.bind(this) );

    fsButtons.appendChild(document.createTextNode(' | ') );

    var saveButton = document.createElement('a');
    saveButton.setAttribute('id', 'fullscreenSaveButton');
    saveButton.href = 'javascript:void(0)';
    saveButton.appendChild( document.createTextNode('save') );
    fsButtons.appendChild(saveButton);
    Event.observe(saveButton, 'click', function() {
        window.location.href = '/files/download.php?path=/img/gallery/' + encodeURIComponent(this.images[index]['filename']);
        return false;
    }.bind(this) );

    fsButtons.appendChild(document.createTextNode(' | ') );

    var emailButton = document.createElement('a');
    emailButton.setAttribute('id', 'fullscreenEmailButton');
    emailButton.href = 'javascript:void(0)';
    emailButton.appendChild( document.createTextNode('email') );
    fsButtons.appendChild(emailButton);
    Event.observe(emailButton, 'click', function() {
        window.open('/files/mailfrom.php?image=/img/gallery/' + encodeURIComponent(this.images[index]['filename']),
                    'mailfrom','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=200,top=200,left=200'
        );
        return false;
    }.bind(this) );

    fsButtons.appendChild(document.createTextNode(' | ') );

    var closeButton = document.createElement('a');
    closeButton.setAttribute('id', 'fullscreenCloseButton');
    closeButton.href = 'javascript:void(0)';
    closeButton.appendChild( document.createTextNode('close') );
    Event.observe(closeButton, 'click', function(){this.closeFullScreen(); return false;}.bind(this) );
    fsButtons.appendChild(closeButton);

    document.body.appendChild(fsContainer);
    
    // Set up Data
    Element.hide(fsContainer);
    caption.innerHTML = unescape(this.images[index]['caption']) + '&nbsp;';
    var dim = getPageSize();
    Element.setStyle(overlay, {height:dim[1]+'px'});
    var preload = new Image();
    preload.onload = function() {
        var dim = getPageSize();
        img.src = preload.src;
        // Position the Container
        var scroll = getScroll();
        var w = this.width + pad;
        var t = parseInt((dim[3] - Element.getHeight(fsContainer))/2) - 12 + scroll['vertical'];
        if( t < 0) t = 0;
        var l = parseInt((dim[2] - Element.getWidth(fsContainer))/2);
        Element.setStyle(fsContainer,{width:w+'px', 'top':t+'px',left:l+'px'});        
        loadingEffect.cancel();
        Element.hide('fullscreenLoad');
        Element.show(fsContainer);
    };
    var dim = this.getFullscreenSize();
    preload.src = '/img/thumbnail.php?img='+encodeURIComponent(this.images[index]['filename'])+'&w='+dim[0]+'&h='+dim[1]+'&enlarge=1';
},

closeFullScreen: function(){
    Element.hide('overlay');
    var elem = $('fullscreenContainer');
    if( elem ) document.body.removeChild(elem);
    document.body.removeChild($('fullscreenLoad'));
},

// Create a new image url from given image and changed attributes
createImgSrc: function(img, attributes) {
    var qstr = img.src.parseQuery();
    Object.extend(qstr, attributes);
    return '/img/thumbnail.php?'+Hash.toQueryString(qstr);
},

// Set the caption
setCaption: function(caption) {
    var caption = unescape(caption);
    var tmp = caption.split(/<br \/?>/);
    while(tmp.length > 4 ) tmp.pop();
    caption = tmp.join('<br />');
    if( this.infoBar) this.infoBar.innerHTML = caption;
},

// Adjust the size of the images based on window dimensions
getFullscreenSize: function() {
    var dim = getPageSize();
    var w = dim[2], h = dim[3];
            
    /*if( w <= 800 || h <= 600 ) {
        imgMaxWidth = 800; imgMaxHeight = 600;
    }*/
    if( w <= 1024 || h <= 768 ) {
        imgMaxWidth = 1024; imgMaxHeight = 1024;
    }
    else { 
        imgMaxWidth = 1280; imgMaxHeight = 1024;
    }
    
    imgMaxWidth = imgMaxWidth*0.80;
    imgMaxHeight = imgMaxHeight*0.60;
    return [imgMaxWidth, imgMaxHeight];
}

};


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 = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getScroll() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return {'horizontal':scrOfX,'vertical':scrOfY };
}
