/*
 vim: ts=4 sw=4 sts=4 noexpandtab
*/

var cs_list, cl_list, CSUsers, CLUsers;
var textarea_min_height = 1;
var splitter_height = 8;
var input_height = 130;
var textarea_max_height = 90;

var STATUS_UPDATE_TIMEOUT = 30000;

function guest_init(){
	try{

		var err_code = -3;//---
		if(arguments.callee.done)
			return;
		err_code = -2;//---
		arguments.callee.done = true;

		var _browser;
		if(_browser = navigator.userAgent.match(/firefox\/\d(\.\d){0,2}/gi)){
			firefox_version = _browser.toString().match(/[\d\.]+/);
		}

		err_code = -1;//---
		var exp = new Date();
		exp.setSeconds(exp.getSeconds() + cookieExpire);
		setCookie("ims_opened", 0, exp, "/");

		webcams_div = $("webcams_div").style;
		input_div = $("input_div").style;
		block = Array($("block1").style,$("block2").style,$('block3').style);

		err_code = "1111";//---

		contacts_div = $('contacts_div').style;

		err_code = "extract";//---
		var elements = $(
			"select_color", "selected_user_name"
			, "user_search_text", "tmpNode", "rooms_img", "rooms_list", "users_img"
			, "users_list", "textarea_div");
		extract(elements);

		textarea_div.onscroll = CHistory.onscroll;

		sizeInit();
		err_code = "onWindowResize";//---
		onWindowResize();

		UIinit();

		err_code = "Contacts.init";//---
		init_contacts();

		err_code = "88";//---
		toggle(false, "intro");
		_hide_loading();

		err_code = "99";//---
		var el = document.getElementsByTagName("img");
		for(var k in el){
			if(el[k].alt != null)
				el[k].title = el[k].alt;
			el[k].ondragstart = ret;
		}

		if(WEBCAMS_ENABLED)
			vchat_load();

		err_code = "handlers";//---
		window.onunload = unload;
		window.onbeforeunload = beforeunload;
		window.onresize = onWindowResize;
		document.body.onmousemove = userAction;

		if(send2uid != "")
			guest_get_user_info(send2uid, true);

		get_users_with_webcams();
		setTimeout(update_statuses, STATUS_UPDATE_TIMEOUT);

		init_error = false;
	} catch(e){
		toggle(true, "intro");
		e.title = "Init error(" + err_code + ")";
		var error = e.title + "\n" + debug(e) + e;
		alert(error);
		report_error(e);
	}
}

function init_contacts(){
	textarea = $("ims_textarea_div");
	cs_list = $("cs_list");
	cl_list = $("cl_list");
	CSUsers = new CUserlist(current_session, "cs");
	CLUsers = new CUserlist(contact_list, "cl");
	draw_contacts();
}

Contacts.safeSelect = function(uid){
	uid = uid || currentUserID;
	if(current_session[uid] != null)
		Contacts.select(uid, "cs");
	else if(contact_list[uid] != null)
		Contacts.select(uid, "cl");
}

Contacts.draw = function(section){
	if(section == "cs" || section == "cl")
		draw_contacts();
}

Contacts.setStatus = function(uid, status, broadcast){
	var refresh = {cs: false, cl: false};

	status = status || (current_session[uid] || contact_list[uid]).status;
	broadcast = vchat_broadcasters[uid] = broadcast != null
		? broadcast
		: vchat_broadcasters[uid];

	if(broadcast){
		switch(status){
			case "on":
				status = "broadcast";
				break;
			case "away":
				status = "away_broadcast";
				break;
		}
	}

	if(current_session[uid] != null)
		current_session[uid].status = status;
	if(contact_list[uid] != null)
		contact_list[uid].status = status;
	var cs_user = $("cs_" + uid + "_st");
	var cl_user = $("cl_" + uid + "_st");

	if(cs_user != null)
		cs_user.innerHTML = getStatusPic(status, contact_list[uid].gender);
	else
		refresh.cs = true;

	if(cl_user != null)
		cl_user.innerHTML = getStatusPic(status, contact_list[uid].gender);
	else
		refresh.cl = true;

	return refresh;
}

