/** Gallery */
ifirave.pbGallery = new Object();
ifirave.pbGallery.editing = false;
ifirave.pbGallery.nb_item_per_page_short = 10;
ifirave.pbGallery.dataAlbum = "";
ifirave.pbGallery.dataV_Account = "";
ifirave.pbGallery.refreshLogin = false;
ifirave.pbGallery.pageAction = "";
ifirave.pbGallery.message = "";
ifirave.pbGallery.itemId = '';
ifirave.pbGallery.vemail = '';
ifirave.pbGallery.dataTemp = new Object();
ifirave.pbGallery.add_queue = true;

// init gallery
ifirave.pbGallery.pbinitGallery = function() {
	//
	ifirave.pbGallery.setHeightIframe();
}

ifirave.pbGallery.pbSetGalleryListCSS = function() {

	// Set style of gallery list width when no linked album
	$('contentRight').style.width = '70%';
}

ifirave.pbGallery.setHeightIframe = function() {
	$("contentWrapper").style.height = parseInt($("contentWrapper").offsetHeight) + 20 + "px";
}

//init gallery album page PUBLIC
ifirave.pbGallery.pbalbumInit = function( user, albumAlias, coefficient, tab_name, gotoPage, sortField) {
		var url = 'index.php?act=pbajaxGalleryAlbumPhotos';
		new Ajax.Request(url, {
				method: 'post',
				parameters: {user:user,albumAlias:albumAlias, page:gotoPage,c:coefficient , sortField: sortField},
				onSuccess: function(transport) {
					$('photos_list').innerHTML = transport.responseText;
					ifirave.pbGallery.pbinitGallery();
				},
				onFailure: function(transport) {
				}

		});
}

ifirave.pbGallery.pbgotoUploadPage = function(  albumAlias ) {
	window.location = "/" + albumAlias + "/?act=pbUploader"  ;
}

ifirave.pbGallery.gotoGalleryList = function() {
	window.location = "/";
}

ifirave.pbGallery.pbgotoAlbum = function( user , albumAlias ) {
	if($(albumAlias + '_type')) {
		var albumType = $(albumAlias + '_type').value; //2: ppa
		if(albumType == 2){
			ifirave.pbGallery.pbGalleryCheckPassword(albumAlias, '');
		}else{
			window.location = "/" + albumAlias + "/";
		}
	}else{
		ifirave.pbGallery.pbGalleryCheckPassword(albumAlias, '');
	}
	//window.location = "/" + albumAlias + "/";
}

ifirave.pbGallery.setValue = function(eId, eValue){
  $(eId).value = eValue;
}

ifirave.pbGallery.pbGalleryUploadAdd = function (uploaderId, action, message) {
	ifirave.pbUpload.pbdoUpload(uploaderId, action, message);
}

ifirave.pbGallery.showString = function( id_active, id_passive, str, id_show) {
    var el_active = $(id_active);
	var el_passive = $(id_passive);
	var el_show = $(id_show);

	if (el_active.className == "active") {
		el_active.className = "";
		el_show.style.display = 'none';
	} else {
		el_active.className = "active";
		el_passive.className = "";
		el_show.style.display = '';
	    el_show.value = str;
	    el_show.title = str;
		el_show.select();
	}

}

ifirave.pbGallery.pbGalleryNotifyPreregister = function ( user, albumAlias  ) {
	//parameters: { user: user , albumAlias: albumAlias , notifyPreregister: true },
	new Ajax.Request('index.php?act=pbajaxGalleryNotifyPreregister', {
			method: 'post',
			parameters: {albumAlias: albumAlias , notifyPreregister: true },
			onSuccess: function(transport) {
				if (transport.responseText == ''){
					$('f_a').style.display ='none';
				}
			},
			onFailure: function(transport) {
			}
	});
}

ifirave.pbGallery.pbgotoHome = function(   ){
	window.location = "/";
}

ifirave.pbGallery.pbgotoPhotoPage = function( albumAlias,   pageNum, sortField) {
	window.location = "/" + albumAlias +   "/?page=" + pageNum+ "&sortField=" + sortField;
}

ifirave.pbGallery.pbsortPhotoPage = function(albumAlias, sortField, sortIds) {
	if(typeof(sortIds) == "undefined")
		sortIds = "";
	window.location = "/" + albumAlias + "/?sortField=" + escape(sortField) + "&sortIds=" + sortIds;
}

//show gallery item detail public
ifirave.pbGallery.pbshowImageDetail = function( albumAlias,  itemId, sortField, sortOrder){
	strKey = "";

	strKey =  strKey + "&sortField=" + sortField + "&sortOrder=" + sortOrder;

	if (albumAlias == '') {
		window.location = "/?act=pbGalleryItem&itemId=" + itemId + strKey;
	} else {
		window.location = "/" + albumAlias + "/" + itemId + "/?" + strKey;
	}
}

/*ifirave.pbGallery.popUpSlideShow = function (albumAlias, sortField) {
	linkpopup = "/" + albumAlias + "/?act=pbSlideShow&sortField=" + sortField;
	wleft = (screen.width - 900) / 2;
	wtop = (screen.height - 600) / 2;
	var popupSS = window.open(linkpopup,'','scrollbars=no,menubar=no,resizable=no,toolbar=no,location=no,status=no,top=0,left=0,width=' + screen.width + ',height=' + screen.height);
}*/

ifirave.pbGallery.popupImage = function (id, fullScreen, forceView){

	linkpopup = "index.php?act=pbshowGalleryItem&id="+id+"&fullScreen="+fullScreen+"&force-view="+ forceView;
	window.open(linkpopup,'','scrollbars=yes,menubar=no,resizable=yes,toolbar=no,location=no,status=no');
}

ifirave.pbGallery.initAlbumPage = function(page, user){
	new Ajax.Request('index.php?act=pbajaxGalleryAlbums' , {
				method: 'post',
				parameters: {page: page, user: user},
				onSuccess: function(transport) {
					$('albumList').innerHTML = transport.responseText;
					ifirave.pbGallery.pbSetGalleryListCSS();
					ifirave.pbGallery.pbinitGallery();
				},
				onFailure: function(transport) {
				}
		});
}

ifirave.pbGallery.gotoAlbumPage = function(pageNum) {
	window.location = "/?page=" + pageNum;
}

//----------------------------- Truong update -----------------------------------//
ifirave.pbGallery.pbGalleryCheckPassword = function(albumAlias, pageAction){

	//
	ifirave.pbGallery.pageAction = pageAction;

	//
	var url = GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryPassword&albumAlias=' + albumAlias;
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var result = transport.responseText;
			if (result.indexOf('Successful') != -1)	{
				if ( ifirave.pbGallery.pageAction.indexOf('Select_Upload')!=-1) {
					ifirave.pbUpload.pbdoSelectAlbum(albumAlias);
				} else {
					window.location = "/" + albumAlias + "/";
				}
			}
			//Album has been deleted or album is not existed!
			else if(result.indexOf('not existed')!=-1 ){
				if(ifirave.pbGallery.pageAction.indexOf('Upload')!=-1)
					popup.popItUp(null, 'Album has been deleted or album is not existed!', null, null);
				else{
					window.location = "/" + albumAlias + "/";
				}
			}else {
				var option = new Object();
				option.html = true;
				option.confirmStr = result;
				popup.popItUp(null, option, 420,130, '');
			}
		},
		onFailure: function(transport) {
		}
	});
}

