/**
 * @author hammer
 */

window.onload = function () {
	if (USERID != "") {
		RelopiaRoot = new RelopiaPage();
		mynotifier = new RelopiaNotifier();
		initStatusPicker();
	} else {
		RelopiaRoot = new RelopiaPage();
	}
	var hlp = $$(".category_head .right")[0]
	if (hlp) {
		hlp.onclick = showHelp;
	}
}

var RelopiaPage = new Class.create();
RelopiaPage.prototype = {
	// Possibly unprototype - single object or function - attach it to window.root or something
	initialize: function () {
		this.application = null;
		this.hotbar = null;
		this.notifiers = null;
		this.cookies = null;
		if($('js_init')) {
			switch ($('js_init').className) {
				case "Relopia_Calendar":
					this.application = new Relopia_Calendar();
					break;
				case "TabWindow":
					this.application = new TabWindow("main");
					this.application.show_win();
					this.parseurl();
					break;
				case "AdressBook":
					this.application = new AddressBook();
					break;
				case "webSms": 
					window.MessageComposeWindow.ToPicker = new ToPicker("/ajax/AdressBook/SMSPicker", [$('toSms')]);
					new textLimiter($('charfree'),$('smstext'));
					break;
				case "MessageNew":	
					$("msg_draft").onclick = function ()  { SubmitMailDraft(); }
					break;
				case "search":
					urlstring = document.location.toString();
					showtab = urlstring.split("#show_")[1];
					if (showtab) {
						toggleSearch($(showtab+"_tab"));	
					}
					break;
				case "Tour":
					this.application = new Tour($('tour_controls'));
				default: 
					break;
			}
		}
	},
	parseurl: function () {
		urlstring = document.location.toString();
		url = urlstring.split("/");
		tabIndex = url[(url.length-1)];
		if ( tabIndex.substr(0,4) == "#tab" ) {
			tab = Number(tabIndex.substr(4,1));
			this.application.show_tab(null, tab);
		}
	}
}

var ToPicker = new Class.create();
ToPicker.prototype = {
	initialize: function (url, fields) {
		myself = this;
		this.resultset = null;
		this.fields = fields;
		/*
		this.ccBox = $("ccbox");
		this.toBox = $("tobox");
		this.bcBox = $("bcbox");
		*/
		this.topicker = $("topicker");
		this.targetfield = null;
		this.validTargets = new Array();
		url = Config._wroot + url;
		
		
		
		new Ajax.Request( url, {
			onComplete: function (transport) {
				myself.resultset = transport.responseText;
				myself.render(myself.topicker);
				for (var i = 0; i < myself.fields.length; i++) {
					new ToPickerField(myself.fields[i],myself)
				}
				/*
				new ToPickerField($("to_input"),this); 
				new ToPickerField($("bcc_input"),this);
				new ToPickerField($("cc_input"),this);*/
			}
		});
		document.onmousedown = ToPickerFieldEvents.looseFocus.bindAsEventListener(this);
	},
	render: function (el) {
		el.update(this.resultset);
		this.IEframe = document.createElement("iframe");
		this.IEframe.setAttribute("frameborder",0);
		this.IEframe.src = "/null";
		el.insertBefore(this.IEframe,this.topicker.down("ul"));
		
		el.down("ul").descendants().each( function (itm) {
			// Event.observe(itm,"click",ToPickerFieldEvents.itemClicked.bindAsEventListener(itm));
			itm.onmousedown = function () {
					tmp = 	window.MessageComposeWindow.ToPicker.targetfield.value.split(",");
					tmp = tmp.without(tmp.last());
					tmp = tmp.join(",");
					if (tmp != "") { tmp = tmp+","};  
					window.MessageComposeWindow.ToPicker.targetfield.value = tmp + itm.innerHTML.unescapeHTML() + ",";
					$("topicker").hide();
				};
			});
		var cwin = document.createElement("div");
		cwin.id = "picker_close";
		$(cwin).update("close");
		cwin.onclick = function () {
			$("topicker").hide();
		}
		el.insertBefore(cwin,this.topicker.down("ul"))
	},
	find: function (e) {
		str = e.value;
		str = str.split(",");
		str = str.last().strip();
		str = str.replace(" ","|");
		Expression = eval("/"+str+"/i");
		results = 0;
		if (!Expression) return;
		this.topicker.down("ul").descendants().each( function (itm) {
			if (Expression.test(itm.innerHTML) == false && Expression.test(itm.getAttribute("nicknames"))== false && Expression.test(itm.getAttribute("tags")) == false) {
					itm.className="invis";
				} else {
					itm.className="vis";
					results++;
				};
		});
		
		if ($("picked")) {
				$("picked").id = "";	
			}
		
		if (results > 0) {

			ttop = e.offsetTop + e.offsetParent.offsetParent.offsetTop + 20;
			lleft = e.offsetLeft + e.offsetParent.offsetLeft;
			
			this.topicker.setStyle({
				"top": ttop+"px" /*,
				 "left": lleft + "px"*/
			});
			this.topicker.show();
			hh = this.topicker.down("ul").getHeight();
			this.IEframe.style.height = hh;
			this.topicker.style.height = hh+"px";
			this.IEframe.style.width = this.topicker.getWidth();
			this.IEframe.style.border = "none";
			this.IEframe.style.zIndex = 1;
			this.IEframe.style.position = "absolute";
			this.IEframe.style.top = 0;
			this.IEframe.style.left = 0;
		
			this.targetfield = e;
			// e.next("div").show();
			this.topicker.down("ul").down("li.vis").id = "picked";
			this.topicker.down("ul").down("li.vis").focus();
			this.topicker.style.height = this.topicker.down("ul").getHeight();
		}
	}
}

