_g_init = false;

_g_timeOn = null;
_g_selected = null;

//FastInit.addOnLoad(mentorshipInit);


sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

Event.observe(window, 'load', function() {
	$$('.focus').each(function(s) { s.focus(); });
	$$('.calendar').each(function(s) { addCalendar(s.id); });
});

function UC(code) {
	return String.fromCharCode(code);
}

function mentorshipInit() {
	globalInit();
	if(typeof _g_location == "undefined") _m_location = '-';
	switch(_g_location) {
	case '':
		break;
	case 'organizatii':
		companiesInit();
		break;
	case 'mentori':
		mentorsInit();
		break;
	case 'contul-meu/inregistrare':
		registerInit();
		break;
	case 'contul-meu/recuperare-parola':
		forgotInit();
		break;
	case 'contul-meu/profil':
		profileInit();
		break;
	case 'contul-meu/sesiuni':
		applyInit();
		break;
	case 'contul-meu/mesaje':
		msgInit();
		break;
	case 'contact':
		contactInit();
		break;
	case 'secretele-ascensiunii-mele/inscriere':
		regformInit();
		break;
	}
	$$('.focus').each(function(s) { s.focus(); });
}

function globalInit() {
	var t;
	if(_g_init) return;
	t = $$('script').first().src;
	_site_base = t.indexOf('/js/') >= 0 ? t.substr(0, t.indexOf('/js/') + 1) : '/';
	if(_site_base.substr(0, 7) == 'http://') {
		t = _site_base.substr(7);
		if(t.indexOf('/') >= 0) {
			_site_base = t.substr(t.indexOf('/'));
		}
	}
	_l_search = 'Scrie aici ' + UC(351) + 'i apas' + UC(259) + ' enter pentru a c' + UC(259) + 'uta.';
	_g_init = true;
}

function partnersInit() {
	var t;
	globalInit();
	t = new SWFObject(_site_base + 'img/partners.swf', 'partnersflash', '100%', '150', '8');
	t.addVariable('url', _site_base + 'data/partners.xml');
	t.write('partners');
}

function profileCommonValidation(reg) {
	Validation.addAllThese([
		['validate-username', 'Numele de utilizator este invalid.', {
			pattern: new RegExp("^[a-z0-9._-]+$", "i"),
			minLength: 3
		}],
		['validate-password', 'Parola este invalid' + UC(259) + '.', function (v,elm) {
			return !v.length || v.length >= 6;
		}],
		['validate-password-confirm', 'Parola nu se potrive' + UC(351) + 'te.', {
			equalToField: reg ? 'f-register-password' : 'f-profile-password'
		}],
		['validate-date-group', 'Nu ai completat data na' + UC(351) + 'terii.', function (v,elm) {
			var p = $(elm.parentNode);
			var options = p.getElementsByTagName('SELECT');
			return $A(options).all(function(elm) {
				return Validation.get('validate-selection').test($F(elm), elm);
			});
		}]
	]);
}

function registerInit() {
	if($('form-register')) {
		profileCommonValidation(1);
		new Validation('form-register', {immediate: true, useTitles : true});
	}
}

function forgotInit() {
	if($('form-change')) {
		profileCommonValidation(1);
		new Validation('form-change', {immediate: true, useTitles : true});
	}
}

function profileInit() {
	if($('form-profile')) {
		profileCommonValidation(0);
		new Validation('form-profile', {immediate: true, useTitles : true});
	}
	if($('form-photo')) {
		new Validation('form-photo', {immediate: true, useTitles : true});
	}
	if($('photo-crop')) {
		new Cropper.Img('photo-crop', {ratioDim: {x: 3, y: 4}, displayOnInit: 1, onloadCoords: {x1: $F('f-cropx1'), y1: $F('f-cropy1'), x2: $F('f-cropx2'), y2: $F('f-cropy2')}, onEndCrop: profilePhotoEndCrop});
	}
}

function profilePhotoEndCrop(coords, dimensions) {
	$('f-cropx1').value = coords.x1;
	$('f-cropx2').value = coords.x2;
	$('f-cropy1').value = coords.y1;
	$('f-cropy2').value = coords.y2;
}

