/* file: User.js */
var User = Class.create(Application.prototype, {
    
    /*basicInit: function () {
        
        this.ajaxForm('checkNickForm', {
            'onSuccess': this.checkNickFormProcessResponse.bind(this),
            'errorList': {
                403: this.checkNickFormProcessResponse.bind(this, 'checkNickForm'),
                409: this.checkNickFormProcessResponse.bind(this, 'checkNickForm')
            }
        });
        //Application.registerHistoryCallback('user', this.handleHashChange.bind(this));
    },*/
    checkNickAvailability: function (checkNickAvailabilityUrl) {
        //var nick = document.getElementById('nick').value;
        var nick = $('#nick').val();
        this.ajaxPost(checkNickAvailabilityUrl, {nick: nick}, {
            'onSuccess': function (response) {
            
                this.checkNickFormProcessResponse(response);
            }.bind(this)
        });
        return false;
    },
    
    identificationCookie: function( cookieValue ) {
        
        // Create cookie value
        var cookieInput = '<input type="hidden" name="gemius_status_id" value="' + cookieValue + '" />';    
        // Append input to comment forms
        $('#checkNickForm').prepend( cookieInput );
        // Remove swf object
        $('#usercookie').remove();
    },

    addEntryActive: false,
    addRecommendationActive: false,    

    entryBox:   '<div id="entryBox">' +
                    '<form id="entryForm" action="%reportUrl" method="post">'+
                        '<label for="content">' + 
                              '%label'  +
                            ' <textarea cols="60" rows="10" name="entryContent"> </textarea>'+
                        '</label>' +
                        '<input type="submit">'+
                    '</form>'+
                '</div>',
	checkNickFormProcessResponse: function (obj) {
        if (obj.isNickAvailable) {
            $('#idDivNickavailable').attr('class', 'actionOK');
            $('#nick').attr('class', 'dataOK');
        } else {
            $('#idDivNickavailable').attr('class', 'actionError');
            $('#nick').attr('class', 'error');
        }
        $('#idDivNickavailable').attr('innerHTML', obj.text);
        return false;
    },
    
	deleteOrder: function (deleteOrderUrl) {

		this.ajaxPost(deleteOrderUrl, {}, {
			onSuccess: function (obj) {
				if (obj.content) 
					$('#uploadOrders').html(obj.content);
			}.bind(this)
		});
		return false;
	},
    
    recommend : function(recommendUrl) {
    
        if (this.addRecommendationActive) {
            return false;
        }
        this.addRecommendationActive = true;    
        
        user.ajaxPost(recommendUrl, {}, {
            onSuccess: function (obj) {
               $('#recommend').remove();
               
               this.showMsg(Application_lang.recommendationAdded, this.REQUEST_STATUS_OK);                     
            }.bind(this)
        });
        return false;

    },
    
    report: function(reportUrl) {
    
        if (this.addEntryActive) {
            return false;
        }
        this.addEntryActive = true;
    
        var form = this.entryBox;
            form = form.replace('%reportUrl', reportUrl);
            form = form.replace('%label', Application_lang.addEntryLabel);
                                        
        $('body').append(form);
        
        $('#entryForm').submit(function() {
        
            var content = $('textarea[name=entryContent]').val();
            
            user.ajaxPost(reportUrl, {content: content}, {
            	onSuccess: function (obj) {
                   $('#entryBox').remove();
                   $('#report').removeAttr('href');
                   $('#report').removeAttr('onclick');
                   
                   this.showMsg(Application_lang.entryAdded, this.REQUEST_STATUS_OK);                     
            	}.bind(this)
        	});
            return false;
        });
    
    },
    
    showFirstLoggin: function(first) {
        var self = this;
    
        if (first) {
            this.showWelcomeMsg(Application_lang.firstLogginMessage, this.REQUEST_STATUS_INFO, self.hideFirstLoggin);
            this.showFirstLogginCommentBox(true);
        }
        
        /*if (!$('#user-albums').html()) {
            this.showFirstLogginAlbumBox(true);
        }*/

        if (!$('#user-photos #smallPhotos .small').html()) {
            this.showFirstLogginPhotoBox(true);
        }        
        
        /*if (!$('.recentPhotoComments').html()) {
            this.showFirstLogginUserCommentBox(true);
        }*/              
            
    },
    
    hideFirstLoggin: function() {
         //user.showFirstLogginAlbumBox(false);    
         user.showFirstLogginPhotoBox(false);
         //user.showFirstLogginUserCommentBox(false);
         user.showFirstLogginCommentBox(false);
    },
    
    showFirstLogginPhotoBox: function(visible) {
    
        if (visible) {
            var html = this.createEmptyBox("emptyPhotos", "tu beda twoje foty", false);
            $('#user-photos').after(html);
        } else {
            $('#emptyPhotos').remove();
        }     
    },

    showFirstLogginUserCommentBox: function(visible) {
    
        if (visible) {
            var html = this.createEmptyBox("emptyUserComments", "tu beda twoje komentarze", false);
            $('#recentCommentsHolder').after(html);
        } else {
            $('#emptyUserComments').remove();
        }     
    },       
    
    showFirstLogginAlbumBox: function(visible) {
    
        if (visible) {
            var html = this.createEmptyBox("emptyAlbum", "tu beda twoje albumy", 'Albumy');
            $('#commentsBox').before(html);
        } else {
            $('#emptyAlbum').remove();
        }            
    },
    
    showFirstLogginCommentBox: function(visible) {
    
        if (visible) {
            var html = this.createEmptyBox("emptyComments", 'Tutaj Twoi znajomi będą wyrażać zachwyt <img src="/images/emots/oklasky.gif" alt=""/> nad Twoją kolekcją zdjęć', false);
            $('#addCommentBox').before(html);
        } else {
            $('#emptyComments').remove();
        }    
    },
    
    createEmptyBox: function(id, msg, title) {
       
       var emptyBox = document.createElement('div');
            $(emptyBox).addClass('emptyBox');
            $(emptyBox).attr('id', id);
            
            var arrow   = document.createElement('span');
                $(arrow).addClass('arrow');      
            var text   = document.createElement('span');
                $(text).addClass('text');
                $(text).html(msg);
            
            if( title !== false ) {
                var heading = document.createElement('span');
                  $(heading).addClass('heading');
                  $(heading).html( title );
                  
                $(emptyBox).append(heading);
            }
            $(emptyBox).append(text);
            $(emptyBox).append(arrow);            
           
        return emptyBox;             
    }
    
});

