var flashvars = {};
var params = { allowscriptaccess: "always" };
var withArrows = false;
var clickOnPrimary = false;
var albumClicked = '';

var direction = '';
var imgWidth = '';
var leftOffset = '';
var currentPreview = '';
/*
 * displays the small bottom jcarousel image in the main image area
 */
albumPhotosClick = function(event){
	var mainImageTag = $(this).parents('a:first');
	var photoName = unescape(mainImageTag.attr('alt'));
	var photoComment = unescape(mainImageTag.attr('imgDesc'));
	var photoInfo = unescape(mainImageTag.attr('imgInfoSize'));
	
	var photoId = $(this).attr('id').split('_');
	currentPhotoId = parseInt(photoId[1]); 
    currentAlbumId = parseInt(photoId[0]);
    
	$("#main-photo-container").fadeOut(100, function (){
		 var replaceHtml = '<div class="main-img-left-arrow" style="top: '+parseInt(mainImageTag.attr('oheight')/2)+'px; display: '+(withArrows == true && $('#'+currentAlbumId+'_'+(currentPhotoId-1)).length ? "block" : "none")+';"></div>';
		 replaceHtml = replaceHtml + '<div class="main-img-right-arrow" style="top: '+parseInt(mainImageTag.attr('oheight')/2)+'px; display: '+(withArrows == true && $('#'+currentAlbumId+'_'+(currentPhotoId+1)).length ? "block" : "none")+';"></div>'; 
		 replaceHtml = replaceHtml + '<div id="photo-container" style="width: '+mainImageTag.attr('owidth')+'px;">';
		 replaceHtml = replaceHtml + '<img src="'+mainImageTag.attr('href')+'" width="'+mainImageTag.attr('owidth')+'" height="'+mainImageTag.attr('oheight')+'" />';
		 replaceHtml = replaceHtml + '<div id="photo-info" style="width: '+(mainImageTag.attr('owidth') - 40)+'px;">';
		 replaceHtml = replaceHtml + '<p id="photo-info-name">'+photoName+'</p>';
		 replaceHtml = replaceHtml + '<p id="photo-info-size">'+photoInfo+'</p>';
		 replaceHtml = replaceHtml + '<p id="photo-info-comment">'+photoComment+'</p>';	
		 replaceHtml = replaceHtml + '</div></div>';
		 $("#main-photo-container").html(replaceHtml).fadeIn(100, function(){ bindEvents();});
		 
	});
	
	//bindEvents();

	return false;
}
/*
 * function that toggles between PROFILE and PORTFOLIO tabs
 */
toggleTab = function(page) {
	var parentHeight = '';
	var leftOffset = $('#profile-content').width();

	if(page == 'profile') {
		//dashboard tab changes
		$('.dashboard-tab li.profile').addClass('active');
		$('.dashboard-tab li.portfolio').removeClass('active');
		$('.dashboard-tab').removeClass('myDashboard-myPortfolio').addClass('myDashboard-myProfile');
		
		//swap main container changes
		$('#profile-container .swap-content').removeClass('active-content');
		$('#profile-container').css('height', $('#profile-content')[0].offsetHeight+'px');
		$('#profile-content').addClass('active-content');
	}
	else if(page == 'portfolio'){
		//dashboard tab changes
		$('.dashboard-tab li.profile').removeClass('active');
		$('.dashboard-tab li.portfolio').addClass('active');
		$('.dashboard-tab').removeClass('myDashboard-myProfile').addClass('myDashboard-myPortfolio');
	
		//swap main container changes
		$('#profile-container .swap-content').removeClass('active-content');
		$('#profile-container').css('height', $('#portfolio-content')[0].offsetHeight+'px');
		$('#portfolio-content').addClass('active-content');
		if (albumClicked == '')
		{
			$('.albums-list li:first').trigger('click');
		}
	}
}

/*
 * function that replace current album content with the other album content
 */
