this.focus();

// prevent errors in browsers lacking console
if (!window.console)
	window.console = {
		log: function () {
			;
		}
	}


// extension
if (Prototype.Browser.IE) {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);
    }
}
	

function printerFriendly(urlToOpen) {
	var x = (screen.width-700)/2, y = (screen.height-600)/2;
	OpenWin = this.open(urlToOpen, "CtrlWindow", "width=700,height=600,toolbar=no,menubar=yes,location=no,scrollbars=yes,resizable=no, screenX="+x+", screenY="+y+", left="+x+", top="+y);
}

function recommend(urlRecommandForThisArticle) {
	var x = (screen.width-420)/2, y = (screen.height-300)/2;
	OpenWin = this.open(urlRecommandForThisArticle, "CtrlWindow", "width=420,height=415,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no, screenX="+x+", screenY="+y+", left="+x+", top="+y);
}

function readFunc(ident){
	var el = $('toggle_' + ident);
	if(el.innerHTML == '<span>detalii...</span>'){
		$('less_' + ident).hide(); 
		Effect.SlideDown('more_' + ident);
		$(el).innerHTML = '<span>ascunde...</span>';
	}else{
		Effect.SlideUp('more_' + ident);
		Effect.SlideDown('less_' + ident);
		$(el).innerHTML = '<span>detalii...</span>';
	}
	return false;
}

function myToggle(myID){
	var el = $(myID);
	if(el.style.display == 'none'){
		el.show();
	} else {
		el.hide();
	}
}

var expandedID = 0;
function emulateAccordion(accordID){
	var myTriggers = $(accordID).select('.accordion_trigger');
	
	myTriggers.each(function(currTrigger){
		var currContent = 'accordion_content_' + currTrigger.getAttribute('triggerID');
		
		currTrigger.observe('click', function(){
			if(currTrigger.getAttribute('triggerID') == expandedID){
				Effect.SlideUp(currContent);
				expandedID = 0;
			} else {
				Effect.SlideDown(currContent);
				if(expandedID){
					var prevContent = 'accordion_content_' + expandedID;
					Effect.SlideUp(prevContent);
				}
				expandedID = currTrigger.getAttribute('triggerID');
			}
		});
		
		var myParrent = $(currContent).up();
		if(!myParrent.hasClassName('activ')){
			$(currContent).hide();
		}
		
	});
}

function removeFilter(fieldID, fieldType, formID){
	if(fieldType == 'zone'){
		var el = $(fieldType);
		var myVars = $A(el.options);
		myVars.each(function(elEach){
			if(elEach.value == fieldID){
				elEach.selected = false;
			}
		});
	} else if(fieldType == 'pic'){
		var el = $(fieldType);
		el.options[0].selected = true;
	} else {
		var el = $(fieldType + '_' + fieldID);
		if(el.checked){
			el.checked = false;
		} else if(el.options){
			el.options[0].selected = true;
		}
	}
	
	$(formID).submit();
}

function setPage(pageID, hInput, formID){
	//alert(pageID);
	$(hInput).value = pageID;
	$(formID).submit();
}

function completeMe(){
	// autocomplete toggle for all elements having completeMe class
	$$('.completeMe').each(function(el) {
		Event.observe(el, 'focus', function(event) {
			if(el.value == el.defaultValue){
				el.value = '';
				if(el.innerHTML)
					el.innerHTML = '';
			}
		});
		Event.observe(el, 'blur', function(event) {
			if(el.value == ''){
				el.value = el.defaultValue;
				if(el.innerHTML)
					el.innerHTML = el.defaultValue;
			}
		});
	});
}

function listen2filters(formID, ajaxThis){
	// listen to an entire form or just some of it's elements for changes that trigger ansubmit/AJAX
	if(ajaxThis){
		var observeThisID = ajaxThis;
	} else {
		var observeThisID = formID;
	}

	var checkboxes = $$('#' + observeThisID + ' input[type=checkbox]');
	checkboxes.each(function(box){
		box.observe('change', function(){
			if(ajaxThis){
				submitMyForm(formID, $(ajaxThis).getAttribute('ajaxResultTo'), $(ajaxThis).getAttribute('ajaxTo'));
			} else {
				$(formID).submit();
			}
		});
	});
	
	var radios = $$('#' + observeThisID + ' input[type=radio]');
	radios.each(function(radio){
		radio.observe('change', function(){
			if(ajaxThis){
				submitMyForm(formID, $(ajaxThis).getAttribute('ajaxResultTo'), $(ajaxThis).getAttribute('ajaxTo'));
			} else {
				$(formID).submit();
			}
		});
	});
	
	var selects = $$('#' + observeThisID + ' select');
	selects.each(function(sele){
		sele.observe('change', function(){
			if(ajaxThis){
				submitMyForm(formID, $(ajaxThis).getAttribute('ajaxResultTo'), $(ajaxThis).getAttribute('ajaxTo'));
			} else {
				$(formID).submit();
			}
		});
	});
	
}

function submitMyForm(formsID, messageDIV, urlOverride) {
	var aVariables = '';
	
	//get data from multiple forms (ids separated by | )
	var formIDs = formsID.split("|");
	formIDs.each(function(formID){
		var currFrmEntries = $(formID).serialize();
		if(aVariables.empty()){
			aVariables = currFrmEntries;
		} else {
			aVariables = aVariables + '&' + currFrmEntries;
		}
	});
	//alert(aVariables);
	
	//if no redirect URL specified, use the first form's action
	if(!urlOverride){
		var formURL = $(formIDs[0]).action;
	} else {
		var baseHref = document.getElementsByTagName('base')[0].href;
		var formURL = baseHref + 'index.html/' + urlOverride;
	}
	//alert(formURL);
	
	new Ajax.Request(formURL, {
		method:'post',
		parameters: {'allVars' : aVariables},
		onSuccess: function(transport){
			//alert(transport.responseText);
			var response = transport.responseXML;
			var iStatus = response.childNodes[0].childNodes[0].firstChild.nodeValue;
			var iMessage = response.childNodes[0].childNodes[1].firstChild.nodeValue;
			var iOption = response.childNodes[0].childNodes[2].firstChild.nodeValue;
			if(iStatus == 'true') {
				$(messageDIV).innerHTML = '';
				if($(messageDIV).hasClassName('error')){
					$(messageDIV).removeClassName('error');
					$(messageDIV).addClassName('message');
				}
				$(messageDIV).innerHTML = iMessage;
				//lock the forms
				formIDs.each(function(formID){
					$(formID).disable();
				});
				if(iOption){
					setTimeout("window.location.reload();", iOption);
				}
			}	else {
				$(messageDIV).innerHTML = '';
				if($(messageDIV).hasClassName('message')){
					$(messageDIV).removeClassName('message');
					$(messageDIV).addClassName('error');
				}
				$(messageDIV).innerHTML = iMessage;
			}
			$(messageDIV).show();
		},
		onFailure: function(error){
			alert('FAIL! ' + error);
		}
	});
}

//Cookie front end handler ( extending JS with cookie object - Prototype style)
//based on Jason McCreary creation - http://jason.pureconcepts.net/articles/javascript_cookie_object

/* Example Usage
Cookie that expires 90 days from visit, and sets a value:
    Cookie.init({name: 'yourdata', expires: 90});
    Cookie.setData('favorites', false);

Cookie that only lasts the session, with default data:
    Cookie.init({name: 'mydata'}, {foo: 'bar', x: 0});
    alert(Cookie.getData('foo'));
*/