var ToPickerField = new Class.create();
ToPickerField.prototype = {
	initialize: function (el,picker) {
		// this.htmlElement = el;
		this.htmlElement = el;
		this.ToPicker = picker;
		this.typing = false;
		this.timer = null;
		this.ToPickerFieldKeyEvent = ToPickerFieldEvents.key.bindAsEventListener(this);
		this.ToPickerFieldReset = ToPickerFieldEvents.keyreset.bindAsEventListener(this);
		this.ToPickerSelectUp = ToPickerFieldEvents.selectUp.bindAsEventListener(this);
		this.ToPickerSelectDown = ToPickerFieldEvents.selectDown.bindAsEventListener(this);
		this.ToPickerEnterSelected = ToPickerFieldEvents.enterSelected.bindAsEventListener(this);
		this.ToPickerBlur = ToPickerFieldEvents.looseFocus.bindAsEventListener(this);
		Event.observe(this.htmlElement,"keydown",this.ToPickerFieldKeyEvent);
		
		//Event.observe(this.htmlElement,"DOMFocusOut",this.ToPickerBlur);
	}	
}

var ToPickerFieldEvents = {
	key: function (e) {
		switch (e.keyCode) {
			case 38:
			this.ToPickerSelectUp();
			if (this.htmlElement.textLength) {
				endpos = this.htmlElement.textLength;
				this.htmlElement.setSelectionRange(endpos,endpos)
			} else {
				Event.stop(e);
				return false;
			}
			break;
			case 40:
			this.ToPickerSelectDown();
			if (this.htmlElement.textLength) {
				endpos = this.htmlElement.textLength;
				this.htmlElement.setSelectionRange(endpos,endpos)
			} else {
				Event.stop(e);
				return false;
			}
			break;
			case 13:
			if ($("topicker").visible()) {
				this.ToPickerEnterSelected();
				Event.stop(e);
				return false;
			}
			break;
			case 9:
			$("topicker").hide();
			break;
			case 27:
			$("topicker").hide();
			break;
			default:
			this.typing = true;
			if (this.timer != null) {
				clearTimeout(this.timer);
				this.timer = null;
			}
			this.timer = setTimeout(this.ToPickerFieldReset.bind(this), 1000);			
			break;
		}
		
	
	},
	keyreset: function (event) {
		this.typing = false;
		this.ToPicker.find(this.htmlElement);
	},
	selectUp: function (event) {
		nuw = $("topicker").down("ul li.vis#picked").previous("li.vis");
		if (nuw) {
			$("picked").id="";
			nuw.id="picked";
		} else {
			return;
		}
	},
	selectDown: function (event) {
		nuw = $("topicker").down("ul li.vis#picked").next("li.vis");
		if (nuw) {	
			$("picked").id="";
			nuw.id="picked";
		} else {
			return;
		}
	},
	enterSelected: function (event) {
		itm = $("topicker").down("ul li.vis#picked");
		tmp = this.ToPicker.targetfield.value.split(",");
		tmp = tmp.without(tmp.last());
		tmp = tmp.join(",");
		if (tmp != "") { tmp = tmp+","}; 
		this.ToPicker.targetfield.value = tmp + itm.innerHTML.unescapeHTML() + ",";
		
		if (this.htmlElement) {
			$("topicker").hide();
		} else {
			$(this).up(1).hide();	
		}
		
		if (this.htmlElement.selectionStart) {
			endpos = this.htmlElement.textLength;
			this.htmlElement.setSelectionRange(endpos,endpos)
		}
		
	},
	looseFocus: function (event) {
		e = event || window.event;
		t = e.target || e.srcElement;
		
		/*if (this.validTargets.member(t) == false ) {
			this.validTargets[0].hide();
			this.validTargets[1].hide();
			this.validTargets[2].hide();
		}/*
		/*
		if (t.id != this.htmlElement.next("div").id || t.id != this.htmlElement.id) {
			this.htmlElement.next("div").hide();	
		} else {
			console.log(t);
		}*/
	}
}