$(document).ready( function () { user = new User(); } ); //user.basicInit();

/* file: Photos.js */
var Photos = Class.create(Application.prototype, {
	
	albumId : 0,
	photoUrl: null,
	REFRESH_TIMES        : [3000, 5000, 10000, 20000],
	MAX_REFRESH_TIME     : 60000,
    refresh              : null,
    refreshHandler       : null,
    orderId : null,
    STATUS_URL : null,
    	
	init: function () {

		this.renderPhotoViews();
		this.registerEditable();
		this.surroundingPhotosManager.photos = this;
		this.surroundingPhotosManager.collectSurroundingPhotos();
	},
	
	renderPhotoViews: function() {
		
		var counter = core.getModuleData('photosViews', 'views');
        
        //for counts from 21 to 99
        var standardModCount = counter % 10;
        //for counts from 11 to 19 
        var excModCount = counter % 100;
        if (counter == 1) 
            var msg = Application_lang.photos_seen_one_time;
        else if (standardModCount > 1 && standardModCount < 5 && (excModCount < 12 || excModCount > 14)) {
            var msg = Application_lang.photos_seen_two_times;
        }
        else 
            var msg = Application_lang.photos_seen_many_times;
        
		var msg = msg.replace(/%value%/, counter);
		if ($('#photoViews'))
			$('#photoViews').html(msg);
	},
	removeFromAlbum: function(url) {

		this.ajaxPost(url, {}, {
			onSuccess: function (data) {
				if (this.getAlbumId() == data.albumId) {
					window.location.href = this.getPhotoUrl();
				}
				$('#album_'+data.albumId).remove();
		}.bind(this)});
	},
	
	addToAlbum: function(url, albumId) {
	
		var name = $('#newAlbum').val();
	
		this.ajaxPost(url, {title: name, albumId: albumId}, {
			onSuccess: function (data) {
				window.location.reload();
		}});
		
		return false;
	},
	
	editAlbums: function (listUurl, addUrl) {
	
		if (this.loaded) return false;
		
		this.loaded = true;
	
		this.ajaxPost(listUurl, {}, {
				onSuccess: function (data) {
	
					var select = document.createElement('select');
						$(select).attr('id', 'albumsEditList');
						$(select).attr('name', 'albumsEditList');
						$(select).change(function() {
							var albumId = $(select).val();
							photos.addToAlbum(addUrl, albumId);
						});
						
						var option = document.createElement('option');
						$(option).val(0);
						$(option).html('--');
						$(option).attr('id', 0);
						$(option).appendTo(select);
						
						$.each(data.albums, function(i, val){
							var option = document.createElement('option');
							$(option).attr('value', i);
							$(option).html(val.title);
							$(option).appendTo(select);
						});
						
					$(select).appendTo('#albumsManager');
					$('#addAlbum').show();
					
			}
		});
	},
	
	remove : function(url) {
	
		this.ajaxPost(url, {}, {
			onSuccess : function (resp) {
				window.location.href = resp.content;
			}
		});
		
		return false;
	},
    
    edit: function (url) {
    
        var self = this;
        $('#button-edytuj').parent().hide();
        
        this.ajaxRequest (url, {
            'onSuccess' : function (resp) {
                self.showLightBox(resp.content);
                self.updateSessionId();                              
            }
        });
        return false;
    }, 
	
    basicInit: function () {
		this.ajaxForm('updatePhotoForm', {
			'onSuccess': this.updateProcessResponse.bind(this, 'updatePhotoForm')
		});
	},
	
	updateProcessResponse: function (id, obj) {
		var errorMsgId = id + 'ErrorMsg';
		if (obj.error) {
			//TODO			
		} else if (obj.rotate) {
			this.closeLightBox();
			this.showLightBox('<div id="updatePhotoForm"><img class="loaded" src="/images/wait-big.gif" /><b>' + Application_lang.rotationOnOrder + '</b></div>');
			photos.orderId = obj.rotate;
			this.refresh();
		} else {
			window.location.reload();
		}
		
		return false;
	},
	
	refresh: function() {
    	photos.chechStatus();
    	
    	var newRefreshTime = photos.REFRESH_TIMES.shift() // * Math.ceil (photoLoader.counter / 3);
    	if(newRefreshTime == null) { 
    		newRefreshTime = photos.MAX_REFRESH_TIME;
    	}
    	
    	clearInterval(photos.refreshHandler);
    	photos.refreshHandler = setTimeout(photos.refresh, newRefreshTime);
    	
    },
    
    setStatusUrl : function(url) {
        this.STATUS_URL = url; 
     },
    
    chechStatus: function() {
        this.ajaxPost(this.STATUS_URL, {'orderIds' : photos.orderId}, {
            onSuccess: function(resp){
        		if(resp.content.length == 0 || resp.content[photos.orderId.toString()] != 'processing') {
        			window.location.reload();
        		}
            }
        });
    },
	
    makePhotoRotatable : function(selector) {
        var params = {
            maxCanvasWidth  : 180,
            maxCanvasHeight : 180   
        };
        
        if (!jQuery.browser.msie) {
            $(selector).rotate($.extend(params, {angle : 0})); //initialize canvas
        }
        
        
        function setRotateClass(elem, rotation) {
            var i = 0;
            for (i = 0; i < 4; i++) {
                elem.removeClass('rotated' + i);
            }
            elem.addClass('rotated' + rotation);
        }
        
        var lastStep = 0;
        
        $(selector).after(
            $('<a class="rotate-button rotateRight">'+Application_lang.rotateRight+'</a>').click(function(){
                var current = $('#updatePhotoForm input[name=rotate]').val(),
                    nextStep = (parseInt(current, 10) + 1) % 4;
                $('#updatePhotoForm input[name=rotate]').val(nextStep);
                
                if( nextStep == 1 || nextStep == 3 ) { 
                    $('.large-photo')
                        .css('top',0)
                        .css('height','180px');
                    $('.rotate-button').css('top',0);
                } 
                else { 
                    $('.large-photo')
                        .css('top','-20px')
                        .css('height','160px');
                    $('.rotate-button').css('top','-20px');
                }
                
                if (jQuery.browser.msie) {
                    setRotateClass($(selector), nextStep);
                } else {
                    $(selector).rotate($.extend(params, {angle : (lastStep = lastStep + 90)}));
                }
                
            })
        ).after(
            $('<a class="rotate-button rotateLeft">'+Application_lang.rotateLeft+'</a>').click(function(){
                var current = $('#updatePhotoForm input[name=rotate]').val(),
                    nextStep = (parseInt(current, 10) + 3) % 4;
                $('#updatePhotoForm input[name=rotate]').val(nextStep);
                
                if( nextStep == 1 || nextStep == 3 ) { 
                    $('.large-photo')
                        .css('top',0)
                        .css('height','180px');
                    $('.rotate-button').css('top',0);
                } 
                else { 
                    $('.large-photo')
                        .css('top','-20px')
                        .css('height','160px');
                    $('.rotate-button').css('top','-20px');
                }
                
                if (jQuery.browser.msie) {
                    setRotateClass($(selector), nextStep);
                } else {
                    $(selector).rotate($.extend(params, {angle : (lastStep = lastStep - 90)}));
                }
            })
        );
    },
    
	setAsWallpaper: function (url) {
		
		this.ajaxPost(url, {}, {
			onSuccess : function (resp) {
				window.location.reload();
			}.bind(this)
		});  
		return false;
	},
	
	setAlbumId: function(albumId) {
		this.albumId = albumId;
	},
	
	getAlbumId: function() {
		return this.albumId;
	},
	
	setPhotoUrl: function(url) {
		this.photoUrl = url;
	},
	
	getPhotoUrl: function() {
		return this.photoUrl;
	},
	setOwnerUin: function(uin) {
		this.ownerUin = uin;
	},
	getOwnerUin: function() {
		return this.ownerUin;
	},
	surroundingPhotosManager: {
		packageSize: 18,
		selectedPhotoId: null,
		centeredPhotoId: null,
		lastPhotoIdInList: null,
		firstPhotoIdInlist: null,
        photos: null,
        prevUrl: null,
        nextUrl: null,
		photoList: [],

        setPhotosUrlPrevNext: function(prevUrl, nextUrl) {
            this.nextUrl = nextUrl;
            this.prevUrl = prevUrl;
        },
		collectSurroundingPhotos: function() {
			var self = this;
			self.photoList = [];
			$('.photo-album-container ul li a').each(function(){
				if ($(this).parent().hasClass('selected')) {
					self.centeredPhotoId = self.selectedPhotoId = this.href.match(/\/\d+\/photo\/(\w+)\/\w+\/?/)[1];
				}

				var photoId = this.href.match(/\/\d+\/photo\/(\w+)\/\w+\/?/)[1];
				var photo = {
					'id': photoId,
					'url': this.href,
					'image': $('img', this).attr('src')
				};
                
				self.photoList.push(photo);
			});

			/* register click handlers */
			
			if ($('.photoPos_2').length) {
				$('.photo-album a.previous').click(function(e) {
					if (!$('.photo-album ul li:first-child').hasClass('empty'))
						self.scrollToPhoto(self.photoList[0].id, false, true);
					e.preventDefault();
				});
			} else {
				//TO DO
				this.firstPhotoIdInlist = this.photoList[0].id;
				$('.photo-album a.previous').hide();
			}
			
			if (!$('.photo-album ul li').eq(9).hasClass('empty')) {
				$('.photo-album a.next').click(function(e) {
					if (!$('.photo-album ul li:last-child').hasClass('empty'))
						self.scrollToPhoto(self.photoList[self.photoList.length-1].id, true, true);
					e.preventDefault();
				});
			} else {
				this.lastPhotoIdInlist = this.photoList[this.photoList.length - 1].id;
				$('.photo-album a.next').hide();
			}
		},
		collectPhotosFromResponse: function(response, photoId, next) {
            //if next zm next if prev zm prev
			var self = this;
            var photoList = response.photos;

			if (photoList.length < this.packageSize+1) {
				if (next)
					this.lastPhotoIdInList = photoList[photoList.length-1].id;
				else
					this.firstPhotoIdInlist = photoList[0].id;
			}
			if (next) {
				this.photoList = this.photoList.concat(photoList.slice(1));
                this.nextUrl = response.nextUrl;
                
			} else {
				this.photoList = photoList.slice(0, -1).concat(this.photoList);
                this.prevUrl = response.prevUrl;
			}
            var currentId, currentObj, image;
            for(currentId in photoList) {
                currentObj = photoList[currentId];
                if (typeof currentObj == 'object') {
                        image     = document.createElement('img');
                        image.src = currentObj.image;
                    }
            }
            
            this.showPhoto(photoId);
		},
        
        showPhoto: function(photoId) {
                    
        },
        
		scrollToPhoto: function(photoId, direction, firstime) {
			var self = this;
            var newPhotoOffset = 0;
            var currentPhotoOffset = 0;

			if(firstime) {
				if(direction){
		            this.fillSurroundingPhotos(this.photoList[this.photoList.length-1].id, this.nextUrl, true /*forward*/);
				}else{
					this.fillSurroundingPhotos(this.photoList[this.photoList.length-1].id, this.prevUrl, false /*backward*/);
				}
			}

            while (this.photoList[newPhotoOffset] && this.photoList[newPhotoOffset].id != photoId) ++newPhotoOffset;
            while (this.photoList[currentPhotoOffset] && this.photoList[currentPhotoOffset].id != this.centeredPhotoId) ++currentPhotoOffset;

			/* perform scroll */
			if(firstime) {
				if(direction) {
					if(this.photoList.length > 12) {
			            newPhotoOffset = newPhotoOffset-3;
					}else{
					    newPhotoOffset = currentPhotoOffset+3;
            }
                } else {
					if(this.photoList.length > 13){
					    newPhotoOffset = newPhotoOffset+3;
					} else {
						newPhotoOffset = currentPhotoOffset-3;
                }
            }
                }
        
			if (newPhotoOffset < 3) {
				/* need fillup at beginning */
				/* fillup only if first photo in array is not first photo in full list */
				if (this.firstPhotoIdInlist != this.photoList[0].id) {
					this.fillSurroundingPhotos(this.photoList[0].id, this.prevUrl, false /*backward*/);
			while (this.photoList[newPhotoOffset] && this.photoList[newPhotoOffset].id != photoId) ++newPhotoOffset;
			while (this.photoList[currentPhotoOffset] && this.photoList[currentPhotoOffset].id != this.centeredPhotoId) ++currentPhotoOffset;
            }
			}
			if (this.photoList.length - newPhotoOffset < 3) {
				/* need fillup at end */
				if (this.lastPhotoIdInList != this.photoList[this.photoList.length-1].id) {
					this.fillSurroundingPhotos(this.photoList[this.photoList.length-1].id, this.nextUrl, true /*forward*/);
					while (this.photoList[newPhotoOffset] && this.photoList[newPhotoOffset].id != photoId) ++newPhotoOffset;
					while (this.photoList[currentPhotoOffset] && this.photoList[currentPhotoOffset].id != this.centeredPhotoId) ++currentPhotoOffset;
				}
			}
            
            var html = '';

            for (var i = -6; i < -3; ++i) {
                if (this.photoList[newPhotoOffset+i]) {
                    html += '<li class="photoPos_' + (i+6) + '" style="display: none;">'+
                        '<a href="'+this.photoList[newPhotoOffset+i].url+'">'+
                        '<img src="'+this.photoList[newPhotoOffset+i].image+'"/>'+
                        '</a></li>';
                } else {
                    //sloneczko
                    html += '<li class="empty" style="display: none;"></li>';
                }
            }
            for (var i = -3; i <= 3; ++i) {
                if (this.photoList[newPhotoOffset+i]) {
                    html += '<li class="photoPos' + (i+3) + (this.selectedPhotoId == this.photoList[newPhotoOffset+i].id ? ' selected' : '') +'">'+
                        '<a href="'+this.photoList[newPhotoOffset+i].url+'">'+
                        '<img src="'+this.photoList[newPhotoOffset+i].image+'"/>'+
                        '</a></li>';
                } else {
                    html += '<li class="empty"></li>';
                }
            }
            for (var i = 4; i <= 6; ++i) {
                if (this.photoList[newPhotoOffset+i]) {
                    html += '<li class="photoPos' + (i+3) + '">'+
                        '<a href="'+this.photoList[newPhotoOffset+i].url+'">'+
                        '<img src="'+this.photoList[newPhotoOffset+i].image+'"/>'+
                        '</a></li>';
                } else {
                    //sloneczko
                    html += '<li class="empty" style="display: none;"></li>';
                }
            }
            this.centeredPhotoId = this.photoList[newPhotoOffset].id;
            
            if (direction) { //w przod
            	if($('.photoPos0').css("margin-left")){
            		var marginValue =  $(".photoPos0").css("margin-left");
            		marginValue = parseInt(marginValue.substr(0,marginValue.length-2));
				}
            	$("#slide").animate({marginLeft: '-234px' }, 500, function(){ 
            		changePhotos(html);
            	});

    			$('.photoPos7').attr("style", "display:inline;");
    			$('.photoPos8').attr("style", "display:inline;");
    			$('.photoPos9').attr("style", "display:inline;");
            } else {
            	$('.photoPos_0').attr("style", "display:inline; margin-left: -234px;");
    			$('.photoPos_1').attr("style", "display:inline; margin-left: -156px;");
    			$('.photoPos_2').attr("style", "display:inline; margin-left: -78px;");
            	$("#slide").animate({marginLeft: '234px' }, 500, function(){
            		changePhotos(html);
            	});
			}

			
            //hide empty_wait
            $('.photo-album-container ul li.empty_wait').each( function(i) {
                $(this).removeClass('empty_wait');
                $(this).addClass('empty');
            });      
            
			
			var scrollToNextPID;
			var scrollToPrevPID;
			if (this.photoList[newPhotoOffset-3]) {
				scrollToPrevPID = this.photoList[newPhotoOffset-3].id;
                $('.photo-album a.previous').show();
			} else {
				scrollToPrevPID = null;
                $('.photo-album a.previous').hide();
			}
			if (this.photoList[newPhotoOffset+3] ) {
				scrollToNextPID = this.photoList[newPhotoOffset+3].id;
                $('.photo-album a.next').show();
			} else {
				scrollToNextPID = null;
                $('.photo-album a.next').hide();
			}
			$('.photo-album a.next').unbind('click').click(function(e) {
				if (scrollToNextPID)
					self.scrollToPhoto(scrollToNextPID, true);
				e.preventDefault();
			});
			$('.photo-album a.previous').unbind('click').click(function(e) {
				if (scrollToPrevPID)
					self.scrollToPhoto(scrollToPrevPID, false);
				e.preventDefault();
			});
            $('#ajax_wait_notification').hide();
		},
		fillSurroundingPhotos: function(photoId, url, next) {
			$.ajax({
				'url': url,
				async: false, // must be synchronous
				dataType: 'json',
				success: function(resp) {
					this.collectPhotosFromResponse(resp, photoId, next);
				}.bind(this),
                error: function(resp) {
                    this.showPhoto(photoId);
                }.bind(this)
			});
		}		
		}
});
$(document).ready( function () {
	if (typeof photos == 'undefined') {
		photos = new Photos();
	}
});
function changePhotos(html) {
	html = "<div id=\"slide\" style=\"left: 0px;\"><ul>" + html + "</ul></div>";
	$('.photo-album-container').html(html);
}