var Cookie = {
  data: {},
  options: {expires: 1, domain: "", path: "", secure: false},

	init: function(options, data) {
		Cookie.options = Object.extend(Cookie.options, options || {});

		var payload = Cookie.retrieve();
		if(payload) {
			Cookie.data = payload.evalJSON();
		} else {
			Cookie.data = data || {};
		}
		Cookie.store();
	},
	getData: function(key) {
		return Cookie.data[key];
	},
	setData: function(key, value) {
		Cookie.data[key] = value;
		Cookie.store();
	},
	removeData: function(key) {
		delete Cookie.data[key];
		Cookie.store();
	},
	retrieve: function() {
		var start = document.cookie.indexOf(Cookie.options.name + "=");

		if(start == -1) {
				return null;
		}
		if(Cookie.options.name != document.cookie.substr(start, Cookie.options.name.length)) {
				return null;
		}

		var len = start + Cookie.options.name.length + 1;   
		var end = document.cookie.indexOf(';', len);

		if(end == -1) {
				end = document.cookie.length;
		} 
		return unescape(document.cookie.substring(len, end));
	},
	store: function() {
		var expires = '';

		if (Cookie.options.expires) {
			var today = new Date();
			expires = Cookie.options.expires * 86400000;
			expires = ';expires=' + new Date(today.getTime() + expires);
		}

		document.cookie = Cookie.options.name + '=' + escape(Object.toJSON(Cookie.data)) + Cookie.getOptions() + expires;
	},
	erase: function() {
		document.cookie = Cookie.options.name + '=' + Cookie.getOptions() + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	},
	getOptions: function() {
		return (Cookie.options.path ? ';path=' + Cookie.options.path : '') + (Cookie.options.domain ? ';domain=' + Cookie.options.domain : '') + (Cookie.options.secure ? ';secure' : '');      
	}
};

function updateStrength(pw) {
	var strength = getStrength(pw);
	var width = (100/32)*strength;
	new Effect.Morph('psStrength', {style:'width:'+width+'px', duration:'0.4'}); 
}

