nav = navigator.appName.indexOf("Microsoft")!= -1 ? 1 : 2;

//////////PROJECT SPECIFIC FUNCTIONS

function votes_vote(type,id,value){
	$('#vote'+type+'_'+id+'_0,#vote'+type+'_'+id+'_1').attr('disabled','disabled');
	sendAndLoad(_root+'-vote.php?type='+type+'&id='+id+'&value='+value,function(value){
		if(value && value!=''){
			value=value.split('|');
			$('#votenum'+type+'_'+id+'_0').html(value[2]);
			$('#votenum'+type+'_'+id+'_1').html(value[1]);
		}
	})
}

function tooltip(obj,html){
	getE('tooltip_content').innerHTML=html;
	var offset=$(obj).offset();
	$('#tooltip').css({top:Math.max(0,offset.top-$('#tooltip').outerHeight()),left:offset.left+$(obj).width()-$('#tooltip').width()}).fadeIn();
}

function validareData(){
	$("select[name='data_nastere[0]']").css('border-color','');
	$("select[name='data_nastere[1]']").css('border-color','');
	$("select[name='data_nastere[2]']").css('border-color','');
	
	if($("select[name='data_nastere[2]']").val()==0 || $("select[name='data_nastere[1]']").val()==0 || $("select[name='data_nastere[0]']").val()==0){
		$("select[name='data_nastere[0]']").css('border-color','red');
		$("select[name='data_nastere[1]']").css('border-color','red');
		$("select[name='data_nastere[2]']").css('border-color','red');
	}else document.formular.submit(); 
}

function showZodie(id,nod){
	if(id==1){
		$("#z"+nod).css("display","none");
		$("#z1"+nod).css("display","");
	}else{
		$("#z"+nod).css("display","");
		$("#z1"+nod).css("display","none");
	}
}

function slideShow(speed) {  
	 //Set the opacity of all images to 0  
	$('ul.slideshow li').css({opacity: 0.0});  
	 //Get the first image and display it (set it to full opacity)  
	 $('ul.slideshow li:first').css({opacity: 1.0});  
	 //Call the gallery function to run the slideshow      
	 var timer = setInterval('gallery()',speed);  
	  //pause the slideshow on mouse over  
	 $('ul.slideshow, #slideshow-caption div a, #up, #down').hover(  
		 function () {  
			 clearInterval(timer);     
		 },    
		 function () {  
			 timer = setInterval('gallery()',speed);           
		 }  
	 );  
	   
 }  
   
function gallery() {
	//if no IMGs have the show class, grab the first image
	var current = ($('ul.slideshow li.sho')?  $('ul.slideshow li.sho') : $('ul.slideshow li:first'));
	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first'));
	var idu = next.attr('id');    
	//Set the fade in effect for the next image, show class has higher z-index
	next.css({opacity: 0.0}).addClass('sho').animate({opacity: 1.0}, 3000);
	$(".sl-sel").removeClass("sl-sel");
	$("#"+idu+"1").addClass('sl-sel');
	//Hide the current image
	current.animate({opacity: 0.0}, 3000).removeClass('sho');
}

//////////COMMON FUNCTIONS

function colorboxPopup(url,width,height){
	$.colorbox({href:url,close:'',iframe:true,innerWidth:width,innerHeight:height});
}

function colorboxAutoResize(container){
	$.colorbox.resize(container ? {innerWidth:$(container).outerWidth(),innerHeight:$(container).outerHeight()} : null);
}

function lockScreen(message,closable){
	$('#jqdlg').html('<table style="width:100%;height:100%"><tr><td align="center">'+(message==null ? __l.loading_msg : message)+'</td></tr></table>').dialog({
		modal:true,
		closeOnEscape:false,
		height:100,
		dialogClass:'abs_float',
		resizable:false,
		open:closable ? null : function(event,ui){
			$('.ui-dialog-titlebar').hide();
		}
	});
}

