/**
 *
 * Image Gallery JavaScript library
 *
 * This file contains functions, extensions and events, 
 * enabling use of the Image Gallery.
 *
 * Use of Mootools framework is required.
 * File can be included anywhere on the site.
 *
 * @author Matej Balantič <matej@balantic.si>
 * @version 1.0
 * @package igalleryjavascript
 */



/**
 * Extend Events class so that it will enable "wheel" events
 * @author Mootools http://mootools.net
 */
Element.Events.extend({
        'wheelup': {
                type: Element.Events.mousewheel.type,
                map: function(event){
                        event = new Event(event);
                        if (event.wheel >= 0) this.fireEvent('wheelup', event)
                }
        },
 
        'wheeldown': {
                type: Element.Events.mousewheel.type,
                map: function(event){
                        event = new Event(event);
                        if (event.wheel <= 0) this.fireEvent('wheeldown', event)
                }
        }
});
 

/**
 * Call function gal_init when DOM is ready
 */ 
window.addEvent('domready',  gal_init);


/**
 * Initialize the animation; prepare buttons & fx 
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_init()
{	
   		/**
		 * Set defaults
		 */
		if (!$defined(window.slideShowInProcess))
			slideShowInProcess = false;

		if (!$defined(window.imagesCount))
			imagesCount		= 0;

		if (!$defined(window.imagesPerPage))
			imagesPerPage	= 7;

		if (!$defined(window.slideshowSpeed))
			slideshowSpeed 	= 2000; // milisecs
	
		if (!$defined(window.currentPage))
			currentPage		= 1;
	
		if (!$defined(window.pages))
			pages			= Math.ceil(imagesCount/imagesPerPage);

		if (!$defined(window.currMediaId))
			currMediaId = false;

		/**
		 * add onclick & wheel events
		 */
        $('leftArrow').addEvent('click', function(e) {
                        e = new Event(e).stop();
                        this.blur();
                        gal_thumbs_prev();
        });

        $('rightArrow').addEvent('click', function(e) {  
                        e = new Event(e).stop();
                        this.blur();
                        gal_thumbs_next();

        });
        $('galHolder').addEvents({
                'wheelup': function(e) {
                        e = new Event(e).stop();
                        gal_thumbs_prev();
                },
                'wheeldown': function(e) {
                        e = new Event(e).stop();
                        gal_thumbs_next();
                }
        });


        /**
		 * initialize FX effect 
		 */
        scrollHolder = new Fx.Scroll('thumb_holder', {
                wait: false,
                duration: 1000,
                transition: Fx.Transitions.Circ.easeOut
        });

        /**
		 * preload first image
		 */
        gal_preload(BigImagesIndex[0]);
        
        // open 1st image
        if (app_lang == 'hr')
        	gal_image_open(BigImagesIndex[0]);
}

/**
 * Adds image to array of images used in gallery.
 * Only add images using this function.
 *
 * Added for compatibility with Google Chrome
 *
 * @author Matej Balantic
 * @date 2009-06-12
 */
function gal_add_image(galid, gmedia_id, gurl, gsource, gcomment, gvideo_id, gseqno)
{
        if (!$defined(window.BigImagesIndex))
                BigImagesIndex =  [];

        if (!$defined(window.BigImages))
                BigImages =  {};

		if (!$defined(gseqno))
			gseqno = "";

        subobject = {};
        subobject[gmedia_id] = [ gurl, gsource, gcomment, gvideo_id , gseqno];

        $extend(BigImages, subobject );
        BigImagesIndex.extend([gmedia_id.toInt()]);
}


/**
 * Function preloads next 3 images
 * @param int media_id Current image
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_preload(media_id)
{
        currIndex = BigImagesIndex.indexOf(media_id);

        if (BigImagesIndex[currIndex+1])
                new Element('img', { src: BigImages[BigImagesIndex[currIndex+1]][0] });

        if (BigImagesIndex[currIndex+2])
                new Element('img', { src: BigImages[BigImagesIndex[currIndex+2]][0] });

        if (BigImagesIndex[currIndex+3])
                new Element('img', { src: BigImages[BigImagesIndex[currIndex+3]][0] });


}

/**
 * Opens next or previous image
 * @param string ty Type of the nav (next|prev)
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_image_nav(ty)
{
        ind = BigImagesIndex.indexOf(currMediaId);

        if (ty == "next" && BigImagesIndex[ind+1])
        {
                gal_image_open ( BigImagesIndex[ind+1] );
        }
        else if (BigImagesIndex[ind-1])
        {
                gal_image_open ( BigImagesIndex[ind-1] );
        }
}

/**
 * Starts / stops slide show
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_slide_show_toggle()
{
	if (!slideShowInProcess)
		gal_slide_show();
	else
		gal_slide_show_stop();
}

/**
 * Starts slide show
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_slide_show(  )
{
	slideShowInProcess = true;

	if (!currMediaId)
		gal_image_open(BigImagesIndex[0]);

	else if (BigImagesIndex.indexOf(currMediaId)+1 == BigImagesIndex.length)
		gal_image_open(BigImagesIndex[0]);

	else
		gal_image_nav('next');
	
	slideshowTimer = gal_slide_show.delay(slideshowSpeed);

}

/**
 * Ends slide show
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_slide_show_stop()
{
	slideShowInProcess=false;
	slideshowTimer = $clear(slideshowTimer);
	gal_create_nav();
}

/**
 * Opens large image  
 * @param int media_id
 * @author Matej Balanti <matej@balantic.si>
 */
