// Init base-level objects
var Bko = new Object();
Bko.StayAlive = new Object();
Bko.Chat = new Object();
Bko.Security = new Object();
Bko.Home = new Object();
Bko.Login = new Object();
Bko.Fb = new Object();
Bko.Register = new Object();
Bko.Welcome = new Object();
Bko.Calen = new Object();
Bko.Mobile = new Object();
Bko.PlanDetails = new Object();
Bko.PlanGroup = new Object();
Bko.NewPlan = new Object();
Bko.Gdo = new Object();
Bko.People = new Object();
Bko.Image = new Object();
Bko.Preference = new Object();
Bko.OtherLangs = new Object();
Bko.PeopleRate = new Object();
Bko.Msg = new Object();
Bko.BList = new Object();
Bko.ABook = new Object();
Bko.Denounce = new Object();
Bko.Invite = new Object();
Bko.Suggest = new Object();
Bko.ForgotPass = new Object();
Bko.Switch = new Object();
Bko.Forms = new Object();
Bko.ItemBox = new Object();
Bko.Candidate = new Object();
Bko.Roster = new Object();
Bko.PeopleSearch = new Object();
Bko.Compatibility = new Object();
Bko.PlanSelection = new Object();
Bko.KeyEvent = new Object();
Bko.CountDown = new Object();
Bko.Subscribe = new Object();
Bko.Upload = new Object();
Bko.Plan = new Object();
Bko.Mbti = new Object();

