/*
	kevin han
	2008-03-28
	profile javascript module
*/


document.title = page_info.name + "'s Pagii Profile";


var API_URL = nasc.API_URL;
var pageOwnerName = page_info.name.split(" ")[0];
var pageOwnerSrl = page_info.page_id;
var viewerSrl = false;

var bubble_tip = null;

var MSG_COMMENT_FRIEDNS_ONLY = "Only friends can add comments from now";
var MSG_COMMENT_ANYONE = "Anyone can add comments from now";


//////////////////////////////////////////////////////////////////////////////////////////
// 



var _init_request = null;

function init() {
	bubble_tip = nus.ui.BubbleTip.createInstance({
		zIndex: 100
	});

	Profile.init();

	if (isOwner) {
		//nus.dom.css.updateRule("owner_only", "display", "");
		nus.dom.css.addCSS(".owner_only", "visibility:inherit");
		nus.dom.css.addCSS("a.tool", "visibility:inherit");
	}
	else {
		nus.dom.css.addCSS(".guest_only", "visibility:inherit");
		nus.dom.css.addCSS("#aboutme .part .focused a.tool", "display:none");
	}

	if (profile_data) {
		initPage(profile_data);
	}
	else {
		var params = {
			method: "profile.getprofile",//"msglist",
			msrl: pageOwnerSrl,
			callback: "onGetInfoComplete"
		}

		_init_request = nus.io.ScriptRequest.sendRequest(API_URL, params, null, "onGetInfoError()");
	}
}

function onGetInfoComplete(rsp) {
	if (rsp.statusCode != "ok") {
		return;
	}		

	initPage(rsp);

	_init_request.setComplete();
	_init_request = null;
}


function onGetInfoError(rsp) {

}


function initPage(rsp) {
	Profile.setOwnerInfo(rsp.data.oMemberInfo);
	
	//Favorite.makeItems(rsp.data.oAboutMe.favorite_list);
	//Question.makeItems(rsp.data.oAboutMe.question_list);
	Gauge.makeItems(rsp.data.oAboutMe.guage_list);

	Friends.update(rsp.data.oFriendList);
	Friends.displayFriendsList(rsp.data.oFriendList.friends);
	Pagelist.init(rsp.data.arrPageList);
}

function updateLayout() {
	$("layout_box").style.height = "auto";
	var size = nus.dom.getScrollSize();
//	nasc.resizeSubPage(size.w, size.h);
}

function recalcLayout(w,h) {
	$("layout_box").style.height = h+"px";
}

function showThrobber(msg_text) {
	isWaiting = true;
	if (msg_text) {
		$("waiting_message").innerHTML = msg_text;
	}

	$("throbber").style.display = "block";
	nus.dom.moveCenter("throbber");
}

function hideThrobber() {
	isWaiting = false;
	$("throbber").style.display = "none";
}

//////////////////////////////////////////////////////////////////////////////
//

var Profile = {
	init: function() {
	},

	setOwnerInfo: function(owner) {	

		if (owner.profileflag == "o" || (isOwner || isMyFriend)) {
			//detail info
			this.setValue("owner.age", owner.age);
			if (owner.region3 != "" && owner.region2 != "") {
				this.setValue("owner.hometown", (owner.region3?owner.region3+" / ":"")+( owner.region2?owner.region2:''));
			}

			this.setValue("owner.country", COUNTRY_CODE.to_country(owner.region1));
			this.setValue("owner.intro", owner.intro.replace(/\n/g, "<br/>") );

			if (owner.suburl) {
				this.setValue("owner.suburl", 
					'<a href="/'+owner.suburl+'" onclick="gotoPage(this.href);return false;">http://'+document.location.hostname+'/'+owner.suburl+'</a>');
			}
		}
		else {
			// detail info 금지
			$("tr.owner.friendsonly").style.display = "block";
		}

		$("owner.picture").style.width = "auto";
		_makeReflection($("owner.picture"), owner.picture_url2);
	
	},

	setValue: function(id, value) {
		if (value) {
			$(id).innerHTML = value;
			if ($("tr."+id)) {
				$("tr."+id).style.display = "";
			}
		}
	},

	onClick_ChangePicture: function() {
		document.location.href = "/Member/my_info.php";
	},

	onClick_SendMessage: function() {
		if (!nasc.User.checkLogin()) {
			return false;
		}

		nasc.SystemMenu.onCommand( isMyFriend?"Send Message":"Request Friend" );
	},

	onClick_EditStatusMessage: function() {
		$("owner.status_msg").style.display = "none";
		$("status_message_button").style.display = "none";
		$("status_message_edit").style.display = "";

		var text = $("owner.status_msg").innerText;

		$("status_message_input").value = (text=="")?"is ":text;
		$("status_message_input").select();
		$("status_message_input").focus();
	},

	onClick_SaveStatusMessage: function() {
		var status_msg = $("status_message_input").value;

		$("owner.status_msg").innerText = status_msg;
		
		$("status_message_edit").style.display = "none";
		$("status_message_throbber").style.display = "";

		var params={
			method: "member.setstatusmsg",
			msrl: nasc.User.getSSN(),
			status_msg: status_msg,
			callback: "Profile.onComplete_SaveStausMessage"
		}

		nus.io.ScriptRequest.sendRequest(nasc.API_URL, params, null, "Profile.onComplete_SaveStausMessage()");		
	},

	onComplete_SaveStausMessage: function(rsp) {
		$("status_message_throbber").style.display = "none";
		this.onClick_CancelStatusMessage();
	},

	onClick_CancelStatusMessage: function() {
		

		$("owner.status_msg").style.display = "";
		$("status_message_button").style.display = "";
		$("status_message_edit").style.display = "none";
	}

}