function getStrength(passwd) {
	intScore = 0;
	if (passwd.match(/[a-z]/)) // [verified] at least one lower case letter
		{
		intScore = (intScore+1)
		}
	if (passwd.match(/[A-Z]/)) // [verified] at least one upper case letter
		{
		intScore = (intScore+5)
		} // NUMBERS
	if (passwd.match(/\d+/)) // [verified] at least one number
		{
		intScore = (intScore+5)
		}
	if (passwd.match(/(\d.*\d.*\d)/)) // [verified] at least three numbers
		{
		intScore = (intScore+5)
		} // SPECIAL CHAR
	if (passwd.match(/[!,@#$%^&*?_~]/)) // [verified] at least one special character
		{
		intScore = (intScore+5)
		}
	if (passwd.match(/([!,@#$%^&*?_~].*[!,@#$%^&*?_~])/)) // [verified] at least two special characters
		{
		intScore = (intScore+5)
		} // COMBOS
	if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/)) // [verified] both upper and lower case
		{
		intScore = (intScore+2)
		}
	if (passwd.match(/\d/) && passwd.match(/\D/)) // [verified] both letters and numbers
		{
		intScore = (intScore+2)
		} // [Verified] Upper Letters, Lower Letters, numbers and special characters
	if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/) && passwd.match(/\d/) && passwd.match(/[!,@#$%^&*?_~]/))
		{
		intScore = (intScore+2)
		}
	return intScore;
}

// ##########comments###########
function getComments(itemType, itemID, page, showRating) {
	var baseHref = document.getElementsByTagName('base')[0].href;
	switch(itemType){
		case 'product':
				var ajaxTo = baseHref + 'index.html' + '/products|productComments';
			break;
		case 'biketrip':
				var ajaxTo = baseHref + 'index.html' + '/biketrips|tripComments';
			break;
		case 'community':
				var ajaxTo = baseHref + 'index.html' + '/community|tripComments';
			break;
		default:
			alert('Eroare: Tip de comentariu nerecunoscut !');
	}
	
	new Ajax.Request(ajaxTo,  {
    method:'post',
    parameters: {'itemID': itemID, 'pageID': page},
    onSuccess: function(transport){   
    	var response = transport.responseXML;
    	writeComments(response, showRating, itemType);    	
    },
    onFailure: function(){
			alert('Eroare: Va rugam incercati mai tarziu !');
		}
  });
}

function writeComments(rXML, showRating, itemType) {
	$('commentsListing').innerHTML = '';
	if(document.all) {
		root = rXML.childNodes[1];
	} else {
		root = rXML.childNodes[0];
	}
	var pagingInfo = root.getElementsByTagName('detalii')[0];
	var comments = root.getElementsByTagName('comentarii')[0];
	var sysMessage = root.getElementsByTagName('sysMessage')[0];
	
	
	if(comments.hasChildNodes()) {
		var items = comments.childNodes;
		for(var i = 0; i < items.length; i++) {
			//adapt to junk comments
			var commentScore = items[i].getElementsByTagName('commentScore')[0].firstChild.nodeValue;
			if(commentScore < 3){
				var classTitle = 'titluRewNegativ';
				var classBody = 'textNegativ';
				var mainBody = 'display: none;';
			} else {
				var classTitle = 'titluRew';
				var classBody = 'text';
				var mainBody = 'display: block;';
			}
			
			// container for each comment
			var divReviews = new Element('div', {'class':'reviews'});
			
			//comment rating paragraph
			var pNotaComentariu = new Element('p', {'class':'notaComentariu'});
			
			//link to report the comment
			// var aReportComment = new Element('a', {'href':'www.google.com'}).update('raporteaza comentariu');
			// pNotaComentariu.appendChild(aReportComment);
			
			//insert break
			var nl = new Element('br');
			pNotaComentariu.appendChild(nl);
			
			var spanNota = new Element('span').update('Gasesti util acest comentariu?&nbsp; | &nbsp;');
			pNotaComentariu.appendChild(spanNota);
			
			//em container for up/down rating a comment
			var emRating = new Element('em', {'id':'rating4_' + items[i].getElementsByTagName('feedbackID')[0].firstChild.nodeValue});
			
			//link for down rating & image for it
			var aMinus = new Element('a', {'href':'#', 'onClick':'rateComment("' + itemType + '", ' + items[i].getElementsByTagName('feedbackID')[0].firstChild.nodeValue + ', "-", ' + showRating + '); return false;'});
			var imgMinus = new Element('img', {'src':'images/icons/ico_scade.gif'});
			aMinus.appendChild(imgMinus);
			
			//link for up rating & image for it
			var aPlus = new Element('a', {'href':'#', 'onClick':'rateComment("' + itemType + '", ' + items[i].getElementsByTagName('feedbackID')[0].firstChild.nodeValue + ', "+", ' + showRating + '); return false;'});
			var imgPlus = new Element('img', {'src':'images/icons/ico_adauga.gif'});
			aPlus.appendChild(imgPlus);
			
			//append up/down rating to em container
			emRating.appendChild(aMinus);
			var spanSpacer = new Element('span').update(' '); //just a spacer
			emRating.appendChild(spanSpacer);
			emRating.appendChild(aPlus);
			
			//append em up/down rating to rating container
			pNotaComentariu.appendChild(emRating);
			
			//append entire rating container to comment
			divReviews.appendChild(pNotaComentariu);
			
			//container for title, username and date
			var pTitluRew = new Element('p', {'class':classTitle});
			
			//strong title/username
			var strongTitle = new Element('strong', {'style':'cursor: pointer;', 'onClick':'myToggle("commentNo_' + i + '")'}).update(items[i].getElementsByTagName('PersonName')[0].firstChild.nodeValue);
			pTitluRew.appendChild(strongTitle);
			
			//insert break
			var nl = new Element('br');
			pTitluRew.appendChild(nl);
			
			//date
			var spanName = new Element('span', {'class':'name'}).update(items[i].getElementsByTagName('postDate')[0].firstChild.nodeValue);
			pTitluRew.appendChild(spanName);
			
			//append for title, username and date to comment
			divReviews.appendChild(pTitluRew);
			
			//main bady container
			var divMainBody = new Element('div', {'id': 'commentNo_' + i, 'style': mainBody});
			
			//comment body
			var pText = new Element('p', {'class':classBody}).update(items[i].getElementsByTagName('body')[0].firstChild.nodeValue);
			//divReviews.appendChild(pText);
			divMainBody.appendChild(pText);
			
			if (showRating != '0' && (items[i].getElementsByTagName('rating')[0].firstChild.nodeValue > 0)){
				var pRating = new Element('p', {'class':'rating'});
				var pos = 90 - (parseInt(items[i].getElementsByTagName('rating')[0].firstChild.nodeValue) * 18);
				var pRank = new Element('div', {'style':'background-image: url(images/backgrounds/rating.png); background-position: -' + pos + 'px 0px; background-repeat: no-repeat; border: none; height: 17px; width: 90px; float: left;'});
				pRating.appendChild(pRank);
				
				var spanRank = new Element('span').update( 'Nota produs: ' + parseInt(items[i].getElementsByTagName('rating')[0].firstChild.nodeValue) + ' din 5 stele');
				//var rankno = document.createTextNode(parseInt(items[i].getElementsByTagName('rank')[0].firstChild.nodeValue));
				pRating.appendChild(spanRank);
				
				//divReviews.appendChild(pRating);
				divMainBody.appendChild(pRating);
			}
			divReviews.appendChild(divMainBody);
			$('commentsListing').appendChild(divReviews);
		}
	} else {
		//var noRev = document.createTextNode('Be the first to write a review for this product.');
		$('commentsListing').innerHTML = '<p style=" color:#054172; font-weight: bold; " > Fii primul sa scrii un comentariu. </p>';
	}
	
	if(pagingInfo && pagingInfo.hasChildNodes) {
		var pageID = pagingInfo.getElementsByTagName('pagina')[0].firstChild.nodeValue;
		var nPages = pagingInfo.getElementsByTagName('totalpagini')[0].firstChild.nodeValue;
		var nElements = pagingInfo.getElementsByTagName('totalcomentarii')[0].firstChild.nodeValue;
		var elementID = pagingInfo.getElementsByTagName('ID')[0].firstChild.nodeValue;
		
		if(nPages && nPages > 1) {
			var cleaner = $(document.createElement('div'));
			cleaner.addClassName('cleaner');
			$('commentsListing').appendChild(cleaner);
			var ppage = $(document.createElement('p'));
			ppage.id = 'paginare';
			ppage.addClassName('paginare');
			var paginare = document.createTextNode('Pagina: ');
			ppage.appendChild(paginare);
			if (pageID>1){
				var prev = $(document.createElement('a'));
				prev.href = 'javascript: void(0);'
				prev.onclick = new Function('getComments("' + itemType + '", ' + elementID + ', ' + (pageID-1) + ')');
			} else {
				var prev = $(document.createElement('span'));
			}
			var prevBtn = $(document.createElement('img'));
			prevBtn.src = 'images/butoane/paginare_inapoi.gif';
			prev.appendChild(prevBtn);
			ppage.appendChild(prev);
			for(var i = 1; i <= nPages; i++) {
					if(i == pageID) {
							var pageTag = $(document.createElement('a'));
							pageTag.addClassName('paginaActiva');
					} else {
							// var sp = document.createTextNode(' ');
							// ppage.appendChild(sp);
							var pageTag = $(document.createElement('a'));
							pageTag.addClassName('pagina');
							pageTag.href = 'javascript: void(0);'
							pageTag.onclick = new Function('getComments("' + itemType + '", ' + elementID + ', ' + i + ')');
					}
					// var sp = document.createTextNode(' ');
					// ppage.appendChild(sp);
					var pageText = document.createTextNode(i);
					pageTag.appendChild(pageText);
					ppage.appendChild(pageTag);
			}
			if(pageID<nPages){
				var next = $(document.createElement('a'));
				next.href = 'javascript: void(0);';
				next.onclick = new Function('getComments("' + itemType + '", ' + elementID + ', ' + (pageID*1+1) + ')');
			} else {
				var next = $(document.createElement('span'));
			}
			var nextBtn = $(document.createElement('img'));
			nextBtn.src = 'images/butoane/paginare_inainte.gif';
			next.appendChild(nextBtn);
			ppage.appendChild(next);
			$('commentsListing').appendChild(ppage);
			$('commentsListing').appendChild(cleaner);
		}
		
	}
	if(sysMessage) {
		showToolTipFader(sysMessage.firstChild.nodeValue, $('comenteazaSiTuID'));
	}
	
}

function nl2br(str) {
 if(typeof(str)=="string") return str.replace(/(\r\n)|(\n\r)|\r|\n/g,"<BR>");
 else return str;
}

//COMMENTS
function displayCommentForm(formID, userID, fieldToFocus, message) {
		//return false;
		if(parseInt(userID)) {
			Effect.toggle($(formID).addClassName('reviews'),'slide');
			setTimeout('$(\''+fieldToFocus+'\').focus();', 1000);
		} else {
//			showToolTipFader(message, $('comenteazaSiTuID'));
			if(!$('commentGoToLogin')) {
				var commentGoToLogin = $(document.createElement('div'));
				commentGoToLogin.id = 'commentGoToLogin';
				commentGoToLogin.setStyle({'display':'none'});
				var div = $(document.createElement('div')).addClassName('reviews');
				var br = document.createElement('br');
				div.appendChild(br);
				var msg = document.createTextNode(message);
				div.appendChild(msg);
				var br = document.createElement('br');
				div.appendChild(br);
				msg = document.createTextNode('Te poti autentifica dand click ');
				div.appendChild(msg);
				var loginLink = $(document.createElement('a'));
				loginLink.href = document.getElementsByTagName('base')[0].href + 'index.html/account|login';
				msg = document.createTextNode('aici');
				loginLink.appendChild(msg);
				div.appendChild(loginLink);
				commentGoToLogin.appendChild(div);
				$('comenteazaSiTuID').parentNode.appendChild(commentGoToLogin);
				new Effect.SlideDown(commentGoToLogin);
			}
		}
}

function validateComment(fieldsToBeValidated) {
	var ok = true;
	if(fieldsToBeValidated.length) {
		for(i = 0; i < fieldsToBeValidated.length; i++) {
			if(!$(fieldsToBeValidated[i]).value.trim().length) {
					ok = false;
					showToolTipFader('Completeaza campul...',$(fieldsToBeValidated[i]));
			}
		}
	}
	return ok;
}

function postComment(formID, itemID, fieldsToBeValidated, showRating, itemType){
	var baseHref = document.getElementsByTagName('base')[0].href;
	switch(itemType){
		case 'product':
				var ajaxTo = baseHref + 'index.html' + '/products|productComments';
			break;
		case 'biketrip':
				var ajaxTo = baseHref + 'index.html' + '/biketrips|tripComments';
			break;
		case 'community':
				var ajaxTo = baseHref + 'index.html' + '/community|tripComments';
			break;
		default:
			alert('Eroare: Tip de comentariu nerecunoscut !');
	}
	
	if(validateComment(fieldsToBeValidated)) {
		Effect.toggle($(formID),'slide');
		new Ajax.Request(ajaxTo,  {
			method:'post',
			parameters: {'itemID': itemID, comment: $('comment').value, 'rank':$('rank').value, postComment: '1' },
			onSuccess: function(transport){
				$('comment').value ='';
				$('rank').value ='';
				$('ranking').style.backgroundPosition = '-90px 0px';
				var response = transport.responseXML;    	
				writeComments(response, showRating, itemType);    	
			},
			onFailure: function(){  }
		});
	}
}

function buildRanking() {
	var ratingSelector = $('ranking');
	
	function mouseOver() {
		this.parentNode.style.backgroundPosition = -(90 - (this.firstChild.nodeValue * 18)) + "px 0px";
	}

	function mouseOut() {
		this.parentNode.style.backgroundPosition = -(90 - (this.parentNode.firstChild.value * 18)) + "px 0px";
	}

	function mouseClick() {
		this.parentNode.firstChild.value = this.firstChild.nodeValue;
		return false;
	}
	
	for (var i = 1; i <= 5; i++) {
		var star = document.createElement("a");

		star.href = "#";
		star.title = i + "/5";
		star.appendChild(document.createTextNode(i));

		star.onmouseover	= mouseOver;
		star.onmouseout		= mouseOut;
		star.onclick		= mouseClick;

		ratingSelector.appendChild(star);
	}
}

function rateComment(itemType, itemID, score, showRating){
	var baseHref = document.getElementsByTagName('base')[0].href;
	switch(itemType){
		case 'product':
				var ajaxTo = baseHref + 'index.html' + '/products|rateComments';
			break;
		case 'biketrip':
				var ajaxTo = baseHref + 'index.html' + '/biketrips|rateComments';
			break;
		default:
			alert('Eroare: Tip de comentariu nerecunoscut !');
	}
	
	new Ajax.Request(ajaxTo,  {
		method:'post',
		parameters: {'itemID': itemID, 'score': score, 'postComment': '1' },
		onSuccess: function(transport){
			var response = transport.responseXML;  
			//alert(transport.responseText);
			//writeComments(response, showRating, itemType); 
			if(document.all) {
				root = response.childNodes[1];
			} else {
				root = response.childNodes[0];
			}
			var pagingInfo = root.getElementsByTagName('detalii')[0];
			var comments = root.getElementsByTagName('comentarii')[0];
			var sysMessage = root.getElementsByTagName('sysMessage')[0];
			showToolTipFader(sysMessage.firstChild.nodeValue, $('rating4_' + itemID));
		},
		onFailure: function(){ alert('Eroare !'); }
	});
}

// tooltip
//end browser user
var globalTimeout = "";
function showToolTipFader(texty,obj,doNotCloseAfter) {	
	
	if($('tooltipX')) {
		document.body.removeChild($('tooltipX'));		
		window.clearTimeout(globalTimeout);	
	}
	
	var newdiv = document.createElement('div');
	newdiv.id="tooltipX";
	newdiv.style.display = "none";
	
	//generating table inside div
	if(document.all) {
		var tbl = document.createElement('<table cellpadding=0 cellspacing=0 border=0>');	
		var tbb = document.createElement("tbody");	
	} else {
		var tbl = document.createElement('table');		
		var tbb = document.createElement("tbody");	
		
		tbl.setAttribute('cellpadding','0');
		tbl.setAttribute('cellspacing','0');
		tbl.setAttribute('border','0');
	}	
	
	
	// create up arrow td
		var row = document.createElement('tr');
			
			if(document.all)
				var cell = document.createElement('<td colspan=3>');
			else 
				var cell = document.createElement('td');	
			cell.setAttribute('colspan','3');
				//create img
				 var nimg = document.createElement('img');
				 if(document.all)
				 	nimg.src="images/pop-up/sageata_sus.gif";
				 else	
				 	nimg.src="images/pop-up/sageata_sus.png";
				 nimg.className="tooltipUpArrow";	
				 nimg.id = "toolArrowU";
				 			 
			cell.appendChild(nimg);			
		row.appendChild(cell);		
	tbb.appendChild(row);
	//end create up arrow td
		
	//create top tooltip
		var row = document.createElement('tr');
			var cell = document.createElement('td');
			cell.className="tooltipCorner_ul";
		row.appendChild(cell);		
		
		
			var cell = document.createElement('td');
			cell.className="tooltipBar_u";
		row.appendChild(cell);
		
		
			var cell = document.createElement('td');
			cell.className="tooltipCorner_ur";
		row.appendChild(cell);
	tbb.appendChild(row);
	//end create top tooltip
	
	if(doNotCloseAfter) {
		var imgClose = "<img src='images/pop-up/icon-close.gif' style='cursor:pointer;float:right; top:-10px;' onClick=\"hidePopup();\"/><b>"+oSiteTexts.atentie+"</b>";
	//create close tooltip
		var row = document.createElement('tr');
			var cell = document.createElement('td');
			cell.className="tooltipBar_l";
		row.appendChild(cell);
		
			var cell = document.createElement('td');
			cell.className="tooltipText";
			cell.innerHTML=imgClose;
		row.appendChild(cell);
				
			var cell = document.createElement('td');
			cell.className="tooltipBar_r";
		row.appendChild(cell);
	tbb.appendChild(row);	
	//end close tooltip		
	}

	//create middle tooltip
		var row = document.createElement('tr');
			var cell = document.createElement('td');
			cell.className="tooltipBar_l";
		row.appendChild(cell);
		
			var cell = document.createElement('td');
			cell.className="tooltipText";			
			cell.innerHTML=texty;
		row.appendChild(cell);
				
			var cell = document.createElement('td');
			cell.className="tooltipBar_r";
		row.appendChild(cell);
	tbb.appendChild(row);	
	//end middle tooltip	
	
	//create bottom tooltip
		var row = document.createElement('tr');
			var cell = document.createElement('td');
			cell.className="tooltipCorner_bl";
		row.appendChild(cell);		
		
		
			var cell = document.createElement('td');
			cell.className="tooltipBar_b";
		row.appendChild(cell);
		
		
			var cell = document.createElement('td');
			cell.className="tooltipCorner_br";
		row.appendChild(cell);
	tbb.appendChild(row);
	//end create bottom tooltip
	
	// create down arrow td
		var row = document.createElement('tr');
			
			if(document.all)
				var cell = document.createElement('<td colspan=3>');
			else 
				var cell = document.createElement('td');	
			cell.setAttribute('colspan','3');
				//create img
				 var nimg = document.createElement('img');
				 if(document.all)
				 	nimg.src="images/pop-up/sageata_jos.gif";
				 else	
				 	nimg.src="images/pop-up/sageata_jos.png";
				 nimg.className="tooltipDownArrow";	
				 nimg.id = "toolArrowD";
				 			 
			cell.appendChild(nimg);			
		row.appendChild(cell);		
	tbb.appendChild(row);
	//end create down arrow td
	
	tbl.appendChild(tbb);
	newdiv.appendChild(tbl);
	
	newdiv.className ="tooltipDiv";
	
	//add tooltip to document
	document.body.appendChild(newdiv);
	
	//position tooltip
	setPopupPosition(obj,newdiv); 
	
	
	Effect.Appear(newdiv.id,{duration:.2});
	
	//set fade out
	if(!doNotCloseAfter)
		globalTimeout = window.setTimeout('Effect.Fade(\'tooltipX\', {duration:.3,from:1.0, to:0.0})',2500);
	
	//========================================	
}

function setPopupPosition(el, x)  {	
	var direction = "up";
	var position = Position.cumulativeOffset(el);
	var scrollY = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
	var viewHeight = (navigator.userAgent.toLowerCase().indexOf("safari") != -1 && window.innerHeight) ? window.innerHeight : document.documentElement.clientHeight;
	x.style.left = position[0]-40 + "px";	
	var popupTop = position[1] + Element.getHeight(el);
	if((popupTop + x.offsetHeight > scrollY + viewHeight) && (position[1] - x.offsetHeight > scrollY)) {
			popupTop = position[1] - x.offsetHeight ;
	}
	if(popupTop > (scrollY + Element.getHeight(x) + 40  + Element.getHeight(el))) {
		direction="down";
		$('toolArrowD').style.visibility = "visible";
	} else {
		$('toolArrowU').style.visibility = "visible";        	
	}
	if(direction == "up")
		x.style.top = (popupTop+30) + "px";
	else 
		x.style.top = (popupTop - Element.getHeight(x) - (document.all ? 15 : 25) - Element.getHeight(el)) + "px";
}

function hidePopup() {
	if($('tooltipX')) {
		document.body.removeChild($('tooltipX'));		
		window.clearTimeout(globalTimeout);			
	}
	
}

// clone a certain element
var cloneNo = 0;
var fChanged = 0;
var bAllSelected = false;
var nSelectedRows = 0;

function doClone(strNodeToCloneID) {
	
	nodeToClone = document.getElementById(strNodeToCloneID);
	
	parentNode = nodeToClone.parentNode;
	
	var clonedElem = nodeToClone.cloneNode(true);		
	
	if (clonedElem.style.display == 'none')
		clonedElem.style.display = 'block';
	
	myString = clonedElem.innerHTML;
	
		
	rExp = /\[_\]/gi;
	cloneNo++;		
	results = myString.replace(rExp, '[_' +  cloneNo + ']')

	/* "selected" lost during cloning */
	results = results.replace(/ghostSelected=\"1\"/, 'selected')

	clonedElem.innerHTML = results;

	clonedElem.id = clonedElem.id.replace(rExp, '[_' +  cloneNo + ']')

	// also clone hidden fields (that aren't inside the cloned div - so search for them first)
	strParameterName = nodeToClone.id.substr(nodeToClone.id.indexOf('[') + 1, nodeToClone.id.indexOf(']') - nodeToClone.id.indexOf('[') - 1);
	for (var i in document.forms[0].elements) {
			var _tmpName = (document.forms[0].elements[i]) ? String(document.forms[0].elements[i].name) : i;
			if (_tmpName.indexOf(strParameterName + '|') >= 0) {// || i.indexOf('r_' + strParameterName + '|') >= 0) {
				if (_tmpName.indexOf('[_]') >= 0) {
					parameterRelatedInput = document.getElementById(_tmpName);
					//alert(parameterRelatedInput);
					if (parameterRelatedInput && parameterRelatedInput.type == 'hidden') {
						newHiddenFieldName = parameterRelatedInput.name.replace(rExp, '[_' +  cloneNo + ']');

						//strNewElement = "<input type=hidden name='" + newHiddenFieldName + "' value='" + parameterRelatedInput.value + "'>";
						//newHiddenElement = document.createElement(strNewElement);

						newHiddenElement = document.createElement("input");
			    	newHiddenElement.setAttribute("name", newHiddenFieldName);
			    	newHiddenElement.setAttribute("type", "hidden");
			    	newHiddenElement.setAttribute("value", parameterRelatedInput.value);

						clonedElem.appendChild(newHiddenElement);
					}
				}
			}
	}

	parentNode.appendChild(clonedElem);
	
	//alert(parentNode.innerHTML);
	//performAfterCloning(cloneNo);
	//document.getElementById('textInfo').style.display = 'none';
}

function removeClone(divElem) {

	// set this entry as deleted
	elementName = divElem.id.substr(divElem.id.indexOf('[') + 1, divElem.id.indexOf(']') - divElem.id.indexOf('[') - 1);
	elementID = divElem.id.substr(divElem.id.indexOf(']') + 2, divElem.id.length - divElem.id.indexOf(']') - 3);


	newHiddenFieldName = elementName + '|_doDelete[' + elementID + ']';	
	newHiddenElement = document.createElement("input");
  newHiddenElement.setAttribute("name", newHiddenFieldName);
  newHiddenElement.setAttribute("type", "hidden");
  newHiddenElement.setAttribute("value", 1);

	document.forms[0].appendChild(newHiddenElement);
	
	// visual removal
	//divElem.removeNode(true);
	//removeNode(divElem);
	divElem.parentNode.removeChild(divElem);
}

function gE(el) {
		return document.getElementById(el);
}

function showSearchFilters(myEL){
	if(myEL.value=='articles'){
		$('p_type').hide();
		$('p_brand').hide();
		$('p_availability').hide();
	} else {
		$('p_type').show();
		$('p_brand').show();
		$('p_availability').show();
	}
}

function populateCities(populateContainer, selElCounty, cityID){
	var countyID = $(selElCounty).getValue();
	
	if(cityID)
		var parameters = {'countyID': countyID, 'cityID': cityID};
	else
		var parameters = {'countyID': countyID};
	// console.log(parameters, cityID);
	new Ajax.Updater(
	populateContainer,
	navigatorPath + '/getajax|getCountyCities', 
		{	
			'evalScripts': true,
			'parameters' : parameters
		});
}

function loaderEl(){
	var img = new Element('img', {src: 'images/ajax-loader.gif'});
	var td = new Element('td', {style:'text-align:center;'});
	var tr = new Element('tr', {id:"ajaxloader"});
	td.insert(img);
	tr.insert(td);
	return tr;
}


function loadProffesionalExperience(type){
	$('containerProfesionalExperience').insert({
		top: loaderEl()
	});
	
	var CVID = 0;
	var loadType = '';
	if(Object.isNumber(type)){
		loadType = 'existing';
		CVID = type;
	}
	else
		loadType = type;
	
	var noItems = $$('tr.profesionalExperience').length;
	
	new Ajax.Updater(
	$('containerProfesionalExperience'),
	navigatorPath + '/getajax|newProffesionalExperience', 
	{	
		'evalScripts': true,
		'parameters' : {'type' : type, 'CVID': CVID, 'noItems': noItems},
		'insertion': 'top',
		'onComplete' : function(){
			$('ajaxloader').remove();
		}
	});	
}


function loadEducationalExperience(type){
	$('containerEducationalExperience').insert({
		top: loaderEl()
	});
	
	var CVID = 0;
	var loadType = '';
	if(Object.isNumber(type)){
		loadType = 'existing';
		CVID = type;
	}
	else
		loadType = type;
	
	var noItems = $$('tr.educationalExperience').length;
	
	new Ajax.Updater(
	$('containerEducationalExperience'),
	navigatorPath + '/getajax|newEducationalExperience', 
	{	
		'evalScripts': true,
		'parameters' : {'type' : type, 'CVID': CVID, 'noItems': noItems},
		'insertion': 'top',
		'onComplete' : function(){
			$('ajaxloader').remove();
		}
	});	
}


function loadForeignLanguage(type){
	
	$('containerForeignLanguage').insert({
		top: loaderEl()
	});
	
	var CVID = 0;
	var loadType = '';
	if(Object.isNumber(type)){
		loadType = 'existing';
		CVID = type;
	}
	else
		loadType = type;
	
	var noItems = $$('tr.foreignLanguage').length;
	
	new Ajax.Updater(
	$('containerForeignLanguage'),
	navigatorPath + '/getajax|newForeignLanguage', 
	{	
		'evalScripts': true,
		'parameters' : {'type' : type, 'CVID': CVID, 'noItems': noItems},
		'insertion': 'top',
		'onComplete' : function(){
			$('ajaxloader').remove();
		}
	});	
}

function deleteComponent(elRemoveID, inputName, inputValue){
	$(elRemoveID).remove();
	//console.log(arguments);
	if(inputValue > 0){
		input = new Element('input', {'type':'hidden', 'name': 'delete['+inputName+'][]', 'value':inputValue});
		$('CVFrm').insert(input);
	}
}

function showMPContainer(showElID, hideElID){
	$('mainpage_'+showElID).show();
	$('mainpage_'+hideElID).hide();
	$('trigger_'+showElID).addClassName('activ');
	$('trigger_'+hideElID).removeClassName('activ');
}


function loadAutocomplete(elID, targetElID){
	new Autocomplete(elID, { 
    serviceUrl:navigatorPath + '/getajax|getAutocompleteCities',
    minChars:2, 
    maxHeight:400,
    width:300,
    deferRequestBy:100,
    onSelect: function(value, data){
			$(targetElID).setValue(data);
    }
  });
}

function performSearch(form){
	if(form.q.getValue() == 'Ex: agent, inginer, etc')
		form.q.clear();
	if(form.q.getValue() == 'Ex: adminstratie, php, etc')
		form.q.clear();
	var oSearchForm = document.searchFrm.serialize({'hash': true});
	new Ajax.Request(navigatorPath + '/getajax|saveLastSearch',  {
    method:'post',
    parameters: oSearchForm,
    onSuccess: function(transport) {
			form.submit();
		}
	});
}

function deploySeachBox(bSetup){
	
	if(bSetup){
		new Ajax.Request(navigatorPath + '/getajax|getLastSearch',  {
    method:'post',
    onSuccess: function(transport) {
			
			var form = document.searchFrm;
			var oForm = transport.responseJSON;
			//console.log(oForm.careerLevelID);
			if(oForm.q) 
				form.q.setValue(oForm.q);
			if(oForm.careerLevelID > 0) 
				selectSetValue(form.careerLevelID, oForm.careerLevelID);
			if(oForm.cityID > 0) {
				form.cityID.setValue(oForm.cityID);
				form.city.setValue(oForm.city);
			}
			if(oForm.domainID > 0)	
				selectSetValue(form.domainID, oForm.domainID);
			
			//console.log(Custom);
			
			$('cautareHP').show();
			$('caleSite').hide();
		}
	});
	}
	else{
		$('cautareHP').show();
		$('caleSite').hide();
	}
}

function selectSetValue(selectEl, newValue){
	selectEl.setValue(newValue);
	
	for (var i=0;i< selectEl.options.length;i++){
		if (selectEl.options[i].value == newValue){
			$('select'+selectEl.name).update(selectEl.options[i].label);
		}        
	}
}


function applyForJob(JOBID){
	
	new Ajax.Request(navigatorPath + '/getajax|remoteCheckAuthentification',  {
    method:'post',
		parameters : {remoteUrl: 'jobs|details?JOBID='+JOBID},
    onSuccess: function(transport) {
			var aResponse = transport.responseJSON;
			if(aResponse.isLogged)
				loadApplyForJob(JOBID);
			else
				window.location = navigatorPath + '/' + aResponse.redirectTo;
			
		}
	});
	
}

function loadApplyForJob(JOBID){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|jobApplication', 
		{	
			'evalScripts': true,
			'parameters' : {'JOBID':JOBID},
			'onComplete' : function(){
				setupDimensionsPosition('jobApplication');
				activeOverlayerID = 'jobApplication';
			}
	});
}


var activeOverlayerID = null;
function showOverlayer(){
	var overlay = new Element('div', {'id':'overlay', 'display':'none'});
	var pageSize = retrievePageSize();
	overlay.style.width = pageSize.width +"px";
	overlay.style.height = pageSize.height +"px";
	$(document.body).insert(overlay);
	new Effect.Appear('overlay', { duration: 0, from: 0.0, to: 0.8 });

	document.observe('keydown', handleKeyUp);

	activeOverlayerID = null;
}

function setupDimensionsPosition(elID, doNotFollow){
	var pageSize = retrievePageSize();
	
	// alert(Prototype.BrowserFeatures['Version']);
	
	if(elID && $(elID)) {
		var scrollOffset = document.viewport.getScrollOffsets();
		
		var top = (scrollOffset.top + document.viewport.getHeight() / 2 - $(elID).getHeight() / 2);
		top = (top > 0) ? top : 0;
		// alert(pageSize.width + '|' + $(elID).getWidth() + '|' + (pageSize.width / 2 - $(elID).getWidth() / 2));
		if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] == 7) {
			
			$(elID).style.left = ((990 / 2 - $(elID).getWidth() / 2)) * 1 + 'px';
		}
		else
			$(elID).style.left = (pageSize.width / 2 - $(elID).getWidth() / 2) + 'px';
		$(elID).style.top = top + 'px';

		// nu urmarim overlayerele mai mari decat viewportul
		if (activeOverlayerID == null && document.viewport.getHeight() > $(elID).getHeight() && !doNotFollow)
			Event.observe(window, 'scroll', handleScroll);
	}
	
	if ($('overlay')) {
		var overlay = $('overlay');
		if($(elID) && $(elID).getHeight() > $$('body')[0].getHeight())
			pageSize.height = $(elID).getHeight() + 50;
		
		overlay.style.width = pageSize.width +"px";
		overlay.style.height = pageSize.height +"px";
	}
	
}

function hidePopupOverlayer(elID){
	$(elID).remove();
	$(document.body).setStyle({ 'margin-top': '0px', 'padding-top': '0px' });
	$('overlay').remove();

	document.stopObserving('keydown', handleKeyUp);

	activeOverlayerID = null;
	Event.stopObserving(window, 'scroll', handleScroll);
}


function retrievePageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}


	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	return {width : pageWidth, height: pageHeight, windowWidth: windowWidth, windowHeight:windowHeight};
}

function handleKeyUp(e) {
	if (Event.KEY_ESC != e.keyCode) 
		return;

	// Esc was pressed
	var overlayers = ['jobApplication', 'bannerDiv', 'addCities', 'sendPrivateMessage', 'associateFolders', 'CVcompanies', 'saveSearch', 'sendEmailJobs', 'sendEmailCV'];
	overlayers.each(function (overlayer) {
		if ($(overlayer) && $(overlayer).style.display != 'none') {
			hidePopupOverlayer($(overlayer));
		}
	})
}


function handleScroll(e) {
	if (activeOverlayerID != null)
		setupDimensionsPosition(activeOverlayerID);
	// $('overlay')
}

function saveApplication(){
	//console.log($('application[CVID]').getValue());
	
	if($('application[CVID]').getValue() == 0)
		showToolTipFader(oSiteTexts.nu_ati_ales_nici_un_CV, $('application[CVID]'));
	else{
		var oJobApplicationForm = document.JobApplicationFrm.serialize({'hash': true});
		new Ajax.Request(navigatorPath + '/getajax|saveApplication',  {
			method:'post',
			parameters: oJobApplicationForm,
			onSuccess: function(transport) {
				hidePopupOverlayer('jobApplication');
				showToolTipFader(oSiteTexts.aplicat_cu_succes, $('titlujob'), true);
				new Effect.ScrollTo('header');
				//form.submit();
			}
		});
	}
}

function doSaveJob(JOBID, targetEl){
	new Ajax.Request(navigatorPath + '/getajax|doSaveJob',  {
			method:'post',
			parameters: {'performAction': 1, 'JOBID' : JOBID},
			onSuccess: function(transport) {
				
				var aResponse = transport.responseJSON;
				targetEl = (targetEl) ? targetEl : $('jobActionBox');
				// console.log(aResponse);
				if(aResponse.succes)
					showToolTipFader(oSiteTexts.job_ul_a_fost_salvat_cu_succes, targetEl, true);
				else	
					showToolTipFader(oSiteTexts.ati_salvat_deja_acest_job, targetEl, true);
			}
	});
}


function doCreateAlertJob(JOBID, targetEl){
	new Ajax.Request(navigatorPath + '/getajax|doCreateAlertJob',  {
			method:'post',
			parameters: {'performAction': 1, 'JOBID' : JOBID},
			onSuccess: function(transport) {
				targetEl = (targetEl) ? targetEl : $('jobActionBox');
				showToolTipFader(oSiteTexts.alerta_pentru_acest_job_a_fost_creata_cu_succes, $('jobActionBox'), true);
			}
	});
}


function doSaveCV(CVID, targetEl){
	new Ajax.Request(navigatorPath + '/getajax|doSaveCV',  {
			method:'post',
			parameters: {'performAction': 1, 'CVID' : CVID},
			onSuccess: function(transport) {
				targetEl = (targetEl) ? targetEl : $('cvActionBox');
				showToolTipFader(oSiteTexts.cv_ul_a_fost_salvat_cu_succes, targetEl, true);
			}
	});
}


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function loadIntoDate(selElID, inputElID, spanElID){
	var valueDate = $(selElID + '_year').getValue() + '-' + $(selElID + '_month').getValue() + '-' + $(selElID + '_day').getValue();
	$(inputElID).value = valueDate;
	$(spanElID).update(valueDate);
}

function loadIntoDateReverse(valueDate, selElID, spanElID){
	$(spanElID).update(valueDate);
	var aBirthDate = valueDate.split('-');
	
	$(selElID + '_year').setValue(aBirthDate[0]);
	$(selElID + '_month').setValue(aBirthDate[1]);
	$(selElID + '_day').setValue(aBirthDate[2]);
}

function verifyDates(section){
	var aProfessionalExperiences = $('CVFrm').select('tr.'+section);
	var errorInDates = false;
	aProfessionalExperiences.each(function(tr){
			if(!errorInDates){
				// console.log(tr);
				aSelInputs = tr.select('input.checkdate');
				startDate = aSelInputs[0].value;
				endDate = aSelInputs[1].value;
				idVal = aSelInputs[1].id.replace('[enploymentEndDate]', '');
				
				if(!startDate){
					showToolTipFader(oSiteTexts.nu_ati_ales_data_de_inceput, tr, 1);
					new Effect.ScrollTo(tr, {'offset':-100});
					errorInDates = true;
					return false;
				}
				
				if(!endDate && !($(idVal+'[lastJob]') && $(idVal+'[lastJob]').checked)){
					showToolTipFader(oSiteTexts.nu_ati_ales_data_de_sfarsit, tr, 1);
					new Effect.ScrollTo(tr, {'offset':-100});
					errorInDates = true;
					return false;
				}
				
				
				if(endDate && endDate < startDate){
					showToolTipFader(oSiteTexts.data_de_inceput_trebuie_sa_fie_mai_mica_decat_data_de_sfarsit, tr, 1);
					new Effect.ScrollTo(tr, {'offset':-100});
					errorInDates = true;
					return false;
				}
				
			}				
	});
	
	return errorInDates;
}

function verifyInfo(section){
	var aInputs = $(section).select('input.formular01', 'textarea.formular01');
	// console.log(aInputs);
	var errorInFields = false;
	aInputs.each(function(input){
		if(!errorInFields){
			var value = input.getValue();
			if(value.length < 4){
				showToolTipFader(oSiteTexts.nu_ati_completat_corect_acest_camp, input, 1);
				new Effect.ScrollTo(input, {'offset':-100});
				errorInFields = true;
				return false;
			}
		}
	});
	
	return errorInFields;
}


function submitCV(){
	
	var errorExists = false;
	// check dates for profesionalExperience
	errorExists = verifyDates('profesionalExperience');
	
	if(!errorExists)
	// check info for profesionalExperience
		errorExists = verifyInfo('containerProfesionalExperience');
	
	if(!errorExists)
	// check dates for educationalExperience
		errorExists = verifyDates('educationalExperience');
		
	if(!errorExists)
	// check info for educationalExperience
		errorExists = verifyInfo('containerEducationalExperience');
	
	// console.log('length', aProfessionalExperiences.length);
	// return false;
	
	if(!errorExists){
		var aProfessionalExperiences = $('containerProfesionalExperience').select('table.componentProfesionalExperience');
		
		if(aProfessionalExperiences.length > 0)
			$('CV[noProfesionalExperience]').checked = false;
		else
			$('CV[noProfesionalExperience]').checked = true;
		
		// var aEducationalExperiences = $('containerEducationalExperience').select('table.componentEducationalExperience');
		
		// if(aEducationalExperiences.length > 0)
			// $('CV[noEducationalExperience]').checked = false;
		// else
			// $('CV[noEducationalExperience]').checked = true;
		
		$('CVFrm').submit();
	}
}


function autoUpdateUsernameFromEmail(el) {
	var form = $(el).up('form');
	var parts = String(el.value).split('@');

	form.username.value = parts[0];
}

function populateDuration(durationID, maxDuration){
	new Ajax.Updater(
	$('jobAd[durationID]'),
	navigatorPath + '/getajax|getDuration', 
		{	
			'evalScripts': false,
			'parameters' : {'durationID': durationID, 'maxDuration': maxDuration}
		});
}

function checkJobAd(el, JOBID){

	new Ajax.Request(navigatorPath + '/getajax|checkJobAd',  {
    method:'post',
		parameters : {'JOBID': JOBID},
    onSuccess: function(transport) {
			var aResponse = transport.responseJSON;
			// console.log(aResponse);
			if(aResponse.isOK)
				window.location = el.href;
			else
				showToolTipFader(aResponse.message, el, 1);
			
		}
	});
	
}

function checkCV(el){

	new Ajax.Request(navigatorPath + '/getajax|checkCV',  {
    method:'post',
		parameters : {},
    onSuccess: function(transport) {
			var aResponse = transport.responseJSON;
			// console.log(aResponse);
			if(aResponse.isOK)
				window.location = el.href;
			else
				showToolTipFader(aResponse.message, el, 1);
			
		}
	});
}

function showSaveSearch(){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|saveSearch', 
		{	
			'evalScripts': true,
			'parameters' : {},
			'onComplete' : function(){
				setupDimensionsPosition('saveSearch');
				activeOverlayerID = 'saveSearch';
			}
	});
}

function saveSearch(){
	var searchName = $('searchName').getValue();
	if(!searchName)
		showToolTipFader('Nu ati completat acest camp', $('searchName'));
	else	
		new Ajax.Request(navigatorPath + '/getajax|saveSearch',  {
			method:'post',
			parameters: {'performAction': 1, 'searchName' : searchName},
			onSuccess: function(transport) {
				hidePopupOverlayer('saveSearch');
				showToolTipFader('Ati salvat cu succes cautarea.', $('showSaveSearch'), true);
				new Effect.ScrollTo('showSaveSearch', {'offset' : -100});
				//form.submit();
			}
		});
}


function loadSendEmailJob(URL, JOBID){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|sendEmailJobs', 
		{	
			'evalScripts': true,
			'parameters' : {'URL': URL, 'JOBID': JOBID},
			'onComplete' : function(){
				setupDimensionsPosition('sendEmailJobs');
				activeOverlayerID = 'sendEmailJobs';
			}
	});
}