var RelopiaEvents = {
	Apicker_select: function (htmlEle) {
		this.owner.dataField.value += htmlEle.innerHTML+","; 
	}
}

var MessageComposeWindow = new Class.create();
MessageComposeWindow.prototype = {
	initialize: function () {
			window.MessageComposeWindow = this;
			
			if (document.getElementById("composewindow")) {
				window.onresize = function () {
					window.MessageComposeWindow.rescale();
				}
				if ($F("bcc_input") != "") $("bccon").show();
				if ($F("cc_input") != "") $("ccon").show();
				if ($("distron").down("select").value != "") $("distron").show();
				window.resizeTo(600, 700);
				this.rescale();
			}	
		
			topickerFields = new Array($("to_input"),$("cc_input"),$("bcc_input"));
			
			this.ToPicker = new ToPicker("/ajax/AdressBook/topicker", topickerFields);
			
			
		},
	rescale: function()  {
			th = window.innerHeight | window.document.documentElement.clientHeight;
			to = $("msgarea").offsetTop;
			ht = (th-to-30)+"px";
			
			$("msgarea").setStyle({
				"height": ht
				})
		}
	
}

function compose_mail (suffix) {
	window.open('/display/compose/'+suffix, suffix + '_compose', 'left=0,top=0,width=600,height=700,toolbar=0,location=0,status=0,menubar=0,resizable=1,scrollbars=0');	
}


function tab_toggle(o_ele, tab_prefix, fset) {
	if ($("tb_selected")) {
		$("tb_selected").id = "";
	}
	$(o_ele).id = "tb_selected";
	for (var i = 0, limit = $(tab_prefix).getAttribute("tabs"); i < limit; i++ ) {
		$(tab_prefix+"_"+i).style.display = "none"
	};
	$(tab_prefix+"_"+fset).style.display = "block"
}

function toggleSearch(o_ele) {
	o_ele = $(o_ele)
	oldSearch = $("subnav_selected").descendants()[0].href.split("_")[1];
	$(oldSearch).hide();
	$("subnav_selected").id = "";
	$(o_ele.href.split("_")[1]).show();
	o_ele.ancestors()[0].id = "subnav_selected";
}