function _makeReflection(img, url) {
	img.onload = _onload_image;
	img.src = url;
}

function _onload_image() {
	this.onload = null;

	var r = nus.effect.Reflection.makeReflection(this, this.width, this.height, 0.3, 0.3);
	if (nus.isFF) {
		r.style.margin ="-2px 0px";		
	}
	else {
		r.style.margin ="1px 0px";
	}

	if (this.width>100) {
		this.width=100;
		r.style.width = 100+"px";
	}
	
	this.insertAdjacentElement("afterEnd", r);
	
	var rc = nus.dom.getObjectRect(r);
	
	if (isOwner) {
		$("button_edit_account").style.margin = -(rc.getHeight()-20)+"px 0px 0px 0px";
	}
	else {
		$("button_send_message").style.margin = -(rc.getHeight()-20)+"px 0px 0px 0px";
	}
}


////////////////////////////////////////////////////////////////////////////////////////////
// ::Favorite

var FAVORITE_ITEM_TEMPLATE = [
	"<div class='item' id='fav_{itemsrl}' onmouseover='$addClassName(this, \"focused\");' onmouseout='$removeClassName(this, \"focused\")'>",
		"<label class='title'>{title}</label>",
		"<a href='javascript:void(0);' onclick='Favorite.onEdit(this.parentNode);return false;' class='tool'>edit</a>",
		"<a href='javascript:void(0);' onclick='Favorite.onDelete(this.parentNode);return false;' class='tool'>delete</a>",
		"<pre class='contents' wrap='soft'>{contents} </pre>",
	"</div>"
]


var Favorite = nus.ui.FormEditor.createInstance({
	ID: "Favorite",

	instanceName: "favorites",
	itemTemplate: FAVORITE_ITEM_TEMPLATE,
	requestURL: API_URL,
	itemInitialData: {itemsrl:0, title:"", contents:""},

	makeItems: function(data_list) {
		this._data_list = data_list;
		var html_list = data_list.forEach(function(data, index) {
			if (data.contents == "") {
				data.contents = "►";
			}
			else {
				data.contents = data.contents.replace(/\r\n/g, "<br/>").replace(/[\n|\r]/g, "<br/>");
			}

			return FAVORITE_ITEM_TEMPLATE.toHTML(data);
		});

		$(this.itemListID).innerHTML = html_list.toHTML();
	},

	onUpdateForm: function(form, item) {
		form.title.value = $node(item, "title").innerText;
		form.contents.value = $node(item, "contents").innerText.trimLeft();

		if (form.contents.value == "►") {
			form.contents.value = "";
		}

	},

	onUpdateItem: function(item, data, form) {
		if (!this.checkValidString(form.title, 200, "Please type in category") ||
			!this.checkValidString(form.contents, 200, "Please type in your favorites") ) {
			return false;
		}
		
		return nus.ui.FormEditor.superCall(this, "onUpdateItem", arguments);	

	},

	onSendRequest: function(request_type, data, item) {
		var successHandler = null;
		var errorHandler = null;

		if (request_type=="save") {
			var params = {
				method: "profile.setfavorite",
				callback: this.ID+".onSaveSuccess",
				msrl: pageOwnerSrl,
				itemsrl: this.getItemSerial(item)
			}
			_copyProperty(params, data);
			errorHandler = this.ID+".onSaveError()";
		}
		else if (request_type == "delete") {
			var params = {
				method: "profile.deletefavorite",
				callback: this.ID+".onDeleteSuccess",
				msrl: pageOwnerSrl,
				itemsrl: this.getItemSerial(item)
			}
			errorHandler = this.ID+".onDeleteError()";
		}

		this._request = nus.io.ScriptRequest.sendRequest(API_URL, params, successHandler, errorHandler);
	},

	onSaveSuccess: function(rsp) {
		if (rsp.statusCode != "ok") {
			this.onSaveError(rsp);
			return;
		}

		this._editing_item.id = "fav_"+rsp.itemsrl;
		
		nus.ui.FormEditor.superCall(this, "onSaveSuccess", arguments);
	}

});