function doSendEmail(){
	var oSendEmailForm = document.sendEmailForm.serialize({'hash': true});
	
	var errorInFields = false;
	if(!$('fromName').getValue()){
		showToolTipFader('Nu ati completat corect acest camp', $('fromName'), 0);
		$('fromName').focus();
		errorInFields = true;
	}
	else if(!$('fromEmail').getValue()){
		showToolTipFader('Nu ati completat corect acest camp', $('fromEmail'), 0);	
		$('fromEmail').focus();
		errorInFields = true;
	}
	else if(!$('toMail[0]').getValue()){
		showToolTipFader('Nu ati completat corect acest camp', $('toMail[0]'), 0);		
		$('toMail[0]').focus();
		errorInFields = true;
	}
		
	// var aFields = $('sendEmailJobs').select('input.formular01');
	// aFields.each(function(input){
		// var inputName = input.name;
		// //console.log(input, inputName, inputName.indexOf('1'), inputName.indexOf('2'));
		// if(inputName.indexOf('1') == -1 && inputName.indexOf('2') == -1 && !input.getValue()){
			// showToolTipFader('Nu ati completat corect acest camp', input, 1);
			// //new Effect.ScrollTo(input, {'offset':-100});
			// errorInFields = true;
			// return false;
		// }		
	// });
	var sendAction = (oSendEmailForm.JOBID > 0) ? 'doSendEmailJobs' : 'doSendEmailCV';
	var hideLayer = (oSendEmailForm.JOBID > 0) ? 'sendEmailJobs' : 'sendEmailCV';
	
	if(!errorInFields)
		new Ajax.Request(navigatorPath + '/getajax|' + sendAction,  {
			method:'post',
			parameters: oSendEmailForm,
			onSuccess: function(transport) {
				hidePopupOverlayer(hideLayer);
				showToolTipFader('Jobul a fost trimis. Va multumim!', $('stanga'), true);
				new Effect.ScrollTo($('stanga'), {'offset' : -100});
			}
		});
}