getHtmlForAlbum = function(albumId, userId){
	$.ajax({
		   type: "POST",
		   url: albumHtmlUrl,
		   data: "albumId="+albumId+"&userId="+userId+"&photoId="+photoId,
		   //data: "albumId="+albumId+"&userId="+userId,
		   success: function(response){
						//replace content
						$('#portfolio-album-photos').html(response);
						flashvars = {
								feed: varUrlCoolIris,
								linkTarget: '_top'
							};
						swfobject.embedSWF("http://apps.cooliris.com/embed/cooliris.swf",
				                   "wall", "927", "500", "9.0.0", "", 
				                   flashvars, params);
						//cooliris.embed.setFeedUrl(escape(varUrlCoolIris));
						
						bindEvents(true);
						$('.jcarousel-container #next').trigger('click');
						if(carouselScrollPosition == 1 && clickOnPrimary)
						{
							$('#photos-list img[name=primary]').click();
							clickOnPrimary = false;
						}
					}
	});
}

/**********************
 * new Ajax Carousel
 */

function mycarousel_initCallback(carousel, state)
{
	carousel.size(albumPhotoNr);
}
function mycarousel_itemLoadCallback(carousel, state)
{
	if (state == 'init' && carouselScrollPosition)
	{
		carousel.scroll(carouselScrollPosition);
	}
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
   $('#photos-viewer #loader-overlay').show();
   $.get(
        albumPartHtmlUrl,
        {
			albumId: albumClicked,
			userId: userId,
			photoId: photoId,
            first: carousel.first
        },
        function(data) {
            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
        }
    );
};

function mycarousel_itemAddCallback(carousel, first, last, data)
{
	var elements = data.substr(3).split('|||');
	var currentElement = '';
	var index = first;
    $(elements).each(function(i, val) {
		currentElement += val;
		if(i%2)
		{
			carousel.add(index, currentElement);
			index++;
			currentElement = '';
		}
    }).after(function(){
		if(currentElement != '')
		{
			carousel.add(index, currentElement);
			currentElement = '';
		}
		bindEvents();
		if ( (carouselScrollPosition >= first) && (carouselScrollPosition <= last) )
		{
			carouselScrollPosition = null;
			if(clickOnPrimary)
			{
				$('#photos-list img[name=primary]').click();
				clickOnPrimary = false;
			}
		}
		$('#photos-viewer #loader-overlay').hide();
	});
};

function mycarousel_getItemHTML(url)
{
	return url;
};

/**********************************/

/*
 * bind jScrollPane, jcarousel, cooliris, clicks and hovers 
 */
bindEvents = function(with_carousel){
	//view large version of the image
	$('#photos-list img').unbind('click').bind('click', albumPhotosClick);
	
	//bottom jCarousel links which wrap the images should never point anywhere
	$('a[name="link-for-preview"]').unbind('click').bind('click', function(e){ e.preventDefault(); return false; });
	//information about photo on hover...
	$('#photo-container').hover(
		function(){ $('#photo-info').fadeIn(); },
		function(){ $('#photo-info').fadeOut(); }
	);
	
	if (with_carousel) 
	{
		//photo carousel...
		$('#photos-list').jcarousel({
			scroll: 7,
			buttonPrevHTML: '<a id="prev"></a>',
			buttonNextHTML: '<a id="next"></a>',
			initCallback: mycarousel_initCallback,
			buttonPrevCallback: imgPreviewOrientation,
			// Uncomment the following option if you want items
			// which are outside the visible range to be removed
			// from the DOM.
			// Useful for carousels with MANY items.
			
			// itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }},
			itemLoadCallback: mycarousel_itemLoadCallback
		});
	}
   
    //cooliris
	$('a.icon-cooliris').click(function(){
		//$('#cooliris-mask').fadeToggle('normal', function(){ $('#cooliris-popup').toggle(); });
		$('.cooliris-popup-mask').toggle();
		$('#cooliris-popup').toggle();
	});
	
	$('#cooliris-popup').click(function(){
		//$('#cooliris-mask').fadeToggle('normal', function(){ $('#cooliris-popup').toggle(); });
		$('.cooliris-popup-mask').toggle();
		$('#cooliris-popup').toggle();
	});
	
	$('#cooliris-x-button').unbind('click').bind('click', function(e){
		$('.cooliris-popup-mask').toggle();
		$('#cooliris-popup').toggle();

		e.preventDefault();
		return false;
	});
    
	$('#cooliris-x-button').click(function() {
		$('#cooliris-popup').hide();
		$('.cooliris-popup-mask').hide();
	});
	
	//main image left/right arrows
	 $('#main-photo-container').unbind('hover').hover(
			 function() { 
				 if($('#'+currentAlbumId+'_'+(currentPhotoId-1)).length)
				 {
					 $('.main-img-left-arrow').show();
				 }
				 if($('#'+currentAlbumId+'_'+(currentPhotoId+1)).length)
				 {
					 $('.main-img-right-arrow').show();
				 }
				 withArrows = true;
			 }, 
			 function() { 
				 $('.main-img-left-arrow, .main-img-right-arrow').hide();
				 withArrows = false;
			 }
	 );

	$('.main-img-right-arrow').unbind('click').bind('click',function() { withArrows = true; $('#'+currentAlbumId+'_'+(currentPhotoId+1)).click(); } );
	$('.main-img-left-arrow').unbind('click').bind('click', function() { withArrows = true; $('#'+currentAlbumId+'_'+(currentPhotoId-1)).click();} );
	
	imgPreviewOrientation();
}