////////////////////////////////////////////////////////////////////////////
// ::Question

var QUESTION_LIST = [
	["You meet aliens, what would you do?",
	"You win a lottery, what would you do?",	
	"You are alone in Island, what would you do?",
	"Your bf/gf cheats on you, what would you do?",
	"You are the US President, what would you do?",
	"You witness a murder, what would you do?"
	],
	["When do you get excited?",
	"When do you get lonely?", 
	"When do you get hyper?", 
	"When do you get angry?",
	"When do you get embarrassed?",
	"When do you get depressed?"
	],
	["Who’s the smartest friend?",
	"Who’s the loudest friend?",
	"Who’s the weirdest friend?",
	"Who’s the funniest friend?",
	"Who’s the most fashionable friend?",
	"Who’s the most trustworthy friend?"
	],
	["Define \"Love\"",
	"About your first love",
	"Do you favor guys or girls",
	"Turn-Ons?",
	"Turn-Offs?",
	"Do you believe love at first sight?"
	],
	["Last time you cried?",
	"Last time you showered?", 
	"Last time you kissed?",
	"Last time you skipped school?",
	"Last time you went clubbing?",
	"Last time you asked out someone?"
	],
	["What are you so into?",
	"What are you watching?",
	"What are you listening to?", 
	"What are you thinking of?",
	"What are you waiting for?",
	"What are you dreaming of?"
	],
	["When do you feel like dying?",
	"When do you feel like drinking?",
	"When do you feel like shopping?",
	"When do you feel like traveling?",
	"When do you feel like falling in love?",
	"When are you proud of yourself?"
	],
	["Where do want to live in?",
	"When do you want to get married?",
	"Place of honeymoon",
	"Future profession",
	"Car of your dreams",
	"Picture yourself 10 years from now"
	]
]


var QUESTION_ITEM_TEMPLATE = [
	"<div class='item' id='quest_{itemsrl}' onmouseover='$addClassName(this, \"focused\");' onmouseout='$removeClassName(this, \"focused\")'>",
		"<span style='font-weight:bold;color:#008AFF;'>Q : </span><span class='question'>{question}</span>",
		"<a href='javascript:void(0);' onclick='Question.onEdit(this.parentNode);return false;' class='tool'>edit</a>",
		"<a href='javascript:void(0);' onclick='Question.onDelete(this.parentNode);return false;' class='tool'>delete</a>",
		"<br/>",
		"<span style='font-weight:bold;color:#77DB01;margin:0px 0px 0px 1px;'>A : </span><pre class='answer' style='display:inline;'>{answer} </pre>",
	"</div>"
]