function form_check(form,inputClassToggle,labelClassToggle){
	inputClassToggle=inputClassToggle==null ? 'input_error' : inputClassToggle;
	labelClassToggle=labelClassToggle==null ? 'error' : labelClassToggle;
	var ok=true;
	(form instanceof Array ? $(form).filter('[validation]') : $(form).find('input[validation]')).filter(":visible").each(function(){
		var valid=isValid(this.value,this.getAttribute('validation'),this.getAttribute('validationallownull')=='true');
		$(this).toggleClass(inputClassToggle,!valid);
		$('#label_'+this.name).toggleClass(labelClassToggle,!valid);
		$('#err_'+this.name).toggle(!valid);
		ok=ok && valid;
	})
	return ok;
}

function elfinder_tinymce(field_name,url,type,win){
	/*if($('#div_elfinder').length>0){
		$('#div_elfinder').elfinder('open');
		return;
	}*/
	var temp=function(){
		var lang=tinyMCE.selectedInstance.settings.language;
		if(lang!='en'){
			$.getScript(_root+'elfinder/js/i18n/elfinder.'+lang+'.js');
		}
		$('<div id="div_elfinder"/>').elfinder({
			url:url_home+'elfinder/connectors/php/connector.php?select='+escape(url),
			lang:lang,
			places:__l.elfinder_places,
			closeOnEditorCallback:true,
			height:500,
			cookie:{expires:30,domain:cookie_domain,path:cookie_path,secure:cookie_secure},
			dialog:{width:'90%',modal:true,title:__l.elfinder_title,zIndex:400000,close:function(event,ui){$(event.target).dialog('destroy')}},
			editorCallback:function(url){
				win.document.forms[0][field_name].value=url;
				win.document.forms[0][field_name].onchange();
			}
		})
	}
	if($.fn.elfinder){
		temp();
	}else{
		loadCSS(_root+'elfinder/css/elfinder.css');
		loadScript(_root+'elfinder/js/elfinder.min.js',temp);
	}
}

function fckfilemanager_tinymce(field_name,url,type,win){
	tinyfck_field=field_name;
	tinyfck=win;
	popup(_root+'fckeditor/editor/filemanager/browser/default/browser.html?Connector='+_root+'fckeditor/editor/filemanager/connectors/php/connector.php&Type='+type.charAt(0).toUpperCase()+type.substr(1),'tinyfck',1024,768);
}

function scrollPage(value,duration,callback){
	$('html,body').stop().animate({scrollTop:parseInt(value)==value ? value : getAbsY(typeof(value)=='string' ? $(value).get(0) : value)},duration==null ? 500 : duration,'easeOutQuad',callback);
}

function hex2rgb(val) {
	//v1.0 (17.06.2005)
	return [val >> 16, val >> 8 & 0xff, val & 0xff];
};

function formatNumber(nr, decimals, dec_point, sep) {
	//17.02.2010
	decimals=decimals == null ? 0 : Math.abs(decimals);
	dec_point=dec_point==null ? "." : dec_point;
	sep=sep==null ? "," : sep;
	var sign=nr<0 ? '-' : '';
	nr = String(Math.abs(nr)).split(".");
	nat = nr[0];
	nr[0] = "";
	if(nr[1]==null){
		nr[1]="";
	}
	for(var i=nr[1].length;i<decimals;i++){
		nr[1]+="0";
	}
	for (var i = nat.length; i>0; i -= 3) {
		nr[0] = nat.substr(Math.max(i-3, 0), 3+Math.min(i-3, 0))+sep+nr[0];
	}
	nr[0] = nr[0].substr(0, nr[0].length-sep.length);
	return sign+nr[0]+(nr[1] != "" ? (decimals>0 ? dec_point : "")+nr[1].substr(0, decimals) : "");
}

function formatSize($size,$dec_point,$thousand_step){
	$dec_point=$dec_point==null ? "." : $dec_point;
	$thousand_step=$thousand_step==null ? "," : $thousand_step;
	$sizes={"TB":Math.pow(1024,4),"GB":Math.pow(1024,3),"MB":Math.pow(1024,2),"KB":1024};
	for($key in $sizes){
		if($size>=($value=$sizes[$key])){
			return formatNumber($size/$value,3-(Math.floor($size/$value)+"").length,$dec_point,$thousand_step)+" "+$key;
		}
	}
	return formatNumber($size,0,"",$thousand_step)+" B";
}