ifirave.pbGallery.pbGalleryDoAction = function(data) {
	var myAction = ifirave.pbGallery.pageAction;

	if ( myAction  == "Comment") {
		//ifirave.pbGallery.pbGalleryCommentAdd_(ifirave.pbGallery.itemId, ifirave.pbGallery.message);
		ifirave.pbGallery.pbGalleryCommentAdd(ifirave.pbGallery.itemId);
		popup.hide();
	}
	else if ( myAction  == "Follow") {
		ifirave.pbGallery.FollowAlbum(ifirave.pbGallery.itemId);
		$('FollowAlbum').innerHTML='Stop following this album';
		if($('v_f')){
		    $('v_f').style.display = 'none';
		}
		popup.hide();
	}
	else if ( myAction.indexOf("Upload") != -1 ) {
		ifirave.pbUpload.pbAfterLogin();
		popup.hide();
	}
	else if ( myAction == "ShareAlbum" ) {
		//ifirave.pbGallery.pbGalleryShareAlbum_( ifirave.pbGallery.albumAlias );
		popup.showQueue();
		$('v_se').value = ifirave.pbGallery.dataTemp.emailLogin + IRAVE_IMAP_EMAIL;
		$('v_se').disabled = true;
		return;
	}
	else if ( myAction == "SharePhoto" ) {
		//ifirave.pbGallery.pbGallerySharePhoto_( ifirave.pbGallery.itemId );
		popup.showQueue();
		$('v_se').value = ifirave.pbGallery.dataTemp.emailLogin + IRAVE_IMAP_EMAIL;
		$('v_se').disabled = true;
		return;
	}
	else if(myAction == "DownloadAlbum") {
		popup.hide();
		ifirave.pbGallery.checkDownloadAlbum();
	}
	else {
		popup.hide();
		//refresh comment page
		if($('v_info')){
		    $('v_info').style.display = 'none';//hidden name and email if login
		    ifirave.pbGallery.pageAction = 'Comment';
		}
	}
}

ifirave.pbGallery.pbSaveGalleryPassword= function(user, albumAlias) {
	// Get password
	var passwd = $('pwd').value.strip();
	if(passwd == ''){
		$('noticeBoard').innerHTML = jsVals.jalert.albumPassRequired;
		//popup.hide();
		return;
	}

	// Get url
	var url = GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryPassword&albumAlias=' + albumAlias + '&passwd=' + passwd ;

	// call ajax
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			//alert(transport.responseText);
			if (transport.responseText == 'Invalid album password') {
				$('noticeBoard').innerHTML = transport.responseText;
				return;
			}
			else {
				popup.hide();
				if ( ifirave.pbGallery.pageAction == 'Select_Upload') {
					ifirave.pbUpload.pbdoSelectAlbum( albumAlias  );
				}
				else {
					window.location = "/" + albumAlias + "/";
				}
			}
		},
		onFailure: function(transport) {
		}
	});
}

ifirave.pbGallery.pbGalleryPreregister_ = function( pageAction ) {
	ifirave.pbGallery.pageAction = pageAction;

	new Ajax.Request(GBP_IRAVE_URL_PUBLIC_ALBUM_ALIAS + '/?act=pbajaxGalleryVerifyPreregister', {
			method: 'post',
			parameters: { },
			onSuccess: function(transport) {
				if ( transport.responseText == 'Successful') { // login Page
					ifirave.pbGallery.pbGalleryHeader();
					ifirave.pbGallery.pbGalleryDoAction(pageAction);

				} else {

					var option = new Object();

					option.html = true;
					option.confirmStr = transport.responseText;
					popup.popItUp(null, option, 400, 40, '');
					//var option = new Object();
					//option.autoSize = true;
					//option.idDialog = 'dlgPreregister';
					//popup.popItUp(GBP_IRAVE_URL_PUBLIC_ALBUM_ALIAS + '/?act=pbajaxGalleryVerifyPreregister', option, 40, 40, '');
				}
				return;
			},
			onFailure: function(transport) {
				$('noticeBoard').innerHTML = "fail";//H them de test
			}
	});


}

ifirave.pbGallery.pbGalleryPreregisterSubmit_ = function() {
	var v_email = $('vemail').value.strip();
	var rememberMe = true;//$('rememberMe').checked ;//true or false
	var autoNotification = $('autoNotificationPopup').checked;
	var v_message = "";

	if ($('v_message')) {
		v_message = $('v_message').value ;
	}

	if(validation.isEmpty(v_email)){
	  $('noticeBoard').innerHTML = 'Please enter an email address.';
	  $('vemail').focus();
	  popup.popItUp(null, 'Please enter an email address.', null, null);
	  return;
	}
	if(!validation.isValidEmail(v_email)){
	  $('noticeBoard').innerHTML = jsVals.jalert.generalEmailInvalid;
	  $('vemail').focus();
	  popup.popItUp(null, jsVals.jalert.generalEmailInvalid, null, null);
	  return;
	}
	if (validation.isIraveEmail(v_email)) {
		ifirave.pbGallery.pbajaxGalleryLogin(v_message, v_email,'');
	}

	new Ajax.Request(GBP_IRAVE_URL_PUBLIC_ALBUM_ALIAS + '/?act=pbajaxGalleryVerifyPreregister', {
			method: 'post',
			parameters: { v_email : v_email, rememberMe : rememberMe, autoNotification : autoNotification, v_message: v_message },
			onSuccess: function(transport) {
				if ( transport.responseText == 'Successful') { // login Page
					//ifirave.pbGallery.preregister = true;
					ifirave.pbGallery.pbGalleryHeader();
					ifirave.pbGallery.message = v_message;
					/*if($('notifyPreregister')){
					  $('notifyPreregister').style.display = 'block';
					}*/

					ifirave.pbGallery.pbGalleryDoAction('');
				}
				return;
			},
			onFailure: function(transport) {}
	});
}

ifirave.pbGallery.pbajaxGalleryLogin = function(message, email, notice) {
	ifirave.pbGallery.message = message;
	if(notice != ''){
		notice = "&notice="+notice;
	}
	popup.popItUp(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryLogin&email='+email+notice ,null,440,270,'vemail');
}

ifirave.pbGallery.pbajaxGalleryLoginSubmit = function() {

	var emailValue = $('vemail').value.strip();
	var passValue = $('v_pwd').value.strip();
	var rememberMe = $('rememberMe').checked;

	//
	ifirave.pbGallery.dataTemp.emailLogin = emailValue;
	//var autoNotification = $('autoNotificationPopup').checked;

	if(emailValue == "username" &&  passValue == "password")
		 $('noticeBoard').innerHTML = jsVals.jalert.publicLoginEmailRequired;
	else if(validation.isEmpty(emailValue))
		 $('noticeBoard').innerHTML = jsVals.jalert.loginEmailRequired;
	else if(!validation.checkEmailName(emailValue) && !validation.isValidEmail(emailValue))
		 $('noticeBoard').innerHTML = jsVals.jalert.loginEmailInvalid;
	else if(validation.isEmpty(passValue))
		 $('noticeBoard').innerHTML = jsVals.jalert.passRequired;
	else if(validation.isContainSpace(passValue))
		 $('noticeBoard').innerHTML = jsVals.jalert.passBlank;
	else if(!validation.isTextOrInteger(passValue))
		 $('noticeBoard').innerHTML = jsVals.jalert.passInvalid;
	else {
		new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=doLogin", {
			method: 'post',
			parameters:{email:emailValue, passwd:passValue, remember: rememberMe},
			onSuccess: function(transport) {
				var result = transport.responseText.strip();
				var obj = result.evalJSON();

				if(obj.status == "done"){ // login successful
					//update albumlinked
					//ifirave.pbGallery.pbUpdateNotify(ifirave.pbGallery.itemId,autoNotification);
					ifirave.pbGallery.pbGalleryHeader();
					//refresh at header

					//ifirave.pbGallery.checkFollower($('albumId').value);alert('123')
					ifirave.pbGallery.pbGalleryDoAction('');

					// If owner refresh the page to make page redirect to owner page
					ifirave.pbGallery.refreshLogin = obj.loginSameOwner;
					//no redirect to owner
					// Check if same owner redirect to owner page
				    //if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//					    return;
//				    }
				}else if(obj.counter <= LIMIT_FAIL_SIGNUP_TIMES) {
					if(obj.msg.indexOf("email") != -1)
					   $('noticeBoard').innerHTML = obj.msg;
					else
					   $('noticeBoard').innerHTML = obj.msg;
			    }
				else {
					window.location = CONFIRMLOGIN_URL;
				}
			}
		});
	}
}