/* General functions */
Bko.debugCount = 0;
Bko.debugEnabled = false;
Bko.debug = function(text) {
	if (Bko.debugEnabled) {
		if(!$('debug'))document.body.appendChild(new Element('div',{id:'debug', style:'position: absolute; top:0; left:0; width:150px; height:350px; overflow:auto; background-color:white; border:solid 1px gray; z-index:999999;'}));
		if($('debug'))$('debug').insert({top:''+(Bko.debugCount++)+': '+text+'<br/>'});
	}
}
Bko.getAnchor = function () {
	var tmp = window.location.href;
	if (tmp.include('#')) {
		tmp = tmp.replace(/.*#/,'a');
		return tmp;
	}
	else {
		return null;
	}
}
Bko.testEmail = function(mail) {
	var emailRegex = /^\w+([\.-]?\w+)*[\.-]?@\w+([\.-]?\w+)*\.(\w{2,4}|museum|travel)$/;
	if (mail.match(emailRegex)) {
		return true;
	}
	else {
		alert("Debes introducir un email correcto");
		return false;
	}
}
Bko.findPos = function(obj) {
	var curleft = curtop = 0;
	while (obj.offsetParent && obj.style.position != 'relative') {
		curleft += obj.offsetLeft;
		curtop += obj.offsetTop;
		obj=obj.offsetParent;
	}	
	return [curleft,curtop];
}
Bko.innerSize = function() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [myWidth,myHeight];
}
Bko.getScrollXY = function() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}
Bko.setCookie = function(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
Bko.getCookie = function(c_name){
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
Bko.allocateModalPanels = function() {
    $$('div.bko-modalpanel-content').each(
    	function(d){
    		d.style.top=''+Math.floor(Math.max((Bko.innerSize()[1]-(d.offsetHeight==0?400:d.offsetHeight))/2,0))+'px';
    	}
    );
}
Event.observe(window,'resize',function(){if(window==window.top) Bko.allocateModalPanels();});
Bko.showModalPanel = function(id) {
	if ($(id)!=null){
		$(id).style.display='block';
		Bko.allocateModalPanels();
	}
}

Bko.newAlert = function(msg,color) {
	if ($('global-alerts')){
		var a = new Element('div',{'class':'alert_box_'+color+''});
		var b = new Element('div',{'class':'ui-'+color+'-corner_lt'});
		var c = new Element('div',{'class':'ui-'+color+'-corner_rt'});
		var d = new Element('div',{'class':'ui-'+color+'-corner_lb'});
		var e = new Element('div',{'class':'ui-'+color+'-corner_rb'});
		var f1 = new Element('div',{'class':'ui-close-alert', onclick:"this.parentNode.parentNode.parentNode.parentNode.parentNode.style.display='none'"});
		var f2 = new Element('div',{'class':'alert_'+color+''});
		var g = new Element('span',{'class':'alert_label'});
		a.insert(b);b.insert(c);c.insert(d);d.insert(e);e.insert(f1);e.insert(f2);f2.insert(g);g.insert(msg);
		$('global-alerts').insert(a);
	}
}
Bko.newGreenAlert = function(msg) {
	Bko.newAlert(msg,'green');
}
Bko.newOrangeAlert = function(msg) {
	Bko.newAlert(msg,'ora');
}
Bko.newRedAlert = function(msg) {
	Bko.newAlert(msg,'red');
}

Bko.requestPanel = function(panel,pub,params) {
	Seam.Remoting.displayLoadingMessage();
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax'+(pub?'-pub':'')+'/'+panel+'.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: params,
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}
Bko.removePanel = function(panel) {
	if ($(panel)!=null)
		$(panel).remove();
}
Bko.hidePanel = function(panel) {
	if ($(panel)!=null)
		$(panel).style.display='none';	
}
Bko.StayAlive.interval=1740;
Bko.StayAlive.sa = function() {
	new PeriodicalExecuter(
		function(pe) {
			var myAjax = new Ajax.Request (
					'/ajax-pub/sa.bookioo',
					{
						method: 'get',
						evalScripts: true
					}
				);
		}
		, Bko.StayAlive.interval
	);
	
}

Bko.Chat.createSession = function(user) {
	var myAjax = new Ajax.Request (
		'/chat/initchat.php',
		{
			method:'post',
			parameters:'n='+user,
			onComplete: function(response) {
				if (response.responseText == '1') {
					Bko.Chat.connect(true);
				}
				else {
					Bko.Chat.connect(false);
				}
			}
		}
	);
}
		
Bko.Chat.connect = function(success) {
	if (!success) {
		$$('div.online_over').each(function(d) { d.remove(); });
	}
	Seam.Component.getInstance("calendarInfo").connectToChat(success,function(resp) {});
}

Bko.Chat.allConnected = function() {
	var myAjax = new Ajax.Updater (
		'chatlist',
		'/ajax/chat-list.bookioo',
		{
			evalScripts: true,
			method: 'get'
		}
	);	
}

/* Security functions */
Bko.Security.requestValidationPanel = function() {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/activation-validation-panel.bookioo',
		{
			evalScripts: true,
			insertion: 'bottom',
			method: 'get'
		}
	);
}

/* Home */
Bko.Home.hCarousel = null;
Bko.Home.hCarouselInAction = false;
Bko.Home.buttonInAction = false;
Bko.Home.nextIndex = 0;
Bko.Home.interval = 8000;
Bko.Home.intervalID = null;
Bko.Home.notProcessed = null;
Bko.Home.lastEffect = null;

Bko.Home.divsToFade = new Array('home_text1', 'home_text2', 'home_text3', 'home_text4', 'home_text5', 'home_text6');

Bko.Home.run = function () {
	Bko.Home.hCarousel = new UI.Carousel("horizontal_carousel");
	$('previous_button').observe("click", function(event){
		var index = Bko.Home.hCarousel.currentIndex() - 1;
		if (!(index < 0) && !Bko.Home.buttonInAction) {
			Bko.Home.buttonInAction = true;
			clearInterval(Bko.Home.intervalID);
			Bko.Home.showStuff(index);
		}
	});
	$('next_button').observe("click", function(event){
		var index = Bko.Home.hCarousel.currentIndex() + 1;
		if (!(index >= 6) && !Bko.Home.buttonInAction) {
			Bko.Home.buttonInAction = true;
			clearInterval(Bko.Home.intervalID);
			Bko.Home.showStuff(index);
		}
	});
	Bko.Home.hCarousel.observe("scroll:started", function(event){
		Bko.Home.hCarouselInAction = true;
		Bko.Home.hideStuff();
	});
	Bko.Home.hCarousel.observe("scroll:ended", function(event){
		var index = Bko.Home.hCarousel.currentIndex();
		Bko.Home.lastEffect = new Effect.Appear(Bko.Home.divsToFade[index], { duration:0.3, from:0.0, to:1.0 });
		Bko.Home.hCarouselInAction = false;
		Bko.Home.buttonInAction = false;
		
		if (Bko.Home.notProcessed!=null) {
			Bko.Home.goToManually(Bko.Home.notProcessed);
			Bko.Home.notProcessed=null;
		}
	});
	Bko.Home.initAuto();
}
Bko.Home.initAuto = function () {
	Bko.Home.intervalID = setInterval("Bko.Home.next()",Bko.Home.interval);
}
Bko.Home.next = function () {
	if (!Bko.Home.hCarouselInAction) {
		var index = (Bko.Home.hCarousel.currentIndex() + 1) % 6
		Bko.Home.showStuff(index);
		Bko.Home.show(index);
	}
}
Bko.Home.goToManually = function (index) {
	if ($('home-summary').style.display=='none'){
		$('home-summary').style.display='block';
		window.scroll(0,350);
		Bko.Home.run();
	}
	if (!Bko.Home.hCarouselInAction) {
		clearInterval(Bko.Home.intervalID);
		Bko.Home.show(index);
		Bko.Home.showStuff(index);
	}
	else {
		Bko.Home.notProcessed=index;
	}
}
Bko.Home.hideStuff = function () {
	// Change texts
	if (Bko.Home.lastEffect != null) Bko.Home.lastEffect.cancel();
	$$('div.fade_box').each(function(d) { d.style.display = 'none'});

}
Bko.Home.showStuff = function (index) {
	// Change buttons
	$$('div.home_option_sel_text2').each(function(d) { d.className = 'home_option_text2'; });
	$$('div.link_option_home_sel').each(function(d) { d.className = 'link_option_home'; });

	$$('div.home_option_text2')[index].className = 'home_option_sel_text2';
	$$('div.link_option_home')[index].className = 'link_option_home_sel';
}
Bko.Home.show = function (index) {
	if (!Bko.Home.hCarouselInAction) {
		// Change slide
		Bko.Home.hCarousel.scrollTo(index);
	}
}

Bko.Home.morePlans = function () {
	Seam.Remoting.displayLoadingMessage();
	var myAjax = new Ajax.Updater (
		'home-plans',
		'/ajax-pub/home-plans.bookioo',
		{ method: 'get', onComplete: Seam.Remoting.hideLoadingMessage }
	);
}

/* Login */
Bko.Login.doLogin = function (user, pass) {
	Seam.Component.getInstance("authenticator").remoteLogin(user, pass, Bko.Login.callBack);
}

Bko.Login.callBack = function (loggedIn) {
	if (loggedIn) {
		top.location = "secure/welcome.bookioo";
	}
	else {
		$('loginTopPass').value = '';
		$('loginFail').style.display = 'block';
	}
}

/* Facebook Connect */
Bko.Fb.login = function (cid,jump2reg) {
	var i=0;
	var loc='/fb/fb-login.bookioo';
	var qstr=null;
	if(cid!=null||jump2reg!=null&&jump2reg){
		qstr = '?';
		qstr+=(cid!=null?'cid='+cid:'');
		if (qstr!='?') {
			qstr+='&';
		}
		qstr+=(jump2reg!=null&&jump2reg?'jump2reg=true':'');
	}
	document.location='/fb/fb-login.bookioo'+(qstr!=null?qstr:'');
}
Bko.Fb.logout = function (sex,chat) {
	if (chat) {
		var myAjax = new Ajax.Request (
			'/chat/closechat.php',
			{
				method:'get',
				onComplete: function(response) {
					var loc='/logout.bookioo';
					document.location=loc;					
				}
			}
		);
	}
	else {
		var loc='/logout.bookioo';
		document.location=loc;
	}
	return true;
}
Bko.Fb.appLogin = function () {
	FB.login(function(response){
		if (response.session) {
			Event.fire('fb-root', 'bko-fb:logged-in');
		}
	}, {perms:'publish_stream'});
}
/* Register actions */
Bko.Register.resendMail = function () {
	Seam.Component.getInstance("registerAction").sendActivationEmail(Bko.Register.resendMailCallback);
}
Bko.Register.resendMailCallback = function (result) {
	alert(result);
}
Bko.Register.checkNick = function (input,cid) {
	Seam.Remoting.getContext().setConversationId(cid);
	Seam.Component.getInstance("registerAction").validateNick($F(input),function(result){Bko.Register.checkNickCb(input,result);});
}
Bko.Register.checkNickCb = function (input, result) {
	Element.extend(Element.extend($(input).parentNode).parentNode).removeClassName('errors');
	var spans = Element.extend($(input).parentNode.getElementsByTagName('span'));
	for( i=0; i< spans.length; i++) spans[i].remove();
	if(result!=null){
		$(input).parentNode.parentNode.addClassName('errors');
		var sp = new Element('span',{'class':'error'});
		sp.insert(result);
		$(input).parentNode.insert(sp);
	}
}

/* Calendar functions */
Bko.Calen.nextMonth = function() {
	var myAjax = new Ajax.Updater (
		'calendar-holder',
		'/ajax/calendar-next-month.bookioo',
		{
			evalScripts: true,
			method: 'get'
		}
	);
}

Bko.Calen.previousMonth = function() {
	var myAjax = new Ajax.Updater (
		'calendar-holder',
		'/ajax/calendar-previous-month.bookioo',
		{
			evalScripts: true,
			method: 'get'
		}
	);
}

Bko.Calen.findPos = function(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent && !obj.style.position == 'relative');
	}
	return [curleft,curtop];
}
Bko.Calen.showPopup = function(day, inThePast, linkObj) {
	$$('div.calen-popup').each(function(d) { d.style.display = 'none'});
	
	var offset = Bko.Calen.findPos(linkObj);
	var popup = $('calen-popup-'+day);
	if (popup != null)
		popup.show();
	else {
		// Create popup
		popup = new Element('div', {'id':'calen-popup-'+day, 'class':'calen-popup'});
		popup.style.left = ''+(offset[0]+17)+'px';
		popup.style.top = ''+(offset[1]-14)+'px';
		var _popupIn = new Element('div');
		_popupIn.setAttribute('class', 'calen-popup-in');
		_popupIn.innerHTML = Seam.Remoting.loadingMessage;
		popup.appendChild(_popupIn);
		$('calendar-holder').appendChild(popup);
		
		// Request interior
		var myAjax = new Ajax.Updater (
			'calen-popup-'+day,
			'/ajax/calendar-day-popup.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: 'day='+day+'&past='+inThePast
			}
		);
	}
}
Bko.Calen.getMorePlans = function(activeTab) {
	var myAjax = new Ajax.Updater (
		'more-plans',
		'/ajax/more-plans-result.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'tab='+activeTab
		}
	);
	return false;
}

