var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event,
handleYes = function() {this.cancel();},
genericPanelWidth="50em",
emailIsNotCorrect, aliasIsNotCorrect, groupNameIsNotCorrect, securityCodeNotCorrect, currentAlias, currentGroupName,
DDM = YAHOO.util.DragDropMgr,
Ajax,
selectedFriend=-1,
friends;

if (Ajax && (Ajax != null)) {
	Ajax.Responders.register({
	  onCreate: function() {
        if($('spinner') && Ajax.activeRequestCount>0)
          Effect.Appear('spinner',{duration:0.5,queue:'end'});
	  },
	  onComplete: function() {
        if($('spinner') && Ajax.activeRequestCount==0)
          Effect.Fade('spinner',{duration:0.5,queue:'end'});
	  }
	});
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function showGenericPanel(url, callbackFn) {

	var AjaxObject = {
		handleSuccess : function(o) {
			Dom.get('genericContainer').innerHTML = o.responseText;            
			doGenericPanel(callbackFn);
		},
		startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
	};
	var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
	AjaxObject.startRequest();

}

function doGenericPanel(callbackFn) {
	
	var handleCancel = function() {
		/*
		if (canCloseThatWindow) {
			window.close();
		}*/		
		this.cancel();
		
	};
	var handleSuccess = function(o) {
	};
	
	var outlineDialog = new YAHOO.widget.Dialog("genericContainer", {
		width :genericPanelWidth,
		fixedcenter :true,
		visible :false,
		constraintoviewport :true,
		modal :false,
		draggable :false,
		zindex :9,
		buttons : [ {
			text :"Ok",
			handler :handleCancel,
			isDefault :true
		} ]
	});

	outlineDialog.callback = {success :handleSuccess,failure :handleFailure};
	outlineDialog.render();
	
	Dom.get('genericContainer').style.display = "block";

    
	outlineDialog.show();

    
	if (callbackFn) {
		callbackFn();	
	}	
}


/* ==== slider nameSpace ==== */
var slider = function() {
	/* ==== private methods ==== */
	function getElementsByClass(object, tag, className) {
		var o = object.getElementsByTagName(tag);
		for ( var i = 0, n = o.length, ret = []; i < n; i++) {
			if (o[i].className == className) ret.push(o[i]);
		}
		if (ret.length == 1) ret = ret[0];
		return ret;
	}
	function setOpacity (obj,o) {
		if (obj.filters) obj.filters.alpha.opacity = Math.round(o);
		else obj.style.opacity = o / 100;
	}
	/* ==== Slider Constructor ==== */
	function Slider(oCont, speed, iW, iH, oP) {
		this.slides = [];
		this.over   = false;
		this.S      = this.S0 = speed;
		this.iW     = iW;
		this.iH     = iH;
		this.oP     = oP;
		this.oc     = document.getElementById(oCont);
		this.frm    = getElementsByClass(this.oc, 'div', 'slide');
		this.NF     = this.frm.length;
		this.resize();
		for (var i = 0; i < this.NF; i++) {
			this.slides[i] = new Slide(this, i);
		}
		this.oc.parent = this;
		this.view      = this.slides[0];
		this.Z         = this.mx;
		/* ==== on mouse out event ==== */
		this.oc.onmouseout = function (event) {
		    var e=(event)?event:window.event;
		    if (window.event) {
		        e.cancelBubble=true;
		    } else {
		        //e.preventDefault();
		        e.stopPropagation();
		    }			
		
//			this.parent.mouseout(event);
			return false;
		}
	}
	Slider.prototype = {
		/* ==== animation loop ==== */
		run : function () {
			this.Z += this.over ? (this.mn - this.Z) * .5 : (this.mx - this.Z) * .5;
			this.view.calc();
			var i = this.NF;
			while (i--) this.slides[i].move();
		},
		/* ==== resize  ==== */	
		resize : function () {
			this.wh = this.oc.clientWidth;
			this.ht = this.oc.clientHeight;
			this.wr = this.wh * this.iW;
			this.r  = this.ht / this.wr;
			this.mx = this.wh / this.NF;
			this.mn = (this.wh * (1 - this.iW)) / (this.NF - 1);
		},
		/* ==== rest  ==== */
		mouseout : function (event) {
			this.over      = false;
			setOpacity(this.view.img, this.oP);
		    var e=(event)?event:window.event;
		    if (window.event) {
		        e.cancelBubble=true;
		    } else {
		        //e.preventDefault();
		        e.stopPropagation();
		    }			
			
		}
	}
	/* ==== Slide Constructor ==== */
	Slide = function (parent, N) {
		this.parent = parent;
		this.N      = N;
		this.x0     = this.x1 = N * parent.mx;
		this.v      = 0;
		this.loaded = false;
		this.cpt    = 0;
		this.start  = new Date();
		this.obj    = parent.frm[N];
		this.txt    = getElementsByClass(this.obj, 'div', 'text');
		this.img    = getElementsByClass(this.obj, 'img', 'diapo');
		this.bkg    = document.createElement('div');
		this.bkg.className = 'backgroundText';
		this.obj.insertBefore(this.bkg, this.txt);
		if (N == 0) this.obj.style.borderLeft = 'none';
		this.obj.style.left = Math.floor(this.x0)  + 'px';
		setOpacity(this.img, parent.oP);
		/* ==== mouse events ==== */
		this.obj.parent = this;
		this.obj.onmouseover = function(event) {
			this.parent.over(event);
		    var e=(event)?event:window.event;
		    if (window.event) {
		        e.cancelBubble=true;
		    } else {
		        //e.preventDefault();
		        e.stopPropagation();
		    }			
			return false;
		}
	}
	Slide.prototype = {
		/* ==== target positions ==== */
		calc : function() {
			var that = this.parent;
			// left slides
			for (var i = 0; i <= this.N; i++) {
				that.slides[i].x1 = i * that.Z;
			}
			// right slides
			for (var i = this.N + 1; i < that.NF; i++) {
				that.slides[i].x1 = that.wh - (that.NF - i) * that.Z;
			}
		},
		/* ==== HTML animation : move slides ==== */
		move : function() {
			var that = this.parent;
			var s = (this.x1 - this.x0) / that.S;
			/* ==== lateral slide ==== */
			if (this.N && Math.abs(s) > .5) {
				this.obj.style.left = Math.floor(this.x0 += s) + 'px';
			}
			/* ==== vertical text ==== */
			var v = (this.N < that.NF - 1) ? that.slides[this.N + 1].x0 - this.x0 : that.wh - this.x0;
			if (Math.abs(v - this.v) > .5) {
				this.bkg.style.top = this.txt.style.top = Math.floor(2 + that.ht - (v - that.Z) * that.iH * that.r) -200 + 'px';
				this.v = v;
				this.cpt++;
			} else {
				if (!this.pro) {
					/* ==== adjust speed ==== */
					this.pro = true;
					var tps = new Date() - this.start;
					if(this.cpt > 1) {
						that.S = Math.max(2, (28 / (tps / this.cpt)) * that.S0);
					}
				}
			}
			if (!this.loaded) {
				if (this.img.complete) {
					this.img.style.visibility = 'visible';
					this.loaded = true;
				}
			}
		},
		/* ==== light ==== */
		over : function (event) {

			this.parent.resize();
			this.parent.over = true;
			setOpacity(this.parent.view.img, this.parent.oP);
			this.parent.view = this;
			this.start = new Date();
			this.cpt = 0;
			this.pro = false;
			this.calc();
			setOpacity(this.img, 100);
		    var e=(event)?event:window.event;
		    if (window.event) {
		        e.cancelBubble=true;
		    } else {
		        //e.preventDefault();
		        e.stopPropagation();
		    }			
		}
	}
	/* ==== public method - script initialization ==== */
	return {
		init : function() {
			// create instances of sliders here
			// parameters : HTMLcontainer name, speed (2 fast - 20 slow), Horizontal ratio, vertical text ratio, opacity
			this.s1 = new Slider("slider", 5, 1.84/3, 1/2.8, 100);
			setInterval("slider.s1.run();", 20);

		}
	}
}();

function handleFailure(o){
	showErrorAlert("Server Error:" + o.responseText);
}

function go(url) {
	document.location = root + url;
}

function goHome() {
	go("member/home")
}
function logout() {
	go("member/logout")
}

function showAlert(text, handler) {

	if (!handler) { 
		handler = handleYes;
	}

	var okDialog = new YAHOO.widget.SimpleDialog("simpledialog1",
		{ width: "300px",
		effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25},		
		  fixedcenter: true,
		  visible: false,
		  draggable: false,
		  close: true,
		  zindex:400,
		  text: text,
		  icon: YAHOO.widget.SimpleDialog.ICON_ALARM,
		  constraintoviewport: true,
		  buttons: [ { text:"Ok", handler: handler,  isDefault:true }]
		} );
	okDialog.setHeader("MakeBook Alert");
	okDialog.render("btn-container");
	okDialog.show();
}

