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

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



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

function popup(url, name, width, height, scroll, modal, resizable, menubar) {
	width=Math.min(screen.availWidth,width);
	height=Math.min(screen.availHeight-40,height);
	var poz_x=(screen.availWidth-width)/2;
	var poz_y=(screen.availHeight-height-30)/2;
	if(menubar==''){
		menubar='no';
	}
	newwin=window.open(url, name, 'scrollbars='+scroll+', menubar='+menubar+', width='+width+', height='+height+', resizable='+(resizable ? 'yes' : 'no')+',toolbar=no, left='+poz_x+', top='+poz_y+', location=no, status=yes');
	if(modal){
		popInt=setInterval(function(n){
			if(typeof(newwin.name)=="string"){
				if(newwin.document.body){
					openerfocus=function(){
						if(typeof(newwin.name)=="string"){
							newwin.focus();
						}else{
							document.body.onfocus=null;
						}
					}
					document.body.onfocus=openerfocus;
					newwin.window.document.body.onunload=function(){alert(66)}
					newwin.focus();
					/*with(newwin){
						self.focus()
						opener.document.body.onfocus=function(){self.focus();opener.alert(4);}
						self.document.body.onunload=function(){opener.document.body.onfocus=null}
					}*/
					clearInterval(popInt);
				}
			}else{
				clearInterval(popInt)
			}
		},1)
	}
}

function hex2rgb(val) {
	//hex2rgb convert
	//created by Sebastian Serban 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 backgroundTrans(obj,color,time,prop,callback){
	//created by Sebastian Serban
	//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();
		}
	}
	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){
	//created by Sebastian Serban
	//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();
		}
	}
	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) {
	//function for finding elements in arrays
	//created by Sebastian Serban, 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 ? '<param name="wmode" value="transparent" />' : '')+'<embed style="'+style+'" name="'+id+'" src="'+url+'" quality="high" allowFullScreen="true" bgcolor="'+bgcolor+'" width="'+width+'" height="'+height+'" flashVars="'+vars+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
}