function applyInit() {
	if($('form-apply')) {
		new Validation('form-apply', {immediate: true, useTitles : true});
	}
	if($('form-feedback')) {
		$$('#form-feedback fieldset ol li').each(function(s) {
			Event.observe(s, 'click', function(e) {
				applyValidate($(Event.findElement(e, 'li')), false);
			});
		});
		Event.observe($('form-feedback'), 'submit', function(e) {
			var err = false, errfield = null;
			$('form-feedback').getElementsBySelector('fieldset ol li').each(function(s) {
				if(!applyValidate(s, true) && !err) {
					err = true;
					errfield = s;
				}
			});
			if(err) {
				Event.stop(e);
				new Effect.ScrollTo(errfield);
			}
		});
	}
}

function applyValidate(obj, hl) {
	var col;
	col = obj.getElementsBySelector('.feedback-rating input');
	if(!col.size()) return true;
	if(col.find(function(s) { return s.checked; })) {
		obj.removeClassName('rate-error');
		return true;
	} else {
		if(hl) obj.addClassName('rate-error');
		return false;
	}
}

function companiesInit() {
	var obj;
	if($('company-list')) {
		$A($('company-list').getElementsByTagName('a')).each(function(s) { s.onclick = companiesShowInfo; });
		$A($('company-search').getElementsByTagName('form')).each(function(s) { s.onSubmit = function() { if(this.search.value == _l_search) return false; }; });
		obj = $('company-search-field');
		obj.onfocus = function() { if(this.value == _l_search) this.value = ''; };
		obj.onblur = function() { if(this.value == '') this.value = _l_search; };
		obj.onblur();
	}
}

function companiesShowInfo() {
	if(this.href) {
		$('company-info-border').innerHTML = 'Se ' + UC(238) + 'ncarc' + UC(259) + '...';
		new Effect.ScrollTo('company-info');
		new Ajax.Updater('company-info-border', this.href + '?output=ajax', {method: 'get'});
	}
	return false;
}

function mentorsInit() {
	var obj;
	if($('mentor-col1')) {
		$A($('mentor-col1').getElementsByTagName('a')).each(function(s) { s.onclick = mentorsShowInfo; });
		$A($('mentor-col2').getElementsByTagName('a')).each(function(s) { s.onclick = mentorsShowInfo; });
		$A($('mentor-col3').getElementsByTagName('a')).each(function(s) { s.onclick = mentorsShowInfo; });
		$A($('mentor-search').getElementsByTagName('form')).each(function(s) { s.onSubmit = function() { if(this.search.value == _l_search) return false; }; });
		obj = $('mentor-search-field');
		obj.onfocus = function() { if(this.value == _l_search) this.value = ''; };
		obj.onblur = function() { if(this.value == '') this.value = _l_search; };
		obj.onblur();
	}
}

function mentorsShowInfo() {
	if(this.href) {
		$('mentor-info-border').innerHTML = 'Se ' + UC(238) + 'ncarc' + UC(259) + '...';
		new Effect.ScrollTo('mentor-info');
		new Ajax.Updater('mentor-info-border', this.href + '?output=ajax', {method: 'get'});
	}
	return false;
}

function contactInit() {
	new Validation('form-contact', {immediate: true, useTitles : true});
}

function msgInit() {
	$$('ul.msg-list').each(function(s) {
		s.descendants();
	});
	if($('form-msgsend')) {
		new Validation('form-msgsend', {useTitles : true});
	}
	$$('li.msg-tools .msg-editor form').each(function(s) {
		new Validation(s, {useTitles : true});
	});
	if($('msg-check-new')) {
		msgupdater = new Ajax.PeriodicalUpdater('msg-check-new', _site_base + 'contul-meu/mesaje/?output=ajax', {method: 'post', parameters: {action: 'check', tstamp: $('msg-check-new').className, force: 0}, frequency: 60, onComplete: function() { if($('msg-check-new').innerHTML != '') { $('msg-check-new').hide(); new Effect.Appear('msg-check-new'); } }});
	}
}

function msgToggleFolder(obj) {
	$(obj).up('li.msg-list').down('ul.msg-topics').toggle();
}

function msgOpenConversation(obj) {
	var t, t1;
	t = $(obj).up('li.msg-topics');
	if(t.hasClassName('msg-new')) {
		new Ajax.Request(_site_base + 'contul-meu/mesaje/?output=ajax', {method: 'post', parameters: {action: 'mark', conv_id: t.id.substr(4)}});
	}
	t.siblings().each(function(s) { s.hide() });
	t.addClassName('msg-expanded').removeClassName('msg-new');
	t1 = t.down('li.msg-unread');
	if(!t1) {
		t1 = t;
	}
	if(t1) {
		new Effect.ScrollTo(t1);
	}
	t = t.up('li.msg-list');
	if(!t.getElementsBySelector('li.msg-new').size()) {
		t.removeClassName('msg-highlight');
	}
}