function showPrivacyPolicy() {
	Dom.get('privacyPolicy').style.display="block";
}

function showSecurityCodeAlert() {
	genericPanelWidth = "35em";
	showGenericPanel("member/code");
}

function checkSecurityCode(el) {

	var code = el.value.trim();
	
	if (code == "") {
		return;
	}
	
	var url = "member/checkSecurityCode?code=" + code;

	var AjaxObject = {
			handleSuccess:function(o){
				if (o.responseText == 'false') {
					securityCodeNotCorrect = true;
					showSecurityCodeAlert();
				} else {
					securityCodeNotCorrect = false;
				}
			},
			startRequest:function() {
				YAHOO.util.Connect.asyncRequest('POST', root + url, callback);
			}
		}, callback = {	success:AjaxObject.handleSuccess,failure:handleFailure,	scope: AjaxObject,cache:false};
		AjaxObject.startRequest();
}


function checkUniqueGroupName(el) {

	var name = el.value.trim();

	if (name == "") {
		return;
	}

    currentGroupName = name;

	var url = "group/isGroupNameUnique?groupName=" + name;

	var AjaxObject = {
			handleSuccess:function(o){
				if (o.responseText == 'false') {
					showGroupNameAlert();
					groupNameIsNotCorrect = true;
				} else {
					groupNameIsNotCorrect = false;
				}
			},
			startRequest:function() {
				YAHOO.util.Connect.asyncRequest('POST', root + url, callback);
			}
		}, callback = {	success:AjaxObject.handleSuccess,failure:handleFailure,	scope: AjaxObject,cache:false};

		AjaxObject.startRequest();
}