ifirave.pbGallery.pbGalleryCommentAdd_ = function ( itemId, message){

	// Set itemId
	ifirave.pbGallery.itemId = itemId;
	ifirave.pbGallery.message = message;

	//alert("pbGalleryCommentAdd_");
	//if (ifirave.pbGallery.preregister == false) {
		//ifirave.pbGallery.pbGalleryPreregister_( 'Comment' );
	//	return;
	//}
	var comment_field =  $F('comment_field').escapeHTML();
	if(validation.isEmpty(comment_field)) {
		popup.popItUp(null, 'Please enter a comment.', null, null);
		return;
	}

	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryCommentAdd', {
			method: 'post',
			parameters: { comment_field : comment_field, itemId : itemId, message: message },
			onSuccess: function(transport) {
				var result = transport.responseText;
				//
				if (result == 'Not check visitor' ) {
					ifirave.pbGallery.pbGalleryPreregister_( 'Comment' );
					return;
				}

				// Check if same owner redirect to owner page
				//if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//					return;
//				}
				//
				if ( result.indexOf('Your comment has been submitted for approval') != -1) {
					setTimeout(function(){
						popup.popItUp(null, transport.responseText, 380, 115, 'v_email');
					}, 400);
				} else {
					$('comment_list').innerHTML = transport.responseText;
				}
				$('comment_field').value = '';

			},
			onFailure: function(transport) {
			}
	});
}

ifirave.pbGallery.pbajaxGalleryResetPreregister_ = function () {
	//ifirave.pbGallery.preregister = false;
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryResetPreregister', {
			method: 'get',
			onSuccess: function(transport) {
				//ifirave.pbGallery.pbGalleryPreregister_();
				ifirave.pbGallery.pbGalleryHeader();
				//address = address.toString();
				//var start = address.indexOf("key");
				//var cutout = address.substring(start,start+38);
				//address = address.replace(cutout,"");
				//var addressReload = address.replace("((\?key=)|(&key=))[^&]+", "");
				var address = window.location.toString();
				address = address.gsub("(key=)[^&]+", "");
				address = address.gsub("(key=)[^&]+", "");
				address = address.replace("&&", "&");
				if (address == window.location.toString())
					window.location.reload();
				else
					window.location = address;
				//parent.document.location.reload();
				$('V_Email').innerHTML ='';
				if ($('V_EmailReset')){
					$('V_EmailReset').style.display = 'none';
				}
				if($('notifyPreregister'))
				  $('notifyPreregister').style.display = 'none';
				//$('beforeLogin').style.display='block';
			    //$('afterLogin').style.display='none';
			    //display follow me
			    if($('v_f')){
			      $('v_f').style.display = 'block';
			      //$('f_a').checked = false;
			    }
			},
			onFailure: function(transport) {
			}
	});
}

ifirave.pbGallery.pbGallerySharePhoto_ = function (itemId) {

	/*ifirave.pbGallery.itemId = itemId;
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGallerySharePhoto', {
			method: 'post',
			parameters: { itemId : itemId },
			onSuccess: function(transport) {
				var result = transport.responseText;
				//
				//if (result == 'Not check visitor' ) {
					//ifirave.pbGallery.pbGalleryPreregister_( 'SharePhoto' );
					return;
				//} else {
					var option = new Object();
					option.html = true;
					option.confirmStr = result;
					popup.popItUp(null, option, 500, 400, '');
				//}
			},
			onFailure: function(transport) {
			}
	});*/
	popup.popItUp(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGallerySharePhoto&itemId='+itemId, null, 460, 450);
	setTimeout(function() { ifirave.pbGallery.initAutoCompleteForSharedPhoto(); }, 500);
}

ifirave.pbGallery.pbGallerySharePhotoOK_ = function (itemId) {
	if(ifirave.pbGallery.add_queue == false) {
 	     return;
 	}
	var dataInput = new Object();

	// Get data input
	dataInput.emailShare =  $('email_share').value.strip();
	var msgContent =  $F('message_share').strip();
	var messageShare =  msgContent.escapeHTML();
	//dataInput.vname = $('v_sn').value.strip();
	var vname = $('v_sn').value.strip();
	dataInput.vemail = $('v_se').value.strip();

	if(validation.isEmpty(dataInput.vemail)) {
		$('noticeBoard').innerHTML = jsVals.jalert.senderEmailRequired;
	  	$('v_se').focus();
	  	return;
	}
	if(!validation.isValidEmail(dataInput.vemail)){
	  $('noticeBoard').innerHTML = jsVals.jalert.senderEmailInvalid;
	  $('v_se').focus();
	  return;
	}

	// Check irave email
	if($('v_se').disabled != true && validation.isIraveEmail(dataInput.vemail) ){
        ifirave.pbGallery.itemId = itemId;
        ifirave.pbGallery.pageAction = "SharePhoto";
        popup.pushQueue();
        ifirave.pbGallery.pbajaxGalleryLogin('',dataInput.vemail,'');
        return;
    }

	//check vemail not null
	if(validation.isEmpty(dataInput.emailShare)) {
		$('noticeBoard').innerHTML = jsVals.jalert.shareEmailRequired;
	    $('email_share').focus();
		return;
	}

	var comma_pos = dataInput.emailShare.indexOf(',');
	if (comma_pos <0){
		if(!validation.isValidEmail(dataInput.emailShare)){
			$('noticeBoard').innerHTML = jsVals.jalert.shareMailInvalid;
			$('email_share').focus();
			return;
		}
	}else{
		var email = dataInput.emailShare.split(',');
		for(i=0;i<email.length;i++)
		{
			email[i] = email[i].trim();
			if(!validation.isValidEmail(email[i])){
				$('noticeBoard').innerHTML = jsVals.jalert.shareMailInvalid;
				$('email_share').focus();
				return;
			}
		}
	}

	/*if(!validation.isValidEmail(dataInput.emailShare)){
		$('noticeBoard').innerHTML = jsVals.jalert.shareMailInvalid;
	    $('email_share').focus();
		return;
	}*/

	//var messageShare = dataInput.messageShare;
	//dataInput.messageShare = messageShare.gsub(/(\r\n|[\r\n])/, "<br/>");
	//dataInput.messageShare = dataInput.messageShare.escapeHTML();

	ifirave.pbGallery.add_queue = !ifirave.pbGallery.add_queue;
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGallerySharePhoto', {
			method: 'post',
			parameters: { itemId:itemId, dataInput : Object.toJSON(dataInput),vname: vname, message: messageShare},
			onSuccess: function(transport) {
				ifirave.pbGallery.pbGalleryHeader();
				ifirave.pbGallery.add_queue = !ifirave.pbGallery.add_queue;
				if (transport.responseText == 'Not check visitor' ) {
					alert('Not check visitor');
					return;
				}

				// Check if same owner redirect to owner page
				//if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//					return;
//				}

				// Display dialog for return result
				setTimeout(function(){
					popup.popItUp(null, transport.responseText, 400, 250, '');
				}, 400);
			},
			onFailure: function(transport) {
			}
	});
	popup.hide();
	//set header
	if($('v_e'))
		$('v_e').value = dataInput.vemail;
	if($('v_n')) {
		if (typeof dataInput.vname != 'undefined')
			$('v_n').value = dataInput.vname;
	}
}