function loadSendEmailCV(URL, CVID){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|sendEmailCV', 
		{	
			'evalScripts': true,
			'parameters' : {'URL': URL, 'CVID': CVID},
			'onComplete' : function(){
				setupDimensionsPosition('sendEmailCV');
				activeOverlayerID = 'sendEmailCV';
			}
	});
}

function setSelectedDomains(el){
	if($('domainsContainer').select('input.toBeChecked:checked').length > 5){
		el.checked = false;
		alert(oSiteTexts.puteti_alege_maxim_5_optiuni);
		return false;
	}
	
	if(Object.isElement(el))
		setSimpleDomain(el);
	else{
		var aInputs = $('domainsContainer').select('input.toBeChecked');
		aInputs.each(function(input){
			setSimpleDomain(input);
		});
	}	
}

function setSimpleDomain(el){
	if(el.checked)
		el.up().addClassName('bold');
	else
		el.up().removeClassName('bold');
}

function toggleTextarea(el, focus){
	if(Object.isElement(el))
		toggleTextareaItem(el, focus);
	else{
		var aTextareas = $('textareaChecker').select('textarea.toBeChecked');
		aTextareas.each(function(textarea){
			textarea.onfocus = function(){
				toggleTextarea(this, 1);
			}
			
			textarea.onblur = function(){
				toggleTextarea(this);
			}
			
			toggleTextareaItem(textarea, focus);
		});
	}	
}