/* Mobile functions */
Bko.Mobile.showVerificationPanel = function () {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/mobile-activation-panel.bookioo',
		{
			evalScripts: true,
			insertion: 'bottom',
			method: 'get'
		}
	);
}

Bko.Mobile.verifyCode = function (code) {
	Seam.Component.getInstance("mobileActivationAction").verifyActivationCode(code, Bko.Mobile.verifyCodeCallback);
}

Bko.Mobile.verifyCodeCallback = function (result) {
	if (result == true) {
		if ($('mobileAlert') != null) {
			$('mobileAlert').remove();
		}
		Bko.Mobile.hideVerificationPanel();
		alert ("Codigo aceptado");
	}
	else {
		alert("Codigo erroneo");
	}
	
}

Bko.Mobile.resendCode = function () {
	Seam.Component.getInstance("mobileActivationAction").sendMobileActivationCode(Bko.Mobile.resendCodeCallback);
}

Bko.Mobile.resendCodeCallback = function (result) {
	alert(result);
}

Bko.Mobile.hideVerificationPanel = function () {
	$('mobile_activation_panel').remove();
}

/* Plan details page */

Bko.PlanDetails.favoriteImage = "<img src='static/img/favorite-star.gif'/>";

// carousel 
Bko.PlanDetails.candidatesCarousel = null;

Bko.PlanDetails.run = function () {
	if ($('candidates_carousel'))
		Bko.People.candidatesCarousel = new UI.Carousel("candidates_carousel");
}

Bko.PlanDetails.selectUser = function (newUser, conversationId) {
	var tmp=(newUser==0)?'':newUser;
	var myAjax = new Ajax.Updater (
		'messages_container',
		'/ajax/plan-details-messages.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+tmp+'&cid='+conversationId,
			onSuccess: Bko.PlanDetails.changeActiveUser(newUser)
		}
	);

}

Bko.PlanDetails.changeActiveUser = function (newUser) {
	$$('div.candidate_white_iz').each(function(d) { d.className = 'candidate_iz'; });
	$$('div.candidate_white_ce').each(function(d) { d.className = 'candidate_ce'; });
	$$('div.candidate_white_de').each(function(d) { d.className = 'candidate_de'; });
	
	$('candidate_iz'+newUser).className = 'candidate_white_iz';
	$('candidate_ce'+newUser).className = 'candidate_white_ce';
	$('candidate_de'+newUser).className = 'candidate_white_de';
}

Bko.PlanDetails.displayCancelPanel = function (conversationId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/cancel-plan-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId
		}
	);
}

Bko.PlanDetails.hideCancelPanel = function () {
	$('cancel_plan_panel').remove();
}

Bko.PlanDetails.displayLeavePanel = function (conversationId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/leave-plan-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId
		}
	);
}

Bko.PlanDetails.hideLeavePanel = function () {
	$('leave_plan_panel').remove();
}

/*
Bko.PlanDetails.myFavorite = function (conversationId, idUser) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("managePlanAction").myFavorite(idUser, Bko.PlanDetails.myFavoriteCallBack);
}
Bko.PlanDetails.myFavoriteCallBack = function (response) {
	alert (response);
	var respObj = response.evalJSON(true);
	if (respObj.klass == 'com.bookioo.core.exceptions.SerializableJSONException') {
		$('optimistic-lock-panel').style.display = 'block';
		window.scroll(0,0);
		return;
	}
	if (respObj) {
		var starDivs = $$('div.box_favorite_star');
		starDivs.each(function(s) {
			s.innerHTML = "";
		});
		$('favorite_star_id'+respObj).innerHTML = Bko.PlanDetails.favoriteImage;
	}
	else {
		alert("Error");
	}
}
*/
Bko.PlanDetails.displayDiscardPanel = function (conversationId, userId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/discard-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId+'&u='+userId
		}
	);
}
Bko.PlanDetails.hideDiscardPanel = function () {
	$('discard_panel').remove();
}
Bko.PlanDetails.discard = function (conversationId, idUser, discardMessage) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("managePlanAction").discard(idUser, discardMessage, Bko.PlanDetails.discardCallBack);
}
Bko.PlanDetails.discardCallBack = function (idUser) {
	if (idUser) {
		alert ("ok");
		Bko.PlanDetails.hideDiscardPanel();
	}
	else {
		alert("Error");
	}
}

Bko.PlanDetails.displayFinalDecisionPanel = function (conversationId, userId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/final-decision-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId+'&u='+userId
		}
	);
}

Bko.PlanDetails.hideFinalDecisionPanel = function (conversationId, userId) {
	$('finalDecisionPanel').remove();
}

Bko.PlanGroup.getMessages = function(usr, linkObj, conversationId, inverse, x, y, altContainer) {
	$$('div.messages-popup').each(function(d) { d.remove(); });
	
	var offset = Bko.findPos(linkObj);
	var popup = $('messages-'+usr);
	if (popup != null)
		popup.show();
	else {
		// Create popup
		popup = new Element('div', {'id':'messages-'+usr, 'class':'messages-popup'});
		popup.style.left = ''+(offset[0]+(x==null?97:x))+'px';
		popup.style.top = ''+(offset[1]+(y==null?-124:y))+'px';
		var _popupIn = new Element('div');
		_popupIn.setAttribute('class', 'messages-popup-in');
		_popupIn.innerHTML = Seam.Remoting.loadingMessage;
		popup.appendChild(_popupIn);
		$(altContainer!=null?altContainer:'conversacion').appendChild(popup);
		
		// Request interior
		var myAjax = new Ajax.Updater (
			'messages-'+usr,
			'/ajax/plan-details-messages-popup.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: 'u='+usr+'&inv='+inverse+'&cid='+conversationId
			}
		);
	}
}