Contacts.select = function(uid, section, object){
	try{
		var _tmp = 0;
		var _user_select = (object != null);
		object = object || $(section + "_" + uid);

		if(object == null)
			throw new Error("can't find object: " + section + "_" + uid);

		object.className = "selected_user";
		if(currentUserObj != null && currentUserObj != object)
			currentUserObj.className = "user";

		var user = current_session[uid] || contact_list[uid];

		if(user == null)
			return;

		currentUserObj = object;
		currentSection = section;
		currentUser = user;
		currentUserID = uid;

		if(_user_select){
			vchat_select(uid, currentUser);
		}

		if(!History.isAvailable(uid)){
			var msg = {action:"guest_uinfo", uid: uid};
			ims_request(msg, _getUserHistory, uid, user.nick);
			showPleaseWait(true);
			textarea.innerHTML = "";
		} else {
			textarea.innerHTML = History.get(uid);
				CHistory.scroll_down(true);
		}
	}catch(e){
		e.title = "CContacts error - select(code:" + _tmp + ")";
		report_error(e, Contacts.select.caller, arguments);
	}
}

function closeSession(uid, section){
	try{
		var pos, user;

		if(section == "cs"){
			if(current_session[uid] == null)
				return;
			delete current_session[uid];
		}
		draw_contacts();

		if(array_len(contact_list) == 0 && array_len(current_session) == 0)
			textarea.innerHTML = "";

	}catch(e){
		e.title = "closeSession error(uid:" + uid + ")";
		report_error(e, closeSession.caller, arguments);
	}
}

function draw_contacts(){
	CSUsers.dropUsers();
	var users = array_len(current_session);
	if(users == 0){
			cs_list.innerHTML = "<span class='empty'>empty</span>";
	} else {
		CSUsers.draw(null, Contacts._cmpTime, cs_list);
	}

	CLUsers.dropUsers();
	var users = array_len(contact_list);
	if(users == 0){
			cl_list.innerHTML = "<span class='empty'>empty</span>";
	} else {
		CLUsers.draw(null, Contacts._cmpOrder, cl_list);
	}

	if(currentUserID != 0)
		Contacts.safeSelect(currentUserID);
}

function UIinit(){
	for(var k in obj_names){
		var el = $(obj_names[k]);
		if(el)
			_objects[obj_names[k]] = el.innerHTML;
	}
	for(var k in _images)
		_objects[k] = _createObject(_images[k]);

	cs_image = $("cs_image");
	cl_image = $("cl_image");
	cs_image.innerHTML = getObj("opened_section");
	cl_image.innerHTML = getObj("opened_section");

	if(webcams_panel == "off"){
		var pic = $("splitter_pic");
		pic.src = pic.src.replace('_up', '_down');
	}
}

function onWindowResize(){
	try{
		var size = getWindowSize();
		windowWidth = size[0];
		windowHeight = size[1];
		size[0] = size[0] < document_min_width ? document_min_width : size[0];
		size[1] = size[1] < document_min_height ? document_min_height : size[1];

		var _tmp = 0;//---
		block[1].width = block[2].width = block2_width = size[0] - block1_width - delimiter_width - 5;
		block[0].height = block[1].height = block_height = size[1] - 5;
		block[0].left = (block_left[0] = position ? block2_width + delimiter_width: 0);
		block[1].left = block[2].left =
			(block_left[1] = position ? 0 : block1_width + 2*isMozilla + delimiter_width);

		block[0].width = block1_width;

		if(WEBCAMS_ENABLED){
			var wc_height = webcams_div.height = webcams_panel == "off" ? (FlashSupport ? webcams_min_height : 1) : webcams_height;
		} else {
			var wc_height = webcams_height = -9;
			webcams_div.display = "none";
			$("splitter").style.display = "none";
		}

		//textarea_height = size[1] - input_height
		//  - 23 + isMozilla - splitter_height - wc_height;

		webcams_div.height = (webcams_height = size[1] - input_height
		  - 7 + isMozilla - splitter_height - textarea_height);
		/*
		if(textarea_height > textarea_min_height)
			textarea_div.style.height = textarea_height;
		else{
			//input_height += textarea_height - textarea_min_height;
			if(input_height > min_input_height){
				//input_div.height = input_height;
				textarea_div.style.height = (textarea_height = textarea_min_height);
			} else {
				webcams_div.height = (webcams_height += input_height - min_input_height);
				//input_div.height = (input_height = min_input_height);
				textarea_div.style.height = (textarea_height = textarea_min_height);
			}
		}
		*/

		contacts_div.height = contacts_div_height = block_height + isMozilla
			- 4 - contacts_div_margin - isMozilla*6;

		HideAllWindows();

	}catch(e){
		e.title = "onWindowResize error(code:" + _tmp + ")";
		report_error(e);
	}
}