function toggleTextareaItem(textarea, focus){
	var hasContent = textarea.present();
	
	if(focus)
		$(textarea).morph('height:120px;');
	else if(!hasContent)
		$(textarea).morph('height:40px;');
	
}

function sendPrivateMessage(userID, remoteUrl, messageID){
	new Ajax.Request(navigatorPath + '/getajax|remoteCheckAuthentification',  {
    method:'post',
		parameters : {remoteUrl: remoteUrl},
    onSuccess: function(transport) {
			var aResponse = transport.responseJSON;
			if(aResponse.isLogged)
				loadSendPrivateMessage(userID, messageID);
			else
				window.location = navigatorPath + '/' + aResponse.redirectTo;	
		}
	});
}


function loadSendPrivateMessage(userID, messageID){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|sendPrivateMessage', 
		{	
			'evalScripts': true,
			'parameters' : {'userID':userID, 'messageID': messageID},
			'onComplete' : function(){
				setupDimensionsPosition('sendPrivateMessage');
				activeOverlayerID = 'sendPrivateMessage';
			}
	});
}


function savePrivateMessage(){
	//console.log($('application[CVID]').getValue());
	
	if(!$('privateMessage[subject]').present())
		showToolTipFader('Nu ati completat subiectul', $('privateMessage[subject]'));
	else if(!$('privateMessage[body]').present())
		showToolTipFader('Nu ati completat mesaj', $('privateMessage[body]'));	
	else{
		var oSendPrivateMessageFrm = document.sendPrivateMessageFrm.serialize({'hash': true});
		new Ajax.Request(navigatorPath + '/getajax|savePrivateMessage',  {
			method:'post',
			parameters: oSendPrivateMessageFrm,
			onSuccess: function(transport) {
				hidePopupOverlayer('sendPrivateMessage');
				showToolTipFader(oSiteTexts.ati_trimis_cu_succes_un_mesaj_acestui_utilizator, $('triggerSendPrivateMessage'), true);
				new Effect.ScrollTo('triggerSendPrivateMessage', {offset:-100});
				//form.submit();
			}
		});
	}
}