/* New plan */
Bko.NewPlan.usersInPlan = false;
Bko.NewPlan.addCandidateToList = function(user, conversationId) {
	var myAjax = new Ajax.Updater (
		'users_in_plan_list',
		'/ajax/add-candidate-to-plan.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+user+'&cid='+conversationId+'&rand='+Math.random(),
			insertion: 'top',
			onComplete: Bko.NewPlan.changeUserResultStyle(user)
		}
	);
}
Bko.NewPlan.changeUserResultStyle = function(idUser) {
	$('user_box_id'+idUser).className = 'box_result_people_selected';
	$('select_button_for'+idUser).style.display = 'none';
	if ($('selected-empty-text'))
		$('selected-empty-text').style.display = 'none';
}

Bko.NewPlan.remCandidateFromList = function(user,conversationId) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("planAction").removeUserFromPlan(user, Bko.NewPlan.remCandidateFromListCallBack);
}

Bko.NewPlan.remCandidateFromListCallBack = function(idUser) {
	$('user_selected_id'+idUser).remove();
	var tmp = $('user_box_id'+idUser);
	if (tmp != null) {
		tmp.className = 'box_result_people';
		$('select_button_for'+idUser).style.display = 'block';
	}
}

Bko.NewPlan.attachToPlan = function (idPlan) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/attach-to-plan-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'p='+idPlan
		}
	);
}

Bko.NewPlan.hideAttachToPlanPanel = function(conversationId) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("managePlanAction").endConversationRemotely();
	$('attach-to-plan-panel').remove();
}

Bko.NewPlan.dateFormat = "dd-MM-yyyy"
Bko.NewPlan.propDateMsg = "Tienes que especificar una fecha";
Bko.NewPlan.propHourMsg = "Si especificas una fecha tienes que elegir una hora";

Bko.NewPlan.proposedDateValid = function(fldPrefix) {
	var dateFld = fldPrefix + ':date';
	var hourFld = fldPrefix + ':hour';
//	if (!($F(dateFld)==null||$F(dateFld).strip()=='')) {
//		alert(Bko.NewPlan.propDateMsg);
//		return false;
//	}
	if (!($F(dateFld)==null||$F(dateFld).strip()=='')&&($F(hourFld)==null||$F(hourFld).strip()==''||$F(hourFld)=='org.jboss.seam.ui.NoSelectionConverter.noSelectionValue')) {
		alert(Bko.NewPlan.propHourMsg);
		return false;
	}
	return true;
}

Bko.NewPlan.switchWithDate = function() {
	var checked = $F('planform:withoutDate');
	var clName = $('new-plan-date').className;
	if (checked) {
		$('planform:date:planDate').disabled = true;
		$('planform:time:hour').disabled = true;
		$('planform:time:minute').disabled = true;

		$('new-plan-date').className = clName + ' fog';
		$('planform:date:planDate').value = '';
	}
	else {
		$('planform:date:planDate').disabled = false;
		$('planform:time:hour').disabled = false;
		$('planform:time:minute').disabled = false;

		$('new-plan-date').className = clName.gsub(' fog','');
	}
}

/* GdO */
Bko.Gdo.requestActivityPanel = function(idActivity) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax-pub/activity-panel.bookioo',
		{
			method: 'get',
			insertion: 'bottom',
			parameters: 'a='+idActivity
		}
	);
} 

Bko.Gdo.hideActivityPanel = function() {
	$('activity-panel').remove();
}

/* Friends carousel */
Bko.People.friendsCarousel = null;

Bko.People.run = function () {
	Bko.People.friendsCarousel = new UI.Carousel("friends_carousel", {direction: "vertical"});
	var selected = $$('div.box_friend_selected');
	if (selected != null && selected.length > 0) {
		var allFriends = $$('div.box_friend');
		for (var i=0; i<allFriends.length; i++) {
			if (selected[0].id == allFriends[i].id) {
				if (i>=6) {
					Bko.People.friendsCarousel.scrollTo(Math.floor(i/3)-1);
				}
				return;
			}
		}
	}
}

/* People */
Bko.People.requestPeoplePanel = function(idUser,idPlan, cid) {
	Seam.Remoting.displayLoadingMessage();
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/people-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+idUser+(idPlan!=null?'&p='+idPlan:''),
			insertion: 'bottom',
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}

Bko.People.requestPeopleCidPanel = function(cid, idUser) {
	Seam.Remoting.displayLoadingMessage();
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/people-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'cid='+cid+'&u='+idUser,
			insertion: 'bottom',
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}


Bko.OtherLangs.show = function(){
	$('otherLangs').style.display = 'block';
	$('showLangs').style.display = 'none';
} 

/*
 * People search
 */
Bko.PeopleSearch.changeTab = function(tab){
	$$('div.search-tab').each(function(e){e.style.display = 'none';});	
	$('search-'+tab).style.display = 'block';
	$('activeTab').value = tab;
	
	['l','c','r'].each(
		function(l){$$('div.box_profile_tabs_v2 div.menu_sel_'+l).each(function(e){e.className='menu_'+l})});
	
	['l','c','r'].each(
		function(l){$$('#tab-'+tab+' div.menu_'+l).each(function(e){e.className='menu_sel_'+l;});});
}

/*
 *  Hidden && Show 
 */
Bko.Preference.menuphystatus = "block";
Bko.Preference.menuphy = function(){
	if(Bko.Preference.menuphystatus=='block'){
		Bko.Preference.menuphystatus = 'none';
		$('menu_phy').style.display = Bko.Preference.menuphystatus;
	}else{
		Bko.Preference.menuphystatus = 'block';
		$('menu_phy').style.display = Bko.Preference.menuphystatus;		
	}
}

Bko.Preference.menuchrstatus = "none";
Bko.Preference.menuchr = function(){
	if(Bko.Preference.menuchrstatus=='block'){
		Bko.Preference.menuchrstatus = 'none';
		$('menu_chr').style.display = Bko.Preference.menuchrstatus;
	}else{
		Bko.Preference.menuchrstatus = 'block';
		$('menu_chr').style.display = Bko.Preference.menuchrstatus;		
	}
}

Bko.Preference.menusocstatus = "none";
Bko.Preference.menusoc = function(){
	if(Bko.Preference.menusocstatus=='block'){
		Bko.Preference.menusocstatus = 'none';
		$('menu_soc').style.display = Bko.Preference.menusocstatus;
	}else{
		Bko.Preference.menusocstatus = 'block';
		$('menu_soc').style.display = Bko.Preference.menusocstatus;		
	}
}