imgPreviewOrientation = function(){
	if($('a[name=link-for-preview]').length)
	{
		$('a[name=link-for-preview]').each(function(){
			
			currentPreview = $(this).attr('id');
			currentPreview = currentPreview.replace('preview-', '');
			
			$('#imgPreviewWithStyles-'+currentPreview).remove();
			
			direction = $(this).attr('class');
			imgWidth = $(this).attr('imgwidth');
			leftOffset = $(this).offset();
			
			if(leftOffset.left  <= 950)
			{
				leftOffset = 20;
			}
			else
			{
				leftOffset = ((-1)*imgWidth) - 40;
			}
		
			$(this).imgPreview({
				containerID: 'imgPreviewWithStyles-'+currentPreview,
				containerLoadingClass: 'loading',
			    onShow: function(link){
							$('img', this).attr('width', $(link).attr('imgwidth'));
							$('img', this).attr('height', $(link).attr('imgheight'));
							$(this).addClass('imgPreviewWithStyles');
							if($(link).attr('alt').length)
					    	{	
								$('<p style="width: '+$(link).attr('imgwidth')+'px; text-align: center; font-weight: bold; color: #fff; ">'+$(link).attr('alt')+'</p>').appendTo(this);
					    	}
			    },
			    onHide: function(link){
			    	if($(link).attr('alt').length)
			    	{	
			    		$('p', this).remove();
			    	}
			    },
			    distanceFromCursor: { top: -210, left: leftOffset }
			});
		});
		
		$('a[name=link-for-preview]').click(function() { return false;});
	}
}
goToAlbum = function(obj){
	var albumId = obj.attr('class').split(' ')[1];
	
	clickOnPrimary = true;
	$('#albums-list-'+albumId).click();
	$('.albums-list')[0].scrollTo($('#albums-list-'+albumId)[0].offsetTop-50);
	toggleTab('portfolio');
};
/*
 * DOCUMENT READY
 */
$(document).ready(function(){
	
	//set profile container height
	$('#profile-container').css('height', $('#profile-content')[0].offsetHeight+'px');
	
	//highlight selected album on list
	$('ul.albums-list a').unbind('click').bind('click',function(e){
		if(!$(this).hasClass('selected')){
			albumClicked = $(this).attr('id').replace('albums-list-', '');
			getHtmlForAlbum(albumClicked, userId);
		}
		$('ul.albums-list li.selected').removeClass('selected');
		$(this).parents('li:first').addClass('selected');
		e.stopPropagation();
	});
	
	$('ul.albums-list li').bind('click', function(e){
		$(this).find('a:first').trigger('click');
	});
	
	//bind events
	//bindEvents(true);
	
	if(viewPortfolio == true)
	{
		toggleTab('portfolio');
	}
	
	//dashboard tab (AJAX)
	$('.dashboard-tab li').not('active').filter(function(){ return $(this).hasClass('profile'); }).click(function(){
		toggleTab('profile');
	})
	$('.dashboard-tab li').not('active').filter(function(){ return $(this).hasClass('portfolio'); }).click(function(){
		toggleTab('portfolio');
	})
	
	///////////////////////////////////// bind events for portfolio page /////////////////////////////////////////////
	$('#show-all').click(function(){ toggleTab('portfolio'); });
	$('a.view-album').click(function(){ getHtmlForAlbum($(this).attr('class').split(' ').slice(-1), userId); });
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	flashvars = {
			feed: varUrlCoolIrisPortfolio,
			linkTarget: '_top'
		};

	swfobject.embedSWF("http://apps.cooliris.com/embed/cooliris.swf",
	                   "wall", "927", "500", "9.0.0", "", 
	                   flashvars, params);
});