function deleteMultipleMessages(){
	var oPrivateMessagesFrm = document.privateMessagesFrm.serialize({'hash': true});
	new Ajax.Request(navigatorPath + '/getajax|deletePrivateMessages',  {
		method:'post',
		parameters: oPrivateMessagesFrm,
		onSuccess: function(transport) {
			window.location.reload();
		}
	});
}


function requestCVpermissions(el, CVID, CVCountyID){
	new Ajax.Request(navigatorPath + '/getajax|requestCVpermissions',  {
		method:'post',
		parameters: {'CVID': CVID, 'CVCountyID':CVCountyID},
		onSuccess: function(transport) {
			showToolTipFader('O cere a fost trimisa catre redactie. Veti fi notificat cand aceasta va fi aprobata.', el, true);
			//new Effect.ScrollTo(el);
		}
	});
}


function associateFolders(saveID, type){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|associateFolders', 
		{	
			'evalScripts': true,
			'parameters' : {'saveID': saveID, 'type' : type},
			'onComplete' : function(){
				setupDimensionsPosition('associateFolders');
				activeOverlayerID = 'associateFolders';
			}
	});
}


function doAssociateFolders(){
		var oAssociateFoldersFrm = $(document.associateFoldersFrm).serialize({'hash': true});
		new Ajax.Request(navigatorPath + '/getajax|doAssociateFolders',
		{
			method:'post',
			parameters: oAssociateFoldersFrm,
			onSuccess: function(transport) {
				window.location.reload();
			}
		});
	
}