function checkUniqueEmail(el) {

	var email = el.value.trim();
	
	if (email == "") {
		return;
	}
	
	var url = "member/isEmailUnique?email=" + email;

	var AjaxObject = {
			handleSuccess:function(o){                
				if (o.responseText == 'false') {                    
					showEmailAlert();
					emailIsNotCorrect = true;
				} else {                    
					emailIsNotCorrect = false;
				}
			},
			startRequest:function() {
				YAHOO.util.Connect.asyncRequest('POST', root + url, callback);
			}
		}, callback = {	success:AjaxObject.handleSuccess,failure:handleFailure,	scope: AjaxObject,cache:false};

		AjaxObject.startRequest();
}

function checkUniqueAlias(el) {
	
	var alias = el.value.trim();
	
	if (alias == "") {
		return;
	}
	
	currentAlias = alias;
	
	var url = "member/isAliasUnique?alias=" + alias;

	var AjaxObject = {
			handleSuccess:function(o){                
				if (o.responseText == 'false') {                    
					aliasIsNotCorrect = true;
					showAliasAlert();	
				} else {
					aliasIsNotCorrect = false;	
				}
			},
			startRequest:function() {
				YAHOO.util.Connect.asyncRequest('POST', root + url, callback);
			}
		}, callback = {	success:AjaxObject.handleSuccess,failure:handleFailure,	scope: AjaxObject,cache:false};
		AjaxObject.startRequest();
}

function isEmpty(v) {
	return (!v || v=='') ? true : false;
}

function isEmptyEl(v) {
	return (!v || !v.value || v=='') ? true : false;
}

function isEmptyId(v) {
	var el = Dom.get(v);
	if (!v || !el) {
		return true;
	}
	return isEmptyEl(el);
	
}

function validateRequired(el) {
	var errorId = el.id + "-err";
	if (isEmpty(el.value)) {
		Dom.get(errorId).innerHTML = el.title;
		Dom.get(errorId).style.display="block";
	} else {
		Dom.get(errorId).style.display="none";
	}
}

function validateSame(el, el2Id) {
	var errorId = el.id + "-err";
	if (isEmpty(el.value) || el.value != Dom.get(el2Id).value) {
		Dom.get(errorId).innerHTML = el.title;
		Dom.get(errorId).style.display="block";
	} else {
		Dom.get(errorId).style.display="none";
	}
}

function validateEmail(el) {
	var errorId = el.id + "-err";
	var value = el.value;
	apos = value.indexOf("@");
	dotpos = value.lastIndexOf(".");
	var valid;
	if (apos<1||dotpos-apos<2) {
		Dom.get(errorId).innerHTML = el.title;
		Dom.get(errorId).style.display="block";
	} else {
		Dom.get(errorId).style.display="none";
	}
}

function validateEmailValue(value) {
	apos = value.indexOf("@");
	dotpos = value.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) {
           return false;
	} else {
		return true;
	}
	
	return false;
}