ifirave.pbGallery.pbGalleryShareAlbum_ = function ( albumAlias ) {
	popup.popItUp(GBP_IRAVE_URL_PUBLIC +  '/?act=pbajaxGalleryShareAlbum&albumAlias=' + albumAlias, null, 460, 415);
	setTimeout(function() { ifirave.pbGallery.initAutoCompleteForSharedPhoto(); }, 500);
}

ifirave.pbGallery.pbGalleryShareAlbumOK_ = function (albumAlias) {
	if(ifirave.pbGallery.add_queue == false) {
 	     return;
 	}
	var dataInput = new Object();

	// Get data input
	dataInput.emailShare =  $('email_share').value.strip();
	var msgContent =  $F('message_share').strip();
	var messageShare =  msgContent.escapeHTML();
	//dataInput.vname = $('v_sn').value.strip();
	var vname = $('v_sn').value.strip();
	dataInput.vemail = $('v_se').value.strip();

	//check email
	if(validation.isEmpty(dataInput.vemail)){
		$('noticeBoard').innerHTML = jsVals.jalert.senderEmailRequired;
	  	$('v_se').focus();
	  	return;
	}
	if(!validation.isValidEmail(dataInput.vemail)){
	  $('noticeBoard').innerHTML = jsVals.jalert.senderEmailInvalid;
	  $('v_se').focus();
	  return;
	}

	// Check irave email
	if($('v_se').disabled != true && validation.isIraveEmail(dataInput.vemail) ){
        ifirave.pbGallery.albumAlias = albumAlias;
        ifirave.pbGallery.pageAction = "ShareAlbum";
        popup.pushQueue();
        ifirave.pbGallery.pbajaxGalleryLogin('',dataInput.vemail,'');
        return;
    }


	//check vemail not null
	if(validation.isEmpty(dataInput.emailShare)) {
		$('noticeBoard').innerHTML = jsVals.jalert.shareEmailRequired;
	    $('email_share').focus();
		return;
	}

	/*
		check for 1 or more email accounts
		author: lam nguyen thanh trung
		modified date: 12/12/2008
	*/
	var comma_pos = dataInput.emailShare.indexOf(',');
	if (comma_pos <0){
		var contact = validation.splitNameAndEmail(dataInput.emailShare);
		if(!validation.isValidEmail(contact.email)){
			$('noticeBoard').innerHTML = jsVals.jalert.shareMailInvalid;
			$('email_share').focus();
			return;
		}
	}else{
		var email = dataInput.emailShare.split(",");
		dataInput.emailShare = "";
		for (i=0; i < email.length; i++) {
			email[i] = email[i].trim();
			var contact = validation.splitNameAndEmail(email[i]);
		  	if(!validation.isValidEmail(contact.email)){
				$('noticeBoard').innerHTML = jsVals.jalert.shareMailInvalid;
				$('email_share').focus();
				return;
			}
			dataInput.emailShare += contact.email + (i < email.length - 1 ? "," : "");
		}
	}

	/*var messageShare = dataInput.messageShare;
	dataInput.messageShare = messageShare.gsub(/(\r\n|[\r\n])/, "<br/>");
	dataInput.messageShare = dataInput.messageShare.escapeHTML();*/

	ifirave.pbGallery.add_queue = !ifirave.pbGallery.add_queue;
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryShareAlbum', {
			method: 'post',
			parameters: { albumAlias: albumAlias, dataInput: Object.toJSON(dataInput), vname: vname, message: messageShare },
			onSuccess: function(transport) {
				ifirave.pbGallery.pbGalleryHeader();
				ifirave.pbGallery.add_queue = !ifirave.pbGallery.add_queue;

				// Check if same owner redirect to owner page
				//if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//					return;
//				}

				// Display dialog for return result
				setTimeout(function(){
					popup.popItUp(null, transport.responseText.strip(), 400, 250, '');
				}, 400);
			},
			onFailure: function(transport) {
			}
	});
	popup.hide();
}

ifirave.pbGallery.pbGalleryReturnOwnerPage = function() {
	if (ifirave.pbGallery.refreshLogin == 1) {
		setTimeout(function(){
			popup.popItUp(null, "System will return to owner page in few seconds.", 380);
		}, 400);
		setTimeout(function(){
			window.open(GBP_IRAVE_PUBLIC_TO_OWNER_URL, '_self');
		}, 2000);
		return true;
	}
	return false;
}
ifirave.pbGallery.pbGalleryHeader = function() {
	//GBP_IRAVE_URL_PUBLIC
	var url = GBP_IRAVE_URL_PUBLIC_ALBUM_ALIAS + '/?act=pbajaxFrameHeader';
	new Ajax.Updater(parent.$('headerWrapper'), url,
		{
			method: 'get',
			parameters: {}
		});
}
ifirave.pbGallery.pbUpdateNotify = function(itemId, autoNotification){

    new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=pbajaxGalleryCommentAdd",{
        method: 'post',
        parameters: {itemId: itemId, autoNotification: autoNotification, comment_field: 'login'},
        onSuccess: function(transport){
        }
    });
}
/*
ifirave.pbGallery.pbShowPhotosForPhotoPage = function(albumId, itemId, sortField, sortOrder, page){
    new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=pbajaxGalleryShowPhotosForPhotoPage",{
        method: 'post',
        parameters: {albumId: albumId, itemId: itemId, sortField: sortField, sortOrder: sortOrder, page: page},
        onSuccess: function(transport){
            $('photolist').innerHTML = transport.responseText;
        }
    });
}

ifirave.pbGallery.pbShowPhotoDetail = function(albumId, itemId,sortField, sortOrder, page){
    new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=pbajaxGalleryShowPhotoDetail",{
        method: 'post',
        parameters: {albumId: albumId, itemId: itemId, sortField: sortField, sortOrder: sortOrder, page: page},
        onSuccess: function(transport){
            $('photoDetail').innerHTML = transport.responseText;
        }
    });
}
*/
ifirave.pbGallery.pbExplainFollow = function(){
    var str = '<div align="center" style="padding:20px"><div>When you follow an album, you will receive updates on photo additions and comments. You have the option to stop following this album at any time.'
						+ '</div><div><input onclick="javascript:popup.hide()" type="button" value="Close" id="butYes" style="width:60px;margin-top:5px"/>'
						+ '</div></div>';

    var option = new Object();
    option.html = true;
    option.confirmStr = str;
    parent.popup.popItUp(null, option, 400, 160,'');
}

/*Delete comment*/
ifirave.pbGallery.pbGalleryCommentDelete = function(itemId, commentId) {
	var commentContent =  $('comment_field').value ;
	new Ajax.Request('index.php?act=pbajaxGalleryCommentDelete', {
			method: 'post',
			parameters: { itemId : itemId, commentId : commentId },
			onSuccess: function(transport) {
				var result = transport.responseText;
				$('comment_list').innerHTML = transport.responseText;
			},
			onFailure: function(transport) {
			}
	});
}