function tabNav(tabElement) {
	var tabTarget = tabElement.href.split("show_")[1];
	var activeTab = $("tabActive");
	if (tabTarget) {
		if (activeTab) {
			$(activeTab.href.split("#show_")[1]).hide();
			activeTab.id = null;
			}
		tabElement.id = "tabActive";
		$(""+tabTarget+"").show();
		return false;
	}
	return true;
}

function initTabNav() {
	if ($("tabActive") && (document.location.toString().split("#").length > 1)) {
		$($("tabActive").href.split("#show_")[1]).hide();
		$("tabActive").id = null;
		$("tabBar").descendants().each( function (tab) {
			if (tab.href == document.location) tab.id = "tabActive";
		} );
	} 
}

function updateUserPic() {
	$("picContent").show();
	$("picContent").src = Config._wroot+"html/addimage";
}

function hideUpload() {
	$("picContent").hide();
	setTimeout(function () {$("personal-picture").src=$("personal-picture").src}, 6000)
}

function checkAll(sourceElement,formElement) {
	$(formElement).getElements().each( function (inputElement) {
		if (inputElement.type == "checkbox") {
			inputElement.checked = sourceElement.checked;
		}
	})
}

function ContactBulkActions() {
	document.forms["bulk_actions"].action = document.forms["bulk_actions"].elements["bulk_action"].value;
	document.forms["bulk_actions"].submit();
}

function setAction(form, action) {
	document.forms[form].action  = action;
	document.forms[form].submit();  
}

function RelopiaRegister() {
	rdata = $("register_form").getElements();
	empty = 0;
	errstring = "";
	rdata.each(function (ielement) {
		if (ielement.present() || ielement.type == "hidden") {
			if (ielement.hasClassName("error")) { 
				ielement.removeClassName("error");
				}
			return;
		} else {
			empty++;
			ielement.addClassName("error");
		}
	});
	if (empty > 0) {
		errstring += "Please fill out all fields\n";
	};
	
	if ( $("pass1").value != $("pass2").value ) {
		errstring += "Passwords do not match\n";
	};
	
	if ( $("pass1").value.length < 6) {
		errstring += "Password must be 6 characters long minimum.\n";
	};
	
	if ( $("pass1").value.length < 6) {
		errstring += "Password must be 6 characters long minimum.\n";
	};
	
	if (!$("agree").checked) {
		errstring += "You have to accept the Terms and Conditions.\n"
	}
	
	if (errstring != "") {
		alert(errstring);
	} else {
		$("register_form").submit();
	}
	
}

function initStatusPicker () {
	if (document.getElementById("onlinestatus")) {
	$("onlinestatus").onchange = function () {
		url = "/ajax/setstatus/change/" + $("onlinestatus").value;
		new Ajax.Request(url);	
	}
	}	
}



function showHint(num) {
	for (var i=1; i <= 10; i++) {
		if (i != num) { $("hint"+i).hide() } else { $("hint"+i).show() }
	}
}