/* Image Crop */
Bko.Image.crop = null;
Bko.Image.coord = null;
// setup the callback function
Bko.Image.endCrop = function (coords, dimensions) {
	Bko.Image.coord = 'top='+coords.y1+'&left='+coords.x1+'&height='+dimensions.height+'&width='+dimensions.width;
}
Bko.Image.cropRefresh = function (imgid) {
	var pc = $('preview_photo'); 
	if (pc != null) {
		var myAjax = new Ajax.Updater (
			'preview_photo',
			'/ajax/image-crop-refresh.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: 'imgid='+imgid+'&'+Bko.Image.coord,
				onComplete: function(){
					Bko.removePanel('crop-panel');
					Bko.Image.crop.remove();
				}
			}
		);
	}
}
Bko.Image.requestGalleryPanel = function(idUser, conversationId) {
	var pc = $('gallery-panel');
	if(pc==null){
		var myAjax = new Ajax.Updater (
			'tail_content',
			'/ajax/image-gallery-panel.bookioo',
			{
				evalScripts: true,
				method: 'get',
				insertion: 'bottom',
				parameters: 'cid='+conversationId+'&u='+idUser
			}
		);
	}else {
		pc.style.display = 'block';
	}
}

Bko.Image.selectImage = function(imageId){
	var pc = $('preview_photo'); 
	if (pc != null) {
		var myAjax = new Ajax.Updater (
			'preview_photo',
			'/ajax/image-profile-refresh.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: (imageId==null?null:'imgid='+imageId),
				onComplete: (imageId==null?null:Bko.Image.hideGalleryPanel)
			}
		);
	}
}

Bko.Image.hideGalleryPanel = function() {
	$('gallery-panel').style.display = 'none';
}

Bko.Image.albumThumbs = function(album,full) {
	if (album!=null){
		var myAjax = new Ajax.Updater (
			'album-content-'+album,
			'/ajax/album-thumbs'+(full?'-full':'')+'.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: 'oid='+album
			}
		);
	}
}
Bko.Image.showTitlePanel = function(id, title) {
	$('imageId').value = id;
	$('newtitle').value = title;
	$('photo-title-panel').style.display='block';
}
Bko.Image.changeTitle = function(id, title) {
	Seam.Component.getInstance("albumAction").changePhotoTitle(
		id, 
		title,
		function(resp){
			$('photo-title-panel').hide();
			if($('thumb-'+id))$('thumb-'+id).title=title;
		},
		function(ex) {
			ex.message.evalScripts();
		}
	);
}
Bko.Image.deletePhoto = function(id) {
	Seam.Component.getInstance("albumAction").deletePhoto(
		id,
		function(resp) {
			if($('thumb-'+id))$('thumb-'+id).remove();
		},
		function(ex) {
			ex.message.evalScripts();
		}
	);
}
Bko.People.hidePeoplePanel = function() {
	$('people-panel').remove();
	Event.stopObserving(window, 'keypress');
}

/* Item Box status */
Bko.ItemBox.status = false;
Bko.ItemBox.iseg = 0; 
Bko.ItemBox.eseg = 0; 
Bko.ItemBox.changestatus = function(){
	fechaHora = new Date();
	if(Bko.ItemBox.iseg==0){
		Bko.ItemBox.iseg = (fechaHora.getMinutes()*60)+fechaHora.getSeconds();
		Bko.ItemBox.eseg = (fechaHora.getMinutes()*60)+fechaHora.getSeconds();
	}else{
		Bko.ItemBox.eseg = (fechaHora.getMinutes()*60)+fechaHora.getSeconds();
	}
	if((Bko.ItemBox.eseg-Bko.ItemBox.iseg) > 10){
		if(Bko.ItemBox.status==true){
			Bko.ItemBox.status=false;
		}else{
			Bko.ItemBox.status=true;
		}
	Bko.ItemBox.iseg = Bko.ItemBox.eseg;	
	}
}

/* People rating */
Bko.PeopleRate.requestPanel = function (userId, planId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/people-rate-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'uto='+userId+(planId!=null?'&p='+planId:''),
			insertion: 'bottom'
		}
	);	
}

Bko.PeopleRate.rate = function (conversationId, stars, opinion) {
	var myAjax = new Ajax.Updater (
		'last_rates',
		'/ajax/people-rate-response.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'cid='+conversationId+'&stars='+stars+'&opinion='+opinion,
			onComplete: Bko.PeopleRate.hidePanel(),
			insertion: 'top'
		}
	);
}
Bko.PeopleRate.hidePanel = function (conversationId) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("rateAction").endConversationRemotely();
	$('people-rate-panel').remove();
	Event.stopObserving(window, 'keypress');
}

/* Messages */
Bko.Msg.showForm = function () {
	$$('#msg-div div.alert_box_green').each(function(div) {div.remove();});
	$$('#msg-div div.alert_box_ora').each(function(div) {div.remove();});
	$$('#msg-div div.alert_box_red').each(function(div) {div.remove();});
	$('msg-form').style.display = 'block';
	$('msg-link').style.display = 'none';
	Bko.allocateModalPanels();
}
/*
Bko.Msg.requestPanel = function (toId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/message-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+toId,
			insertion: 'bottom'
		}
	);
}
*/
Bko.Msg.send = function (frm) { 
	var fParams = Element.extend(frm).serialize();
	var myAjax = new Ajax.Updater (
		'msg-div',
		'/ajax/message-result.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: fParams,
			insertion: 'bottom',
			onComplete: Bko.allocateModalPanels
		}
	);
	return false;
}

/* Black list */
Bko.BList.requestPanel = function (blacklistedId) {

	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/blacklistpanel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+blacklistedId,
			insertion: 'bottom'
		}
	);
}

Bko.BList.hidePanel = function () {
	$('blackListPanel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.BList.doBlacklist = function (blacklistedId) {
	Seam.Component.getInstance("blacklistAction").addToBlacklist(blacklistedId, Bko.BList.callBack);
}

Bko.BList.callBack = function (blacklistedId) {
	Bko.BList.hidePanel();
	$('box_profile_'+blacklistedId).className = 'box_profile_locked';
	$('lock_button').style.display = 'none';
	$('unlock_button').style.display = 'block';	
}

Bko.BList.delFromBlacklist = function (blacklistedId) {
	Seam.Component.getInstance("blacklistAction").delFromBlacklist(blacklistedId, Bko.BList.delCallBack);
}

Bko.BList.delCallBack = function (blacklistedId) {
	$('box_profile_'+blacklistedId).className = '';
	$('lock_button').style.display = 'block';
	$('unlock_button').style.display = 'none';
}
/* Plan blacklist */
Bko.BList.blacklistPlan = function(id) {
	Seam.Component.getInstance("blacklistPlanAction").addToBlacklist(id, 
		function(resp){ 
			$('plan'+id).remove();
			Bko.newGreenAlert(resp);
		},
		function(ex){ex.message.evalScripts();}
	);
}
/* Address Book */
Bko.ABook.requestPanel = function (deletedId, conversationId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/deletecontactpanel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+deletedId+'&cid='+conversationId,
			insertion: 'bottom'
		}
	);
}

Bko.ABook.hidePanel = function () {
	$('deleteFromABookPanel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.ABook.requestProf = function (contactId,container) {
	var pcid=container==null?'prof_container':container;
	var pc = $(pcid); 
	if (pc != null) {
		var myAjax = new Ajax.Updater (
			pcid,
			'/ajax/profile-full.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: 'u='+contactId,
				onComplete: function() {
					if ($('prof-scroll'))
						$('prof-scroll').scrollTop = 130;
				}
			}
		);
		pc.style.display = 'block';
	}
}