function Resize(e, wc_clientY){
	try{
		if(resizing && wc_clientY == null){
			var py = isMozilla ? e.pageY : event.clientY + document.body.scrollTop;
			var wc = WEBCAMS_ENABLED ? (webcams_panel == "off" ? webcams_min_height : webcams_height) : -9;
			var shift = py - header_height - 5 - textarea_height
				- wc - scroller_height;

			shift = shift + textarea_height > textarea_min_height ? shift : textarea_min_height - textarea_height;
			shift = input_height - shift > min_input_height ? shift : input_height - min_input_height;

			textarea_div.style.height = (textarea_height += shift);

			input_div.height = (input_height -= shift);

		}else if(resizing_wc){
			var py = isMozilla ? e.pageY : (event ? event.clientY : wc_clientY) + document.body.scrollTop;
			var shift = py - header_height - 5 - webcams_height + 30;

			webcams_min_height = textarea_height + webcams_height - textarea_max_height;

			shift = shift + webcams_height > webcams_min_height ? shift : webcams_min_height - webcams_height;
			shift = textarea_height - shift > textarea_min_height ? shift : textarea_height - textarea_min_height;

			webcams_div.height = (webcams_height += shift);
			textarea_div.style.height = (textarea_height -= shift);

		}
	}catch(e){
	}
}

function sizeInit(){
	try{
		var _tmp = 0;
		size = getWindowSize();
		windowWidth = size[0];
		windowHeight = size[1];
		if(windowWidth < document_min_width)
			windowWidth = document_min_width;
		if(windowHeight < document_min_height)
			windowHeight = document_min_height;

		_tmp = 19;
		$("splitter").style.height = splitter_height;

		_tmp = 1;
		var size = getWindowSize();

		var max_input_height = size[1] - header_height - textarea_min_height - 6 - scroller_height;
		if(input_height > max_input_height)
			input_height = max_input_height;
		else if(input_height < min_input_height)
			input_height = min_input_height;
		input_div.height = input_height > 0 ? input_height : 0;

		textarea_div.style.height = (textarea_height = textarea_max_height);
		webcams_div.height = (webcams_height = size[1] - textarea_height - scroller_height - 140);
	}catch(e){
		throw new Error("size init error(code " + _tmp + "): windowWidth=" + windowWidth + "; windowHeight=" + windowHeight + "\n" + (e.message || e));
	}
}

function get_users_with_webcams(from_flash){
	for(var k in contact_list)
		delete contact_list[k];

	if(from_flash){
		var counter = 0;
		var users = "862_2691_666_6_1";//*************************
		for(var k in vchat_broadcasters){
			if(counter++ >= 20)
				break;
			users += (users == "" ? "" : "_") + k;
		}
		if(users != "")
			getUserInfo(users, _usersLoad, "cl");
	} else {
		var request = {service:"adviser", action: "guest_rnd_cams"};
		msgd_request(request, null, _usersLoad, "cl", null, null, null, true);
	}

}
function _usersLoad(req, section){
	var users = _getUserInfo(req);
	/*
	users = [
		{uid: 100, nick: "tt", gender: "woman", status: "on"}
		, {uid: 102, nick: "rr", gender: "man", status: "on"}
		, {uid: 103, nick: "ll", gender: "man", status: "on"}
		, {uid: 104, nick: "aaakkaaa", gender: "woman", status: "on"}
		, {uid: 105, nick: "aaaaaa", gender: "man", status: "on"}
		, {uid: 106, nick: "aaajjaaa", gender: "man", status: "on"}
		, {uid: 107, nick: "hh", gender: "man", status: "on"}
		, {uid: 108, nick: "gg", gender: "woman", status: "on"}
		, {uid: 109, nick: "aaaaaa", gender: "man", status: "on"}
		, {uid: 111, nick: "ff", gender: "man", status: "on"}
		, {uid: 112, nick: "dd", gender: "woman", status: "on"}
		, {uid: 113, nick: "qqq", gender: "man", status: "on"}
		, {uid: 114, nick: "zz", gender: "woman", status: "on"}
		, {uid: 115, nick: "aaavvaaa", gender: "man", status: "on"}
		, {uid: 116, nick: "bb", gender: "man", status: "on"}
	];
	/**/
	if(users != null){
		var man_count = 0;
		var woman_count = 0;

		for(var k in users){
			if(section == "cl"){
				add2cl(users[k].uid, users[k]);
				if(users[k].gender == "man")
					contact_list[users[k].uid].order = 1 + 2 * man_count++;
				else
					contact_list[users[k].uid].order = 2 * woman_count++;
			} else if(section == "cs"){
				add2cs(users[k].uid, users[k]);
			}
		}
		//alert(debug(current_session))
		draw_contacts();
	}
}