RelopiaNotifier = new Class.create();
RelopiaNotifier.prototype = {
	initialize: function () {
		if (this.elemnt = $("notifier")) {
		this.contacts = $("notify_online");
		this.inbox = $("notify_mail");
		this.events = $("notify_event");
		this.invites = $("notify_invites");
		this.ims = $("notify_im");
		this.elemnt = $("notifier");
		this.nstart();
		}
	},
	nstart: function () {
		var notifier = this;
		this.contacts.className = this.inbox.className = this.events.className = this.invites.className = this.ims.className = ""; 
		var last = null;
		setonline = Config._wroot + "/setonline/";
		new Ajax.Request(setonline);
		url = Config._wroot + "/ajax/notifier/"
		new Ajax.Request(url, {
		onSuccess: function (transport,json) {
				dhash = eval('('+transport.responseText+')');
				var count = 0;
				
				if (dhash.contacts != "0") {
					notifier.contacts.show();
					notifier.contacts.up().show();
					notifier.contacts.down("span").update(dhash.contacts);
					last = notifier.contacts;
					count++;	
				} else {
					notifier.contacts.hide();
					notifier.contacts.up().hide();	
				}
				
				if (dhash.inbox != "0") {
					notifier.inbox.show();
					notifier.inbox.up().show();
					notifier.inbox.down("span").update(dhash.inbox);
					last = notifier.inbox;
					count++;
				} else {
					notifier.inbox.hide();
					notifier.inbox.up().hide();	
				}
				
				
				if (dhash.events) {
					notifier.events.show();
					notifier.events.up().show();
					notifier.events.down("span").update(dhash.events);
					notifier.events.href = dhash.nextevent;
					last = notifier.events;
					count++;
					} else {
					notifier.events.hide();
					notifier.events.up().hide();
					}
					
				if (dhash.invites != "") {
					notifier.invites.show();
					notifier.invites.up().show();
					notifier.invites.down("span").update(dhash.invites);
					last = notifier.invites;
					count++;
				} else {
					notifier.invites.hide();
					notifier.invites.up().hide();	
				}
					
				if (dhash.im_msgs.length > 0) {
					notifier.ims.show();
					notifier.ims.up().show();
					notifier.ims.down("span").update("");
					
					dhash.im_msgs.each(function (nick) {
						if (nick == "") return;
						sp = document.createElement("div");
						sp.className = "fcontrol";
						sp.id = "im_pop_"+nick;
						sp.innerHTML = "<img src='/static/img/icons/chat_icon.gif'> <font style='font-weight:bold; color: #fff;'>"+nick+"</font>";
						notifier.ims.down("span").appendChild(sp);
						
						sp.onclick = function (e) {
							im_popup(nick);
							}
					});
					last = notifier.ims;
					count++;
					if (notifier.ims.down("span").descendants().length == 0) {
						notifier.ims.hide();
						notifier.ims.up().hide();	
					}
				} else {
					notifier.ims.hide();
					notifier.ims.up().hide();
				}
				if (count > 0) {
					// notifier.elemnt.show();
					last.className = "noborder";
				} else {
					// notifier.elemnt.hide();
				}
		}
		})
		setTimeout( this.nstart.bind(this), (Config._timer*1000));
	}
}

window.changeLanguage= function(node) {
	document.langForm.submit();
}

function im_popup(username) {
	// UGLY fix for enabling more than one window...
	//Stamp = new Date(); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds()); s = (s.length > 1) ? s : "0"+s; m = (m.length > 1) ? m : "0"+m;
	window.open('http://www.relopia.com/chat/'+username+'/', name + '_im_'+username, 'left=0,top=0,width=320,height=380,toolbar=0,location=0,status=0,menubar=0,resizable=1,scrollbars=0');
		if ($("im_pop_"+username)) {
			$("notify_im").descendants()[0].removeChild($("im_pop_"+username));	
		}
		if ($("notify_im").descendants()[0].descendants().length == 0) {
			$("notify_im").hide();
		}
	
}

function shoutquote (htmlEle) {
	prfx = $(htmlEle).up('h5').innerHTML.split("|")[0].stripTags().strip();
	txt = $(htmlEle).up('div').down('p').innerHTML.stripTags().strip();
	lines_in = txt.split("\n");
	lines_out = new Array;
	var linecounter = 0;
	var charcounter = 0;
	line = "> ";
	txt_buffer_out = new Array;
	
	for (var i = 0, l = lines_in.length; i < l; i++) {
	
	if (lines_in[i].length < 75) {	
		lines_out.push("> "+lines_in[i]);
		} else {
			var tmpline = lines_in[i].split(" ");
			tmpout = new Array();
			tmpcounter = 0;
			for (var k = 0, tl = tmpline.length; k < tl; k++) {
				tmpcounter += tmpline[k].length;
				if (tmpcounter > 75) {
					lines_out.push("> " + tmpout.join(" "));
					tmpout = new Array();
					tmpout.push(tmpline[k]);
					tmpcounter = tmpline[k].length;
				} else {
					tmpout.push(tmpline[k]);
				}
			}
			lines_out.push("> " + tmpout.join(" "));
		}
	}
	
	txt = lines_out.join("\n");
	
	$("text_reply").value = "> " + prfx + "\n" + txt + "\n> --------------------------------------------\n";
	
}