var Question = nus.ui.FormEditor.createInstance({
	ID: "Question",

	instanceName: "question",
	itemTemplate: QUESTION_ITEM_TEMPLATE,
	requestURL: API_URL,
	itemInitialData: {itemsrl:0, question:"", answer:""},
	
	bubble_tip: null, 


	_init: function() {
		this.bubble_tip = nus.ui.BubbleTip.createInstance({
			width: (nus.isIE6)?400:0,
			zIndex: 100
		});
	},

	makeItems: function(data_list) {
		var _template = this.itemTemplate;
		this._data_list = data_list;
		var html_list = data_list.forEach(function(data, index) {
			data.answer = data.answer.replace(/\r\n/g, "<br/>").replace(/[\n|\r]/g, "<br/>");
			return _template.toHTML(data);
		});

		$(this.itemListID).innerHTML = html_list.toHTML();
	},

	onChangeCategory: function(selectedIndex) {
		select = this.bubble_tip.$node(1, "bubble_tip_contents", "examples_block", "examples");
		select.innerHTML = "";

		var html = QUESTION_LIST[ selectedIndex ].forEach(function(e, index) {
			//return "<option>"+e+"</option>";
			var opt = document.createElement("OPTION");
			opt.selected = (index == 0);
			opt.innerText = e;
			select.appendChild(opt);
		});

		//select.innerHTML = html.toHTML();
	},

	onApplyExample: function() {
		select = this.bubble_tip.$node(1, "bubble_tip_contents", "examples_block", "examples");

		var form = $(this.formID);
		form.question.value = select.options[select.selectedIndex].innerText;
		form.answer.select();
		form.answer.focus();
	},

	onEdit: function() {
		Gauge.onCancel();
		nus.ui.FormEditor.superCall(this, "onEdit", arguments);

		var rc = nus.dom.getObjectRect( $(this.formID) );
		this.bubble_tip.show(rc.right+20, rc.top, $("question_example").innerHTML, "left");
		
		var category = this.bubble_tip.$node(1, "bubble_tip_contents", "category_block", "category");
		this.onChangeCategory(category.selectedIndex);
	},

	onCancel: function() {
		nus.ui.FormEditor.superCall(this, "onCancel", arguments);
		this.bubble_tip.hide();
	},

	onUpdateForm: function(form, item) {
		form.question.value = $node(item, "question").innerText;
		form.answer.value = $node(item, "answer").innerText.trimLeft();
	},

	onUpdateItem: function(item, data, form) {
		if (!this.checkValidString(form.question, 200, "Please type in or select one from sample questions") ||
			!this.checkValidString(form.answer, 200, "Please type in your answer") ) {
			return false;
		}


		return nus.ui.FormEditor.superCall(this, "onUpdateItem", arguments);	
/*		
		$node(item, "question").innerText = data.question;
		$node(item, "answer").innerText = data.answer;
		return true;
*/
	},

	onSendRequest: function(request_type, data, item) {
		var successHandler = null;
		var errorHandler = null;

		if (request_type=="save") {
			var params = {
				method: "profile.setquestion",
				callback: this.ID+".onSaveSuccess",
				msrl: pageOwnerSrl,
				csrl: 0,
				itemsrl: this.getItemSerial(item)
			}
			_copyProperty(params, data);
			errorHandler = this.ID+".onSaveError()";
		}
		else if (request_type == "delete") {
			var params = {
				method: "profile.deletequestion",
				callback: this.ID+".onDeleteSuccess",
				msrl: pageOwnerSrl,
				itemsrl: this.getItemSerial(item)
			}
			errorHandler = this.ID+".onDeleteError()";
		}

		this._request = nus.io.ScriptRequest.sendRequest(API_URL, params, successHandler, errorHandler);
	},

	onSaveSuccess: function(rsp) {
		if (rsp.statusCode != "ok") {
			this.onSaveError(rsp);
			return;
		}

		this._editing_item.id = "quest_"+rsp.itemsrl;
		
		
		nus.ui.FormEditor.superCall(this, "onSaveSuccess", arguments);
	}

});


////////////////////////////////////////////////////////////////////////////
// ::Gauge

var GaugeItem = nus.dom.DivClass.extend({
	
	_value: 0,
	_is_editing: false,

	attach: function(element) {
		nus.dom.DivClass.superCall(this, "attach", arguments);
	},

	updateStatus: function() {
		var value = this.getValue();
		value = Math.min(value,91);
		this.$node("title1").style.fontSize = 10+(10-value/10)+"px";
		this.$node("title2").style.fontSize = 10+(value/10)+"px";
		this.$node("volume", "gauge_bar").style.marginLeft = -205+(value*2)+"px";
	},

	getValue: function() {
		return this._value;
	},

	setValue: function(value) {
		this._value = value;
		this.updateStatus();
	},

	_mousedown_Handler: function (ev){
		if (!$hasClassName(ev.srcElement, "gauge_bar") || !this._is_editing) {
			return;
		}

		nus.dom.DivClass.superCall(this, "_mousedown_Handler", arguments);
	},

	onMouseDown: function(ev) {
		this.onMouseMove(ev);
	},

	onMouseMove: function(ev) {
		//if (!isOwner) return;
		if (!this._isLButtonDown) return;
		if (ev.srcElement != this.$node("volume", "gauge_bar")) {
			return;
		}

		var x = ev.offsetX;
		var value = (parseInt(ev.srcElement.style.marginLeft)+x)/2;
		this.setValue(value);
	}

});



var GUAGE_ITEM_TEMPLATE = [
	"<div class='item' id='gauge_{itemsrl}' onmouseover='$addClassName(this, \"focused\");' onmouseout='$removeClassName(this, \"focused\")'>",
		"<div class='title1'>{title1}</div>",
		"<div class='volume'><img class='gauge_bar' src='/Home/app/profile/images/gauge_bar.gif'></div>",
		"<div class='title2'>{title2}</div>",
		"<div style='clear:both;font-size:1px;width:1px;height:1px;'></div>",
		"<div align='center' style='margin:0px 0px 0px 0px;height:16px;'>",
			"<a href='javascript:void(0);' onclick='Guage.onEdit(this.parentNode.parentNode);return false;' class='tool' >edit</a>",
			"<a href='javascript:void(0);' onclick='Guage.onDelete(this.parentNode.parentNode);return false;' class='tool' >delete</a>",
		"</div>",
	"</div>"
]