ifirave.pbGallery.pbGalleryCommentAdd = function (itemId){
	if(ifirave.pbGallery.add_queue == false) {
 	     return;
 	}

	// Set itemId
	ifirave.pbGallery.itemId = itemId;
	//ifirave.pbGallery.message = message;
	var comment_field =  $F('comment_field').escapeHTML();
	if(validation.isEmpty(comment_field)) {
		popup.popItUp(null, 'Please enter a comment.', null, null);
		return;
	}
	var followme = false;
	if($('f_a'))
        followme = $('f_a').checked;
    if(ifirave.pbGallery.pageAction != "Comment"){
	    var vname = $('v_n').value.strip();
	    var vemail = $('v_e').value.strip();
	    if($('f_a'))
	        followme = $('f_a').checked;

	    if(validation.isEmpty(vemail)){
	        popup.popItUp(null, 'Please enter an email address.', null, null);
	        return;
	    }
	    if(validation.isIraveEmail(vemail) ){
	        itemId = $('itemId').value;
	        ifirave.pbGallery.itemId = itemId;
	        ifirave.pbGallery.pageAction = "Comment";
	        ifirave.pbGallery.pbajaxGalleryLogin('',vemail,'');
	        return;
	    }
	    if(vemail == $('email2nd').value){
	    	itemId = $('itemId').value;
	        ifirave.pbGallery.itemId = itemId;
	        ifirave.pbGallery.pageAction = "Comment";
	        var notice = "You have just entered your alternative email, please login!";
	        ifirave.pbGallery.pbajaxGalleryLogin('','', notice);
	        return;
	    }

	    if(vemail == $('email_mobile').value){
	    	itemId = $('itemId').value;
	        ifirave.pbGallery.itemId = itemId;
	        ifirave.pbGallery.pageAction = "Comment";
	        var notice = "You have just entered your mobile email, please login!";
	        ifirave.pbGallery.pbajaxGalleryLogin('','', notice);
	        return;
	    }

	    if(!validation.isValidEmail(vemail)){
	        popup.popItUp(null, jsVals.jalert.senderEmailInvalid, null, null);
	        return;
	    }
	}

	ifirave.pbGallery.add_queue = !ifirave.pbGallery.add_queue;
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryCommentAdd', {
			method: 'post',
			parameters: { comment_field: comment_field, itemId: itemId, v_name: vname, v_email: vemail, followme: followme },
			onSuccess: function(transport) {
				var result = transport.responseText;
				ifirave.pbGallery.add_queue = !ifirave.pbGallery.add_queue;

				if (result == 'Not check visitor' ) {
					//ifirave.pbGallery.pbGalleryPreregister_( 'Comment' );
					alert('Not check visitor');
					return;
				}

				//not redirect owner
				// Check if same owner redirect to owner page
				//if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//					return;
//				}

				//
				if ( result.indexOf('Your comment has been submitted for approval') != -1) {
					//if(followme == true && ifirave.pbGallery.pageAction != "Comment"){
//					  //followAlbum for visitor
//					  ifirave.pbGallery.VisitorFollowAlbum($('albumId').value,vemail);
//					}
					//setTimeout(function(){
//						popup.popItUp(null, transport.responseText, 380, 115, 'v_email');
//					}, 400);
					popup.popItUp(null, transport.responseText, 380, 115, 'v_email');
				} else {
					//if(followme == true && ifirave.pbGallery.pageAction != "Comment"){
//					  //followAlbum for visitor
//					  ifirave.pbGallery.VisitorFollowAlbum($('albumId').value,vemail);
//					}
					$('comment_list').innerHTML = transport.responseText;
				}
				//
				$('comment_field').value = '';
				ifirave.pbGallery.pbGalleryHeader();
				if(followme == true){
				    $('v_f').style.display = 'none';
				    var js = "ifirave.pbGallery.changeFollowAlbum('stopFollow')";
					$('buttonFollow').setAttribute("onclick",js);
				    $('FollowAlbum').innerHTML='Stop following this album';
				}
			},
			onFailure: function(transport) {
			}
	});
}
ifirave.pbGallery.pbSetAction = function(action){
    ifirave.pbGallery.pageAction = action;
}
ifirave.pbGallery.pbNextPrevPhotoPage = function(albumAlias, itemId, sortField, sortOrder, page){
    strKey = "";
    strKey = strKey + "&sortField=" + sortField + "&sortOrder=" + sortOrder +"&page="+page;
    if(albumAlias == ''){
        window.location = "/?act=pbGalleryItem&itemId=" + itemId + strKey;
    }else{
        window.location = "/" + albumAlias + "/" + itemId + "/?" + strKey;
    }
}

ifirave.pbGallery.FollowAlbum = function(Aid){
var opt = '';

// Check if same owner redirect to owner page
//if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//	return;
//}
if ($('FollowAlbum').innerHTML == 'Stop following this album'){
	opt='stop';
	if($('v_f')){
	    $('v_f').innerHTML = '<input type="checkbox" id="f_a" name="f_a" /> <span onclick="$(\'f_a\').checked = !$(\'f_a\').checked" style="cursor:pointer;">Follow this album</span><a onClick="javascript:ifirave.pbGallery.pbExplainFollow();" style="cursor:pointer;">What does this mean?</a>';
	    $('v_f').style.display = 'block';
	}
}

		new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=pbajaxGalleryFollowAlbum",{
        method: 'post',
        parameters: {albumId: Aid, opts: opt, oemail: ifirave.pbGallery.vemail},
        onSuccess: function(transport){
        	if(transport.responseText.indexOf('0') != -1){
        		$('FollowAlbum').innerHTML='Follow this album';
        	}
        	else if(transport.responseText.indexOf('1') != -1){
        		$('FollowAlbum').innerHTML='Stop following this album';
        		if($('v_f')){
				    $('v_f').style.display = 'none';
				}
        	}
        	else if(transport.responseText.indexOf('2') != -1){
        	//in black list, show popup confirm
        		popup.popItUp(null, "To follow this album, please check your email and confirm your email address. Thanks!", 500, 100);
        		return;
        	}
        	else if(transport.responseText.indexOf('3') != -1){
        	//show popup
        		popup.popItUp(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryShowFollowAlbum&albumId='+Aid, null, 550, 175,'.v_email');
        	}

        },
         onFailure: function(transport) {
			}
    });
    //popup.hide();
}

ifirave.pbGallery.changeFollowAlbum = function(option){
	var albumId = $F('albumId').strip();
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryFollowAlbum', {
		method: 'post',
		parameters: {albumId: albumId, opts: option, oemail: ifirave.pbGallery.vemail, action: 'checkFollow'},
		onSuccess: function(transport){
			var result = transport.responseText.strip();
			if(result.indexOf('0') != -1){
				var js = "ifirave.pbGallery.changeFollowAlbum('follow')";
				$('buttonFollow').setAttribute("onclick",js);
				$('FollowAlbum').innerHTML='Follow this album';
			}else if(result.indexOf('1') != -1){
				var js = "ifirave.pbGallery.changeFollowAlbum('stopFollow')";
				$('buttonFollow').setAttribute("onclick",js);
				$('FollowAlbum').innerHTML='Stop following this album';
			}else if(result.indexOf('2') != -1){
				popup.popItUp(null, "To follow this album, please check your email and confirm your email address. Thanks!", 500, 100);
        		return;
			}else if(result.indexOf('3') != -1){
				popup.popItUp(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryShowFollowAlbum&albumId='+albumId, null, 550, 175,'.v_email');
			}else{ // 4
				popup.popItUp(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGallerySelectedFollow&albumId='+albumId, null, 450, 215, '');
			}
		}
	});
}