function chkboxchk(cid) {
	$("chk"+cid).checked = true;
}

function SubmitMailDraft() {
	myform = $("sendmail"); // use prototype to get the form by ID.
	mypostdata = myform.serialize(true) // serialize the form for POST data (true flag)
	url = "/messaging/draft" // my controler for the draft
	new Ajax.Request(url, {method: "post",parameters: mypostdata});
	$("savedDraft").show();
}

function showHelp() {
	var loc_ = document.location.toString().split("/");
	window.open('/help/'+loc_[3]+'/', 'help', 'left=0,top=0,width=300,height=500,toolbar=0,location=0,status=0,menubar=0,resizable=1,scrollbars=1');
}

// Tour

var Tour = new Class.create();
Tour.prototype = {
	initialize: function (ctrlEle) {
		this.buttons = ctrlEle.getElementsBySelector("dt");
		this.areas = ctrlEle.getElementsBySelector("dd");
		this.picts = $("disp").getElementsBySelector("img");
		this.focused = $("first");
		this.fpict = $("pfirst");
		
		for (var i = 0, l = this.buttons.length; i < l; i++) {
			Event.observe(this.buttons[i],"click",TourEvents.evtClicked.bindAsEventListener(this,i))	
		}
		
	}
}

var TourEvents = {
	evtClicked: function (event,itm) {
		
		if ( this.focused != this.areas[itm] ) {
			if (this.focused != null) {
				document.getElementById("focused").id = "";
				Effect.BlindUp(this.focused, {duration: 0.4, transition: Effect.Transitions.linear});
				Effect.Fade(this.fpict)
			}
			this.buttons[itm].id = "focused";
			this.fpict = this.picts[itm];
			this.focused = this.areas[itm];
			Effect.BlindDown(this.focused, {duration: 0.4, transition: Effect.Transitions.linear});
			Effect.Appear(this.picts[itm]); 
		}
		
	}
}


// toggle elements in impressum
var lasteshown=null;

function imtoggle(eid) {
	if (lasteshown == null) {
		$("aboutname").hide();	
	} else {
		$(lasteshown).hide();
	}
	$(eid).show();
	lasteshown = eid;
}

function st_roll(ele) {
	if ($(ele).visible()) {
		new Effect.BlindUp(ele);
	} else {
		new Effect.BlindDown(ele);
	}
}

var textLimiter = new Class.create();
textLimiter.prototype = {
	initialize: function ( checkF, textF ) {
		this.maxChars = Number(checkF.value);
		this.checkField = checkF;
		this.textArea = textF;
		this.tlength = null;
		this.keyDown = this.keyDownEvent.bindAsEventListener(this);
		Event.observe(this.textArea,"keyup",this.keyDown);
		Event.observe(this.textArea,"keydown",this.keyDown);
	},
	keyDownEvent: function (event) {
		if (!this.textArea.textLength) {
			this.tlength  = this.textArea.value.length;
		} else {
			this.tlength = this.textArea.textLength;
		}
		
		if (this.maxChars >= this.tlength) {
			this.checkField.value = this.maxChars - this.tlength;
			
		} else {
			this.checkField.value = 0;
			this.textArea.value = this.textArea.value.substr(0,this.maxChars);
			if (this.textArea.createTextRange) {
				var Auswahl = this.textArea.createTextRange();
				Auswahl.moveStart( "character", this.maxChars );
				Auswahl.moveEnd( "character", this.maxChars );
				Auswahl.select();
			} else {
				this.textArea.setSelectionRange(this.maxChars,this.maxChars);				
			}

		}
		 
	}
}

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

function goselected(selectObj) {
	document.location = selectObj.value;
}