var Guage = nus.ui.FormEditor.createInstance({
	ID: "Gauge",

	instanceName: "gauge",
	itemTemplate: GUAGE_ITEM_TEMPLATE,
	requestURL: API_URL,
	itemInitialData: {itemsrl:0, title1:"", title2:"", volume:50},

	_item_gauge_list: [],
	_editor_gauge: null, 

	bubble_tip: null,

	_init: function() {
		nus.ui.FormEditor.superCall(this, "_init", arguments);

		this._editor_gauge = this.subclassItem($("gauge_editor"), 50);
		this._editor_gauge._is_editing = true;

		this.bubble_tip = nus.ui.BubbleTip.createInstance({
			width: (nus.isIE6)?400:0,
			zIndex: 100
		});
	},

	makeItems: function(data_list) {
		this._data_list = data_list;
		/*
		var _template = this.itemTemplate;
		var html_list = data_list.forEach(function(data, index) {
			return _template.toHTML(data);
		});

		$(this.itemListID).innerHTML = html_list.toHTML();
		*/

		$childByClass(this.itemListID, "item").forEach(function(item, index) {
			Gauge.subclassItem(item, parseInt( Gauge._data_list[index].volume ));
		});

	},

	subclassItem: function(item, value) {
		var obj = new GaugeItem;
		obj.attach(item);
		obj.setValue(value);

		this._item_gauge_list.push(obj);

		return obj;
	},

	onAdd: function() {
		var html = this.itemTemplate.toHTML(this.itemInitialData);
		$(this.itemListID).insertAdjacentHTML("beforeEnd", html);
		var new_item = $node(this.itemListID, -1);
		$addClassName(new_item, "new_item");

		var new_gauge = this.subclassItem(new_item, 50);
		this.onEdit(new_item);
	},

	onApplyExample: function() {
		select = this.bubble_tip.$node(1, "bubble_tip_contents", "examples_block", "examples");

		var temp = select.options[select.selectedIndex].innerText.split("/");

		var form = $(this.formID);
		form.title1.value = temp[0].trim();
		form.title2.value = temp[1].trim();
		form.title1.select();
		form.title1.focus();
	},

	onEdit: function() {
		Question.onCancel();
		nus.ui.FormEditor.superCall(this, "onEdit", arguments);

		var rc = nus.dom.getObjectRect( $(this.formID) );
		this.bubble_tip.show(rc.right+20, rc.top, $("gauge_example").innerHTML, "left");
	},

	onCancel: function() {
		nus.ui.FormEditor.superCall(this, "onCancel", arguments);
		this.bubble_tip.hide();
	},


	onGetFormData: function() {
		var data = nus.ui.FormEditor.superCall(this, "onGetFormData", arguments);
		data.volume = this._editor_gauge.getValue();

		return data;
	},

	onUpdateForm: function(form, item) {
		form.title1.value = $node(item, "title1").innerText;
		form.title2.value = $node(item, "title2").innerText;

		var item_gauge = this._item_gauge_list.find(function(e) {return e.$ == item});
		this._editor_gauge.setValue(item_gauge.getValue());

	},

	onUpdateItem: function(item, data, form) {
		if (!this.checkValidString(form.title1, 50, "Please type in or select one from examples") ||
			!this.checkValidString(form.title2, 50, "Please type on both sides") ) {
			return false;
		}
	
		$node(item, "title1").innerText = data.title1;
		$node(item, "title2").innerText = data.title2;
		
		var item_gauge = this._item_gauge_list.find(function(e) {return e.$ == item});
		item_gauge.setValue( this._editor_gauge.getValue() );

		return true;
	},

	onSendRequest: function(request_type, data, item) {
		var successHandler = null;
		var errorHandler = null;

		if (request_type=="save") {
			var params = {
				method: "profile.setguage",
				callback: this.ID+".onSaveSuccess",
				msrl: pageOwnerSrl,
				itemsrl: this.getItemSerial(item)
			}
			_copyProperty(params, data);
			errorHandler = this.ID+".onSaveError()";
		}
		else if (request_type == "delete") {
			var params = {
				method: "profile.deleteguage",
				callback: this.ID+".onDeleteSuccess",
				msrl: pageOwnerSrl,
				itemsrl: this.getItemSerial(item)
			}
			errorHandler = this.ID+".onDeleteError()";
		}

		this._request = nus.io.ScriptRequest.sendRequest(API_URL, params, successHandler, errorHandler);
	},

	onSaveSuccess: function(rsp) {
		if (rsp.statusCode != "ok") {
			this.onSaveError(rsp);
			return;
		}

		this._editing_item.id = "gauge_"+rsp.itemsrl;
		
		
		nus.ui.FormEditor.superCall(this, "onSaveSuccess", arguments);
	}
});