function msgQuote(obj, id) {
	var t;
	t = $(obj).up('li.msg-body');
	t.up().down('textarea').value = t.down('.msg-text').innerHTML.stripTags().strip().replace(/\t/g, '') + "\n\n";
	msgReply(t.up().down('.msg-toolbar-reply a'));
}

function msgEdit(obj, id) {
}

function msgDelete(obj, id) {
}

function msgClose(obj) {
	var t;
	obj = $(obj);
	obj.up('ul.msg-body').getElementsBySelector('li.msg-unread').each(function(s) { s.removeClassName('msg-unread'); });
	t = obj.up('li.msg-topics');
	t.siblings().each(function(s) { s.show(); });
	t.removeClassName('msg-expanded');
	new Effect.ScrollTo(obj.up('li.msg-list'));
}

function msgReply(obj) {
	obj = $(obj);
	obj.up('li').addClassName('msg-toolbar-active');
	obj.up('li.msg-tools').down('.msg-editor').show().down('textarea').focus();
}

function msgCloseReply(obj) {
	obj = $(obj);
	obj.up('.msg-editor').hide();
	obj.up('.msg-tools').down('.msg-toolbar-active').removeClassName('msg-toolbar-active');
}

function msgReport(obj) {
	if(confirm('Raportezi mesajul ca fiind irelevant?')) {
	}
}

function msgCheck() {
	new Ajax.Updater('msg-check-new', _site_base + 'contul-meu/mesaje/?output=ajax', {method: 'post', parameters: {action: 'check', tstamp: $('msg-check-new').className, force: 1}, onComplete: function() { $('msg-check-new').hide(); new Effect.Appear('msg-check-new'); }});
}

function msgCompose() {
	$('msg-options').hide();
	$('msg-compose').show();
	$('f-msg-subject').focus();
	new Effect.ScrollTo($('msg-compose'));
}

function msgComposeCancel() {
	$('msg-options').show();
	$('msg-compose').hide();
}

function feedbackRate(obj, t) {
	var col, val = '';
	col = $(obj).up('tr').getElementsBySelector('input');
	col.each(function(s) {
		if(s.checked) val = parseInt(s.value);
	});
	if(!val) val = 3;
	else val += t;
	if(val < 1) val = 1;
	if(val > 5) val = 5;
	col.each(function(s) {
		s.checked = s.value == val;
	});
}

function regformInit() {
	if($('form-regform')) {
		profileCommonValidation(1);
		new Validation('form-regform', {immediate: true, useTitles : true});
	}
}

function fastFeedbackInit() {
	if($('fast-feedback')) {
		t = new SWFObject('http://widget.meebo.com/mm.swf?tXcSVLuCTE', 'fastfeedback', '300', '300', '8');
		t.addParam('wmode', 'transparent');
		t.write('fast-feedback');
	}
}

function calLoad(url) {
	new Ajax.Updater('calendar', url + '&output=ajax', {method: 'get'});
}

function liveChatInit() {
	Event.observe(window, 'beforeunload', liveChatConfirmExit);
}

function liveChatConfirmExit(e) {
	e.returnValue = 'Dac'+UC(259)+' p'+UC(259)+'r'+UC(259)+'se'+UC(351)+'ti pagina vei fi deconectat din Live Chat.\n\nE'+UC(351)+'ti sigur c'+UC(259)+' vrei s'+UC(259)+' ie'+UC(351)+'i?';
	Event.stop(e);
}

function getCookie(check_name) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function setCookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime( today.getTime() );
	
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function delCookie(name, path, domain) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function handleNode() {
	var openNodesCookie = getCookie('openNodes');
	var openNodes = Array();
	var tmp = Array();
	var parser, tmp2;
	if(openNodesCookie != null) openNodes = openNodesCookie.split(',');
	
	var ul = this.parentNode.getElementsByTagName('UL');
	ul = ul[0];
	if(this.innerHTML == '+') {
		this.innerHTML = '-';
		ul.style.display = 'block';
		openNodes.push(ul.id);
	} else {
		this.innerHTML = '+';
		ul.style.display = 'none';
		tmp = ul.getElementsByClassName('expand');
		for(parser = 0; parser < tmp.length; parser++) {
			tmp2 = tmp[parser].parentNode.getElementsByTagName('UL');
			tmp2 = tmp2[0];
			if(openNodes.indexOf(tmp2.id) != -1) {
				tmp[parser].onclick();
			}
		}
		openNodes = openNodes.without(ul.id);
	}
	setCookie('openNodes', openNodes.toString());
}