ifirave.pbGallery.followSelectedEmail = function(){
	var albumId = $F('albumId').strip();
	var selectedEmail = "";
	var radio = $$('input[name=followEmail]');
	for(i=0;i<radio.length;i++){
	    if(radio[i].checked == true){
	        selectedEmail = radio[i].value;
	    }
	}
	if (selectedEmail == ""){
		$('noticeBoard').innerHTML = "Please select an email!";
		return;
	}
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=pbajaxGalleryFollowAlbum", {
		method: 'post',
		parameters: {albumId: albumId, vemail: selectedEmail, action:'selectedFollow'},
		onSuccess: function(transport) {
			var result = transport.responseText.strip();
			if(result.indexOf('1') != -1){
				var js = "ifirave.pbGallery.changeFollowAlbum('stopFollow')";
				$('buttonFollow').setAttribute("onclick",js);
				$('FollowAlbum').innerHTML='Stop following this album';
			}
		}
	});
	popup.hide()
}

ifirave.pbGallery.VisitorFollowAlbum = function(Aid,vemail){
	vemail = vemail.strip();
	// Get data input
	var albumId = Aid;
	//check email
	if(validation.isEmpty(vemail)){
		$('noticeBoard').innerHTML = 'Please enter an email address.';
	  	$('v_email').focus();
	  	return;
	}
	if(!validation.isValidEmail(vemail)){
	  $('noticeBoard').innerHTML = jsVals.jalert.generalEmailInvalid;
	  $('v_email').focus();
	  return;
	}

    if(vemail==$('2ndEmail').value.strip() || vemail==$('address').value.strip()){//hidden on headerblocker
    	popup.popItUp(null, 'Sorry! You can not follow yourself', 300, 80);
    	//$('noticeBoard').innerHTML = 'Sorry! You can not follow yourself!';
	    //$('v_email').focus();
    	return;
    }
    if(validation.isIraveEmail(vemail)){
    	ifirave.pbGallery.itemId=Aid;
    	ifirave.pbGallery.vemail=vemail;
    	ifirave.pbGallery.pageAction = "Follow";
        ifirave.pbGallery.pbajaxGalleryLogin('',vemail,'');
        return;
    }

	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxGalleryFollowAlbum', {
			method: 'post',
			parameters: { albumId:albumId, vemail : vemail, action : 'save'},
			onSuccess: function(transport) {
				var result = transport.responseText.strip();
				ifirave.pbGallery.pbGalleryHeader();
				// Check if same owner redirect to owner page
				//if (ifirave.pbGallery.pbGalleryReturnOwnerPage() == true) {
//					return;
//				}
				if(result.indexOf('0')!= -1){
					var js = "ifirave.pbGallery.changeFollowAlbum('follow')";
					$('buttonFollow').setAttribute("onclick",js);
        			$('FollowAlbum').innerHTML='Follow this album';
	        		popup.hide();
        		}
	        	else if(result.indexOf('1') != -1){
	        		var js = "ifirave.pbGallery.changeFollowAlbum('stopFollow')";
					$('buttonFollow').setAttribute("onclick",js);
	        		$('FollowAlbum').innerHTML='Stop following this album';
	        		if($('v_f')){
					    $('v_f').style.display = 'none';
					}
	        		popup.hide();
	        	}
	        	else if(result.indexOf('2') != -1){
	        		//in black list, show popup confirm
	        		popup.popItUp(null, "To follow this album, please check your email and confirm your email address. Thanks!", 500, 100);
	        		return;
        		}

			},
			onFailure: function(transport) {
			}
	});
	//popup.hide();
}

ifirave.pbGallery.checkFollower = function( albumId){
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + '/?act=pbajaxCheckFollower',{
		method: 'post',
		parameters:{ albumId: albumId},
		onSuccess:function(transport){
			if(transport.responseText == 1){
				$('FollowAlbum').innerHTML='Stop following this album';
        		if($('v_f'))
				    $('v_f').style.display = 'none';
				if($('followAlbum'))
				    $('followAlbum').style.display = 'none';
			}else{
				$('FollowAlbum').innerHTML='Follow this album';
				if($('v_f')){
				    $('v_f').style.display = 'block';
				    $('v_f').innerHTML = '<input type="checkbox" id="f_a" name="f_a" /> <span onclick="$(\'f_a\').checked = !$(\'f_a\').checked" style="cursor:pointer;">Follow this album</span><a onClick="javascript:ifirave.pbGallery.pbExplainFollow();" style="cursor:pointer;">What does this mean?</a>';
				    if($('f_a'))
				    $('f_a').checked = false;
				}
				if($('followAlbum')){
					$('followAlbum').style.display = 'block';
					$('followAlbum').innerHTML = '<input type="checkbox" style="float:left;" id="followAlbumCB"/><span id="followAlbumText" style="float:left; width:auto; display:block; padding-top:3px; cursor:default;" onclick="$(\'followAlbumCB\').checked = !$(\'followAlbumCB\').checked"> Follow this album</span><a onClick="javascript:ifirave.pbGallery.pbExplainFollow();" style="cursor:pointer;">What does this mean?</a>';
					if($('followAlbumCB'))
					  $('followAlbumCB').checked = false;
				}
			}
		}
	})
}

ifirave.pbGallery.initAutoCompleteForSharedPhoto = function(){
    new AutoCompleteTextbox($("email_share"), $("autoShareList"), $("contactListForAuto"), false, true);
}

ifirave.pbGallery.mousePosition = function(e){
	//alert('tet');
	//var ns4 = (document.layers) ? true : false ;
	//var ie4 = (document.all) ? true : false;
	var e = e? e : window.event;
	var mouseX = e.clientX;
	var mouseY = e.clientY;

	$('autoShareList').setStyle({
		position:'absolute',
		display:'block',
		top:mouseY+50,
		left:mouseX
	});
}

ifirave.pbGallery.albumPerPageChanging = function(oldAlbumPerPage, albumPerPage, totalAlbum){
	new Ajax.Request("index.php?act=pbajaxSetItemPerPage", {
		method: "post",
		parameters: {albumPerPage: albumPerPage, option: 'albumPerPage'},
		onSuccess: function(transport){
			var res = transport.responseText.strip();
			if(res.indexOf("Done") != -1){
				var address = window.location.toString();
				var obj = address.toQueryParams();
				address = address.gsub("(&page=)[^&]+", "");
				address = address.gsub("(page=)[^&]+", "");
				address = address.replace("&&", "&");
				var page = obj.page;
				var rpage = pageAsChangeItem(oldAlbumPerPage, albumPerPage, page);
				if(page == undefined){
					window.location = address + "?&page=" + rpage;
				}else {
					window.location = address + "&page=" + rpage;
				}
			}
		}
	});
}

ifirave.pbGallery.itemPerPageChanging = function(oldItemPerPage, itemPerPage,totalPhoto){
	new Ajax.Request("index.php?act=pbajaxSetItemPerPage", {
		method: "post",
		parameters: {itemPerPage: itemPerPage, option: 'itemPerPage'},
		onSuccess: function(transport){
			var res = transport.responseText.strip();
			if(res.indexOf("Done") != -1){
				var address = window.location.toString();
				var obj = address.toQueryParams();
				address = address.gsub("(&page=)[^&]+", "");
				address = address.gsub("(page=)[^&]+", "");
				address = address.replace("&&", "&");
				var page = obj.page;
				var rpage = pageAsChangeItem(oldItemPerPage, itemPerPage, page);
				if(page == undefined) {
					window.location = address + "/?&page=" + rpage;
				}else{
					window.location = address + "&page=" + rpage;
				}
//				if(page == undefined ){
//					window.location = address + "?page=1";
//				}else {
//					var rpage = parseInt(totalPhoto/number + (totalPhoto%number > 0 ? 1 : 0));
//					if(rpage == 0){
//						window.location = address;
//					}else if(page > rpage){
//						page = rpage;
//						window.location = address + "&page=" + page;
//					}else{
//						window.location.reload();
//					}
//				}
			}
		}
	});
}