function validatePassword(el) {
	var errorId = el.id + "-err";
	if (isEmpty(el.value) || el.value.length < 6) {
		Dom.get(errorId).innerHTML = el.title;
		Dom.get(errorId).style.display="block";
	} else {
		Dom.get(errorId).style.display="none";
	}
}

function showAlertId(id) {
	
	showErrorAlert(Dom.get(id).title, "Signup Error");
}

function signup() {
	
	if (!Dom.get('agree-chb-id').checked) {
		showAlertId('agree-chb-id');
		return;
	}
	
	if (isEmptyId('firstName')) {
		showAlertId('firstName');
		return;
	}
	if (isEmptyId('lastName')) {
		showAlertId('lastName');
		return;
	}
	if (isEmptyId('alias')) {
		showAlertId('alias');
		return;
	}
	if (isEmptyId('emailField') || !validateEmailValue(Dom.get('emailField').value)) {
		showAlertId('emailField');
		return;
	}
	
	if (isEmptyId('confirm-email') || Dom.get('confirm-email').value != Dom.get('emailField').value) {
		showAlertId('confirm-email');
		return;
	}
	if (isEmptyId('password') || Dom.get('password').value.length < 6 ) {
		showAlertId('password');
		return;
	}	
	if (isEmptyId('confirmPassword') || Dom.get('confirmPassword').value != Dom.get('password').value) {
		showAlertId('confirmPassword');
		return;
	}	
	if (isEmptyId('code')) {
		showAlertId('code');
		return;
	}
	
	if (securityCodeNotCorrect) {
		showSecurityCodeAlert();
		return;
	}
	if (aliasIsNotCorrect) {
		showAliasAlert();
		return;
	}
	if (emailIsNotCorrect) {
		showEmailAlert();
		return;
	}
    if (groupNameIsNotCorrect) {
		showGroupNameAlert();
		return;
	}
	
	var code = Dom.get('code').value.trim();
	
	if (code == "") {
		return;
	}
	
	var url = "member/checkSecurityCode?code=" + code;

	var AjaxObject = {
			handleSuccess:function(o){
				submitSignUpForm();
			},
			startRequest:function() {
				YAHOO.util.Connect.asyncRequest('POST', root + url, callback);
			}
		}, callback = {	success:AjaxObject.handleSuccess,failure:handleFailure,	scope: AjaxObject,cache:false};
		AjaxObject.startRequest();	
	
}

function submitSignUpForm() {
	document.signupForm.submit();	
}

function showEmailAlert() {
	genericPanelWidth = "30em";
	showGenericPanel("member/email");
}

function showAliasAlert() {
	genericPanelWidth = "30em";
	showGenericPanel("member/alias?alias="+currentAlias);
}

function showGroupNameAlert() {
	genericPanelWidth = "30em";
	showGenericPanel("group/groupName?groupName="+currentGroupName);
}

function showErrors() {}

function setAlias(alias) {
	aliasIsNotCorrect = false;
	Dom.get('alias').value=alias; 
	Dom.get('genericContainer').style.display='none';
}

var shareBookId = 0;
var shareWin 
function shareBook(id) {
	shareWin = window.open(root+"friends/share?id="+id,'ShareABook', 'left=20,top=20,location=0,width=750,height=450,toolbar=0,resizable=0');
}

function closeFriendsPopup() {
	window.close();
}

function initFriendsPanel() {
	doInitFriends();
}

function doInitFriends() {
    var btnSaveF = new YAHOO.widget.Button({ label:"Add to My Friends list", id:"btnSaveF", container:"btnSaveF" });
    btnSaveF.on("click", saveFriendFFn);

    var btnRemoveFromFr = new YAHOO.widget.Button({ label:"Remove from friends list", id:"btnRemoveFromFr", container:"btnRemoveFromFr" });
    btnRemoveFromFr.on("click", removeFriend);
    
    var btnLeftFr = new YAHOO.widget.Button({ id:"btnLeftFr", container:"btnLeftFr" });
    btnLeftFr.on("click", removeFriendsFromAssoc);
    
    var btnRightFr = new YAHOO.widget.Button({ id:"btnRightFr", container:"btnRightFr" });
    btnRightFr.on("click", addFriendsToAssoc);
    
    var btnRemoveFromViewFr = new YAHOO.widget.Button({ label:"Remove from view list", id:"btnRemoveFromViewFr", container:"btnRemoveFromViewFr" });
    btnRemoveFromViewFr.on("click", removeFriendsFromAssoc);
    
    var btnSaveAndNotifyFr = new YAHOO.widget.Button({ label:"Send e-mail to friends", id:"btnSaveAndNotifyFr", container:"btnSaveAndNotifyFr" });
    btnSaveAndNotifyFr.on("click", showShareEmailMessage);

    loadMyFriends();
    loadMyAssocFriends();

}