////////////////////////////////////////////////////////////////////////////////////////////
// Pagelist

var PAGELIST_ITEM_TEMPLATE = [
		"<a href='/"+nus.env.address.path[0]+"/{listsrl}' class='item' onmouseover='Pagelist.onMouseOver(this)' onmouseout='Pagelist.onMouseOut(this)'  onclick='Pagelist.onClick(this);return false;' style='left:{left}px;top:{top}px;color:{color};font-size:{fontsize}px;text-decoration:none;'>{title}</a>"
]

var Pagelist = {
	_list : [],
	_colors:["#CDEB8B", "#C3D9FF", "#36393D", "#CC0000", "#FF7400", "#008C00", "#4096EE", "#FF0084", "#C79810", "#73880A", "#6BBA70"],

	init: function(data_list) {
		this._list = data_list;

		var temp = [];
		this._list.forEach(function(page) {
			var i=0;
			for(i=0;i<temp.length;i++) {
				if (page.regdate < temp[i].regdate) {
					break;
				}
			}
			page.title = page.title.decodeSpecialChars();
			temp.insert(page, i);
		});
		
		this._list = temp;
		
		this.update();
		
		nus.io.ScriptRequest.sendRequest("http://snapshot.mail-pagii.com/get_pages.asp?callback=Pagelist.onLoadSnapshot&msrl="+pageOwnerSrl, null);
	},

	update: function() {
		var pagelist_div  = $("pagelist_contents");
		pagelist_div.innerHTML = "";

		var count = Math.min(this._list.length, 10);
		var y = parseInt(Math.random()*5)*25;

		for(i=0;i<count;i++) {
			this._list[i].color = this._colors[i];
			this._list[i].fontsize = 22-i*1;
			var html = PAGELIST_ITEM_TEMPLATE.toHTML(this._list[i]);
		
			var item = null;
			var children = pagelist_div.childNodes;
			if (i>0) {
				children[ parseInt(Math.random()*children.length) ].insertAdjacentHTML("beforeBegin", html);
			}
			else {
				pagelist_div.insertAdjacentHTML("beforeEnd", html);
			}

			y += 25;
			if (y>125) {
				y = 15;
			}
		}
	},

	onMouseOver: function(item) {
		this._save_item_style = item.style.cssText;
		item.style.color = "#ffffff";
		item.style.backgroundColor = "#606060";
		//item.style.fontSize = parseInt(item.style.fontSize)+2+"px";
	},

	onMouseOut: function(item) {
		item.style.cssText = this._save_item_style;
	},

	onClick: function(link) {
		document.location.href = link.href;
	},

	onLoadSnapshot: function(rsp) {
		if (rsp.status!="ok") return;
		
		var html = [];
		for(var i=0;i<rsp.total_count;i++) {
			var page = rsp.pages[i];
			var path = ((Math.floor(page.srl/1000000))%1000).toStringfy(3)+"/"+((Math.floor(page.srl/1000))%1000).toStringfy(3)+"/"+(page.srl%1000).toStringfy(3)+"/"+page.srl+"_t.jpg";
			var title = "";
			var page_data = this._list.find("e.listsrl == "+page.srl);
			if (page_data) {
				title = page_data.title;
			}

			html.push("<a href='/"+pageOwnerSrl+"/"+page.srl+"' class='snapshot_link'><img src='http://snapshot.mail-pagii.com/images/"+path+"' title=\""+title+"\" class='snapshot'/></a>");
		}
		$("page_snapshot").innerHTML = html.toHTML();
		$("page_snapshot").style.display = "block";
	}

}


////////////////////////////////////////////////////////////////////////////////////////////
// comments