/*show and fade-in album List combobox*/
ifirave.pbGallery.comboboxId = "quicklyAlbumList";
ifirave.pbGallery.isShowCombo = false;
var timeoutId;

ifirave.pbGallery.mouseoverGallery = function() {
	if(ifirave.pbGallery.isShowCombo) {
		clearTimeout(timeoutId);
	}
	else {
		ifirave.pbGallery.isShowCombo = true;
		ifirave.pbGallery.showFadeInAlbumCombo();
	}
}

ifirave.pbGallery.mouseoutGallery = function() {
	if(ifirave.pbGallery.isShowCombo) {
		timeoutId = setTimeout(function() {
								ifirave.pbGallery.isShowCombo = false;
								ifirave.pbGallery.hideFadeInAlbumCombo();
							}, 100);
	}
}

ifirave.pbGallery.mouseoverAlbumCombo = function() {
	ifirave.pbGallery.mouseoverGallery();
}

ifirave.pbGallery.mouseoutAlbumCombo = function() {
	ifirave.pbGallery.mouseoutGallery();
}

ifirave.pbGallery.hideFadeInAlbumCombo = function() {
	new Rico.Effect.FadeTo(ifirave.pbGallery.comboboxId,0,300,3);
	if(util.isIE())
		ifirave.pbGallery.hideAlbumCombo();
	else
		setTimeout(function(){ifirave.pbGallery.hideAlbumCombo();}, 300);
}

ifirave.pbGallery.showFadeInAlbumCombo = function() {
	$(ifirave.pbGallery.comboboxId).style.display = 'block';
	new Rico.Effect.FadeTo(ifirave.pbGallery.comboboxId,1,400,3);
}

ifirave.pbGallery.hideAlbumCombo = function() {
	$(ifirave.pbGallery.comboboxId).style.display = 'none';
}

ifirave.pbGallery.showPhoto = function(itemId){
	$('div_loadingIcon2').style.display = '';
	$('div_detailImage').style.display = '';
	//if($('item_'+selectingIndex)){
//		if(itemId != selectingIndex ) {
//			$('item_' + selectingIndex).className = '';
//		}
//		if($('item_' + itemId))
//			$('item_' + itemId).className = 'active';
//	}
	selectingIndex = itemId;
	var albumId = $('albumId').value;
	var page = $('page').value;
	var sortField = $('sortField').value;
	var sortOrder = $('sortOrder').value;

	new Ajax.Request('index.php?act=pbajaxGalleryItemDetail', {
		method: 'post',
		parameters: {itemId: itemId, albumId: albumId, page: page, sortField: sortField, sortOrder: sortOrder},
		onSuccess: function(transport) {
			var result = transport.responseText.strip();
			result = result.evalJSON();
			$('photoDetail').innerHTML = result.photoDetail;
			$('tag_finish').style.display = "none";
			$('commentPlace').innerHTML = result.commentList;
			//doing for IE bug
			$('page').value = $('page1').value;
			$('sortOrder').value = $('sortOrder1').value;
			$('sortField').value = $('sortField1').value;
			$('itemId').value = $('itemId1').value;
			ImageObject.reset2NewImg(itemId);
			loadAllTagDiv(itemId);
		},
		onFailure: function(transport) {}
	});
}

/*
* go to next, previous photo, paging
* string hash = 'itemId, page'
*/
ifirave.pbGallery.getThumbPage = function(hash){
	$('div_loadingIcon2').style.display = '';
	$('div_detailImage').style.display = '';
	hash = hash.toString();
	var index = hash.indexOf(',');
	var page, id;
	if(index != -1){
		id = hash.substr(0, index);
		page = hash.substr(index+1, hash.length);
	}else{
		page = $F('page');//1;
		id = hash;
	}
	var albumId = $('albumId').value;
    var sortField = $('sortField').value;
    var sortOrder = $('sortOrder').value;
    var prevPage = $('prevPage').value;

	new Ajax.Request('index.php?act=pbajaxGalleryPhotoThumbPage', {
		method: 'post',
		parameters: {page: page, albumId: albumId, itemId: id, prevPage: prevPage, sortField: sortField, sortOrder: sortOrder},
		onSuccess: function(transport) {
			var result = transport.responseText;
			result = result.evalJSON();
			$('photolist').innerHTML = result.listThumb;
			$('photolist').style.display = 'block';
			$('page').value = page;
			$('paginationN').innerHTML = result.pageNav;
			$('itemId').value = result.itemId2;//$('itemId2').value;
			var itemId = $('itemId').value;
			var newHash = itemId + ',' + page;
			irave.addAjaxBack(newHash);
			ifirave.pbGallery.showPhoto(itemId);
			$('item_'+itemId).className = 'active';
			$('prevPage').value = 0;
			ImageObject.setMaxId(result.maxItemId);
		},
		onFailure: function(transport) {}
	});
}

//reload photo page (update thumnail list)
ifirave.pbGallery.autoUpdatePhotoPage = function(){
	if(ifirave.pbGallery.action == "undefined" || ifirave.pbGallery.action != "pbgalleryitem") {
		irave.clearAutoCheckTime();
		return;
	}
	var albumId = $('albumId').value;
	var sortField = $('sortField').value;
    var sortOrder = $('sortOrder').value;
    var prevPage = $('prevPage').value;
    var page = $('page').value;
    var id = $('itemId').value;
	var maxItemId = ImageObject.getMaxId();
	//alert(maxItemId);
	new Ajax.Request('index.php?act=pbajaxGalleryPhotoThumbPage', {
		method: 'post',
		parameters: {maxItemId: maxItemId, albumId: albumId, option: 'checkNewPhoto', page: page, itemId: id, prevPage: prevPage, sortField: sortField, sortOrder: sortOrder},
		onSuccess: function(transport){
			var result = transport.responseText;
			if(result != '' && result.indexOf('NoNew') < 0){
				result = result.evalJSON();
				var itemId_result = result.itemId2;
				var listThumb_result = result.listThumb;
				if(itemId_result != '' && listThumb_result.indexOf('item_') > 0) {
					$('photolist').innerHTML = result.listThumb;
					$('photolist').style.display = 'block';
					$('page').value = result.page;
					$('paginationN').innerHTML = result.pageNav;
					$('itemId').value = itemId_result;//$('itemId2').value;
					if(result.totalPhoto > 1){
						$('totalPhoto').innerHTML = result.totalPhoto + ' photos';
					}else{
						$('totalPhoto').innerHTML = result.totalPhoto + ' photo';
					}
					var itemId = $('itemId').value;
					var newHash = itemId + ',' + result.page;
					irave.addAjaxBack(newHash);
					//$('item_'+itemId).className = 'active';
					$('prevPage').value = 0;
					//set maxId again
					ImageObject.setMaxId(result.maxItemId);
				}
			}
		}
	});
}

ifirave.pbGallery.reload = function(){
	//garther the current parameters
	//params = document.location.toString().toQueryParams();
	//if( params['act']){
	//	delete(params['act']);
	//}

	new Ajax.Request(document.location.toString(), {
		method: 'post',
		parameters: {reload:true},
		onSuccess: function(transport) {
			var result = transport.responseText.strip();
			$('album_list').update(result);
		}
	});
}