function gal_image_open(media_id)
{
        currMediaId = media_id.toInt();

		/**
		 * Handle thumb navigation
		 */
        page_should_be = Math.ceil((BigImagesIndex.indexOf(currMediaId)+1)/imagesPerPage);
        if (currentPage != page_should_be)
                gal_thumbs_nav(page_should_be);

		/**
		 * Border around thumb
		 */
        $ES('.galleryThumb img').each ( function (el) {
		el.removeClass('imgselected');
        });
        $('thumb_'+currMediaId).getElements('img')[0].addClass('imgselected');

        /**
         * Preload images
         */
        gal_preload(media_id);

		/**
		 * Catch & handle old image
		 */
        if($('currentImage'))
        {
        		/**
				 * remove image navigation 
				 */
	 			if ($('leftNav'))
                        $('leftNav').remove();
                if ($('leftNavArr'))
                        $('leftNavArr').remove();

                if ($('rightNav'))
                        $('rightNav').remove();
                if ($('rightNavArr'))
                        $('rightNavArr').remove();

				/**
				 * Catch old image
				 */
                oldImage = $('currentImage');
                oldImage.id = 'oldImage';
                oldImage.setStyle('z-index', '70');

				/**
				 * Start FX which removes old image
				 */
                oldFx = new Fx.Style(oldImage, 'opacity', { 
						duration: 500,
                        
						onComplete: function() {
                               	$('oldImage').remove();
						}
				})
                .start(1,0);

        }

		/**
		 * Create new image
		 */
        currImage = new Element('img')
        
		/**
		 * Add onload event. HAS to be set BEFORE 'src' element is set.
		 * It also has to be repeated on FX complete later, since OnLoad
		 * will not be triggered in the right way IE when image is cached.
		 */
        .addEvent('load', function() {
                $('imageBig').setStyle( 'height',  currImage.getCoordinates().height);
        })
        .setStyles({
                'opacity' : '0',
                'position': 'absolute',
                'top': '10px',
                'left': '20px',
                'z-index': 50
        })
        .set ({
                'src': BigImages[media_id][0],
                'alt': BigImages[media_id][2],
                'id' : 'currentImage'
        })
        .injectInside($('imageBig'));

		/**
		 * Start the effect which shows new image
		 */
        currFx = new Fx.Style(currImage, 'opacity', { 
			duration: 500,
            onComplete: function()
			{
				/**
				 * update container size
				 */
                $('imageBig').setStyle( 'height',  currImage.getCoordinates().height);

				/**
				 *  create navigation
				 */
                if (!slideShowInProcess)
					gal_create_nav();
    			
				/**
				 * insert comment
				 */
				if (BigImages[currMediaId][1] != '') {
					$('galComment').setText(stripslashes(BigImages[currMediaId][2]) + ' (' + stripslashes(BigImages[currMediaId][1]) + ')');
				} else {
					$('galComment').setText(stripslashes(BigImages[currMediaId][2]));
				}
           }
        });
        currFx.start(0,1);


}

