function SymError()
{
   return true;
}
window.onerror = SymError;
jQuery.noConflict();
var globals = new Object();
var queueBigImages = new Array();
var win = new Object();
jQuery(document).ready(function(){
	//setting and fixing dimensions for real photo (defining the obvious for IE browsers)
	maxWidth = jQuery('#real-content').width();
	maxHeight = jQuery('#real-content').height();
	jQuery('#real-content').width(maxWidth);
	jQuery('#real-content').height(maxHeight);
	jQuery('#frames').parent().css('height',maxHeight-98);
	//explicit width for frames in IE browsers
	jQuery('#frames').css('width',jQuery('#frames').width())
	$itemSize = (jQuery.browser.msie)?63.5:67
	photosVisible = Math.floor(jQuery('#frames').height()/$itemSize);
	jQuery('#frames').css('height',photosVisible*$itemSize)
	jQuery('#frames').parent().css('height',jQuery('#frames').height());
	//fix outline CSS property to IE browsers
	if(jQuery.browser.msie){
		jQuery('a').each(function(){
			this.hideFocus = true;
		});
	}
	/*CAROUSEL*/	
	// globals
	$carousel = new Object();
	numberPreload = 2;
	objHttpFileDataRequest = null;
	indexXml = 0;
	flag = true;
	carouselTimer = null;
	var timerDelay=3000;
	lastPhoto = null;
	waitTimer = null;
	// cache
	imageCache = new Array();
	// get current photo
	try{
		currentPhoto = jQuery.cookie('currentPhoto');
		if(!currentPhoto) currentPhoto = 3;
	}
	catch(e){
		currentPhoto = 3;
	}
	//init carousel
	realCarouselSize = $realCarouselSize;
	carouselSize = (realCarouselSize < photosVisible)?photosVisible+1:realCarouselSize;
	jQuery('#carousel').jcarousel({
		vertical: true,	
		scroll: 1,
		animation:200,
		size:carouselSize,
		start:(currentPhoto*1)-2,
		initCallback:renderCarousel,
		itemLoadCallback:loadItems,
		itemLastInCallback:{onBeforeAnimation:beforeScroll,onAfterAnimation:afterScroll},
		buttonNextHTML:null,
		buttonPrevHTML:null
	});
	// setting events
	function beforeScroll (){
		jQuery('#go-right').unbind('click',goRight).css('opacity',0.8);
		jQuery('#go-left').unbind('click',goLeft).css('opacity',0.8);
	}
	function afterScroll(){
		jQuery('#go-right').bind('click',goRight).css('opacity',1);		
		jQuery('#go-left').bind('click',goLeft).css('opacity',1);
		jQuery('#go-right').bind('mouseup',animateStop);		
		jQuery('#go-right').bind('mousedown',goRightAuto);		
		jQuery('#go-left').bind('mouseup',animateStop);		
		jQuery('#go-left').bind('mousedown',goLeftAuto);		
		
	}
	timerAnimate = null
	function goRightAuto(){
		if(timerAnimate!=null) {
			clearInterval(timerAnimate); return;
		}
		timerAnimate = setInterval(function(){
			$carousel.next();
			return;
		},500)
	}
	function goLeftAuto(){
		if(timerAnimate!=null) {
			clearInterval(timerAnimate); return;
		}
		timerAnimate = setInterval(function(){
			$carousel.prev();
			return;
		},500)
	}
	function animateStop(){
		if(timerAnimate!=null) {
			clearInterval(timerAnimate);
			timerAnimate = null;
			return;
		}
	}
	function goRight() {
		if(queueBigImages[0]<$carousel.first) garbage = queueBigImages.shift();
		$carousel.next();
		return false;
	}
	function goLeft() {
		if(queueBigImages[queueBigImages.length-1]>$carousel.last) garbage = queueBigImages.pop();		
        $carousel.prev();
        return false;
	}
	//init callback
	function renderCarousel(carousel){
		$carousel = carousel;
		//fixin box model IE
		jQuery('#frames div').each(function(){
			jQuery(this).height(jQuery('#frames').height()+28);
		});
		//attach events
		jQuery('#go-right').bind('click',goRight);
		jQuery('#go-left').bind('click',goLeft);
	}	
	//load items on request
	function loadItems(carousel){
		firstIndex = carousel.first-numberPreload;
		if(firstIndex<1) firstIndex = carousel.first;
		lastIndex = carousel.last+numberPreload;
		if (carousel.has(firstIndex, lastIndex)){
			if(lastPhoto){
				lastPhoto=null;
				handlerInterval(timerDelay);
			}
			return;
		} 
		if (objHttpFileDataRequest) objHttpFileDataRequest.abort();
		objHttpFileDataRequest = jQuery.get(
			'get-photos-invitation.php',
			{
				first: firstIndex,
				last: lastIndex
			},
			function(xml) {
				itemAdd(carousel, firstIndex, lastIndex, xml);
			},
			'xml'
		);		
	}
	//adding a photo
		function itemAdd(carousel, first, last, xml){
			if(realCarouselSize < photosVisible)
				for(i=realCarouselSize;i<=carouselSize;i++)
					jQuery(jQuery('photo',xml)[jQuery('photo',xml).length-1]).clone().appendTo(jQuery('album',xml))
			jQuery('photo', xml).each(function(i) {
				if(!carousel.has(first+i)){
					jQuery('#tmp').html(jQuery('comment',this).text());
					imageCache[first+i] = new Object();
					imageCache[first+i]['url'] = jQuery('name',this).text();
					imageCache[first+i]['path'] = jQuery('path',this).text();
					imageCache[first+i]['width'] = jQuery('width',this).text();
					imageCache[first+i]['id'] = jQuery('photoId:eq(0)',this).text();
					imageCache[first+i]['height'] = jQuery('height',this).text();
					imageCache[first+i]['comments'] = jQuery('photoComments',this);
					imageCache[first+i]['autor'] = jQuery('autor',this).text();
					// parsing the raw HTML
					jQuery('#tmp').html(jQuery('comment',this).text());
					imageCache[first+i]['name'] = jQuery('#tmp').html();
					imageCache[first+i]['thumbnail'] = new Image();
					jQuery(imageCache[first+i]['thumbnail']).load(function () {
						pattern = /.*_/
						indexPhoto = this.id.replace(pattern,'');
						if(queueBigImages.length==0){
							queueBigImages.push(indexPhoto);
							bigImage(indexPhoto,carousel)
						}
						else{
							queueBigImages.push(indexPhoto);
						}
						jQuery(this).css({marginTop:'-'+Math.abs(28-(jQuery(this).attr('height')/2)-2)+'px',marginLeft: '-'+Math.abs(28-(jQuery(this).attr('width')/2)-2)+'px'});
						if(jQuery('.jcarousel-item-'+indexPhoto).length<1){
							$carousel.add(indexPhoto,this);
						}
						else{
				        	jQuery('.jcarousel-item-'+indexPhoto).removeClass('jcarousel-item-placeholder').append(this);						
						}
						jQuery(this).addClass('disabled')
						jQuery(this).fadeIn();
						jQuery(this).wrap('<a href="#"></a>');
						jQuery(this).parent().click(function(){							
							stopDiaporama();
							if(!(/.*small_gray.*/i.test(jQuery('img',this).attr('src')))){
								jQuery('body').css('cursor','wait');
								index = Number(jQuery('img',this).attr('id').replace(/.*_/,''));
								currentPhoto = index+1;
								flag = true;
								queueBigImages.splice(1,0,index);
								if(carousel.first >= index && index>1) carousel.prev();
								else if(carousel.last <= index && carousel.size()-carousel.last>=1) carousel.next();
							}
						});
					}).error(function () {
						// notify the user that the image could not be loaded
					}).attr({
						id:jQuery('photoId:eq(0)',this).text()+'_'+(first+i),
						src:(jQuery('path',this).text()=="")?$URL_SERVER_PHOTO+'photo/SMALL_' + jQuery('name',this).text():$URL_SERVER_PHOTO+'photo/'+jQuery('path',this).text()+'SMALL_' + jQuery('name',this).text(),
						width:jQuery('width',this).text(),
						height:jQuery('height',this).text(),
						title:jQuery('#tmp').html(),
						alt:jQuery('#tmp').html()
					});
				}
			});
		}
		function bigImage(index,carousel){
			try{
				if(!imageCache[index]['imageResized'] && imageCache[index]['url']!='gray.jpg'){
					width = imageCache[index]['width'];
					height = imageCache[index]['height'];
					title = imageCache[index]['name'];
					url = imageCache[index]['url'];
					path = imageCache[index]['path'];
					ratio = width/height;
					maxHeight = jQuery('#frames').height();
					maxWidth = jQuery('#real-content').width()-36;
					newWidth = ((maxHeight*ratio)>maxWidth)?maxWidth-72:maxHeight*ratio;
					newHeight = maxHeight;
					imageCache[index]['imageResized'] = new Image();
					jQuery(imageCache[index]['imageResized']).load(function(){
					jQuery(imageCache[index]['thumbnail']).removeClass('disabled').addClass('enabled');
						jQuery('#imageCacheContainer').append('<div id="photo'+index+'" class="frame-photo"><table>'+
						'<tr><td class="frame-topleft"><img src="/css2_FR/blank.gif" width="18" height="17" border="0" /></td><td class="frame-top"></td><td class="frame-topright"><img src="/css2_FR/blank.gif" width="18" height="17" border="0" /></td></tr>'+
						'<tr><td class="frame-left"></td><td class="frame-content"></td><td class="frame-right"></td></tr>'+
						'<tr><td class="frame-bottomleft"></td><td class="frame-bottom"></td><td class="frame-bottomright"></td></tr>'+
						'<tr><td></td><td class="frame-fake"></td><td></td></tr>'+
						'</table></div>');
						if(jQuery('#photo'+index).find('img:eq(3)').length==0){
							jQuery('#photo'+index).find('.frame-content').append(this);				
							jQuery('#photo'+index).find('.frame-content').append('<p class="title" style="width:'+this.width+'px"><span>'+imageCache[index]['name']+'</span></p>');
							jQuery('#photo'+index).find('.frame-content').append('<div class="comments"></div>');	
							jQuery('#photo'+index).css({left:(maxWidth/2)-(this.width/2)+110,top:(maxHeight/2)-(this.height/2)+100})
							if(jQuery('item',imageCache[index]['comments']).length>0){
								text = '<a style="width:'+this.width+'px" href="#"><u>'+$comment1+'</u>: ['+jQuery('autorComment:eq(0)',imageCache[index]['comments']).text()+'] '+jQuery('textComment:eq(0)',imageCache[index]['comments']).text()+'</a>';
								jQuery('#photo'+index).find('.frame-bottom').append(text)
							}
							else{
								jQuery('#photo'+index).find('.frame-bottom').append('<a href="#">'+$commentDefault+'</a>')
							}
							jQuery('#photo'+index+' .frame-bottom a').click(function(){stopDiaporama();showComments(index)})
							jQuery('#real-content').removeClass('loading-photo');
						}
						
							jQuery(imageCache[index]['thumbnail']).parent().unbind('click');
							jQuery(imageCache[index]['thumbnail']).parent().click(function(){
								stopDiaporama();
								pattern = /.*_/
								indexPhoto = jQuery(imageCache[index]['thumbnail'])[0].id.replace(/.*_/,'');
								if(indexPhoto == 1 || indexPhoto == carousel.size()) return false;
								currentPhoto = indexPhoto;
								if(carousel.first >= indexPhoto && indexPhoto>1) {
									carousel.prev();
								}
								else if(carousel.last <= indexPhoto && carousel.size()-carousel.last>=1){
									carousel.next();
								}
								effectPhoto(indexPhoto);
							});
							
						if(flag && index==(currentPhoto-1)){
							if(lastPhoto){
								lastPhoto=null;
								currentPhoto = currentPhoto-1
								handlerInterval(timerDelay);
							}
							else{
								effectPhoto(currentPhoto-1);
							}
							flag = false;							
						}
						garbage = queueBigImages.shift();
						bigImage(queueBigImages[0],carousel)	
					}).error(function(){
					}).attr({
						id:'bigPhotoId'+index,
						src:(path=='')?$URL_SERVER_PHOTO+'resize.php?img=BIG_'+url+'&h='+newHeight+'&w='+newWidth+'&q='+$BIG_QUALITY:$URL_SERVER_PHOTO+'resize.php?img='+path+'BIG_'+url+'&h='+newHeight+'&w='+newWidth+'&q='+$BIG_QUALITY
					});	
				}
				else{
					garbage = queueBigImages.shift();
					bigImage(queueBigImages[0],carousel)
				}
			}
			catch(e){}
		}
		function effectPhoto(index,timerDelay){
			jQuery('body').css('cursor','auto');		
			jQuery('.frame-photo').fadeOut();
			jQuery('#photo'+index).fadeIn();
			currentPhoto = jQuery(jQuery('.jcarousel-item-'+index).nextAll('li:visible').find('img')[0]).attr('id').replace(/.*_/,'')
			jQuery.cookie('currentPhoto',currentPhoto);
			return;
		}
		//binding events
		jQuery('.other-functions').click(function(){
			jQuery('.delete-photo,.download-photo').toggleClass('advanced-features');
		});
		function waitUntilNextPhotoIsAvailable (photoIndex){
					waitTimer = setInterval(function(){
						if(jQuery(jQuery('.jcarousel-item-'+currentPhoto).nextAll('li:visible').find('img')[0]).hasClass('enabled')){
							clearInterval(waitTimer);
							waitTimer = null
							currentPhoto = (parseInt(currentPhoto)*1);
							handlerInterval(timerDelay);
						}
					},500);
				}
		function handlerInterval(timerDelay){
			carouselTimer = setInterval(function(){
				if(jQuery(jQuery('.jcarousel-item-'+currentPhoto).nextAll('li:visible').find('img')[0]).hasClass('disabled') && ($carousel.size()-currentPhoto)>1){
					clearInterval(waitTimer);
					waitTimer = null
					stopDiaporama();
					waitUntilNextPhotoIsAvailable(jQuery(jQuery('.jcarousel-item-'+currentPhoto).nextAll('li:visible').find('img')[0]).attr('id').replace(/.*_/,''));
				}			
				else if($carousel.last <= currentPhoto && $carousel.size()-$carousel.last>=1){
					$carousel.next();
					effectPhoto(currentPhoto,timerDelay);
				}	
				else if(($carousel.size()-currentPhoto)<1){
					lastPhoto = currentPhoto;
					try{
						currentPhoto = jQuery(jQuery('.jcarousel-item:visible')[1]).find('img').attr('id').replace(/.*_/,'');
					}
					catch(e){
						currentPhoto = 3
					}
					flag=true;
					jQuery.cookie('currentPhoto',currentPhoto);
					stopDiaporama();
					$carousel.scroll(0)
				}
				else{
					effectPhoto(currentPhoto,timerDelay);
				}
			},timerDelay);
		}
		jQuery('.fast').click(function(){
			timerDelay=3000;
			stopDiaporama();
			handlerInterval(timerDelay)
		});
		jQuery('.slow').click(function(){
			timerDelay=6000;
			stopDiaporama();
			handlerInterval(timerDelay)
		});
		jQuery('.static').click(function(){
			stopDiaporama();
		})
		function stopDiaporama(){
			if(carouselTimer!=null){				
				clearInterval(carouselTimer);
				carouselTimer = null;
			}
			if(waitTimer!=null){
				clearInterval(waitTimer);
				waitTimer = null
			}
		}
		jQuery('.download-album').click(function(){
			blockDiaporama();	
			downloadAlbum();
		});
		jQuery('.download-photo').click(function(){
			stopDiaporama();
			try{
				photoIndex = jQuery('.frame-photo:visible')[0].id.replace('photo','');
				id = jQuery('.jcarousel-item-'+photoIndex).find('img')[0].id.replace(/_.*/,'');						
			}
			catch(e){id = null}
			blockDiaporama();	
			download(id);
		});
		function blockDiaporama(message){
				jQuery.blockUI({
				message: (message)?message:null,
				fadeIn: 700, 
	            fadeOut: 700,
				overlayCSS: {
					backgroundColor: '#59A7FE' 
				},
				css:{
					border: 'none', 
	            	background: '#FFF',
					color:'#6291A4',
					fontHeight:'bold',
					opacity:0.8,
					'-webkit-border-radius': '10px', 
					'-moz-border-radius': '10px'
				}
			});
			myObserver = {
			    onDestroy: function(eventName, winObs) {
			      if (winObs == win ) {
			        win = null;
			        Windows.removeObserver(this);
					jQuery('body').css('cursor','auto');		
					jQuery.unblockUI();
			      }
			    }
			  }
			Windows.addObserver(myObserver);
		}
		function alerts(){
			win = new Window('Alert', {
				className: "via_album",
				width:503, height:90, 
				closable: false,
				maximizable:false,
				minimizable:false
			});
			win.setTitle($alertTitle);
		    win.setDestroyOnClose();								
			win.setZIndex(2000);
			win.showCenter();
			win.getContent().innerHTML= $alertHTML;
		}
			function downloadAlbum(){
			//get queue
				win = new Window('Telecharger', {className: "via_album",
								  width:543, height:170, 
								  closable:false,maximizable:false,minimizable:false}); 
								  win.setTitle($downloadTitle);
								  win.setDestroyOnClose();								
								  win.showCenter();
								  win.getContent().innerHTML= $downloadHTML;
  								  win.setZIndex(2000);
								  id=$id;
								  x_downloadAlbum(id,globals.do_downloadAlbum);				  
								  
	   }
	   globals.do_downloadAlbum=function(val)
	   {
    	   val=val.split('/--/');
	       jQuery('#sizefile').html(val[0])
		   jQuery('#download').click(function(){
		   window.open(val[1],'_blank','location=no,menubar=no,scrollbars=no,resize=no,resizable=no,status=no,toolbar=no,directories=no,width=5,height=5,top=0,left=0');parent.win.destroy();
		   });
	       jQuery('#wait').hide();
		   jQuery('#downloadalbum').show();
	   }

		function download(id){
			if (id == null || !id || id<=0){
				alerts();
				return;
			}
			else{
			//get queue
			win = new Window('Telecharger', {
				className: "via_album",
				width:543, height:170,
				closable:false,
				maximizable:false,
				minimizable:false, 
				url: "telecharger_photos.php?id="+id+"&albumid="+$id
			});
			win.setTitle($downloadTitle);
		    win.setDestroyOnClose();								
			win.setZIndex(2000);
			win.showCenter();
		 }
		}
		function showComments(index){
			jQuery('#photo'+index+' table .frame-bottom a')
				.fadeOut('slow',
				function(){
					jQuery('#photo'+index)
						.css({width:jQuery('#real-content').width()+'px',
							height:jQuery('#real-content').height()+'px',
							left:'109px'}
						)
						.data('offset',
							{top:jQuery('#photo'+index).css('top'),
							left:jQuery('#photo'+index).css('left')}
						)
						.animate(
							{top:'102px'}
							,1000,'swing'
						);		
					jQuery('#photo'+index+' table .frame-fake')
						.data('dimensions',
							{width:jQuery('#photo'+index+' table .frame-fake').width()}
						)
						.animate(
							{width:(jQuery('#real-content').width()-40)+'px'},1000,'swing',
							function(){
								
							}
						);
					jQuery('#photo'+index+' table .frame-content .title')
						.data('dimensions',
							{width:jQuery('#photo'+index+' table .frame-content .title').width(),
							height:jQuery('#photo'+index+' table .frame-content .title').height()}
						)
						.css(
							{width:'auto',
							height:'auto',
							padding:'3px 0 0 15px',
							textAlign:'left'}
						);
					jQuery('#photo'+index+' table .frame-content img:eq(0)')
						.data('dimensions',
							{width:jQuery('#photo'+index+' table .frame-content img:eq(0)').width(),
							height:jQuery('#photo'+index+' table .frame-content img:eq(0)').height()}
						)
						.css('float','left')
						.animate(
							{width:jQuery('.jcarousel-item-'+index+' img').width()+'px',
							height:jQuery('.jcarousel-item-'+index+' img').height()+'px'},1000,'swing',
							function(){
							
							}
						);
					jQuery('#photo'+index+' table .frame-content .title')
						.append('<br/><label class="autor">'+$commentAdded+': '+imageCache[index]['autor']+'</label>');				
					drawComments(index);
					jQuery('#photo'+index+' table .frame-content .comments')
						.css('clear','both')
						.animate(
							{height:(jQuery('#real-content').height()-150)+'px'},1000,'swing',
							function(){
								
							}
						);
					jQuery('#photo'+index+' table .frame-content .list-comments')
						.height(jQuery('#photo'+index+' table .frame-content .comments').height()-60);
					jQuery('#photo'+index+' table .frame-content .list-comments, #photo'+index+' table .frame-content .comment-input')
						.fadeIn('slow');
				}
			);
		}
		function hideComments(index){			
			jQuery('#photo'+index+' table .frame-content .list-comments, #photo'+index+' table .frame-content .comment-input')
				.fadeOut('slow',
				function(){
					
				}
			);
			jQuery('#photo'+index+' table .frame-content .list-comments')
				.css('height','auto');
			jQuery('#photo'+index+' table .frame-content .comments')
				.animate(
					{height:0},1000,'swing',
					function(){
						
					}
				);
			jQuery('#photo'+index+' table .frame-content .title')
				.css(
					{width:jQuery('#photo'+index+' table .frame-content .title').data('dimensions').width+'px',
					padding:'3px 0 0 0',
					textAlign:'center'}
				);
			jQuery('#photo'+index+' table .frame-content .title br, #photo'+index+' table .frame-content .title label')
				.remove();
			jQuery('#photo'+index+' table .frame-content img:eq(0)')
				.css('float','none')
				.animate(
					{width:jQuery('#photo'+index+' table .frame-content img:eq(0)').data('dimensions').width+'px',
					height:jQuery('#photo'+index+' table .frame-content img:eq(0)').data('dimensions').height+'px'},1000,'swing',
					function(){
					
					}
				);
			jQuery('#photo'+index)
				.animate(
					{top:jQuery('#photo'+index).data('offset').top},1000,'swing'
				);
			jQuery('#photo'+index+' table .frame-fake')
				.animate(
					{width:jQuery('#photo'+index+' table .frame-content img').data('dimensions').width+'px'},1000,'swing',
					function(){
						jQuery('#photo'+index+' table .frame-bottom a')
							.fadeIn('slow');
					}
				);
		}
		function drawComments(index){
			if(jQuery('#photo'+index+' table .frame-content .comments .list-comments').length==0){
				jQuery('#photo'+index+' table .frame-content .comments')
					.append('<div class="list-comments"></div><div class="comment-input"><a href="#">'+$commentBack+'</a></div>');
				text="";
				jQuery('item',imageCache[index]['comments'])
					.each(
						function(){
							text += '<p id="comment'+jQuery('photoCommentId',this).text()+'" class="item-comment bubbleInfo"><span class="trigger"><strong>'+jQuery('autorComment',this).text()+':</strong> <span>'+jQuery('textComment',this).text()+'</span></span></p>';
						}
					);
				jQuery('#photo'+index+' table .frame-content .list-comments')
					.append(text);

				jQuery('#photo'+index+' table .frame-content .comments .comment-input a')
					.unbind()
					.click(
						function(){
							hideComments(index);
						}
					);
			}
		}	
});