ifirave.pbGallery.reloadAlbum = function(){
	//garther the current parameters
	//params = document.location.toString().toQueryParams();
	//if( params['act']){
	//	delete(params['act']);
	//}

	new Ajax.Request(document.location.toString(), {
		method: 'post',
		parameters: {reload:true},
		onSuccess: function(transport) {
			var result = transport.responseText.strip().evalJSON();
			$$('div.subMenuPublic')[0].update(result.blockedHeader);
			//$('contentAlbumPublic').update(result);
			$('totalPhotoText').update(result.totalPhotoText);
			$('pageNav1').update(result.pageNav1);
			$('pageNav2Top').update(result.pageNav2);
			$('pageNav2Bottom').update(result.pageNav2);
			//$$('div.allPer')[0].update(result.allPer);
			$('divPhotoList').update(result.photoDetailAlbPublic);
		}
	});
}

ifirave.pbGallery.checkDownloadAlbum = function() {
	new Ajax.Request(GBP_IRAVE_URL_PUBLIC + "/?act=pbajaxGalleryCheckContributor", {
		method: 'post',
		parameters: {reqContributor : true, albumId: $F('albumId')},
		onSuccess: function(transport) {
			var result = transport.responseText.strip();
			var obj = result.evalJSON();
			var isLogin = obj.isLogin;
			var isContributor = obj.isContributor;

			if(isContributor) {
				window.location = $('download_url').value;
				return;
			}
			if(isLogin) {
				popup.popItUp(null, 'Sorry! Only Contributors are allowed to download the entire album. Please contact the album owner directly to request being added as a Contributor.', null, null)
			}
			else {
				ifirave.pbGallery.pageAction = "DownloadAlbum";
				ifirave.pbGallery.pbajaxGalleryLogin('', '', '');
			}
		}
	});
}

ifirave.pbGallery.pbGalleryShareAlbumOnTwitter = function ( shareUrl ) {
	var defaultStatus = $('albumName').innerHTML;
	popup.popItUp('index.php?act=pbajaxGalleryShareOnTwitter&shareUrl=' + shareUrl + '&defaultStatus=' + defaultStatus, null, 460, 270, '');
}

ifirave.pbGallery.pbGallerySharePhotoOnTwitter = function ( shareUrl ) {
	var defaultStatus = $('caption').innerHTML;
	defaultStatus = defaultStatus.substring(1, defaultStatus.length-1);
	popup.popItUp('index.php?act=pbajaxGalleryShareOnTwitter&type=photo&shareUrl=' + shareUrl + '&defaultStatus=' + defaultStatus, null, 460, 270, '');
}

ifirave.pbGallery.updateTwitterStatus = function(url, newStatus){
	new Ajax.Request(url, {
		method: 'post',
		parameters: {newStatus: newStatus},
		onSuccess: function(transport) {
			var result = transport.responseText.strip();
			if( result != '' && result != null) {
				popup.popItUp(null, "You've successfully updated Twitter status. Please see it <a target='_blank' href='http://twitter.com/" + result + "'>here</a>.", 350,115);
			}
			else document.location.reload();
		}
	});
}

ifirave.pbGallery.checkUpdateTwitterStatus = function(action){
	$('popupLoadingIcon').show();
	$('shareA').replace('<a class="tabRight"><em class="tabLeft"><span class="tabInner">Share</span></em></a>');
	$('shareButton').className = "disableButtonPopup";

	var reqLogin = $F('reqLogin');
	var newStatus = $F('twitterStatus');
	var shareUrl = $F('shareUrl');
	newStatus += " " + shareUrl;
	var url = GBP_IRAVE_URL_PUBLIC + '/?act=' + action;

	//update twitter status khi da login tu truoc (da luu session)
	if(reqLogin == 0) {
		ifirave.pbGallery.updateTwitterStatus(url, newStatus);
		return;
	}

	var currentUrl = document.location.toString();
	var isRemember = $('twitterShareRemember').checked?1:0;

	//save status va currentUrl vao session truoc khi redirect den twitter de login
	new Ajax.Request(url, {
		method: 'post',
		parameters: {newStatus: newStatus, currentUrl: currentUrl, isRemember: isRemember},
		onSuccess: function(transport) {
			var twitterLink = transport.responseText.strip();
			if( twitterLink != "" && twitterLink.indexOf("http") != -1) {
				window.location = twitterLink;
			}
		}
	});
}

ifirave.pbGallery.updateRemainChars = function(evt) {
	var remainCharsLimit = parseInt($F('remainCharsLimit'));
	var crossEvent = (evt)? evt : event;
	var keyCode = crossEvent.keyCode;
	var typedChars = $F('twitterStatus');
	var remainChars = remainCharsLimit - (typedChars.length);
	if(remainChars > 0)
		$('remainChars').innerHTML = remainChars;
	else {
		$('twitterStatus').value = typedChars.substring(0, remainCharsLimit);
		$('remainChars').innerHTML = 0;
	}
}

ifirave.pbGallery.downloadAlbum = function(option){
	var albumAlias = $('albumAlias').value;
	var user = $('userAlbum').value;
	var cost = $('downloadType').options[$('downloadType').selectedIndex].value;
	new Ajax.Request('index.php?act=pbDownloadAlbum',{
		method: 'post',
		parameters: {albumAlias: albumAlias, creditPay: cost, creditAction: option},
		onSuccess: function(transport){
			var result = transport.responseText.strip();
			if(result.indexOf('purchase') != -1){
				window.location = IRAVE_URL_ROOT + "index.php?act=ifSettings&tab=5&page=1&albumAlias="+albumAlias+"&user="+user;
			}else if(result.indexOf('INVALID') != -1){
				//$('notice').innerHTML = "Invalid download type.";
				popup.popItUp(null, "The value you have entered is invalid!", 350,115);
			}
			else{
		    	$('contentDownload').innerHTML = result;
		    }
		}
	});
}

ifirave.pbGallery.clearTwitter = function(callbackAction, name) {
	//urlCallback to recreate twitter authorize link
	var urlCallback = GBP_IRAVE_URL_PUBLIC + '/?act=' + callbackAction;
	new Ajax.Request('index.php?act=pbajaxGalleryClearTwitterAccount', {
		method: 'post',
		parameters: {urlCallback: urlCallback, name: name},
		onSuccess: function(transport) {
			var result = transport.responseText.strip();
			if( result != "") {
				$('twitterAcount').remove();
				$('rememberContainer').show();
				//$('twitterLink').value = result;
			}
			else alert('Fail');
		}
	});
}

ifirave.pbGallery.showHTMLView = function(user, albumAlias) {
	var currentLink = window.location.toString();

	var RaveParam = "&viewType=" + const_RaveView;
	currentLink.gsub(RaveParam, '');
	//address = address.gsub("(viewType=)[^?]+", "");
	//address = address.replace("/?", "");
	var HTMLparam = "/?viewType=" + const_HTMLView;

	window.location = currentLink + HTMLparam;
}

ifirave.pbGallery.showPhotoLink = function() {
	var content = $('photoUrl_Cont').innerHTML;
	popup.popItUp(null, content, 450, 115);
}

ifirave.pbGallery.getEmbedCodeOfPhoto = function(albumId, itemId) {
	popup.popItUp('index.php?act=ajaxGalleryItemEmbedCode&itemId='+itemId+'&albumId='+albumId, null, 500, 200, '');
}
ifirave.pbGallery.switchView = function(albumId, view){
	new Ajax.Request('index.php?act=pbajaxGallerySwitchView',{
		method: 'post',
		parameters: {albumId: albumId, view: view},
		onSuccess: function(transport){
			var result = transport.responseText.strip();
			if(result.indexOf('Done') != -1){
				document.location.reload();
			}
		}
	});
}