function updateCounter(txt,counter,limit,cut){
	var l=limit-txt.value.replace(/\r\n/g,'\n').replace(/\n/g,'\r\n').length;
	if(counter.value!=null){
		counter.value=l;
	}else{
		counter.innerHTML=l;
	}
	if(cut && l<=0){
		txt.value=txt.value.replace(/\r\n/g,'\n').replace(/\n/g,'\r\n').substr(0,limit);
	}
	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 "nonull":
			$valid = $value!="";
			break;
		case "name":
			$valid = $value.trim().match(/^[^`~!@#$%^&*()_=+\[{\]}\\|;:'",<.>\/?]+$/);
			break;
		case "username":
			$valid = $value.match(/^[^\s]+$/i);
			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 "float":
			$valid = $value.match(/^[0-9\-]+((,|\.)[0-9\-]+)?$/);
			break;
		case "float+":
			$valid = $value.match(/^\-?[0-9\-]+((,|\.)[0-9\-]+)?$/);
			break;
		case "phone":
			$valid = $value.trim().match(/^\+?([0-9]+[\s\-\.]?)*[0-9]+$/);
			break;
		case "password":
			$valid = $value.length>=6 && $value.length<=50 && $value.match(/[0-9].*[a-z]|[a-z].*[0-9]/i);
			break;
		case "nozero":
			$valid = $value!="0";
			break;
		default:
			var $m=$type.match(/\/(.*)\/(.*)/);
			$valid = $m!=null ? $value.match(new RegExp($m[1],$m[2])) : null;
	}
	return $value=="" && $allow_null || Number($valid)!=0;
}

function changecat(val)
{
	val=val.split("|");
	document.formular.distanta1.value=val[0];
	document.formular.distanta2.value=val[1];
	calculate();
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function changetip(i)
{

	if (i==1)
	{
		document.getElementById("tip11").style.display="";
		document.getElementById("tip21").style.display="";
		document.getElementById("tip22").style.display="";
		document.getElementById("tip33").style.display="";
		val=document.formular.tipcultura.value;

		changecat(val);
		document.formular.distanta1.disabled=true;
		document.formular.distanta2.disabled=true;


	}
	if (i==2)
	{
		document.getElementById("tip11").style.display="none";
		document.getElementById("tip22").style.display="none";
		document.formular.distanta1.disabled=false;
		document.formular.distanta2.disabled=false;
		calculate();
	}
	if (i==3)
	{
		document.getElementById("tip11").style.display="none";
		document.getElementById("tip22").style.display="";
		document.formular.distanta1.disabled=false;
		document.formular.distanta2.disabled=false;
		calculate();

	}

}

function calculate()
{
	tip_randuri=getCheckedValue(document.formular.tip);
	lungime=parseFloat(document.formular.lungime.value.replace(/,/,".").replace(/[^0-9,\.]/g,""));
	latime=parseFloat(document.formular.latime.value.replace(/,/,".").replace(/[^0-9,\.]/g,""));
	d1=parseFloat(document.formular.distanta1.value.replace(/,/,".").replace(/[^0-9,\.]/g,""));
	d2=parseFloat(document.formular.distanta2.value.replace(/,/,".").replace(/[^0-9,\.]/g,""));
	if (isNaN(d1))
	d1=0;
	if (isNaN(d2))
	d2=0;
	directie=getCheckedValue(document.formular.d);

	cat=document.formular.tipcultura.value;
	distanta=parseFloat(document.formular.dist.value.replace(/,/,".").replace(/[^0-9,\.]/g,""));

	L=(directie==1 ? lungime : latime);
	LR=(directie==0 ? lungime : latime);
	D=(tip_randuri==2 ? d1 : (d1+d2)/2);
	R=(D!=0 ? (Math.round((L*100)/D)+1) : 0);
	if (isNaN(R))
	R=0;
	if (isNaN(L))
	L=0;
	if (isNaN(distanta))
	distanta=0;

	document.getElementById("nr_randuri").innerHTML=R;
	document.getElementById("nr_m").innerHTML=(R*LR)+" m";
	document.getElementById("nr_c").innerHTML=R;
	document.getElementById("nr_d").innerHTML=R;
	document.getElementById("nr_a").innerHTML=(L+distanta)+" m";
}

function loadLocalitate(cod,rt){
	var rot;
	if(rt){
		rot=rt;
	}else{
		rot='';
	}
	$.get(rot+'-operatii.php',{op:6,jud:cod},function(data){
		$('#arr_localitate').html(data);
		$('#arr_localitate').css('display','inline');		
	});
}

function loadLocalitate1(cod,id,rt){
	var rot;
	if(rt){
		rot=rt;
	}else{
		rot='';
	}
	$.get(rot+'-operatii.php',{op:6,jud:cod},function(data){
		$('#'+id).html(data);
	});
}

function loadLocalitate2(cod,cod1,id){
	$.get('-operatii.php',{op:6,jud:cod,loc:cod1},function(data){
		$('#'+id).html(data);
	});
}


function validareCIF(cif){
	if(cif.substring(0,2).toUpperCase()=='RO'){ cif=cif.substring(2);}
	if (isNaN(cif)||cif.length>10){
		return false;
	}else{
		cifra_control=cif.substring(cif.length-1);
		cif=cif.substring(0,cif.length-1);
		while (cif.length!=9){
	    	cif='0'+cif;
	    }
        suma=cif[0] * 7 + cif[1] * 5 + cif[2] * 3 + cif[3] * 2 + cif[4] * 1 + cif[5] * 7 + cif[6] * 5 + cif[7] * 3 + cif[8] * 2;
        suma=suma*10;
        rest=suma%11;
        if( rest==10 ) rest=0;
        if(rest==cifra_control){ 
        	return true;
        }else{ 
        	return false; 
        }
    }
}

function checkdate(m,d,y) {
    return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}

function validareCNP(cnp){
	if(cnp==''||isNaN(cnp)||cnp.length!=13){
		return false;
	}else{
		var sex=new Array('1','2','5','6','9');
		an=cnp[1]+cnp[2];
		luna=cnp[3]+cnp[4];
		zi=cnp[5]+cnp[6];
		jud=cnp[7]+cnp[8];
		sumac=cnp[0]*2+cnp[1]*7+cnp[2]*9+cnp[3]*1+cnp[4]*4+cnp[5]*6+cnp[6]*3+cnp[7]*5+cnp[8]*8+cnp[9]*2+cnp[10]*7+cnp[11]*9;
		rest=sumac%11;
		if(jQuery.inArray(cnp[0],sex)||(luna==0&&luna>12)||(zi>31||zi==0)||!checkdate(luna,zi,an)||(jud>52||jud==0)||((rest<10&&rest!=cnp[12])||(rest==10&&cnp[12]!=1))){
			return false;
		}else{
			return true;
		}
	}	
}

this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.wordtip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='wordtip'>"+ this.t +"</p>");
		$("#wordtip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#wordtip").remove();
    });	
	$("a.wordtip").mousemove(function(e){
		$("#wordtip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