function initSharePanel() {
	doInitFriends();
	
    var btnExitPopupFr = new YAHOO.widget.Button({ label:"Close", id:"btnExitPopupFr", container:"btnExitPopupFr" });
    btnExitPopupFr.on("click", closeFriendsPopup);
	
}

function clickMBTextBox(el) {
	
	var emptyText = el.title;

	if (isEmptyEl(el)) {
		el.className="mbtextActive"
	}		
	
	if (!isEmptyEl(el) && el.value == emptyText) {
		el.value = "";
		el.className="mbtextActive"
	}
	
	if (!isEmptyEl(el) && el.value != emptyText) {
		el.className="mbtextActive"
	}		
}

function blurMBTextBox(el) {
	
	var emptyText = el.title;
	
	if (isEmptyEl(el)) {
		el.className="mbtext"
		el.value = emptyText;
	}
	
	if (!isEmptyEl(el) && el.value == emptyText) {
		el.className="mbtext"
	}
	
	if (!isEmptyEl(el) && el.value != emptyText) {
		el.className="mbtextActive"
	}		
}

function saveFriendFFn() {
	
	if (isEmpty('emailF') || Dom.get('emailF').value == 'email' || false == validateEmailValue(Dom.get('emailF').value)) {
		showErrorAlert('Please, enter valid friend\'s email address');
		return;
	}
	/*
	if (isEmpty('nameF') || Dom.get('nameF').value == 'first name & last name') {
		showAlert('Please, enter friend\'s name');
		return;
	}*/
	
	var name = Dom.get('nameF').value;
	var email = Dom.get('emailF').value;
	
	var url = "friends/invite?name="+name+"&email="+email+"&id="+shareBookId;
	
	var AjaxObject = {
		handleSuccess : function(o) {
		
			clearFriendsSelection();
			
			//showAlert('Thank you! Your friend was invited to view the book');
			
			Dom.get('nameF').value = Dom.get('nameF').title;
			Dom.get('emailF').value = Dom.get('emailF').title;
			//Dom.get('ageF').value=Dom.get('ageF').title;
			
			blurMBTextBox(Dom.get('nameF'));
			blurMBTextBox(Dom.get('emailF'));
			//blurMBTextBox(Dom.get('ageF'));
			
			loadMyFriends();
			loadMyAssocFriends();
			
		},
		startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
	};
	var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
	AjaxObject.startRequest();
}

function safety(el) {
	var dob_day = Dom.get('dob_day').value;
	var dob_month = Dom.get('dob_month').value;
	var dob_year = Dom.get('dob_year').value;
	if (false == el.checked) {
		var url = "member/isUser18orYounger?dob_day="+dob_day+"&dob_month="+dob_month+"&dob_year="+dob_year;
		var AjaxObject = {
			handleSuccess : function(o) {
				if (o.responseText == "true") {
					el.checked = true;
				}
			},
			startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
		};
		var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
		AjaxObject.startRequest();
	}
}

var selectedFriends = new Array();

function selectFriend(id) {

	var newArray = new Array();
	
	var wasAlreadySelected = false;
	for (var i=0; i<selectedFriends.length; i++) {
		if (selectedFriends[i] == id) {
			wasAlreadySelected = true;
			Dom.get('fr-row-'+id).className = 'friendUnselected';
		} else {
			newArray.push(selectedFriends[i]);
		}
	}

	if (wasAlreadySelected == false) {
		Dom.get('fr-row-'+id).className = 'friendSelected';
		newArray.push(id);
	}

	selectedFriends = newArray;

}

function getSelectedFriendsIndexes() {
	return selectedFriends;
} 

function removeFriend() {
	
	var indexes = getSelectedFriendsIndexes();
	
	if (!indexes || !indexes.length || indexes.length == 0) {
		showErrorAlert("Please, select a friend you want to delete.");
		return;
	}
	
	var handleDeleteAction = function() {
		doRemoveFriend(indexes);
		this.hide();
	}
	var handleDeleteNo = function() {
		this.hide();
	};
	var deleteDialog = new YAHOO.widget.SimpleDialog("simpledialog1", {
		width :"300px",
		fixedcenter :true,
		zindex :10,
		visible :false,
		draggable :true,
		close :true,
		text :"Do you want to delete this friend?",
		icon :YAHOO.widget.SimpleDialog.ICON_HELP,
		constraintoviewport :true,
		buttons : [ {
			text :"Yes",
			handler :handleDeleteAction
		}, {
			text :"No",
			handler :handleDeleteNo,
			isDefault :true
		} ]
	});
	deleteDialog.setHeader("Are you sure?");
	deleteDialog.render("deleteDialog");
	deleteDialog.show();
	
}