function showCVCompanies(CVID){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|showCVCompanies', 
		{	
		'evalScripts': true,
		'parameters' : {'CVID': CVID},
		'onComplete' : function(){
			setupDimensionsPosition('CVcompanies');
			activeOverlayerID = 'CVcompanies';
		}
	});
}

function confirmDelete(el){
	var ok = confirm(oSiteTexts.sunteti_sigur_ca_vreti_sa_stergeti_elementul);
	if(ok)
		window.location.href = el.href;

}

// var lastValidSelection
var aLimitOptions = {};
function limitOptions(el, no){
	var aSelected = el.getValue();
	if(aSelected.length > 5){
		// el.update(el.lastInnerHTML);
		console.log('update:' + aLimitOptions[el.name]);
		for(index in el.options)
			el.options[index].selected = (aLimitOptions[el.name].indexOf(el.options[index].value) != -1);
		alert(oSiteTexts.puteti_alege_maxim_5_optiuni);
	}
	else{
		aLimitOptions[el.name] = el.getValue();
		console.log('insert:' + aLimitOptions[el.name]);
	}
	
	//console.log(el.innerHTML);
}


function selectAccountNextStep(el){
	// console.log();
	if($('account[mainUserID]').getValue() == 0){
		showToolTipFader('nu ati ales un cont!', $('account[mainUserID]'));
		return false;
	}
	else{
		var mainUserID = $('account[mainUserID]').getValue();
		var mainUserName = $('account[mainUserID]').options[$('account[mainUserID]').selectedIndex].label;
		$('mainUserIDContainer').update('<strong>' + mainUserName + '</strong>');
		input = new Element('input', {'type':'hidden', 'name':'account[mainUserID]', 'value': mainUserID});
		$('mainUserIDContainer').insert(input);
		el.remove();
		
		
		// console.log(mainUserName);
		// return false;
		var parameters = {
			'performAction' : 1,
			'email' : $('account[email]').getValue(),
			'transactionKey' : $('account[transactionKey]').getValue(),
			'mainUserID' : mainUserID
		};
		new Ajax.Updater(
		$('nextStepReceiver'),
		navigatorPath + '/getajax|getAccountNextStep', 
		{	
			'evalScripts': true,
			'parameters' : parameters
		});
	}	
}

var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
function selectAccount(){
	var aAccountEmails = $('nextstep').select('input.formular01'), isValid = 1, aEmails = new Array();
	
	aAccountEmails.each(function(input){
		var value = input.getValue();
		if(value.match(emailRegEx)){
			aEmails.push(value);
		}
		else{
			showToolTipFader('Email necompletat corect. Daca nu doriti sa pastrati contul, folositi optiunea <strong>sterge</strong>.', input);
			isValid = 0;
			throw $break;
		}
	});
	
	if(isValid){
		console.log(aEmails);
		new Ajax.Request(navigatorPath + '/getajax|checkAccountEmails',  {
    method:'post',
    parameters: {'aEmails': Object.toJSON(aEmails), 'email':$('account[email]').getValue(), 'transactionKey' : $('account[transactionKey]').getValue()},
    onSuccess: function(response){   
    	var data = response.responseJSON;
			
			if(data.isValid){
				document.selectAccountFrm.submit();
			}
			else{
				var str = 'Urmatoarele email-uri sunt asociate unor conturi pe acest site:';
				data.errors.each(function(errorEmail){
					str += '<br/>- ' + errorEmail;
				});
				showToolTipFader(str, $('triggerSelectAccount'), true);
			}
				
    	// writeComments(response, showRating, itemType);    	
    },
    onFailure: function(){
			alert('Eroare: Va rugam incercati mai tarziu !');
		}
  });
	}
	
}



function addCities(type){
	showOverlayer();
	new Ajax.Updater(
	'popupContainer',
	navigatorPath + '/getajax|addCities', 
		{	
		'evalScripts': true,
		'parameters' : {'type': type},
		'onComplete' : function(){
			setupDimensionsPosition('addCities');
			activeOverlayerID = 'addCities';
		}
	});
}


function saveCities(type){
	var aCities = $('tmpCities[cityID]').childElements(), type = (type) ? type : 'CV', cityID = 0, cityName = '';
	
	aCities.each(function(option){
		if(option.selected && !$('addCitiesID_' + option.value)){
			cityID = option.value; cityName = option.innerHTML;
			var strHTML = '<div id="addCitiesID_' + cityID + '" class="orase"><input type="hidden" name="'+type+'[cityID]['+cityID+']" id="CV[cityID]['+cityID+']" value="'+cityID+'"/> ' + cityName + ' <a class="sterge" href="#" onclick="this.up().remove();return false;">x</a></div>';
			$('citiesReceiver').insert(strHTML);
		}
	});
	
	hidePopupOverlayer('addCities');
}

function setupShareLinks(el) {
	var baseHref = document.getElementsByTagName('base')[0].href;
	var ajaxTo = baseHref + 'index.html' + '/mainpage|getShortUrl';
	
	var icon = el.down('img');
	icon.setAttribute('data-orig-src', icon.getAttribute('src'));
	icon.setAttribute('src', 'images/butoane/r0.gif');

	new Ajax.Request(ajaxTo,  {
		method:'post',
		parameters: {'url': escape(window.location.href) },
		onSuccess: function(transport){
			var shareLinks = el.up('div').select('a.shareLink');
			shareLinks.each(function(shareLink) {
				shareLink.setAttribute('href', shareLink.href + transport.responseText);
				shareLink.setAttribute('onclick', ';');
			});

			icon.setAttribute('src', icon.getAttribute('data-orig-src'));

		},
		onFailure: function(){  }
	});
}


function loadOverBanner(imgSrc){
	showOverlayer();
	$('popupContainer').update('');
	var div = new Element('div', {'class':'boxMic', 'id':'bannerDiv', 'style':'width: 635px;'});
	var subdiv = new Element('div', {'class':'continutBox'});
	var img = new Element('img', {'src':imgSrc});
	subdiv.insert(img);
	div.insert(subdiv);
	$('popupContainer').insert(div);
	$('popupContainer').insert('<div class="cleaner">&nbsp;</div>');
	$('popupContainer').firstDescendant().firstDescendant().insert('<center style="margin:20px 0px 10px 0px;"><a class="portoMare" href="#" onclick="hidePopupOverlayer(\'bannerDiv\'); return false;"><span>' +oSiteTexts.inchide +'</span></a></center>');
	setupDimensionsPosition('bannerDiv', true);
	activeOverlayerID = 'bannerDiv';
	new Effect.ScrollTo($('bannerDiv'));
}