function formatTime(seconds,showMiliseconds,showHours){
	showHours=showHours==null ? seconds>=3600 : showHours;
	return (showHours ? (seconds<36000 && showHours>1 ? '0' : '')+Math.floor(seconds/3600)+':' : '')+((showHours ? seconds%3600 : seconds)<600 ? '0' : '')+Math.floor((showHours ? seconds%3600 : seconds)/60)+':'+(seconds%60<10 ? '0' : '')+formatNumber(seconds-Math.floor(seconds/60)*60,showMiliseconds ? 3 : 0);
}

function backgroundTrans(obj,color,time,prop,callback){
	//v1.3 (26.10.2005)
	if(prop == undefined){
		prop = "bgColor";
	}
	clearInterval(obj.interval);
	var endValue = color;
	color = hex2rgb(Number("0x"+color.substr(1)));
	var startValue = hex2rgb(Number("0x"+obj[prop].substr(1)));
	var timePast = 0;
	obj.stopTrans = function(){
		clearInterval(this.interval);
	}
	obj.endTrans = function(){
		this.stopTrans();
		this[prop] = endValue;
		if(callback!=null){
			callback(this);
		}
	}
	var callf = function(){
		timePast+=50;
		if(timePast >= time){
			obj.endTrans();
		}else{
			var new_color = (parseInt(startValue[0]+timePast*(color[0]-startValue[0])/time))*0x10000;
			new_color += (parseInt(startValue[1]+timePast*(color[1]-startValue[1])/time))*0x100;
			new_color += (parseInt(startValue[2]+timePast*(color[2]-startValue[2])/time));
			new_color = new_color.toString(16);
			try{
				obj[prop] = "#"+new_color;
			}catch(err){
				//alert(err.description+new_color);
			}
		}
	}
	obj.interval=setInterval(callf,10);
	callf();
}

function bgTrans(obj,start_color,color,time,callback){
	//v1 (25.01.2006)
	obj.style.backgroundColor=start_color;
	clearInterval(obj.interval);
	var endValue = color;
	color = hex2rgb(Number("0x"+color.substr(1)));
	//var startValue = hex2rgb(Number("0x"+obj.style.backgroundColor.substr(1)));
	var startValue = hex2rgb(Number("0x"+start_color.substr(1)));
	var timePast = 0;
	obj.stopTrans = function(){
		clearInterval(this.interval);
	}
	obj.endTrans = function(){
		this.stopTrans();
		this.style.backgroundColor = endValue;
		if(callback!=null){
			callback(this);
		}
	}
	var callf = function(){
		timePast+=50;
		if(timePast >= time){
			obj.endTrans();
		}else{
			var new_color = (parseInt(startValue[0]+timePast*(color[0]-startValue[0])/time))*0x10000;
			new_color += (parseInt(startValue[1]+timePast*(color[1]-startValue[1])/time))*0x100;
			new_color += (parseInt(startValue[2]+timePast*(color[2]-startValue[2])/time));
			new_color = new_color.toString(16);
			try{
				obj.style.backgroundColor = "#"+new_color;
			}catch(err){
				//alert(err.description+new_color);
			}
		}
	}
	obj.interval=setInterval(callf,10);
	callf();
}

function addOption(theSel, theText, theValue){
	var newOpt = new Option(theText, theValue);
	var selLength = theSel.length;
	theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex){ 
	var selLength = theSel.length;
	if(selLength>0){
		theSel.options[theIndex] = null;
	}
}