function doRemoveFriend(indexes) {
	
	var url = "friends/removeFriends?";
	
	for (var i=0; indexes && i < indexes.length;i++ ) {
		url += "ids=" + indexes[i] + "&";
	}
	
	if (indexes && !indexes.length) {
		url += "ids=" + indexes;
	}
	
	var AjaxObject = {
		handleSuccess : function(o) {
		
			var e={opacity:{to:0}};
			var f=new YAHOO.util.Anim('fr-row-'+selectedFriend,e);
			f.animate();
			selectedFriend = -1;
			loadMyFriends();
			loadMyAssocFriends();
			
			selectedFriends = new Array();
			
		},
		startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
	};
	var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
	AjaxObject.startRequest();
}

function loadMyFriends() {
	
	var url = "friends/myFriends?id=" + Dom.get('shares-book-id').value;
	
	var AjaxObject = {
		handleSuccess : function(o) {
			Dom.get('myfriends-list').innerHTML = o.responseText;
		},
		startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
	};
	var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
	AjaxObject.startRequest();
}

function loadMyAssocFriends() {

	var url = "friends/friendsForBook?id=" + Dom.get('shares-book-id').value;
	
	var AjaxObject = {
		handleSuccess : function(o) {
			Dom.get('myassocfriends-list').innerHTML = o.responseText;
		},
		startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
	};
	var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
	AjaxObject.startRequest();
	
}

function addFriendsToAssoc() {
	
	var indexes = getSelectedFriendsIndexes();
	
	if (!indexes || !indexes.length || indexes.length == 0) {
		showErrorAlert("Please, select a friend you want to add.");
		return;
	}

	for (var i=0; indexes && i < indexes.length;i++ ) {
		Dom.get('assoc-ul').appendChild(Dom.get('fr-row-'+indexes[i]));
	}
	
	clearFriendsSelection();
	
}

function clearFriendsSelection() {
	for (var i=0; i<selectedFriends.length; i++) {
		Dom.get('fr-row-'+selectedFriends[i]).className = 'friendUnselected';
	}
	selectedFriends = new Array();
}

function removeFriendsFromAssoc() {
	
	var indexes = getSelectedFriendsIndexes();
	
	if (!indexes || !indexes.length || indexes.length == 0) {
		showErrorAlert("Please, select a friend you want to remove.");
		return;
	}

	for (var i=0; indexes && i < indexes.length;i++ ) {
		Dom.get('fr-ul').appendChild(Dom.get('fr-row-'+indexes[i]));
	}
	
	clearFriendsSelection();
	
}

var userHomeEmailChanged = false;

function userHomeUpdate() {

	// was password changes?
	var p = Dom.get('password-id').value;
	if (p && p.trim() != "" && p.length < 6) {
		
		
		showErrorAlert("Password has minimum length of 6 characters.");
		return;
	}
	
	if (p && p.trim() != "" && isEmptyId('password-id-cofirm') || Dom.get('password-id-cofirm').value != Dom.get('password-id').value) {
		showErrorAlert('Passwords do not match');
		return;
	}	
	
	
	if (userHomeEmailChanged) {
		
		var handleAction = function() {
			
			// check if the email is valid
			var email = Dom.get('email').value;
			
			var url = "member/isEmailUnique?email=" + email;

			var AjaxObject = {
					handleSuccess:function(o){
						if (o.responseText == 'false') {
							showErrorAlert("The e-mail is already in use.");
							return;
						} else {
							document.myForm.submit();
						}
					},
					startRequest:function() {
						YAHOO.util.Connect.asyncRequest('POST', root + url, callback);
					}
			}, callback = {	success:AjaxObject.handleSuccess,failure:handleFailure,	scope: AjaxObject,cache:false};
			
			AjaxObject.startRequest();
				
			this.hide();
				
		}
		var handleDeleteNo = function() {
			this.hide();
		};
		var aDialog = new YAHOO.widget.SimpleDialog("simpledialog1", {
			width :"300px",
			fixedcenter :true,
			zindex :10,
			visible :false,
			draggable :true,
			close :true,
			text :"You have changed the email address. You will be logged out of the system. Please, check your email inbox and click on the activation link we will send you. Are you sure you want to continue? " ,
			constraintoviewport :true,
			buttons : [ {
				text :"Yes",
				handler :handleAction
			}, {
				text :"No",
				handler :handleDeleteNo,
				isDefault :true
			} ]
		});
		aDialog.setHeader('<div class="hd" style="border-style:none;"><div class="pop-title">Are you sure?</div></div>');
		aDialog.render("deleteDialog");
		aDialog.show();
	} else {
		document.myForm.submit();
	}
}