function start_broadcast(uid){
	vchat_broadcasters[uid] = now();
	Contacts.setStatus(uid, null, true);
	/*debug*/ return uid;
}

var old_vchat_handler = vchat_handler;
vchat_handler = function(command, param, param2){
	if(command != "open_user")
		old_vchat_handler(command, param, param2);
}

function update_statuses(){
	var users = {};
	for(var k in current_session)
		users[k] = 1;
	for(var k in contact_list)
		users[k] = 1;
	var uids = implode("_", users, false);

	if(uids == "")
		return;

	var msg = {action:"guest_ustatus", uids: uids};
	ims_request(msg, _update_statuses);
	setTimeout(update_statuses, STATUS_UPDATE_TIMEOUT);
}

function _update_statuses(req){
	var onliners = {};
	var statuses = _parseStatuses(req.responseJS[0]);

//for(var k in req.responseJS)
//		onliners[req.responseJS[k]] = 1;
//	alert("_update_statuses - id: " + currentUserID + "\n>>>" + debug(vchat_broadcasters) + "\n>>>>>" + debug(onliners));

	for(var k in current_session){
		current_session[k].status = statuses ? statuses.getStatus(k) : "off";
	}
	for(var k in contact_list){
		if(vchat_broadcasters[k] == null)
			contact_list[k].status = statuses ? statuses.getStatus(k) : "off";
	}
	draw_contacts();
}

function _getUserInfo(req){

	var res = Array(), uinfoes;

  	if(req.responseJS[0] != null && req.responseJS[0].uinfoes != null){
		uinfoes = req.responseJS[0].uinfoes;
		statuses = _parseStatuses(req.responseJS[0].statuses);
	} else {
		uinfoes = req.responseJS;
	}

	for(var k in uinfoes){
		var uinfo = uinfoes[k];
		History.save(uinfo.uid, uinfo.nick, [uinfo]);
		var uinfo_resp = {
				uid: uinfo.uid,
				nick: uinfo.nick,
				status: statuses ? statuses.getStatus(uinfo.uid) : "off",
				gr_id: uinfo.group_id || -1,
				gender: uinfo.gender == 1 ? "man" : "woman",
				mass_ignore: uinfo.mass_ignore,
				cname: uinfo.cname || "",
				age: uinfo.age || 0,
				ignore: uinfo.ignore,
				cid: uinfo.cid
			}
		res.push(uinfo_resp);
	}
	return res.length == 0 ? null : res;
}

function activateSession(){
}

function activateCam(uid){
	/*
	if(contact_list[uid] != null || current_session[uid] != null){
		Contacts.safeSelect(uid);
		return;
	}
	*/
	guest_get_user_info(uid, true);
}

function guest_get_user_info(uids, select){
	var msg = {action:"guest_uinfo", uid: uids};
	ims_request(msg, on_guest_user_info, select, uids);
	showPleaseWait(true);
	textarea.innerHTML = "";
}

function on_guest_user_info(req, select, uid){
	showPleaseWait(false);
	var users = _getUserInfo(req);
	if(users != null){
		for(var k in users)
			add2cs(users[k].uid, users[k]);
	}
	draw_contacts();
	if(select){
		Contacts.safeSelect(uid);
		vchat_select(uid, currentUser);
	}
}

function unload(){
}