/* Compatibility */
Bko.Compatibility.requestPref = function (contactId,container) {
	var pcid=container==null?'prof_container':container;
	var pc = $(pcid); 
	if (pc != null) {
		var myAjax = new Ajax.Updater (
			pcid,
			'/ajax/similar-compatibility.bookioo',
			{
				evalScripts: true,
				method: 'get',
				parameters: 'u='+contactId,
				onComplete: function() {
					if ($('prof-scroll'))
						$('prof-scroll').scrollTop = 130;
				}
			}
		);
		pc.style.display = 'block';
	}
}

/* Denounce */
Bko.Denounce.requestPanel = function (uid,pid,beid,albumid) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/denouncepanel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'u='+uid +(pid!=null?'&p='+pid:'') +(beid!=null?'&be='+beid:'') +(albumid!=null?'&album='+albumid:'')
		}
	);
}

Bko.Denounce.hidePanel = function () {
	$('denouncePanel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.Denounce.doDenounce = function (description, uid, pid, beid, albumid) {
	Seam.Component.getInstance("denounceAction").reportDenounce(description, uid, pid, beid, albumid, Bko.Denounce.callBack);
}

Bko.Denounce.callBack = function (denouncedId) {
	var myAjax = new Ajax.Updater (
		'alerts_container',
		'/ajax/denounce-alert.bookioo',
		{
			evalScripts: true,
			method: 'get',
			onSuccess: function(){window.scroll(0,0);}
		}
	);

	Bko.Denounce.hidePanel();
	
}

/* Invite */
Bko.Invite.swapProvider = function(id,name) {
	document.getElementById('provider').value=id;
	document.getElementById('provider-name').innerHTML=name;
	document.getElementById('credentials-form').style.display='block';
	var uMail = '#{user.email}';
	var pattern = ('@'+name+'.').toLowerCase();
	if (uMail.indexOf(pattern) >= 0) {
		document.getElementById('extCredentials:emailDec:extEmail').value = uMail;
	}
	else {
		document.getElementById('extCredentials:emailDec:extEmail').value = '';
	}
	var f=document.getElementById('extCredentials:emailDec:extEmail');
	if(f.value=='')f.focus();
	else document.getElementById('extCredentials:passDec:extPassword').focus();
}
Bko.Invite.selectAll = function () {
	var jsfForm = document.getElementsByTagName("input");
	for( i=0; i< jsfForm.length; i++){
		if( jsfForm[i].type == 'checkbox' ){
			jsfForm[i].checked = true;
		}
	}
}
Bko.Invite.deleteSelection = function () {
	var jsfForm = document.getElementsByTagName("input");
	for( i=0; i< jsfForm.length; i++){
		if( jsfForm[i].type == 'checkbox' ){
			jsfForm[i].checked = false;
		}
	}
}

Bko.Invite.sendRememberInvitation = function (idUser, idUserInvited, msg) {
	Seam.Component.getInstance("inviteAction").sendRememberInvitation(idUser, idUserInvited, msg, Bko.Invite.sendRememberInvitationCallback);
}

Bko.Invite.sendRememberInvitationCallback = function (result) {
	$('insist-invite-div' + result).style.display = 'none';
	$('invitation-remind-sent' + result).style.display = 'block';
}

/* Suggest */
Bko.Suggest.requestPanel = function () {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax-pub/suggestpanel.bookioo',
		{
			method: 'get',
			evalScripts: true,
			insertion: 'bottom'
		}
	);
}

Bko.Suggest.hidePanel = function () {
	$('suggestPanel').remove();
}

Bko.Suggest.category = function (cat) {
	['l','c','r'].each(
		function(l){$$('div#suggest-tabs div.menu_sel_'+l).each(function(e){e.className='menu_'+l})});
	['l','c','r'].each(
		function(l){$$('#sug-tab-'+cat+' div.menu_'+l).each(function(e){e.className='menu_sel_'+l;});});

	$$('.suggest_cat').each(function(e){e.style.display='none';});
	$('sug-category-'+cat).style.display='block';
}
Bko.Suggest.rate = function (rate) {
	$('sug-rate').value=rate;
	$$('div#suggest-rate div.icon_notext24').each(function(e){e.addClassName('fog');});
	$('sug-rate-'+rate).removeClassName('fog');
}
Bko.Suggest.doSuggest = function (sug, msg) {
	var email = sug['suggest-email'];
	var text = sug['suggest-body'];
	var cat = sug['sug-category'];
	var rate = sug['sug-rate'];
	Seam.Component.getInstance("suggestAction").suggest(
			email, text, cat, rate, 
			function() {
				Bko.newGreenAlert(msg);
				Bko.Suggest.hidePanel();
			}
	);
}

/* Forgot password */
Bko.ForgotPass.requestPanel = function () {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax-pub/forgotpasspanel.bookioo',
		{
			method: 'get',
			evalScripts: true,
			insertion: 'bottom'
		}
	);
}
Bko.ForgotPass.hidePanel = function () {
	$('forgotPassPanel').remove();
}
Bko.ForgotPass.remind = function (email) {
	Seam.Component.getInstance("authenticator").retrievePassword(email, Bko.ForgotPass.callBack);
}
Bko.ForgotPass.callBack = function () {
	Bko.ForgotPass.hidePanel();
}

/* Div Switcher */
//here you place the ids of every element you want.
Bko.Switch.ids=new Array('a1','a2', 'a3','a4', 'a5','a6', 'a7','a8','a9','a10', 'a11','a12', 'a13','a14', 'a15');

Bko.Switch.addItems = function (items) {
	Bko.Switch.ids = items;
}

Bko.Switch.switchid = function (id){
	if (id != null) {	
		Bko.Switch.hideallids();
		Bko.Switch.showdiv(id);
		return false; // don't like scroll
	}
}

Bko.Switch.hideallids = function (){
    //loop through the array and hide each element by id
    for (var i=0;i<Bko.Switch.ids.length;i++){
        Bko.Switch.hidediv(Bko.Switch.ids[i]);
    }		  
}

Bko.Switch.hidediv = function (id) {
    //safe function to hide an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'none';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'none';
        }
        else { // IE 4
            document.all.id.style.display = 'none';
        }
    }
}

Bko.Switch.showdiv = function (id) {
    //safe function to show an element with a specified id
          
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'block';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'block';
        }
        else { // IE 4
            document.all.id.style.display = 'block';
        }
    }
}

/* Functions for helping form editting */

Bko.Forms.tagClicked = function (egValue, field, tag) {
	if (field.value == null || field.value === '' || field.value == egValue) {
		field.value = tag;
	}
	else {
		field.value += ' ' + tag;
	}
}

