var formIsActive = 0;
var Albumbox = {

	init: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false,	// default transition
			initialWidth: 20,
			initialHeight: 20,
			imagesURL: "http://images.friendster.com/images/"
		}, options || {});

		var editHost = 'http://' + window.location.hostname;
		if(window.location.port != 80 || window.location.port != '')
			editHost += ':' + window.location.port;
			
		this.ajaxReqHandlerUrl = editHost + '/editalbum.php';
		this.editreq = new XHR({onSuccess: this.processEdit, onFailure: this.handleEditFail, headers: { 'Content-Type':'application/x-www-form-urlencoded' }});
		this.loadreq = new XHR({onSuccess: this.processLoad, onFailure: this.handleLoadFail, headers: { 'Content-Type':'application/x-www-form-urlencoded' }});		
		this.eventPosition = this.position.bind(this);

		this.overlay = new Element('div', {'id': 'lbOverlay'}).injectInside(document.body);
		this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
		this.image = new Element('div', {'id': 'lbImage'}).injectInside(this.center);

		this.modalContainer = new Element('div', {'class': 'modal-container'}).injectInside(this.center);
		this.modalTop = new Element('div', {'class': 'modal-top'}).injectInside(this.modalContainer);
		this.modalAround = new Element('div', {'class': 'modal-around'}).injectAfter(this.modalTop);
		this.modalTitle = new Element('div', {'class': 'modal-title'}).injectInside(this.modalAround);
		this.modalContent = new Element('div', {'class': 'modal-content'}).injectAfter(this.modalTitle);
		this.modalContentBot = new Element('div', {'class': 'modal-content-bot'}).injectAfter(this.modalContent);
		this.modalBot = new Element('div', {'class': 'modal-bot'}).injectAfter(this.modalAround);

		this.boxHeader = new Element('span').injectInside(this.modalTitle);

		this.formContainer = new Element('div',{'id': 'formContainer', 'class' : 'innerAlbumForm'}).injectInside(this.modalContent);

		this.dialogDiv = new Element('div', {'class': 'dialog_content'}).injectAfter(this.formContainer);	
		this.dialogBtns = new Element('div').injectAfter(this.dialogDiv);	
		this.msg = new Element('div', {'id':'msg'}).injectAfter(this.dialogBtns);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.image.effect('opacity', {duration: 500, onComplete: nextEffect}),
			closeLink: this.image.effect('opacity', {duration: 500}),
			formdiv: this.formContainer.effect('opacity', {duration: 500, onComplete: nextEffect})
		};
		
		if($('lbOverlay')) {
			showEditLinks();
			showShareLinks();
		}
	},

	click: function(link){
		var j, imageNum, images = [];
		return this.open(images, imageNum);
	},

	show: function(url, album_id, action){
		if(formIsActive == 1) {
			this.clearBox();
		} else {
			formIsActive = 1;
		}
		return this.open([[url, album_id]], album_id, 0, action);
	},

	open: function(images, album_id, imageNum, action){
		this.images = images;
		this.albumId = album_id;
		this.action = action;
		this.position();
		this.setup(true);
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		this.top = st + (wh / 15);
		this.center.setStyles({top: this.top+'px', display: ''});		
		//this.fx.overlay.start(0.05);
		return this.changeImage(imageNum);
	},

	position: function(){
		//this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
		
		//IE6 - XML prolog problem.
		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		this.overlay.setStyles({top: st+'px', height: wh+'px', width:ww+'px'});		
	},

	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		
		this.step = 0;
	},

	
	changeImage: function(imageNum){
		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;
		this.fx.image.hide();
		this.fx.formdiv.hide();
		this.fx.closeLink.hide();
		this.center.className = 'lbLoading';

		this.preload = new Image();
		this.preload.onload = this.nextEffect.bind(this);
		this.preload.src = this.images[imageNum][0];
		return false;
	},

	nextEffect: function(){

		switch (this.step++){
		case 1:
			this.center.className = '';
			this.image.style.backgroundImage = 'url('+this.images[this.activeImage][0]+')';
			this.image.style.width = this.preload.width+'px';
			this.image.style.height = this.preload.height+'px';
			
			if($('photos-statusbox'))
				$('photos-statusbox').remove();
			
			// create the form
			if(this.action == 'edit') {
				this.createEditForm();
				// load album details
				this.loadAlbum();
			} else {
				this.createShareForm();
			}
			
			
			if (this.center.clientHeight != this.image.offsetHeight){
				if(this.action == 'edit'){
					this.fx.resize.start({height: 300});
				} else {
					this.fx.resize.start({height: 300});
				}
				break;
			}
			
			this.step++;
		case 2:
			if (this.center.clientWidth != 506){
				this.fx.resize.start({width: 506, marginLeft: -this.image.offsetWidth/2});
				break;
			}
			this.step++;
		case 3:
			this.fx.image.start(1);
			this.fx.closeLink.start(1);
			this.fx.formdiv.start(1);
			break;
		case 4:

		case 5:
			this.step = 0;
		}
	},

	close: function(){
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display =  'none';
		
		this.clearBox();
			
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
	},
	
	clearBox : function() {
	
		if($('editAlbumForm')) {
			$('editAlbumForm').remove();			
		}
			
		if($('shareAlbumForm')) {
			$('shareAlbumForm').remove();
		}
		
		if(this.boxHeader)
			this.boxHeader.innerHTML = '';
		
		if(this.dialogBtns)
			this.dialogBtns.innerHTML = '';	

		if(this.msg)
			this.msg.innerHTML = '';	
			
		return false;
	},
	createEditForm: function(){
		this.albumForm = new Element('form', {'id' : 'editAlbumForm'}).injectInside(this.formContainer);
		this.nameSet = new Element('fieldSet', {'id': 'nameField'}).injectInside(this.albumForm);				
		this.privSet = new Element('fieldSet', {'id': 'privField'}).injectInside(this.albumForm);			
		this.submitSet = new Element('fieldSet', {'id': 'submitField'}).injectInside(this.albumForm);
		//this.sendSet = new Element('fieldSet', {'id': 'sendField'}).injectInside(this.albumForm);	

		//header
		textNode = document.createTextNode(Locale.getString('albumHeader'));		
		this.boxHeader.appendChild(textNode);
		
		// fields		
		textNode = document.createTextNode(Locale.getString('editAlbumName'));				
		new Element('label', {'for': 'album-name'}).injectInside(this.nameSet).appendChild(textNode);
		new Element('input', {'type' : 'text', 'id': 'album-name', 'name': 'album-name', 'maxlength' : '50'}).injectInside(this.nameSet);

		textNode = document.createTextNode(Locale.getString('editAlbumPriv'));

		this.privLbl = new Element('label', {'for': 'album-priv'}).injectInside(this.privSet).appendChild(textNode);

		this.privSel = new Element('input', {'type': 'radio', 'id': 'album-priv-public', 'name': 'album-priv', 'value': 0});
		this.privSel.injectInside(this.privSet);
		textNode = document.createTextNode(Locale.getString('privacyPublic'));
		this.privSelLbl = new Element('label', {'for': 'album-priv-public'}).setStyles({display:'inline'}).injectInside(this.privSet).appendChild(textNode);

		if(primaryAlbumRid == '') {
			this.privSel2 = new Element('input', {'type': 'radio', 'id': 'album-priv-private', 'name': 'album-priv', 'value': 1, 'disabled':'true'}).injectInside(this.privSet);
			this.privSelLbl2 = new Element('label',{'class': 'disabledText', 'for': 'album-priv-private'}).setStyles({display:'inline'});		
		} else {
			if(this.albumId == primaryAlbumRid) {
				this.privSel2 = new Element('input', {'type': 'radio', 'id': 'album-priv-private', 'name': 'album-priv', 'value': 1, 'disabled':'true'}).injectInside(this.privSet);
				this.privSelLbl2 = new Element('label',{'class': 'disabledText', 'for': 'album-priv-private'}).setStyles({display:'inline'});
			}
			else {
				this.privSel2 = new Element('input', {'type': 'radio', 'id': 'album-priv-private', 'name': 'album-priv', 'value': 1}).injectInside(this.privSet);
				this.privSelLbl2 = new Element('label', {'for': 'album-priv-private'}).setStyles({display:'inline'});
			}		
		}

		textNode = document.createTextNode(Locale.getString('privacyPrivate'));
		this.privSelLbl2.injectInside(this.privSet).appendChild(textNode);

		if(this.albumId == primaryAlbumRid) {
			textNode = document.createTextNode(Locale.getString('primaryAlbumNote'));
			this.primaryPic = new Element('div',{'class': 'primaryErr'}).injectInside(this.privSet).appendChild(textNode);
		}
		
		textNode = document.createTextNode(Locale.getString('allowFriendsToUpload'));

		this.submitChk = new Element('input', {'type' : 'checkbox', 'id' : 'album-submit', 'name' : 'album-submit'}).injectInside(this.submitSet);		
		this.submitLbl = new Element('label', {'for': 'album-submit'}).injectAfter(this.submitChk).appendChild(textNode);

		this.bottomButtons = new Element('div', {'id' : 'action-btns'}).injectInside(this.dialogBtns);
		this.leftButtons = new Element('div', {'class':'floatL'}).injectInside(this.bottomButtons);
		new Element('input', {'disabled': true, 'type': 'button', 'id': 'editBtn', 'class': 'submitAlbum', 'value': Locale.getString('saveChanges'), 'styles':{'float':'left'}}).injectInside(this.leftButtons).onclick = this.editAlbum.bind(this);			
		new Element('input', {'type': 'button', 'id': 'cancelBtn', 'class': 'submitAlbum', 'value': Locale.getString('cancel'), 'styles':{'float':'left'}}).injectInside(this.leftButtons).onclick = this.close.bind(this);
		this.rightButtons = new Element('div', {'class':'floatR'}).injectAfter(this.leftButtons);
		new Element('input', {'type': 'button', 'id': 'delBtn', 'class': 'submitAlbum', 'value': Locale.getString('deleteAlbum')}).injectInside(this.rightButtons).onclick = this.deleteAlbumScreen.bind(this);		
	},
	
	createShareForm: function(){
		this.shareForm = new Element('form', {'id' : 'shareAlbumForm', 'method':'POST'}).injectInside(this.formContainer);
		this.emailSet = new Element('fieldSet', {'id': 'emailField'}).injectInside(this.shareForm);		
		//this.sendSet = new Element('fieldSet', {'id': 'sendField'}).injectInside(this.shareForm);	

		//header
		textNode = document.createTextNode(Locale.getString('shareThisAlbum'));
		this.boxHeader.appendChild(textNode);
		
		// fields		
		textNode = document.createTextNode(Locale.getString('enterEmailAddresses'));				
		new Element('label', {'for': 'email-addresses'}).injectInside(this.emailSet).appendChild(textNode);
		new Element('textarea', {'id': 'email-addresses', 'name': 'emails'}).injectInside(this.emailSet);
		new Element('input', {'type': 'hidden','id': 'shared-album', 'name': 'shared_album', 'value': this.albumId}).injectInside(this.emailSet);
		this.bottomButtons = new Element('div', {'class':'clearFix', 'id' : 'action-btns'}).injectInside(this.dialogBtns);
		this.leftButtons = new Element('div', {'class':'floatL'}).injectInside(this.bottomButtons);
		new Element('input', {'type': 'submit', 'id': 'shareBtn', 'name': 'share_action', 'class': 'submitAlbum', 'value': Locale.getString('send'), 'styles':{'float':'left'}}).injectInside(this.leftButtons).onclick = this.closeAndSendInvite.bind(this);
		new Element('input', {'type': 'button', 'id': 'cancelBtn', 'class': 'submitAlbum', 'value': Locale.getString('cancel'), 'styles':{'float':'left'}}).injectInside(this.leftButtons).onclick = this.close.bind(this);

	},
	
	deleteAlbumScreen : function(){
		var sPath = window.location.pathname;
		var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
		var delURL = sPage + '?action=delete&a=' + this.albumId;
		
		if(this.bottomButtons)
			this.bottomButtons.innerHTML = Locale.getString('plsWait');
		
		window.location = delURL;
	},
	
	closeAndSendInvite: function(){
		$('shareAlbumForm').submit(); 	
		//this.close();	
  	    pageUpdated();		
		return false;
	},
	
	editAlbum: function(){
		if($('msg'))
			$('msg').innerHTML = '';
			var albumName = escape(utf8_encode($('album-name').value)),
			//albumDesc = $('album-story').value,
			albumPriv = ($('album-priv-public').checked) ? 0 : 1;
		var albumSub = ($('album-submit').checked) ? 0 : 2;
	    //postParam = 'x=edit&a=' + this.albumId + '&name=' + albumName + '&desc=' + albumDesc + '&priv=' + albumPriv;
	    postParam = 'x=edit&a=' + this.albumId + '&name=' + albumName + '&priv=' + albumPriv + "&sl=" + albumSub;
	    if(albumName.length > 0) {	 
			Albumbox.showLoader(true, false);			
			Albumbox.showMsg(Locale.getString('editAlbumSaving'), 'message');				       
	    	this.editreq.send(this.ajaxReqHandlerUrl, postParam);
	    } else {
	    	Albumbox.showMsg(Locale.getString('editAlbumNameCannotBeEmpty'), 'error');
	    }
	},
	
	loadAlbum : function(){
	    postParam = 'x=load&a=' + this.albumId;
	   	this.loadreq.send(this.ajaxReqHandlerUrl, postParam);
	    Albumbox.showLoader(true, false);
		Albumbox.showMsg(Locale.getString('editAlbumLoading'), 'message');
	},
	
	handleEditFail : function(){
		Albumbox.showMsg(Locale.getString('editAlbumFail'), 'error');
		Albumbox.showLoader(true, true);
	},
	
	handleLoadFail : function()	{
		Albumbox.showMsg(Locale.getString('editAlbumFailedToLoad'), 'error');
		Albumbox.showLoader(true, true);
		
	},
	
	processEdit : function(req)	{
	    try
	    {
	        eval('resp = ' + req);
	        if(resp['req_stat'] == 'FAIL') {
		        Albumbox.showMsg(Locale.getString('editAlbumFail'), 'error');
		        Albumbox.showLoader(true, true);
	        } else {
	        	if(resp['refresh']) {
	        		Albumbox.close();
	        	} else {
					// update name
					albumNameId = 'abAlbumName-' + resp['id'];
					if($(albumNameId)) {
						var nameLabel = resp['name'];
						if(nameLabel.length > 20)
							var nameLabel = nameLabel.substring(0,19) + '...';
						   $(albumNameId).innerHTML = htmlspecialchars(nameLabel);	
					}
					
					// update privacy
					albumPrivId = 'abAlbumPrivacy-' + resp['id'];
					if($(albumPrivId)) {
						var privLabel = (resp['privacy'] == 0) ? Locale.getString('privacyPublic') : Locale.getString('privacyPrivate');
						$(albumPrivId).innerHTML = privLabel;
					}
				}
				
		        Albumbox.showMsg(Locale.getString('editAlbumSuccess'), 'success');	        	
	        }        
	    }
	    catch(e) { }
	    finally 
	    {
		    Albumbox.close();
	    	Albumbox.showLoader(false, true);	    
	    }
	},
	
	processLoad : function(req)	{
	    try
	    {
	        eval('resp = ' + req);
	        if(resp['req_stat'] == 'FAIL') {
	        	Albumbox.showMsg(Locale.getString('editAlbumFailedToLoad'), 'error');
	        	Albumbox.showLoader(true, true);
	        } else {
	        	$('editBtn').disabled = false;
	        	Albumbox.showMsg(null, null);
				var details = resp['details'];
	        	var albumName = details['name'];
	        	var albumPrivacy = details['privacy'];
	        	var albumSubmit = details['submit_level'];
	
		        $('album-name').value = albumName;
		        //$('album-story').value = details['description'];
		        var privacyRadio = (albumPrivacy == 0) ? 'album-priv-public' : 'album-priv-private';
		        $(privacyRadio).checked = true;
		        
		        if(albumSubmit == 0)
		        	$('album-submit').checked = 'checked';	        
	        }

	    }
	    catch(e) { }
	    finally 
	    {
	    	Albumbox.showLoader(false, true);	    	
	    }
	},
	
	showMsg : function(txt, type) {
		if($('msg')) {
			if(txt != null) {
				$('msg').style.color = '#000';
				$('msg').innerHTML = txt;
			} else {
				$('msg').innerHTML = '';
			}
		}
	},
	
	showLoader : function(state, leaveCancel) {
		if($('loader')) {
			if(state == true) {
				$('loader').style.display = '';
				this.disableFields(true);
			} else {
				this.disableFields(false, leaveCancel);
				$('loader').style.display = 'none';
			}
		}
	},
	
	disableFields : function(state, leaveCancel) {
		$('delBtn').disabled = $('editBtn').disabled = $('album-name').disabled = state;
		$('album-priv').disabled = $('album-submit').disabled = $('album-sub').disabled = state;
		
		if(leaveCancel == true) {
			$('cancelBtn').disabled = false;
		}
	},
	
	pleaseWait: function()
	{
		if($('action-btns'))
			$('action-btns').innerHTML = Locale.getString('plsWait');
		
		
	}
	
}

window.addEvent('load', Albumbox.init.bind(Albumbox));

function showEditLinks() {
	editlinks = $$('.edit-link');
	for(var cnt = 0; cnt <= editlinks.length; cnt++) {
		if(editlinks[cnt]) {
			editlinks[cnt].style.visibility = "visible";
		}
	}
}

function showShareLinks() {
	sharelinks = $$('.share-link');
	for(var cnt = 0; cnt <= sharelinks.length; cnt++) {
		if(sharelinks[cnt]) {
			sharelinks[cnt].style.visibility = "visible";
		}
	}
}

//attachOnDomReadyHandler(Albumbox.init.bind(Albumbox));
//Window.onDomReady(function(){Albumbox.init.bind(Albumbox);});
