/**
 *
 * 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>
 * @author Marko Pavlišič <marko.pavlisic@gmail.com>
 * @version 1.1
 * @package igalleryjavascript
 * Marko change library to support more than one image gallery on site
 */


var imagesCount = [];
var imagesPerPage = [];
var imagesWidth = [];
var gallery_show_first = [];
var BigImages = [];
var BigImagesIndex = [];
var slideShowInProcess = [];
var slideshowSpeed = [];
var currentPage = [];
var pages = [];
var currMediaId = [];
var scrollHolder = [];
var currImage = [];
var currFx = [];
var oldImage = [];
var slideshowTimer = [];
var verticalGallery = [];
var imagesGap = [];

//prefix image description
var gallery_prefix = [];

// custom icons for left and right nav icons
var leftNavArrSrc ='';
var rightNavArrSrc ='';

var leftOffset = -8;
var rightOffset = 14

/**
 * 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)
                }
        }
});
 

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

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

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

		if (!$defined(window.slideshowSpeed[galid]))
			slideshowSpeed[galid] 	= 2000; // milisecs

		if (!$defined(window.currentPage[galid]))
			currentPage[galid]		= 1;
	
		if (!$defined(window.pages[galid]))
			pages[galid]			= Math.ceil(imagesCount[galid]/imagesPerPage[galid]);

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

		/**
		 * add onclick & wheel events
		 */

        $('leftArrow'+galid).addEvent('click', function(e) {
                        e = new Event(e).stop();
                        this.blur();
                        gal_thumbs_prev(galid);
        });

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

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

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

        /**
		 * preload first image
		 */
		if ($defined(gallery_show_first[galid]) && gallery_show_first[galid])
		{
			image_to_open = 0; 
			the_anchor = window.location.hash;
			if (the_anchor)
			{
				the_anchor = the_anchor.split("#image_");
				if (the_anchor.length==2)
				{
					image_to_open = the_anchor[1];
					image_to_open = image_to_open.toInt();
					image_to_open = image_to_open-1;
				
					if (image_to_open<0) image_to_open=0;
				}
			}
			gal_image_open(BigImagesIndex[galid][image_to_open], galid);
		}

        gal_preload(BigImagesIndex[0], galid);
}

/**
 * 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[galid]))
		BigImagesIndex[galid] =  [];

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

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

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

	$extend(BigImages[galid], subobject );
	BigImagesIndex[galid].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, galid)
{
	if (!$defined(window.BigImagesIndex[galid]))
		BigImagesIndex[galid] =  [];

        currIndex = BigImagesIndex[galid].indexOf(media_id);

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

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

        if (BigImagesIndex[galid][currIndex[galid]+3])
                new Element('img', { src: BigImages[galid][BigImagesIndex[galid][currIndex[galid]+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,galid)
{
        ind = BigImagesIndex[galid].indexOf(currMediaId[galid]);
        if (ty == "next" && BigImagesIndex[galid][ind+1])
        {
                gal_image_open ( BigImagesIndex[galid][ind+1], galid );
        }
        else if (ty == "prev" && BigImagesIndex[galid][ind-1])
        {
                gal_image_open ( BigImagesIndex[galid][ind-1], galid );
        }
}

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

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

	if (!currMediaId[galid]) {
		gal_image_open(BigImagesIndex[galid][0], galid);
	}
	else if (BigImagesIndex[galid].indexOf(currMediaId[galid])+1 == BigImagesIndex[galid].length) {
		gal_image_open(BigImagesIndex[galid][0], galid);
	}
	else {
		gal_image_nav('next', galid);
	}
	// alert(slideshowSpeed[galid]);
	// gal_slide_show(galid);
	slideshowTimer[galid] = (function() { gal_slide_show(galid); }).delay(slideshowSpeed[galid]);

}

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

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

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

		/**
		 * Border around thumb
		 */
        $ES('.galleryThumb img').each ( function (el) {
		el.removeClass('imgselected');
        });

	/**
	 * Also border around divs
	 */
	document.getElements('div[rel=thumb]').each ( function (el) {
		el.removeClass('imgselected');
	});


	if (currMediaId)
	{
		$('thumb_'+galid+'_'+currMediaId[galid]).getElements('img')[0].addClass('imgselected');

		altdiv = $('thumb_'+galid+'_'+currMediaId[galid]).getElements('div[rel=thumb]');
		if (altdiv.length>0)
			altdiv[0].addClass('imgselected');
	}

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

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

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

				/**
				 * Catch old image
				 */
                oldImage[galid] = $('currentImage_'+galid);
                oldImage[galid].id = 'oldImage';
                oldImage[galid].setStyle('z-index', '70');

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

        }

		/**
		 * Create new image
		 */
        currImage[galid] = 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() {
        	try {
                $('imageBig_'+galid).setStyle( 'height',  currImage[galid].getCoordinates().height);
            }
            catch(err) {
            	
            }
        })
        .setStyles({
                'opacity' : '0',
                'position': 'absolute',
                'top': '0px',
                'left': '0px',
                'z-index': 50
        })
        .set ({
                'src': BigImages[galid][media_id][0],
                'alt': BigImages[galid][media_id][2],
                'id' : 'currentImage_'+galid
        })
        .injectInside($('imageBig_'+galid));

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

				/**
				 *  create navigation
				 */
                if (!slideShowInProcess[galid])
					gal_create_nav(galid);
    			
				/**
				 * insert comment
				 */
				if (BigImages[galid][currMediaId[galid]][1] != '') {
					//$('galComment_'+galid).setText(stripslashes(BigImages[galid][currMediaId[galid]][2]) + ' (' + stripslashes(BigImages[galid][currMediaId[galid]][1]) + ')');
					if (gallery_prefix[galid]) {
						$('galComment_'+galid).innerHTML = "<b>" + gallery_prefix[galid] + " " +  BigImages[galid][currMediaId[galid]][4] + "</b> " + stripslashes(BigImages[galid][currMediaId[galid]][2]) + ' (' + stripslashes(BigImages[galid][currMediaId[galid]][1]) + ')';
					} else {
						$('galComment_'+galid).innerHTML = stripslashes(BigImages[galid][currMediaId[galid]][2]) + ' (' + stripslashes(BigImages[galid][currMediaId[galid]][1]) + ')';
					}
				} else {
					//$('galComment_'+galid).setText(BigImages[galid][currMediaId[galid]][2]);
					if (gallery_prefix[galid]) {
						$('galComment_'+galid).innerHTML = "<b>" + gallery_prefix[galid] + " " +  BigImages[galid][currMediaId[galid]][4] + "</b> " + BigImages[galid][currMediaId[galid]][2];
					} else {
						$('galComment_'+galid).innerHTML = BigImages[galid][currMediaId[galid]][2];
					}
				}
           }
        });
        currFx[galid].start(0,1);
}