Bko.Forms.profileModified = false;
Bko.Forms.profileLeaveMsg = "You have modified your profile. If you leave this page without saving it, you'll loose your changes.";
Bko.Forms.profileLeaveMsg2 = "\n\nPress Accept to continue, or Cancel to stay in the current page";

Bko.Forms.profileChanged = function() {
	Bko.Forms.profileModified = true;
}
Bko.Forms.profileNotChanged = function() {
	Bko.Forms.profileModified = false;
}

Bko.Forms.profileAlert = function (event) {
	if (Bko.Forms.profileModified) {
		event.returnValue = Bko.Forms.profileLeaveMsg;
	}
}

/* Override of SEAM methods */

Seam.Remoting.loadingMsgDiv = null;
Seam.Remoting.loadingMessage = "<div class='ajax_wait'></div>";
Seam.Remoting.displayLoadingMessage = function()
{
  if (!Seam.Remoting.loadingMsgDiv)
  {
    Seam.Remoting.loadingMsgDiv = document.createElement('div');
    var msgDiv = Seam.Remoting.loadingMsgDiv;
    msgDiv.setAttribute('id', 'loadingMsg');

    msgDiv.style.position = "fixed";
    msgDiv.style.top = "0px";
    msgDiv.style.right = "0px";
    msgDiv.style.border = "none";
    msgDiv.innerHTML = Seam.Remoting.loadingMessage;

    document.body.appendChild(msgDiv);

  }
  else
  {
    Seam.Remoting.loadingMsgDiv.innerHTML = Seam.Remoting.loadingMessage;
    Seam.Remoting.loadingMsgDiv.style.visibility = 'visible';
  }
    
}


/* Add Candidate to Plan */
Bko.Candidate.addCandidateToList = function(user, conversationId) {
	var myAjax = new Ajax.Updater (
		'users_in_plan_list',
		'/ajax/add-candidate-to-old-plan.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+user+'&cid='+conversationId+'&rand='+Math.random(),
			insertion: 'top',
			onComplete: Bko.NewPlan.changeUserResultStyle(user)
		}
	);
}

Bko.Candidate.remCandidateFromList = function(user,conversationId) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("managePlanAction").removeUserFromPlan(user, Bko.Candidate.remCandidateFromListCallBack);
}

Bko.Candidate.remCandidateFromListCallBack = function(idUser) {
	$('user_selected_id'+idUser).remove();
	var tmp = $('user_box_id'+idUser);
	if (tmp != null) {
		tmp.className = 'box_result_people';
		$('select_button_for'+idUser).style.display = 'block';
	}
}

/* HOT or NOT */
Bko.Roster.requestInfoPanel = function(conversationId, idFavorite, from) {
	Seam.Remoting.displayLoadingMessage();
	if(from!=null){
		var param = '&from='+from;
	}else{
		var param = '&ajax=true';
	}
	
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/hot-or-not-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId+'&u='+idFavorite+param,
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}

Bko.Roster.hideInfoPanel = function() {
	$('hot-or-not-panel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.Roster.addUser = function (conversationId, idUser, discardMessage) {
	Seam.Remoting.getContext().setConversationId(conversationId);
	Seam.Component.getInstance("rosterAction").addToRosterlist(idUser, discardMessage, Bko.Roster.addUserCallBack);
}

Bko.Roster.addUserCallBack = function (objResult) {
	var state = objResult[0];
	var message = objResult[1];
//	if (state=="OK") {
//		alert (message);
	Bko.Roster.hideInfoPanel();
//	}
//	else {
//		alert(message);
//	}
}

Bko.Roster.removeUser = function(user, conversationId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/roster-remove-user-from-list.bookioo',
		{
			evalScripts: true,
			method: 'get',
			parameters: 'u='+user+'&cid='+conversationId+'&rand='+Math.random(),
			insertion: 'bottom'
		}
	);
}

Bko.Roster.hideRemoveUserPanel = function () {
	$('remove_user_panel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.Roster.sendMessagePanel = function (conversationId, userId) {
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/roster-sendmessage-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId+'&u='+userId
		}
	);
}

Bko.Roster.goToUser = function(from,pag,cid){
	Seam.Remoting.displayLoadingMessage();
	var pc = $('roster_container'); 
	if (pc != null) {
		var myAjax = new Ajax.Updater (
			'roster_container',
			'/ajax/roster-goto-user.bookioo',
			{
				evalScripts: true,
				parameters: 'from='+from+'&pag='+pag+(cid!=null?'&cid='+cid:''),
				method: 'get',
				onComplete: Seam.Remoting.hideLoadingMessage
			}
		);
	}
}

Bko.Roster.previousUser = function(from){
	Seam.Remoting.displayLoadingMessage();
	var pc = $('roster_container'); 
	if (pc != null) {
		var myAjax = new Ajax.Updater (
			'roster_container',
			'/ajax/roster-previous-user.bookioo',
			{
				evalScripts: true,
				parameters: 'from='+from,
				method: 'get',
				onComplete: Seam.Remoting.hideLoadingMessage
			}
		);
	}
}

/* Welcome */
Bko.Welcome.hCarousel = null;
Bko.Welcome.hCarouselInAction = false;
Bko.Welcome.nextIndex = 0;
Bko.Welcome.interval = 12000;
Bko.Welcome.intervalID = null;
Bko.Welcome.carouselL = 0;

Bko.Welcome.run = function () {
	if ($('welcome_carousel')) Bko.Welcome.carouselL = $('welcome_carousel').getElementsByTagName('li').length;
	if (Bko.Welcome.carouselL > 1) {
		Bko.Welcome.hCarousel = new UI.Carousel("welcome_carousel");
		Bko.Welcome.hCarousel.observe("scroll:started", function(event){
			Bko.Welcome.hCarouselInAction = true;
		});
		Bko.Welcome.hCarousel.observe("scroll:ended", function(event){
			var index = Bko.Welcome.hCarousel.currentIndex();
			Bko.Welcome.hCarouselInAction = false;
		});
		Bko.Welcome.initAuto();
	}
}

Bko.Welcome.initAuto = function () {
	if (Bko.Welcome.intervalID==null)
		Bko.Welcome.intervalID = setInterval("Bko.Welcome.next()",Bko.Welcome.interval);
}

Bko.Welcome.next = function () {
	if (!Bko.Welcome.hCarouselInAction) {
		var index = (Bko.Welcome.hCarousel.currentIndex() + 1) % Bko.Welcome.carouselL;
		Bko.Welcome.show(index);
	}
}

Bko.Welcome.show = function (index) {
	if (!Bko.Welcome.hCarouselInAction) {
		// Change slide
		Bko.Welcome.hCarousel.scrollTo(index);
	}
}

Bko.Welcome.showFreeMsg = function(nick) {
	if (Bko.getCookie('free-msg') != nick) {
		Bko.showModalPanel('welcome-free-msg');
	}
}