var Comments = {
	width:450,
	_isPrivate: true,
	_isLoadComplete: false,
	_board_id: 0,
	_is_private: false,

	init: function() {
		$("comment_list").innerHTML = "<iframe id='comment_iframe' frameborder='no' width='450' scrolling='no' src='/Home/modules/comment/skin/profile/list.html' style='visibility:hidden;' onload='Comments.onLoad_Iframe()'></iframe>";
	},

	onLoad_Iframe: function() {
		var iframe = $("comment_iframe");
		iframe.contentWindow.init(this);
		iframe.style.visibility = "inherit";
		this._isLoadComplete = true;
	},

	autoSize: function() {

		var asp = $("comment_iframe");
		asp.contentWindow.resize(this.width, 0);
		var size = asp.contentWindow.getScrollSize();
		asp.height = Math.max(size.h,500);

		updateLayout();
	},
	
	setBoardInfo: function(id, isPrivate) {
		this._board_id = id;
		this._is_private = isPrivate;

		if (isOwner) {

			//var html = ["<label style='margin:0px 0px 0px 15px;'><input type='checkbox' id='comment_setting_privacy' onclick='Comments.onChangePrivacy(this.checked);' ",
			//	isPrivate? " checked='true'" : "", 
			//	"></input> Only friends can add comments</label>"
			//];

			//$("comment_setting").innerHTML = html.toHTML();

		}
		else {
		}
	},

	onChangePrivacy: function(isPrivate) {
		if (!isOwner) return;

		if (isPrivate) {
			alert(MSG_COMMENT_FRIEDNS_ONLY);
		}
		else {
			alert(MSG_COMMENT_ANYONE);
		}

		$("comment_setting").style.display = "none";
		$("comment_setting_throbber").style.display = "";

		this._is_private = isPrivate;
		
		var params={
			method: "board.setattr",
			owner_msrl: nasc.User.getSSN(),
			boardtype  : "CW",
			id : this._board_id,
			boardtitle: " ",
			boarddesc: " ",
			openlevel: (this._is_private)?"F":"P",
			callback: "Comments.onCompleteChangePrivacy"
		}

		nus.io.ScriptRequest.sendRequest(nasc.API_URL, params);
			
		//this.getAsp().contentWindow.CommentList.setPrivacy(this._is_private);
	},

	onCompleteChangePrivacy: function(rsp) {
		$("comment_setting").style.display = "";
		$("comment_setting_throbber").style.display = "none";
	},

	uploadImage: function() {
		nasc.ImageUpload.doUpload(1, $callback(Comments, Comments.onUploadImageComplete));
	},
	onUploadImageComplete: function(result) {
		$("comment_iframe").contentWindow.insertCommentImage(result[0].path);
	}
}



//////////////////////////////////////////////////////////////////////////////
//

var FRINDE_ENTRY_TEMPLATE = [
	"<div class='friend_entry' id='friend_{index}'>",
		"<div class='photo'>",
			"<a href='{friend_url}/profile' onclick='Toolbox.gotoHome(this);return false;'>",
				"<img src='{thumbnail}' style='width:{photo_size}px;' onfocus='this.blur()' ",
				" onload='Friends._onload_thumbnail(this)'  onmouseover='Friends.onRollOver(window.event || arguments[0], this, {index});' onmouseout='Friends.onRollOut(window.event || arguments[0], this, {index});' />",
				"</a>",
		"</div>",
		"<div class='info'>",
			"<div class='name'><a href='{friend_url}/profile'  onclick='Toolbox.gotoHome(this);return false;' rel='friend'>{name}</a></div>",
			"</div>",
		"</div>",
		"<div class='delimeter'></div>",
	"</div>"
];