function moveOptions(theSelFrom,theSelTo,mode){
	//mode: 0-move,1-copy,2-delete

	mode=mode==null ? 0 : mode;
	var selLength = theSelFrom.length;
	var selectedText = new Array();
	var selectedValues = new Array();
	var selectedCount = 0;

	// Find the selected Options in reverse order
	// and delete them from the 'from' Select.
	for(var i=selLength-1;i>=0;i--){
		if(theSelFrom.options[i].selected){
			selectedText[selectedCount] = theSelFrom.options[i].text;
			selectedValues[selectedCount] = theSelFrom.options[i].value;
			if(mode!=1){
				deleteOption(theSelFrom, i);
			}
			selectedCount++;
		}
	}

	// Add the selected text/values in reverse order.
	// This will add the Options to the 'to' Select
	// in the same order as they were in the 'from' Select.
	if(mode<2){
		for(i=selectedCount-1; i>=0; i--){
			if(mode==1){
				var duplicate=0;
				for(var j=0;j<theSelTo.options.length;j++){
					if(theSelTo.options[j].value==selectedValues[i]){
						duplicate=1;
						break;
					}
				}
				if(duplicate){
					continue;
				}
			}
			addOption(theSelTo, selectedText[i], selectedValues[i]);
		}
	}
	if(theSelFrom.onchange){
		theSelFrom.onchange();
	}
	if(theSelTo.onchange){
		theSelTo.onchange();
	}
}

function isBisYear(year){
	return (year%4==0 && year%100!=0) || year%400==0
}

function correctDate(f,nume){
	var zileinluna=[31,31,29,31,30,31,30,31,31,30,31,30,31];
	zileinluna[2]=isBisYear(f[nume+'[0]'].value) ? 29 : 28;
	var nrz=zileinluna[Number(f[nume+'[1]'].value)];
	if(f[nume+'[2]'].value>nrz){
		try{
			f[nume+'[2]'].selectedIndex=nrz-(f[nume+'[2]'].options.length==31 ? 1 : 0);
		}catch(e){
		}
	}
}

Array.prototype.find = function(elem, all) {
	//v3.2 (18.10.2004)
	//this function receives "elem" which may be an number or an array and returns the position or an array of the positions
	//if param "all" is defined, then function return array with all the positions instead of position of the first element found
	if (elem.length == undefined || typeof (elem) != "object") {
		elem = [elem];
		single = true;
	}else{
		single = false;
	}
	var result = [];
	if (all == undefined) {
		for (var k = 0; k<elem.length; k++) {
			result[k] = -1;
			toFind = elem[k];
			for (var i = 0; i<this.length; i++) {
				if (this[i] == toFind) {
					result[k] = i;
					break;
				}
			}
		}
	} else {
		for (var k = 0; k<elem.length; k++) {
			result[k] = [];
			toFind = elem[k];
			for (var i = 0; i<this.length; i++) {
				if (this[i] == toFind) {
					result[k].push(i);
				}
			}
			if (result[k][0] == undefined) {
				result[k] = -1;
			}
		}
	}
	if (single) {
		return result[0];
	} else {
		return result;
	}
}

function writeFlash(divid,url,width,height,bgcolor,id,vars,transparent,menu,style){
	document.getElementById(divid).innerHTML = '<object charset="UTF-8" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="'+id+'" width="'+width+'" height="'+height+'" style="'+style+'" flashvars="'+vars+'"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="'+url+'" /><param name="quality" value="high" /><param name="allowFullScreen" value="true" /><param name="bgcolor" value="'+bgcolor+'" /><param name="flashVars" value="'+vars+'" />'+(menu==0 || menu==1 ? '<param name="menu" value="'+menu+'" />' : '')+(transparent!=0 ? '<param name="wmode" value="'+(transparent==1 ? 'transparent' : transparent)+'" />' : '')+'<embed style="'+style+'" name="'+id+'" src="'+url+'" quality="high" allowFullScreen="true" bgcolor="'+bgcolor+'" width="'+width+'" height="'+height+'" flashVars="'+vars+'"'+(menu==0 || menu==1 ? ' menu="'+menu+'"' : '')+(transparent!=0 ? ' wmode="'+(transparent==1 ? 'transparent' : transparent)+'"' : '')+' align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
}