function initExpandButtons() {
	var openNodesCookie = getCookie('openNodes');
	var openNodes = Array();
	if(openNodesCookie != null) openNodes = openNodesCookie.split(',');
	var objs = document.getElementsByClassName('expand');
	var ul;
	for(var parser = 0; parser < objs.length; parser++) {
		ul = objs[parser].parentNode.getElementsByTagName('UL');
		ul = ul[0];
		if(openNodes.length > 0 && openNodes.indexOf(ul.id) != -1) {
			objs[parser].innerHTML = '-';
			objs[parser].onclick = handleNode;
			ul.style.display = 'block';
		} else {
			objs[parser].innerHTML = '+';
			objs[parser].onclick = handleNode;
			ul.style.display = 'none';
		}
	}
}

function addCalendar(e, init) {
	new Insertion.After(e, '<input type="button" id="' + e + '_pick" class="datepicker" value="&nbsp;" />');
	if(typeof init == 'undefined') init = {};
	if($(e) && $(e).maxLength == 19) {
		init.showsTime = true;
		init.ifFormat = '%Y-%m-%d %H:%M:%S';
		init.daFormat = '%Y-%m-%d %H:%M:%S';
	}
	init.inputField = e;
	init.button = e + '_pick';
	Calendar.setup(init);
}

function word_count(obj) {
  if(typeof(obj) == 'string') obj = document.getElementById(obj);
  var tmp, words;
  tmp = obj.value + " ";
  tmp = tmp.replace(/^[^A-Za-z0-9]+/gi, "");
  tmp = tmp.replace(/[^A-Za-z0-9]+/gi, " ");
  words = tmp.split(" ");
  return words.length - 1;
}

function update_word_count(obj, num, out) {
  var nr, nrc;
  nr = word_count(obj);
  nrc = document.getElementById(out);
  nrc.value = nr;
  nrc.style.fontWeight = nr <= num ? "normal" : "bold";
  nrc.style.color = nr <= num ? "" : "#C00000";
}

function checkFormular(obj, form) {
	switch(form) {
		case 'conferinta':
			var list = Array('firstname', 'lastname', 'birthdate', 'sex', 'email', 'min', 'place', 'study', 'work', 'q1', 'q2');
		break;
		case 'training':
			var list = Array('firstname', 'lastname', 'birthdate', 'sex', 'place', 'email', 'phone', 'q1', 'q2');
		break;
		default:
			alert('Eroare la validarea formularului!');
			return false;
		break;
	}
	for(var parser = 0; parser < list.length; parser++) {
		if(list[parser] == 'sex') {
			var m = document.getElementById('f_sex_m');
			var f = document.getElementById('f_sex_f');
			if(!m.checked && !f.checked) {
				alert('Nu ai completat campul sex.');
				m.focus();
				return false;
			}
		} else if(list[parser] == 'place') {
			if(obj[list[parser]].selectedIndex == 0) {
				alert('Nu ai ales orasul in care vrei sa iei parte la eveniment!');
				obj[list[parser]].focus();
				return false;
			}
		} else if(list[parser] == 'q1') {
			if(word_count(obj[list[parser]]) > 200 || obj[list[parser]].value.length < 1) {
				alert('Nu ai completat campul 1 sau ai intrecut numarul maxim de cuvinte.');
				obj[list[parser]].focus();
				return false;
			}
		} else if(list[parser] == 'q2') {
			if(word_count(obj[list[parser]]) > 200 || obj[list[parser]].value.length < 1) {
				alert('Nu ai completat campul 2 sau ai intrecut numarul maxim de cuvinte.');
				obj[list[parser]].focus();
				return false;
			}
		} else {
			if(obj[list[parser]].value.length < 1) {
				alert('Nu ai completat campul ' + list[parser] + '.');
				obj[list[parser]].focus();
				return false;
			}
		}
	}

	return true;
}