/* file: Favourites.js */
var Favourites = Class.create(Application.prototype, {
    
    init: function() {
		
    },
    
    add: function(url, link, message) {
        this.ajaxPost(url, {}, {
        	onSuccess: function (obj) {
	            if (obj.content) {
	                $('#addToFavourites')
                        .attr('href', link)
                        .html( '<span class="png buttons-common" id="button-w-ulubionych"></span>'+ message);
	            }
        	}.bind(this)
        });
        return false;
    },
    
    remove: function(favouriteId) {
        var sessionId = $.cookie(this.COOKIE_SESSION_NAME) == null ? '' : $.cookie(this.COOKIE_SESSION_NAME).substring(0, 32);
        $("input#favouriteId").val(favouriteId);
        $("input#sessionId").val(sessionId);
        $("#removeFavouritesForm").submit();
            
        return false;           
    }
        
});

$(document).ready( function () { favourites = new Favourites();} );

/* file: AlbumsManager.js */
var AlbumsManager = Class.create(Application.prototype, {
    
    albumListId: 'albums_list',
    albumToAdd:  'albums_add',
    albumNewId:  'album_name', 
    
    counter: 0,
    newAlbumsManager: [],
    
    init: function () {
    
        $('.albumListItem').each(function(){
            if ($('input', this).attr('checked'))
                $(this).addClass('selected');
            else
                $(this).removeClass('selected');
        });
        $('.albumListItem').click(this.handleCheckboxChange);
        
        var self = this;
        $('#album_name').click(function(){
            if (this.value == Application_lang.addAlbumDefaultValue)
                this.value = '';
        });
        $('#album_name').focus(function(){
            if (this.value == Application_lang.addAlbumDefaultValue)
                this.value = '';
        });
        $('#album_name').blur(function(){
            if (this.value == '')
                this.value = Application_lang.addAlbumDefaultValue;
        });
    },
    
    getLinkAlbumsIds : function() {
        return $.map($('#albumList .selected').not('.newAlbum'), function(n, i) {
            return $(n).attr('id').split(/_/)[1];
        });
    },
    
    removeFromAlbum: function(url) {

        this.ajaxPost(url, {}, {
            onSuccess: function (data) {
                $('#photo_'+data.photoId).remove();
                window.location.reload();
        }});
        return false;      
    },
    
    addAlbum: function(cleanInput, setDefaultText) {
    
        var name = $('#'+this.albumNewId).val();
        if (name.replace(/^\s*|\s*$/g, '') == '' || name == Application_lang.addAlbumDefaultValue) {
            application.showMsg(Application_lang.addAlbumDefaultValue, application.REQUEST_STATUS_ERROR);
            return false;
        }
        var counter = this.counter++;
        if (typeof setDefaultText == "undefined") {
            setDefaultText = true;
        }
        
        
        if (counter == 0) {
            $('<li class="newAlbumsSeparator">'+Application_lang.albumsToBeAdded+'</li>').appendTo('#albumList');
        }
        
        var elem = $('<li class="albumListItem newAlbum selected" id="newAlbum'+counter+'">'+
            '<label for="albumSelection_'+counter+'">'+
                '<span class="albumCheckbox"><input checked="checked" disabled="disabled" type="checkbox" id="albumSelection_'+counter+'" name="albumSelection_'+counter+'"/></span>'+
                '<span class="albumCover newAlbum"></span>'+
                '<span class="albumTitle">'+
                    '<span class="middle">'+
                        '<span class="inner">'+ name +
                        '</span>'+
                    '</span>'+
                '</span>'+
                '<span class="albumRemove">'+Application_lang.removeAlbum+'</span>'+
            '</label>'+
        '</li>'); //<img class="png" src="'+Application.urls.defaultAlbumCover+'" />

        this.newAlbumsManager.push(name.replace(/,/g, '%2C'));
        elem.attr('albumName', name);
        
        var self = this;
        $('.albumRemove', elem).click(function() {
            if ($('#albumList li.newAlbum').length == 1) {
                $('#albumList .newAlbumsSeparator').remove();
                self.counter = 0;
            }
            self.newAlbumsManager.remove($(this.parentNode.parentNode).attr('albumName'));
            $(this.parentNode.parentNode).remove();
            
        });
        
        $(elem).appendTo('#albumList');
        
        $(elem).click(this.handleCheckboxChange);
        $('#albumList').animate({scrollTop: '+=' + ($(elem).offset().top - $('#albumList').offset().top) + 'px'}, 0);
        
        if (cleanInput)
            cleanInput.val(setDefaultText ? Application_lang.addAlbumDefaultValue : '');
        
        return false;
    },  
    
    handleCheckboxChange: function() {
        if ($(this).hasClass('newAlbum')) {
            return false;
        }
        if ($('input', this).attr('checked'))
            $(this).addClass('selected');
        else
            $(this).removeClass('selected');
    },
    
    handleAlbumNameKeyDown: function (e) {
        if (e.keyCode == 13 || e.keyCode == 10) {
            if (false == albumsManager.addAlbum($('#album_name'), false)) {
                e.preventDefault();
                return false;
            }
        }
        return true;
    },
    passNewAlbums: function (hiddenId) {
        $('#' + hiddenId).attr('value', this.newAlbumsManager);
        return true;
    }
       
});
$(document).ready( function () {
    albumsManager = new AlbumsManager();
});