function resetPassword() {
	var p1 = Dom.get('password1').value;
	var p2 = Dom.get('password2').value;
	if (p1!=p2) {
		showErrorAlert('The passwords do not match');
		return
	}
	if (Dom.get('password1').value.length < 6) {
		showErrorAlert('Minimum length of a password is 6 characters');
		return
	}
	Dom.get('resetForm').submit();
}

function createShares() {
	Dom.get('shares-access-id').value = Dom.get('access-drop-id').value
}

function showShareEmailMessage() {
	
	var bookId = Dom.get('shares-book-id').value;
	var access = 'viewonly';//Dom.get('access-drop-id').value;
	
	var url = "friends/shareEmailMessage?id="+bookId+"&access="+access;
	var els = Dom.get('assoc-ul').childNodes;
	
	if (els) {
		for (var i=0; i<els.length;i++) {
			if (els[i] && els[i].tagName && (els[i].tagName == 'li' || els[i].tagName == 'LI')) {
				if (els[i].alt) {
					url += "&ids="+els[i].alt;	 
				} else {
					url += "&ids=" + els[i].attributes.getNamedItem("alt").nodeValue;
				}
				
			}
		}
	}
	
	url += "&ids=0";
	
	var AjaxObject = {
		handleSuccess : function(o) {
			try {
			if (opener) opener.location.reload();
			} catch (err) {}
			if (o.responseText && o.responseText != "removedAll") {
				Dom.get('genericContainer-2').innerHTML = o.responseText;
				doShareEmailMessage();
			}
		},
		startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
	};
	var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
	AjaxObject.startRequest();

}

function doShareEmailMessage() {

	var handleCancel = function() {
		showShareEmailMessage();
	};
	var handleSuccess = function(o) {
		sendNotifyShareEmails();
	};
	
	var newDialog = new YAHOO.widget.Dialog("genericContainer-2", {
		width :"50em",
		fixedcenter :true,
		visible :true,
		constraintoviewport :true,
		modal :false,
		draggable :false,
		zindex :15,
		buttons : [ {
			text :"Reset message",
			handler :handleCancel
		},{
			text :"Send e-mail",
			handler :handleSuccess,
			isDefault :true
		}]
	});

	newDialog.callback = {success :handleSuccess,failure :handleFailure};
	newDialog.render();
	Dom.get('genericContainer-2').style.display = "block";
	newDialog.show();
	
}

function sendNotifyShareEmails() {
	Dom.get('share-notif-email-form').submit();
}

function showCompetitionDetails(id) {
	genericPanelWidth = "35em";
	showGenericPanel("competition/details?id="+id);
	
}

function removeSharedBookRecord() {
	Dom.get('shared-book-id-'+sharedBookRecordId).style.display = "none";
}

var sharedBookRecordId = 0;

function removeSharedFromFriend(id) {
	
	sharedBookRecordId = id;
	
	var handleDeleteAction = function() {
		
		var AjaxObject = {
				handleSuccess : function(o) {
					var e={opacity:{to:0}};
					var f=new YAHOO.util.Anim('shared-book-id-'+id,e);
					f.onComplete.subscribe(removeSharedBookRecord);
					f.animate();
			
				},
				startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + "friends/removeSharedFromFriend?id="+id, callback);}
			};
		var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
		AjaxObject.startRequest();
		
		this.hide();
	}
	var handleDeleteNo = function() {
		this.hide();
	};
	var deleteDialog = new YAHOO.widget.SimpleDialog("simpledialog1", {
		width :"300px",
		fixedcenter :true,
		zindex :10,
		visible :false,
		draggable :true,
		close :true,
		text :"Do you want to remove this book from the list?",
		icon :YAHOO.widget.SimpleDialog.ICON_HELP,
		constraintoviewport :true,
		buttons : [ {
			text :"Yes",
			handler :handleDeleteAction
		}, {
			text :"No",
			handler :handleDeleteNo,
			isDefault :true
		} ]
	});
	deleteDialog.setHeader("Are you sure?");
	deleteDialog.render("deleteDialog");
	deleteDialog.show();
	
}