var Friends = {

	_friends_list: null,
	

	init: function() {
	},

	readList: function(page) {

		var params = {
			method: "friend.getlist",//"msglist",
			return_type: "json",
			callback: "Friends.onGetListComplete",
			msrl: pageOwnerSrl,
			pageno: page,
			memperpage: 20,
			isfriend:1,
			newsfeed:0
		}

		this._request = nus.io.ScriptRequest.sendRequest(API_URL, params, null, "Friends.onGetListError(rsp)");
	},

	onGetListComplete : function(rsp) {
		if (rsp.statusCode != "ok") {
			return;
		}

		this.update(rsp);
		this.displayFriendsList(rsp.friends);

		this._request.setComplete();
		this._request = null;
	},

	onGetListError : function(rsp) {

	},

	getPhotoSize : function(intimacy) {
		var size = 100;
		size += intimacy/100;
		if (size>120) size = 120;

		return size;
	},

	_onload_thumbnail: function(img) {

		var r = nus.effect.Reflection.makeReflection(img, img.width, img.height,0.3, 0.3);
		r.style.display="block";
		if (nus.isIE) {
			r.style.margin ="1px 0px";
		}
		else {
			r.style.margin ="-2px 0px";
		}
	
		img.parentNode.insertAdjacentElement("afterEnd", r);
	},

	makeEntryHTML : function(info, index) {
		info.index = index;
		info.friend_url = "/"+info.pageid; 
		info.photo_size = Friends.getPhotoSize(info.intimacy);

		return FRINDE_ENTRY_TEMPLATE.toHTML(info);
	},

	displayFriendsList: function(list) {
		this._list = list;

		// sign in, sign out 이 항상 바뀔수 있으므로 init가 아닌 display 전에 check하도록 한다.
		isOwner = nasc.User.isOwner();
		viewerSrl = nasc.User.getSSN();

		var html_list = list.forEach( function(e, index) {
			var html = Friends.makeEntryHTML(e, index);

			if (index>0 && index%4 == 3) {
				html += "<div class='line_break'></div>";
			}

			return html;
		});

		var html = "";
		if (list.length == 0) {
			if (isOwner) {
				html = "<div style='margin:10px;padding:10px;text-align:center;'><a href='javascript:void(0)' onclick='nasc.message.showInvitationBox();return false;' style='font-size:14px;color: #E07D08;text-decoration:underline;'>Invite your friends to join you on Pagii</a></div>";
			}
		}
		else {
			html = html_list.toHTML();
		}

		$("friends_list").innerHTML = html;
		updateLayout();
	},


	update: function(rsp) {

		var html = "";
		if (rsp.totfriends==0) {
			html = pageOwnerName+" has no friend.";
		}
		else if (rsp.totfriends == 1) {
			html = pageOwnerName+" has "+"1 friend.";
		}
		else {
			html = pageOwnerName+" has "+rsp.totfriends+" friends.";
		}

		$("friends_count").innerHTML = html + "&nbsp;<a href='http://"+document.location.hostname+"/"+pageOwnerSrl+"/friends' style='font-size:12px;text-decoration:underline;'>More ...</a>";	
		
	},

	onRollOver: function(ev, photo, index) {
		var info = this._list[index];
		var rc = nus.dom.getObjectRect(photo);
		var html = ["<div stryle='color:#000000;'>", (info.desc=="")?"No comment":info.desc,"<div/><br/>",
			"<div style='color:#B45000;'>", info.name, "<span style='color:#606060;'> ", info.status_msg, "</span><div/>", 
			"<div style='color:#606060;'>", 
			(info.gender=="m")? "Male" : "Female", 
			(info.age!=0)?" ("+info.age+") " : "", 
			(info.region !="")? " / "+info.region : "", "</div>"]

		bubble_tip.show(rc.left, rc.bottom+rc.getHeight()*0.3, html.toHTML());

		var tb = $("user_toolbox");
		var rc = nus.dom.getObjectRect(photo);
		nus.dom.move(tb, rc.right-60, rc.bottom-30);
		tb.style.display = "block";

		Toolbox.userURL = "/"+this._list[index].pageid;
		Toolbox.userName = this._list[index].name;
		Toolbox.msrl = this._list[index].fmsrl;
		Toolbox.ismyfriend = this._list[index].ismyfriend;

	},

	onRollOut: function(ev, photo, index) {
		bubble_tip.hide();

		var pos = nus.event.getEventPosition(ev);
		var rc = nus.dom.getObjectRect(photo);
		if (rc.ptInRect(pos.x ,pos.y)) {
			return;
		}

		var tb = $("user_toolbox");
		tb.style.display = "none";
	}

}


var Toolbox = {
	userURL: null,
	userName: null,
	msrl: 0,
	ismyfriend: null,

	_request: null,

	gotoHome: function(link) {
		var url = link?link.href : this.userURL+"/profile";
		gotoPage(url);
	},

	gotoUserPage: function() {
		gotoPage(this.userURL);
	},

	sendMessage: function() {
		if (!nasc.User.checkLogin()) {
			return false;
		}
		
		/*
		// 모든 ismyfriend가 0으로 내려온다.
		if (this.ismyfriend != null) {
			this._sendMessage();
			return;
		}
		*/

		if (this._request) {
			return;
		}

		nus.ui.showThrobber("Waiting...");

		var params = {
			method: "friend.ismyfriend",//"msglist",
			callback:"Toolbox.onCheckFriendComplete",
			fmsrl: this.msrl
		};
				
		this._request = nus.io.ScriptRequest.sendRequest(nasc.API_URL, params);
	},


	_sendMessage: function() {
		if (this.ismyfriend) {
			sendMessage(this.userName, this.msrl);
		}
		else {
			requestFriend(this.userName, this.msrl);
		}
	},

	onCheckFriendComplete: function(rsp) {
		nus.ui.hideThrobber();

		if (rsp.statusCode != "ok") {
			return;
		}
		
		this.ismyfriend = rsp.friend.isfriend;
		this._sendMessage();

		this._request.setComplete();
		this._request = null;
	}
}

function gotoPage(url) {
	document.location.href = url;
	//window.open(url, "_blank");
}

function sendMessage(name, msrl) {
	if (!nasc.User.checkLogin()) {
		return false;
	}

	nasc.message.showMessageBox("send_message", name, msrl);
}

function requestFriend(name, msrl) {
	if (!nasc.User.checkLogin()) {
		return false;
	}
	nasc.message.showMessageBox("request_friend", name, msrl);	
}