/**
 * Creates navigation over the image
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_create_nav(galid)
{
	/**
	 * Left part of navigation
	 * Create only if this is not the first image
	 */
	
	if ($("leftNavArr")) $("leftNavArr").remove(); 
	if ($("rightNavArr")) $("rightNavArr").remove(); 
	
	embedVideo = false;
	if (BigImages[galid][currMediaId[galid]][3]!="") embedVideo = true;

		leftNav = new Element('div', { 'id': "leftNav" } )
		.setStyles({
			'background-color' : 'white',
			'position' : 'absolute',
			'z-index': 100,
			'top': '0px',
			'left': '0px',
			'opacity': 0,
			'visibility': 'visible',
			'height': currImage[galid].getCoordinates().height,
			'width': currImage[galid].getCoordinates().width/2,
			'cursor':'pointer'

		})
		.addEvents({
			'click':  function(e) {
				e = new Event(e).stop();
				if (embedVideo) {
					leftNavArr.setStyle('visibility', 'hidden');
					ind = BigImagesIndex[galid].indexOf(currMediaId[galid]);
					media_id = BigImages[galid][currMediaId[galid]][3];
					video_at_thumb(media_id, 'leftNav',currImage[galid].getCoordinates().width,currImage[galid].getCoordinates().height - 40);
				} else {
					gal_image_nav('prev',galid);
				}
			},
			'mouseover': function(e) {
				e = new Event(e).stop();
				ind = BigImagesIndex[galid].indexOf(currMediaId[galid]);
				if (ind>0) leftNavArr.setStyle('visibility', 'visible');
			},
			'mouseout': function(e) {
				e = new Event(e).stop();
				leftNavArr.setStyle('visibility', 'hidden');
			}/*,
			'wheelup': function(e) {
			   e = new Event(e).stop();
			   ('next');
			},
			'wheeldown': function(e) {
				e = new Event(e).stop();
				('prev');
			 }*/
		})
		.injectInside($('imageBig_'+galid));

		if (leftNavArrSrc === 'undefined' || leftNavArrSrc == '')
			leftNavArrSrc = '/static/'+app_lang+'/main/img/buttons/button_big_photo_left_on.gif';
		
		if (rightNavArrSrc === 'undefined' || rightNavArrSrc == '')
			rightNavArrSrc = '/static/'+app_lang+'/main/img/buttons/button_big_photo_right_on.gif';
		
		/**
		 * Create the left arrow
		 */
		leftNavArr = new Element('img',         {
				'src': leftNavArrSrc,
				'id': 'leftNavArr'
		})
		.setStyles({
				'cursor':'pointer',
				'visibility' : 'hidden',
				'z-index': 120,
				'position':'absolute',
				'left': leftOffset,
				'top': currImage[galid].getCoordinates().height / 2 - 11
		})
		.addEvents({
				'click':  function(e) {
					e = new Event(e).stop();
					gal_image_nav('prev',galid);
				},
				'mouseover': function(e) {
					e = new Event(e).stop();
					leftNavArr.setStyle('visibility', 'visible');				
				}
				
				/*'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_'+galid));


	/**
	 * Right part of navigation
	 */
		rightNav = new Element('div', { 'id': 'rightNav' } )
		.setStyles({
			'background-color' : 'white',
			'position' : 'absolute',
			'z-index': 100,
			'opacity': '0',
			'visibility': 'visible',
			'top': '0px',
			'left': currImage[galid].getCoordinates().width/2 ,
			'height': currImage[galid].getCoordinates().height,
			'width': currImage[galid].getCoordinates().width/2,
			'cursor':'pointer'

		})
		.addEvents({
			'click':  function(e) {
				e = new Event(e).stop();
				if (embedVideo) {
					rightNavArr.setStyle('visibility', 'hidden');
					ind = BigImagesIndex[galid].indexOf(currMediaId[galid]);
					media_id = BigImages[galid][currMediaId[galid]][3];
					video_at_thumb(media_id, 'leftNav',currImage[galid].getCoordinates().width,currImage[galid].getCoordinates().height - 40);
				} else {
					gal_image_nav('next',galid);
				}
			},
			'mouseover': function(e) {
				e = new Event(e).stop();
				ind = BigImagesIndex[galid].indexOf(currMediaId[galid]);
				if (ind<imagesCount[galid]-1) rightNavArr.setStyle('visibility', 'visible');
			},
			'mouseout': function(e) {
				e = new Event(e).stop();
				rightNavArr.setStyle('visibility', 'hidden');

			}/*,
		   'wheelup': function(e) {
			   e = new Event(e).stop();
			   ('next');
		   },
		   'wheeldown': function(e) {
			   e = new Event(e).stop();
			   ('prev');
			}*/
		})
		.injectInside($('imageBig_'+galid));
		
		/**
		 * Right arrow
		 */
		rightNavArr = new Element('img', {
				'src': rightNavArrSrc,
				'id': 'rightNavArr'
		})
		.setStyles({
				'cursor': 'pointer',
				'z-index': 120,
				'position':'absolute',
				'visibility': 'hidden',
				'left': currImage[galid].getCoordinates().width - rightOffset,
				'top': currImage[galid].getCoordinates().height / 2 - 11
		})
		.addEvents({
				'click':  function(e) {
					e = new Event(e).stop();
					gal_image_nav('next',galid);
				},
				'mouseover': function(e) {
					e = new Event(e).stop();
					rightNavArr.setStyle('visibility', 'visible');				
				}
				/*,
				'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_'+galid));

}


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

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

/**
 * Navigate to page
 * @param int page Page to navigate to
 * @author Matej Balantič <matej@balantic.si>
 */
function gal_thumbs_nav(page, galid)
{
	/**
	 *  handle page overflow
	 */
	 
	if (page < 1 || page > pages[galid])
		return false;
	
	// display different left-right icons when on first or last page on ru and ua site 
	if (window.app_lang == 'ua' || window.app_lang == 'ru') {
		if (parseInt(page) == 1)
			$('leftArrowImg'+galid).src = '/static/ua/main/img/buttons/gallery_prev_disabled.gif';
		else 
			$('leftArrowImg'+galid).src = '/static/ua/main/img/buttons/gallery_prev.gif';
		
		if (parseInt(page) == parseInt(pages[galid]))
			$('rightArrowImg'+galid).src = '/static/ua/main/img/buttons/gallery_next_disabled.gif';
		else 
			$('rightArrowImg'+galid).src = '/static/ua/main/img/buttons/gallery_next.gif';
	}
	
	/** 
	 * mark page change
	 */
	currentPage[galid] = page;
	
	if (typeof(imagesWidth[galid]) === 'undefined')
		imagesWidth[galid] = 74;

	if (typeof(imagesGap[galid]) === 'undefined')
		imagesGap[galid] = 4;

	if (typeof(imagesPerPage[galid]) === 'undefined')
		imagesPerPage[galid] = 9;

	/**
	 * slide thumbs
	 */
	if (typeof(verticalGallery[galid]) === 'undefined')
		verticalGallery[galid] = false;

	if (verticalGallery[galid]) {
		scrollHolder[galid].scrollTo( 0, (imagesWidth[galid]+imagesGap[galid]) * imagesPerPage[galid] * (currentPage[galid]-1));
	} else {
		scrollHolder[galid].scrollTo( (imagesWidth[galid]+imagesGap[galid]) * imagesPerPage[galid] * (currentPage[galid]-1), 0);
	}
	
	// $('rightNavArr'+galid).set('src', '/static/ua/main/img/buttons/gallery_next_disabled.gif');
}

/**
 * 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;
}