function updateCounter(txt,counter,limit,cut){
	counter.tabIndex='-1';
	var l=limit-txt.value.replace(/\r\n/g,'\n').replace(/\n/g,'\r\n').length;
	if(cut && l<0){
		var caret=getSelStart(txt);
		var scroll=txt.scrollTop;
		txt.value=txt.value.replace(/\r\n/g,'\n').replace(/\n/g,'\r\n').substr(0,limit);
		setSelRange(txt,caret,caret);
		txt.scrollTop=scroll;
		l=0;
	}
	if(counter.value!=null){
		counter.value=l;
	}else{
		counter.innerHTML=l;
	}
	counter.style.color=l<0 ? "#ff0000" : "#6699cc";
}

function isNumberKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	return charCode<31 || charCode>48 && charCode<57;
}

arr_escape={
"ă":"%C4%83",
"Ă":"%C4%82",
"î":"%C3%AE",
"Î":"%C3%8E",
"â":"%C3%A2",
"Â":"%C3%82",
"ş":"%C5%9F",
"Ş":"%C5%9E",
"ţ":"%C5%A3",
"Ţ":"%C5%A2",
"Ţ":"%C5%A2",
"+":"%2B",
"/":"%2F"
};

function rawurlencode(str){
	var result="";
	for(var i=0;i<str.length;i++){
		var chr=str.charAt(i);
		if(arr_escape[chr]!=undefined){
			result+=arr_escape[chr];
		}else{
			result+=escape(chr);
		}
	}
	return result;
}

function rawurldecode(str){
	for(var i in arr_escape){
		str=str.replace(new RegExp(arr_escape[i],"g"),i);
	}
	return unescape(str);
}

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

function mailTo(email){
	email=decodeURIComponent(email);
	var new_email='';
	for(var i=email.length-1;i>=0;i--){
		new_email+=email.charAt(i);
	}
	document.location='mailto:'+new_email;
}