function visit(url) {
	document.location = url;
}

function showDemoBook() {
	if (Dom.get('flashContentId')) {
		Dom.get('flashContentId').style.display = "block";
	}
	if (this.cancel) {
		this.cancel();
	}
}
function showErrorAlert(text, title, handler) {

	if (!title) {
		title = "Makebook Alert";
	}
	
	if (!handler) {
		handler = showDemoBook;
	}

	var okDialog = new YAHOO.widget.SimpleDialog("simpledialog1",
		{ width: "300px",
		  fixedcenter: true,
		  visible: false,
		  draggable: false,
		  close: true,
		  zindex:4000,
		  //text: text,
		  constraintoviewport: true,
		  buttons: [ { text:"Ok", handler: handler,  isDefault:true }]
		} );
	//okDialog.setHeader('<div class="hd" style="border-style:none;"><div class="pop-title">'+title+'</div></div>');

    okDialog.setBody('<p>'+text+'</p>');
	okDialog.render("btn-container");

    var close = Dom.getElementsByClassName('container-close', 'a');
    Event.on(close, 'click', showDemoBook); 
    
    
	okDialog.show();
}

function canLogin () {
	var url = "member/canLogin?password=" +Dom.get('login-password').value + "&email=" + Dom.get("login-email").value;  
	var AjaxObject = {
			handleSuccess : function(o) {
				if (o.responseText) {
					if (o.responseText == "notActive") {
						if (Dom.get('flashContentId')) {
							Dom.get('flashContentId').style.display = "none";
						}			
						
						showErrorAlert("The account is not active yet", "Login Error");
					} else if (o.responseText == "false") {
						
						if (Dom.get('flashContentId')) {
							Dom.get('flashContentId').style.display = "none";
						}			
						
						showErrorAlert("The user doesn't exist or the password is not correct", "Login Error");
					} else {
						Dom.get('login-form').submit();
						//document.location = root + "member/home"
					}
					
				}
			},
			startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
		};
		var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
		AjaxObject.startRequest();
}

function editBook(id, published) {

	if (!published) {
		document.location=root+'document/runapp?id='+id;
		return;
	}
	
	var handler = handleYes;
	
	var handleEdit = function() {
		document.location=root+'document/runapp?id='+id;
		this.cancel();
	};
	
	var handleEditDraft = function() {
		document.location=root+'document/editDraft?id='+id;
		this.cancel();
	}
	
	var text="This is a published book.<br/><br/>";
	text+="You can create a draft version of the book, and edit that. If you create a draft, then your published book will not be updated with your changes until you re-publish it. This is a good option if you are making lots of changes to the book, that might take a while to finish.<br/><br/>";
	text+="<div style='text-align:center;'>or</div><br/>";
	text+="You can directly edit the published book.  If you directly edit the published book, all your changes will immediately update the book, and you will not need to re-publish the book to see your changes. This is a good option if you are making small changes to the book, that you want people to see right away.";

	var okDialog = new YAHOO.widget.SimpleDialog("simpledialog1",
		{ width: "600px",
		effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25},		
		  fixedcenter: true,
		  visible: false,
		  draggable: false,
		  close: true,
		  zindex:400,
		  text: text,
		  constraintoviewport: true,
		  buttons: [ { text:"Create draft", handler: handleEditDraft},
		             { text:"Direct edit", handler: handleEdit}
		             ]
		} );
	okDialog.setHeader('<div class="hd" style="border-style:none;"><div class="pop-title">MakeBook</div></div>');
	okDialog.render("btn-container");
	okDialog.show();
	
//	document.location=root+'document/runapp?id='+id;
}

function canEdit(bookId, published) {
	
	if (!published) {
		editBook(bookId, published);
	}
	
	var url = "document/isBookInCompetition?id=" +bookId;  
	var AjaxObject = {
			handleSuccess : function(o) {
				if (o.responseText) {
					if (o.responseText != "false") {
						showErrorAlert("This book has been entered into '"+o.responseText+"'. You will not be able to edit the book until competition judging is complete on entry release date.", "MakeBook Warning");
					} else {
						editBook(bookId, published);
					} 
				}
			},
			startRequest : function() {YAHOO.util.Connect.asyncRequest('GET', root + url, callback);}
		};
		var callback={success:AjaxObject.handleSuccess,failure:handleFailure,scope:AjaxObject,cache:false};
		AjaxObject.startRequest();
}
