/**
 * Creates navigation over the image
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_create_nav()
{
	/**
	 * Left part of navigation
	 * Create only if this is not the first image
	 */
	if (BigImagesIndex.indexOf(currMediaId)+1 > 1)
	{
		leftNav = new Element('div', { 'id': "leftNav" } )
		.setStyles({
			'background-color' : 'white',
			'position' : 'absolute',
			'z-index': 100,
			'top': '10px',
			'left': '20px',
			'opacity': 0,
			'visibility': 'visible',
			'height': currImage.getCoordinates().height,
			'width': currImage.getCoordinates().width/2,
			'cursor':'pointer'

		})
		.addEvents({
			'click':  function(e) {
				e = new Event(e).stop();
				gal_image_nav('prev');
			},
			'mouseover': function(e) {
				e = new Event(e).stop();
				leftNavArr.setStyle('visibility', 'visible');
			},
			'mouseout': function(e) {
				e = new Event(e).stop();
				leftNavArr.setStyle('visibility', 'hidden');
			}/*,
			'wheelup': function(e) {
			   e = new Event(e).stop();
			   gal_image_nav('next');
			},
			'wheeldown': function(e) {
				e = new Event(e).stop();
				gal_image_nav('prev');
			 }*/
		})
		.injectInside($('imageBig'));

		/**
		 * Create the left arrow
		 */
		leftNavArr = new Element('img',         {
				'src': '/static/'+app_lang+'/main/img/buttons/button_big_photo_left_on.gif',
				'id': 'leftNavArr'
		})
		.setStyles({
				'cursor':'pointer',
				'visibility' : 'hidden',
				'z-index': 60,
				'position':'absolute',
				'left': 20 - 11,
				'top': '100px'
		})
		.addEvents({
				'click':  function(e) {
					e = new Event(e).stop();
					gal_image_nav('prev');
				}
				/*'mouseover': function(e) {
					e = new Event(e).stop();
					leftNavArr.src = '/static/hr/main/img/buttons/button_big_photo_left_on.gif';
				},
				'mouseout': function(e) {
					e = new Event(e).stop();
					leftNavArr.src = '/static/hr/main/img/buttons/button_big_photo_left_off.gif';
				}*/
		})
		.injectInside($('imageBig'));
	}


	/**
	 * Right part of navigation
	 */
	if (BigImagesIndex.indexOf(currMediaId)+1 < imagesCount)
	{
		rightNav = new Element('div', { 'id': 'rightNav' } )
		.setStyles({
			'background-color' : 'white',
			'position' : 'absolute',
			'z-index': 100,
			'opacity': '0',
			'visibility': 'visible',
			'top': '10px',
			'left': currImage.getCoordinates().width/2 +20 ,
			'height': currImage.getCoordinates().height,
			'width': currImage.getCoordinates().width/2,
			'cursor':'pointer'

		})
		.addEvents({
			'click':  function(e) {
				e = new Event(e).stop();
				gal_image_nav('next');
			},
			'mouseover': function(e) {
				e = new Event(e).stop();
				rightNavArr.setStyle('visibility', 'visible');
			},
			'mouseout': function(e) {
				e = new Event(e).stop();
				rightNavArr.setStyle('visibility', 'hidden');

			}/*,
		   'wheelup': function(e) {
			   e = new Event(e).stop();
			   gal_image_nav('next');
		   },
		   'wheeldown': function(e) {
			   e = new Event(e).stop();
			   gal_image_nav('prev');
			}*/
		})
		.injectInside($('imageBig'));

		/**
		 * Right arrow
		 */
		rightNavArr = new Element('img', {
				'src': '/static/'+app_lang+'/main/img/buttons/button_big_photo_right_on.gif',
				'id': 'rightNavArr'
		})
		.setStyles({
				'cursor': 'pointer',
				'z-index': 60,
				'position':'absolute',
				'visibility': 'hidden',
				'left': currImage.getCoordinates().width + 20 - 11,
				'top': '100px'
		})
		.addEvents({
				'click':  function(e) {
					e = new Event(e).stop();
					gal_image_nav('next');
				}/*,
				'mouseover': function(e) {
					e = new Event(e).stop();
					rightNavArr.src = '/static/hr/main/img/buttons/button_big_photo_right_on.gif';
				},
				'mouseout': function(e) {
					e = new Event(e).stop();
					rightNavArr.src = '/static/hr/main/img/buttons/button_big_photo_right_off.gif';
				}*/
		})
		.injectInside($('imageBig'));
	}

}


/**
 * Scroll to next "page"
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_thumbs_next()
{
	gal_thumbs_nav(currentPage+1);
}

/**
 * Scroll to previous "page"
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_thumbs_prev()
{
	gal_thumbs_nav(currentPage-1);
}

/**
 * Navigate to page
 * @param int page Page to navigate to
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_thumbs_nav(page)
{
	/**
	 *  handle page overflow
	 */
	if (page < 1 || page > pages)
		return false;

	/** 
	 * mark page change
	 */
	currentPage = page;
	
	if (typeof(imagesWidth) === 'undefined')
		imagesWidth = 74;

	if (typeof(imagesPerPage) === 'undefined')
		imagesPerPage = 7;

	/**
	 * slide thumbs
	 */
	scrollHolder.scrollTo( imagesWidth * imagesPerPage * (currentPage-1), 0);

}

/**
 * PHP-like addslashes function
 * @author http://javascript.about.com/library/bladdslash.htm
 */
function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}

/**
 * PHP-like stripslashes function
 * @author http://javascript.about.com/library/bladdslash.htm
 */
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