Bko.Welcome.hideFreeMsg = function(nick) {
	Bko.setCookie("free-msg",nick,60);
	$('welcome-free-msg').style.display = 'none';
}

Bko.Welcome.fromDateFog = function() {
	if (!$F('welcome-filters:includeExpired') && !$F('welcome-filters:includeCancelled'))
		$('from-date-filter').addClassName('fog');
	else
		$('from-date-filter').removeClassName('fog');
}

/* Plan Type Selection */
Bko.PlanSelection.requestActivityInfoPanel = function(conversationId, idActivitySelect) {
	Seam.Remoting.displayLoadingMessage();
		
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax-pub/plan-type-selection-activity-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId+'&a='+idActivitySelect,
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}

Bko.PlanSelection.requestEmptyInfoPanel = function(conversationId) {
	Seam.Remoting.displayLoadingMessage();
		
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/secure/checker-plan-empty-selection-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId,
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}

Bko.PlanSelection.requestSimpleInfoPanel = function(conversationId) {
	Seam.Remoting.displayLoadingMessage();
		
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/plan-type-selection-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId,
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}

Bko.PlanSelection.requestInfoPanel = function(conversationId, idUserSelect) {
	Seam.Remoting.displayLoadingMessage();
		
	var myAjax = new Ajax.Updater (
		'tail_content',
		'/ajax/plan-type-selection-panel.bookioo',
		{
			evalScripts: true,
			method: 'get',
			insertion: 'bottom',
			parameters: 'cid='+conversationId+'&u='+idUserSelect,
			onComplete: Seam.Remoting.hideLoadingMessage
		}
	);
}

Bko.PlanSelection.hideInfoPanel = function() {
	$('plan-type-selection-panel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.PlanSelection.hideActivityInfoPanel = function() {
	$('plan-type-selection-activity-panel').remove();
	Event.stopObserving(window, 'keypress');
}

Bko.PlanSelection.hideEmptyInfoPanel = function() {
	$('plan-empty-selection-panel').remove();
	Event.stopObserving(window, 'keypress');
}


Bko.KeyEvent.escPanel = function(panel, ev){
	if($(panel) != null && ev != null){
		if (Event.KEY_ESC === (ev.keyCode || ev.which)){
			$(panel).remove();
		}
	}
	Event.stopObserving(document,'keypress');	
}

Bko.CountDown.count =0;
Bko.CountDown.clock = function(){
	if (Bko.CountDown.count > 0)
	{
		Bko.CountDown.count--;
		if(Bko.CountDown.count == 0)
		{
			if($('people-panel:people-sum:buttonDec')) $('people-panel:people-sum:buttonDec').className = 'buttons_right';
			if($('people-panel:people-sum:buttonProp')) $('people-panel:people-sum:buttonProp').className = 'buttons_right';
			if($('directMsgButton')) $('directMsgButton').disabled = false;
			if($('directPlanButton')) $('directPlanButton').disabled = false;
			if($('countdown-msg')) $('countdown-msg').remove();
		}
		if(Bko.CountDown.count > 0 && $('countdown'))
		{
			$('countdown-msg').style.display='block';
			$('countdown').innerHTML = Bko.CountDown.count;
			setTimeout('Bko.CountDown.clock()',1000);
		}
	}
}

Bko.Subscribe.priceChosen = function(id){
	if ($('paypal-container').style.display == 'none') {
 		$('cecaframe').style.display='none';
 		$('cecaframe').src='about:blank';
 		new Effect.Morph('ceca-container', {
			style:'width:210px;',
			duration:0.3,
			afterFinish:function(){
 				$('cecamsg').style.display='block';
 				$('paypal-container').style.display='block';
 			}
		});
 	}
	if ($('cecaform')) Event.observe($('cecaform'), 'submit', Bko.Subscribe.cecaSubmit);

 	$('subscription').value=id;
 	$$('div.price_box').each(function(e){e.className='price_box fog';});
 	$('price_box'+id).className='price_box';
 	if($('Importe')) $('Importe').value='';
}

Bko.Subscribe.cecaSubmit = function() {
	Seam.Component.getInstance("tpvCecaAction").sign(
			$F('subscription'),
			$F('TipoMoneda'),
			$F('Exponente'),
			$F('Referencia'),
			function(resp) {
				$('Num_operacion').value=resp[0];
				$('Descripcion').value=resp[1];
				$('Importe').value=resp[2];
				$('Datos_operaciones').value=resp[3];
				$('Firma').value=resp[4];
				Event.stopObserving($('cecaform'), 'submit');
				$('cecaform').submit();
				$('paypal-container').style.display='none';
				$('cecamsg').style.display='none';
				new Effect.Morph('ceca-container', {
					style:'width:430px;',
					duration:0.3,
					afterFinish:function(){
						$('cecaframe').style.display='block';
					}
				});
			},
			function(ex) {
				ex.message.evalScripts();
			}
	);
	return false;
}

Bko.Upload.slot = function(uploader,name,elem) {
	Seam.Component.getInstance("fileUpload").requestSlot(
		function(cid) {
			uploader.setCid(cid);
			uploader.submit();
			if(elem!=null) {
				var a = new Element('div',{'class':'progress_bar'});
				var b = new Element('div',{'id':'bar-'+name,'class':'progress_bar_in'});
				var c = new Element('span',{'id':'status-'+name,'class':'label_11 label_black'});
				a.insert(b);b.insert(c);c.insert('0%');
				$(elem).update(a);
			}
			new PeriodicalExecuter(function(pe) {
				Seam.Remoting.getContext().setConversationId(null);
				Seam.Remoting.enabledLoadingMsg=false;
				Seam.Component.getInstance("fileUploadChecker").retrieveUploadInfo(
						cid,
						function(info) {
							if(info==null || 'done'===info.status || 'error'===info.status) pe.stop();
							if(elem!=null) {
								var perc=Math.round(100*info.bytesRead/info.totalSize)+'%';
								$('bar-'+name).style.width=perc;
								$('status-'+name).update(perc);
							}
						}
				);
			}, 3);
		},
		function(ex) {
			ex.message.evalScripts();
		}
	);
}

Bko.Plan.share = function(idPlan, email, message, alert) {
	if(!Bko.testEmail(email)) return;
	Seam.Component.getInstance("sharePlanAction").sharePlan(
		idPlan,
		email,
		message,
		function(cid) {
			$('share-plan-panel').remove();
			if(alert) Bko.newGreenAlert(alert);
		},
		function(ex) {
			ex.message.evalScripts();
		}
	);
}

Bko.Mbti.share = function(email, message, alert, emailFrom) {
	if(!Bko.testEmail(email)) return;
	if(emailFrom != null && !Bko.testEmail(emailFrom)) return;
	Seam.Component.getInstance("mbtiTestAction").share(
		email,
		message,
		emailFrom,
		function(cid) {
			$('share-test-panel').hide();
			if(alert) Bko.newGreenAlert(alert);
		},
		function(ex) {
			ex.message.evalScripts();
		}
	);
}