$(window).load(function(){
	//custom scrollbar for albums list...
	$('.albums-list').jScrollPane({scrollbarOnLeft:true});
	
	if(openTab == 'portfolio')
	{
		if (typeof(albumId) != 'undefined' && albumId.length != 0) {
			clickOnPrimary = true;
			$('#albums-list-'+albumId).click();
			$('.albums-list')[0].scrollTo($('#albums-list-'+albumId)[0].offsetTop-50);
		}
		toggleTab('portfolio');
	}
	
	$('#photos a').click(function(){
		goToAlbum($(this));
	});
});

//OLD

/*var firstClick = true;
var currentPhotoId = null;
var currentAlbumId = null;
var withArrows = false;

bindPreviews = function(){
	$('a[name=link-for-preview]').imgPreview({
		containerID: 'imgPreviewWithStyles',
		containerLoadingClass: 'loading',
	    onShow: function(link){
					$('img', this).attr('width', $(link).attr('imgwidth'));
					$('img', this).attr('height', $(link).attr('imgheight'));
					
					if($(link).attr('alt').length)
			    	{	
						$('<span style="width: '+$(link).attr('imgwidth')+'px;">'+$(link).attr('alt')+'</span>').appendTo(this);
			    	}
	    },
	    onHide: function(link){
	    	if($(link).attr('alt').length)
	    	{	
	    		$('span', this).remove();
	    	}
	    },
	    distanceFromCursor: {top: -210,left: 20}
	});
	
	$('a[name=link-for-preview]').click(function() { return false;});
}
albumPhotosClick = function(event){
	var mainImageTag = $(this).parent();
	var photoName = mainImageTag.next();
	var photoComment = photoName.next();
	var photoInfo = $(this).attr('id').split('_');
	currentPhotoId = parseInt(photoInfo[1]); 
    currentAlbumId = parseInt(photoInfo[0]);

	if(!firstClick)
	{
		/*$('#main_album_photo').fadeOut('fast', function(){
			$('#main_album_photo').html('<img src="'+mainImageTag.attr('src')+'" width="'+mainImageTag.width()+'" height="'+mainImageTag.height()+'" />');
			$('#main_album_photo').fadeIn();
		});*/
		/*
		 $("#main_album_photo").fadeTo(100, 0,function (){
			 var replaceHtml =  '<div class="main-img-left-arrow" style="top: '+parseInt(mainImageTag.attr('oheight')/2)+'px; display: '+(withArrows == true && $('#'+currentAlbumId+'_'+(currentPhotoId-1)).length ? "block" : "none")+';"></div>'+
			 					'<div class="main-img-right-arrow" style="top: '+parseInt(mainImageTag.attr('oheight')/2)+'px; display: '+(withArrows == true && $('#'+currentAlbumId+'_'+(currentPhotoId+1)).length ? "block" : "none")+';"></div>'+
				 				'<div class="main_img_holder" style="width: '+mainImageTag.attr('owidth')+'px;">'+
									'<img src="'+mainImageTag.attr('href')+'" width="'+mainImageTag.attr('owidth')+'" height="'+mainImageTag.attr('oheight')+'" />';
			 if(photoName.html().length || photoComment.html().length)
			 {
				replaceHtml = replaceHtml + '<label class="portfolio_main_image_title" style="display: '+(withArrows == true ? "block" : "none")+';">'+photoName.html()+'<br/><span>'+photoComment.html()+'</span></label>';
			 }
			 replaceHtml = replaceHtml + '</div>';
			 
            $("#main_album_photo").html(replaceHtml).fadeTo(100, 1);
            $('#main_album_photo').hover(function() { 
												if($('#'+currentAlbumId+'_'+(currentPhotoId-1)).length)
												{
													$('.main-img-left-arrow').show();
												}
												if($('#'+currentAlbumId+'_'+(currentPhotoId+1)).length)
												{
													$('.main-img-right-arrow').show();
												}
												$('.portfolio_main_image_title').fadeIn();
												withArrows = true;
											}, 
										function() { 
												$('.main-img-left-arrow, .main-img-right-arrow').hide();
												$('.portfolio_main_image_title').fadeOut();
												withArrows = false;
											}
							);
			$('.main-img-right-arrow').click(function() { withArrows = true; $('#'+currentAlbumId+'_'+(currentPhotoId+1)).click();});
			$('.main-img-left-arrow').click(function() { withArrows = true; $('#'+currentAlbumId+'_'+(currentPhotoId-1)).click();});
		 });
	}
	firstClick = false;

	if(photoName.html() || photoComment.html())
	{
		$('#photo_row_holder div.row .infobar').show();
		if(photoName.html())
		{
			$('.album-name').show();
			$('.photo_name').html(photoName.html());
		}
		else
		{
			$('.album-name').hide();
		}
		if(photoComment.html())
		{
			$('.photo-comment-name').show();
			$('.photo_comment').html(photoComment.html());
		}
		else
		{
			$('.photo-comment-name').hide();
		}
	}
	else
	{
		$('#photo_row_holder div.row .infobar').hide();
	}
	
	return false;
}

buildCarousel = function(elementId){
	
	if(typeof elementId == 'undefined')
	{
		elementId = 'ul[name=album-photos]';
	}
	else
	{	
		elementId = '#'+elementId+' ul[name=album-photos]';
	}

	imageCount = $(elementId+' li').length;

	if(imageCount <= 11)
	{
		$(elementId).jcarousel({
			scroll: 11,
			buttonNextHTML: null,
			buttonPrevHTML: null
		});		
	}
	else
	{
		$(elementId).jcarousel({
			scroll: 11
		});
	}
}
getHtmlForAlbum = function(albumId, alsoShow)
{

	if(typeof albumId == 'undefined')
	{
		nextAlbum = $('#albums-list').children(':eq(1)');
		nextAlbumId = nextAlbum.children(':eq(0)').attr('id');
		if(typeof nextAlbumId != 'undefined')
		{
			albumId = nextAlbumId.substr(9, nextAlbumId.length);
		}
	}
	if($('#photo_row_holder div#'+albumId).length == 0 && typeof albumId != 'undefined')
	{
		$.ajax({
			   type: "POST",
			   url: albumHtmlUrl,
			   data: "albumId="+albumId+"&userId="+userId+"&photoId="+photoId,
			   success: function(msg){
					$('#photo_row_holder').append(msg);
					$('ul[name=album-photos] img').bind('click', albumPhotosClick);
					bindPreviews();
					if(typeof alsoShow != 'undefined' && alsoShow == true)
					{
						$('#link_for_'+albumId).click();
					}
			}
		});
	}
}

$(window).load(function(){
//$(document).ready(function(){
//window.onload = function() {
	
	$('#albums-list').jScrollPane({
		scrollbarWidth: 17, 
		scrollbarMargin: 10,
		showArrows: true,
		arrowSize: 14
	});

	$('#portfolio-content').hide();
	$('#portfolio-content').css('left', 0);
	$('#profile-content').show();	

	var flashvars = {
			feed: varUrlCoolIris,
			linkTarget: '_top'
		};
	var params = {
		    allowscriptaccess: "always"
		};
		
	swfobject.embedSWF("http://apps.cooliris.com/embed/cooliris.swf",
	                   "wall", "995", "600", "9.0.0", "", 
	                   flashvars, params);

	$('img[name=carousel_images]').click(
			function(event)
			{
				var id = $(this).attr('id');
				var numId = id.substr(12, id.length-1);

				$('div[name=main_image]').hide();
				$('#main_image_'+numId).show();
				
				return false;
			}
	);
	$('#use-cooliris').click(function(){
		$('#cooliris-popup').toggle();
		$('#cooliris-mask').toggle();
	});
	
	$('#cooliris-popup').click(function(){
		$('#cooliris-popup').toggle();
		$('#cooliris-mask').toggle();
	});
	
	$('.profile-tabs a').click(function(){
		$('.profile-tabs a').removeClass('active');
		$('.profile-content').hide();
		$('#' + this.id).addClass('active');
		$('#' + this.id + '-content').show();
		if(this.id == 'portfolio')
		{
			firstClick = false;
			$('#albums-list li a:first').click();
			getHtmlForAlbum();
		}
	});
	$('a[name="album_title_link"]').click(
			function(event)
			{
				var albumId = $(this).attr('id');
				
				albumId = albumId.substr(9, albumId.length);
				$('#albums-list li').removeClass('active-album');
				$(this).parents(':first').addClass('active-album');
				$('.overlay').hide();
				if($('#photo_row_holder div#'+albumId).length == 0)
				{
					$('.overlay').show();
					getHtmlForAlbum(albumId, true);
				}
				else
				{	
					$('div.box[name=title]').hide();
					
					$('#title_'+albumId).show();
					$('#photo_row_holder div.row').hide();
					$('#photo_row_holder div.row[id='+albumId+']').show();
					
					if($('#photo_row_holder div.row[id='+albumId+'] img[name=primary]').length != 0)
					{
						$('#photo_row_holder div.row[id='+albumId+'] img[name=primary]').click();
					}
					else
					{
						$('#photo_row_holder div.row[id='+albumId+'] img:first').click();
					}
					var nextId = $(this).parent().next().children().attr('id');
	
					if(typeof nextId != 'undefined' && $('#albums-list li:first a').attr('id') != $(this).attr('id') )
					{	
						nextId = nextId.substr(9, nextId.length);
						getHtmlForAlbum(nextId, false);
					}
					buildCarousel(albumId);
				}
				
				return false;
			}
	);
	$('ul[name=album-photos] img').bind('click', albumPhotosClick);
	
	$('#go-to-portfolio').click(function(){
		$('.profile-tabs a').removeClass('active');
		$('.profile-content').hide();
		$('#portfolio').addClass('active');
		$('#portfolio-content').show();
		$('#albums-list li a:first').click();
		$('#albums-list')[0].scrollTo(0);
	});
	
	$('#portfolio').click(function() {
		if($('#albums-list').length == 1)
		{
			$('#albums-list')[0].scrollTo(0);
		}
	});
	
	if(openTab == 'portfolio')
	{
		$('.profile-tabs a').removeClass('active');
		//$('#profile-content').hide('fast', function() { $('#portfolio-content').show(); });
		$('#profile-content').hide('fast');
		$('#portfolio-content').show('fast');
		$('#portfolio').addClass('active');
		
		firstClick = false;

		if (typeof(albumId) != 'undefined' && albumId.length != 0) {
			$('#link_for_sitm' + albumId).click();
			$('#albums-list')[0].scrollTo('#link_for_sitm' + albumId);
		}
		else
		{
			id = $('#albums-list li a:first')[0].id;
			id = id.replace('link_for_sitm', '');
			buildCarousel(id);
		}
		//buildCarousel();
	}
	else
	{
		//window.onload = buildCarousel();
		buildCarousel();
	}
	
	$('.covers a').mouseenter(function(){
		$('.album-cover label').fadeOut("fast");
		var labelId = 'label_'+$(this).children('img').attr('id').replace('album_', '');
		$('#'+labelId).fadeIn();
	}).mouseleave(function(){
		var labelId = 'label_'+$(this).children('img').attr('id').replace('album_', '');
		$('#'+labelId).fadeOut();
	});

	bindPreviews();
});*/
//}