function isValid($value,$type,$allow_null){
	switch($type){
		case 'novoid':
			$valid = $value.trim()!='';
			break;
		case 'novoid2':
			$valid = $value.trim().length>=2;
			break;
		case 'nonull':
			$valid = $value.toString()!='';
			break;
		case 'name':
			$valid = $value.trim().match(/^[^`~!@#$%^&*()_=+\[{\]}\\|;:'",<.>\/?]{2,}$/) && $value.trim().length>=2;
			break;
		case 'username':
			$valid = $value.match(/^[-a-z0-9_.]*[a-zA-Z][-a-z0-9_.]*$/i) && $value.length>=2 && $value.length<=20;
			break;
		case 'email':
			$valid = $value.match(/^([-0-9a-z_~%+]+[-\.0-9a-z_~%+]*[-0-9a-z_~%+]+|[-0-9a-z_~%+])@[-0-9a-z_~]+(\.[-0-9a-z_~]+)*\.[0-9a-z_]{2,5}$/i);
			break;
		case 'int':
			$valid = $value.match(/^\-?[0-9]+$/);
			break;
		case 'int+':
			$valid = $value.match(/^[0-9]+$/);
			break;
		case 'int>0':
			$valid = $value.match(/^[0-9]+$/) && parseInt($value)>0;
			break;
		case 'float':
			$valid = $value.match(/^\-?[0-9\-]+((,|\.)[0-9\-]+)?$/);
			break;
		case 'float+':
			$valid = $value.match(/^[0-9\-]+((,|\.)[0-9\-]+)?$/);
			break;
		case 'float>0':
			$valid = $value.match(/^[0-9\-]+((,|\.)[0-9\-]+)?$/) && parseFloat($value)>0;
			break;
		case 'phone':
			$valid = $value.trim().match(/^\+?([0-9]+[- .]?)*[0-9]+$/) && $value.length>4;
			break;
		case 'password':
			$valid = $value.length>=6 && $value.length<=32 && $value.match(/[0-9].*[a-z]|[a-z].*[0-9]/i);
			break;
		case 'ip':
			$valid = $value.match(/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]?)$/);
			break;
		case 'url':
			$valid = $value.match(/^https?\:\/\/([a-z0-9](\-|(\-?[a-z0-9])+)[a-z0-9]\.){1,}[a-z]{2,5}(\/.*)?$/i);
			break;
		case 'url_video':
			$valid = $value.match(new RegExp('^(?:http\://)?(?:www.)?('+video_patterns.join('|')+')'));
			break;
		case 'urlid':
			$valid = $value.match(/^[0-9a-z-]+$/i);
			break;
		case 'hour':
			$valid = $value>=0 && $value<24;
			break;
		case 'nozero':
			$valid = $value!='0';
			break;
		case 'date':
			$valid = typeof($value)=='string' ? ($m=$value.match(/(\d{4})-([0-2]\d)-([0-3]\d)/)) && checkDate($m[2],$m[3],$m[1]) : checkDate($value[1],$value[2],$value[0]);
			break;
		case 'cnp':
			$valid = ($m=$value.match(/^([1-9])(\d\d)([0-2]\d)([0-3]\d)(\d\d)(\d\d\d)(\d)$/)) && checkDate($m[3],$m[4],($m[1]<3 ? '19' : ($m[1]<5 ? '18' : ($m[1]<7 ? '20' : '19')))+$m[2])/* && ($m[1]!=5 && $m[1]!=6 || '20'+$m[2]+$m[3]+$m[4]<=date('Ymd'))*/ && $m[5]>0 && $m[5]<53 && $m[6]>0 && ((($value[0]*2+$value[1]*7+$value[2]*9+$value[3]*1+$value[4]*4+$value[5]*6+$value[6]*3+$value[7]*5+$value[8]*8+$value[9]*2+$value[10]*7+$value[11]*9)%11)+'').replace('10','1')==$value[12];
			break;
		case 'cif':
			$valid = ($m=$value.match(/^(?:ro)?(\d*[1-9]\d+)$/i)) && ($m=strPad($m[1],10,'0','left')).length<11 && ((($m[0]*7+$m[1]*5+$m[2]*3+$m[3]*2+$m[4]*1+$m[5]*7+$m[6]*5+$m[7]*3+$m[8]*2)*10)%11)%10==$m[9];
			break;
		default:
			if($type.charAt(0)=='='){
				$valid = $value==$type.substr(1);
			}else if($type.charAt(0)=='>'){
				$valid = $type.charAt(1)=='=' ? parseFloat($value)>=parseFloat($type.substr(2)) : parseFloat($value)>parseFloat($type.substr(1));
			}else if($type.charAt(0)=='<'){
				$valid = $type.charAt(1)=='=' ? parseFloat($value)<=parseFloat($type.substr(2)) : parseFloat($value)<parseFloat($type.substr(1));
			}else{
				var $m=$type.match(/\/(.*)\/(.*)/);
				$valid = $m!=null ? $value.toString().match(new RegExp($m[1],$m[2])) : null;
			}
	}
	return $value=='' && $allow_null || Number($valid)!=0;
}

function spy(obj, all, extra, depth, html) {
	//v1.1 (11.08.2011)
	var result = "";
	extra = extra == null ? "" : extra;
	depth = depth == null ? 10 : depth;
	for (var i in obj) {
		result += extra+i+" : "+typeof(obj[i])+" = "+obj[i]+(html ? '<br />' : "\n");
		if (all && depth>0) {
			if ((typeof(obj[i]) == "object")) {
				result += spy(obj[i], true, extra+(html ? '&nbsp;&nbsp;' : "\t"),depth-1,br);
			}
		}
	}
	return result;
}

function trace(str,showProperties){
	var div=getE('div_trace');
	div.innerHTML+=(showProperties ? spy(str,null,null,null,1) : str)+'<br />';
	$(div).scrollTop(100000);
	div.style.display='';
	div.onmouseover=function(){
		$(div).css({opacity:1,height:200});
	}
	div.ondblclick=function(){
		$(div).css({opacity:0,height:20});
	}
	div.onmouseover();
}
