var nickExistent = 0;
var emailExistent;
var pasProfil = 1;
var url_ = "http://www.businessworkshop.ro/mat/";
var flag = 0;

function sprintf( ) {
	    // *     example 1: sprintf("%01.2f", 123.1);
	    // *     returns 1: 123.10
	 
	    var regex = /%%|%(\d+\$)?([-+#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
	    var a = arguments, i = 0, format = a[i++];
	 
	    // pad()
	    var pad = function(str, len, chr, leftJustify) {
	        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
	        return leftJustify ? str + padding : padding + str;
	    };
	 
	    // justify()
	    var justify = function(value, prefix, leftJustify, minWidth, zeroPad) {
	        var diff = minWidth - value.length;
	        if (diff > 0) {
	            if (leftJustify || !zeroPad) {
            value = pad(value, minWidth, ' ', leftJustify);
            } else {
            value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };
 
    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };
 
    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad);
    };
 
    // finalFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        if (substring == '%%') return '%';
 
        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false;
        for (var j = 0; flags && j < flags.length; j++) switch (flags.charAt(j)) {
            case ' ': positivePrefix = ' '; break;
            case '+': positivePrefix = '+'; break;
            case '-': leftJustify = true; break;
            case '0': zeroPad = true; break;
            case '#': prefixBaseX = true; break;
        }
 
        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }
 
        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }
 
        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }
 
        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }
 
        // grab value using valueIndex if required?
        var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
 
        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd': {
                        var number = parseInt(+value);
                        var prefix = number < 0 ? '-' : positivePrefix;
                        value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                        return justify(value, prefix, leftJustify, minWidth, zeroPad);
                    }
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                        {
                        var number = +value;
                        var prefix = number < 0 ? '-' : positivePrefix;
                        var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                        var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                        value = prefix + Math.abs(number)[method](precision);
                        return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
                    }
            default: return substring;
        }
    };
 
    return format.replace(regex, doFormat);
}


function populareOrase(judetID){
	$("oras").innerHTML = "";
	url = url_ + 'listaOrase.php' + '?r='+Math.random(); 
	new Ajax.Request(url,{
		method:'post',
		parameters:{judetID:judetID},
		onSuccess: fData,
		onFailure: function(){ alert('connection lost..'); }
	});
}

function fData(t){
	R = t.responseText.evalJSON();  
	R.items.each(function(pair) {
	el = new Element("option");
	//el.id = pair.id;
	el.innerHTML = pair.category;
	el.value = pair.id;
	$("oras").appendChild(el);
 	});
}

function verify_form(){
	var err = "";
	verificareNick($F('nick'));
	if( $('nume').value=='' || $('prenume').value=='' || $('nick').value=='' || $('email').value=='' ) {
		flag=1;
		err = "Completati toate campurile !";
	}else if (nickExistent==2){
		flag=1;
		err= "Nume de utilizator existent !";
	}
	
	if(flag) {
		nickExistent = 0;
		flag=0;
		showMessage(err);
	}	
	else $('frm').submit();
	//$('btn_submit').style.disable = "";
}

function verificareNick(nick){ alert(nick);
	//$('btn_submit').style.disable = "true";
	url = url_ + 'verificare_existenta_nick.php' + '?r='+Math.random(); 
	new Ajax.Request(url,{
		method:'post',
		parameters:{nick:nick},
		onSuccess: fDataNick,
		onFailure: function(){ showMessage('Eroare de conectare..'); }
	});
}

function fDataNick(t){
	R = t.responseText; alert(R);
	if (R) nickExistent = 2;
	else nickExistent = 1;
}

function listaOrase (judet){
	url = 'http://localhost/listaOrase.php' + '?r='+Math.random(); 
	new Ajax.Request(url,{
		method:'post',
		parameters:{judetID:judet},
		onSuccess: function(){
			R = t.responseText.evalJSON();  
			R.items.each(function(pair) {
			el = new Element("option");
			//el.id = pair.id;
			el.innerHTML = pair.category;
			el.value = pair.id;
			$("oras").appendChild(el);
		 	});
		},
		onFailure: function(){ alert('connection lost..'); }
	});
}

function changeTab(tab){
	switch(tab){
		case "aspect":
			$('tbl_aspect').show();
			$('tab_aspect').setStyle({
				backgroundColor : '#EBEBEB'
			});
			$('tbl_statut').hide();
			$('tab_statut').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_stil').hide();
			$('tab_stil').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_descriere').hide();
			$('tab_descriere').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_contact').hide();
			$('tab_contact').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_poza').hide();
			$('tab_poza').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('btn_submit').hide();
			break;
		
		case "statut":
			$('tbl_aspect').hide();
			$('tab_aspect').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_statut').show();
			$('tab_statut').setStyle({
				backgroundColor : '#EBEBEB'
			});
			$('tbl_stil').hide();
			$('tab_stil').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_descriere').hide();
			$('tab_descriere').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_contact').hide();
			$('tab_contact').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_poza').hide();
			$('tab_poza').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('btn_submit').hide();
			break;
		
		case "stil":
			$('tbl_aspect').hide();
			$('tab_aspect').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_statut').hide();
			$('tab_statut').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_stil').show();
			$('tab_stil').setStyle({
				backgroundColor : '#EBEBEB'
			});
			$('tbl_descriere').hide();
			$('tab_descriere').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_contact').hide();
			$('tab_contact').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_poza').hide();
			$('tab_poza').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('btn_submit').hide();
			break;
			
		case "descriere":
			$('tbl_aspect').hide();
			$('tab_aspect').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_statut').hide();
			$('tab_statut').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_stil').hide();
			$('tab_stil').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_descriere').show();
			$('tab_descriere').setStyle({
				backgroundColor : '#EBEBEB'
			});
			$('tbl_contact').hide();
			$('tab_contact').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_poza').hide();
			$('tab_poza').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('btn_submit').hide();
			break;
		
		case "contact":
			$('tbl_aspect').hide();
			$('tab_aspect').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_statut').hide();
			$('tab_statut').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_stil').hide();
			$('tab_stil').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_descriere').hide();
			$('tab_descriere').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_contact').show();
			$('tab_contact').setStyle({
				backgroundColor : '#EBEBEB'
			});
			$('tbl_poza').hide();
			$('tab_poza').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('btn_submit').show();
			break;
				
			
		case "poza":
			$('tbl_aspect').hide();
			$('tab_aspect').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_statut').hide();
			$('tab_statut').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_stil').hide();
			$('tab_stil').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_descriere').hide();
			$('tab_descriere').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_contact').hide();
			$('tab_contact').setStyle({
				backgroundColor : '#FFFFFF'
			});
			$('tbl_poza').show();
			$('tab_poza').setStyle({
				backgroundColor : '#EBEBEB'
			});
			$('btn_submit').hide();
			break;	
	}
}

var icons = new Array();
icons[0] = ":) ";
icons[1] = "(roll) ";
icons[2] = ":D ";

function txt_icons(icon_no, area){
	if (area) document.getElementById('desc_'+area).value += icons[icon_no];
	else document.getElementById('desc').value += icons[icon_no];
}

function txt_icons_user(icon_no, id){
	document.getElementById(id).value += icons[icon_no];
}

function pasi_profil(){
	if (pasProfil==1){
		$('p1').hide();
		$('p2').show();
		pasProfil=2;
		$('pasi_profil').innerHTML = "<< inapoi";
	}else{
		$('p2').hide();
		$('p1').show();
		pasProfil=1;
		$('pasi_profil').innerHTML = "mai mult >>";
	}
}

function switch_textarea(){
	if($('cnt_txtarea').style.display == 'none') {
		$('cnt_txtarea').show();
		$('txt_coment').innerHTML = 'inchide comentariul';
	}
	else {
		$('cnt_txtarea').hide();
		$('txt_coment').innerHTML = 'adauga comentariu';
	}
}

function verifica_comentariu(id){
	if($(id).value != '') $('frm_'+id).submit();
}

function ch_b(id){
	$('b_'+id).className='bar_sex_b';
}

function ch_r(id){
	$('b_'+id).className='bar_sex_r';
}

function ch_back(id){
	$('b_'+id).className='bar_sex';
}

function trimite_mesaj(m){
	if(m){
		$$('.dummy').each(function(el){
			el.remove();
		});
		aPr.each(function(id){
			a = id.split("-");
			e = new Element("input",{type:'hidden', value:a[0], name:'destinatieID[]'});
			e.className="dummy";
			$('frm_mesaj').appendChild(e);
		});
		if(!$F('sub') || !$F('desc') || !aPr.length){
			showMessage('Completati toate campurile !');
		} else $('frm_mesaj').submit();
	}else{
		if(!$F('sub') || !$F('desc')){
			showMessage('Completati toate campurile !');
		} else $('frm_mesaj').submit();
	}	
}


var aPr = [];
function addUser(userID, userNick){ 
	aPr.push(userID+"-"+userNick);
	aPr = aPr.uniq();
	$('add_pr').innerHTML="";
	
	aPr.each(function(id){
		a = id.split("-");
		s = new Element("span",{id:'s'+a[0], title:'sterge'});
		s.setStyle({color:'#34ADEF', margin:'3px', display:'inline-block', fontWeight:'bold', cursor:'hand', cursor:'pointer'});
		s.innerHTML = a[1];
		s.observe('mouseover', mouseOver);
		s.observe('mouseout', mouseOut);
		s.observe('click', mouseClick);
//		c = new Element("img", {id:'c'+a[0], src:"http://www.businessworkshop.ro/mat/templates/images/cancel.jpg"});
//		c.setStyle({});
//		e.appendChild(c);
		$('add_pr').appendChild(s);
	});
}

function updateCounterPr(){
	$('cnt_pr').innerHTML = aPr.length;
}

function mouseClick(e){
	el = e.element();
	el.remove();
	id  = (el.id).substring(1,(el.id).length);
	nick = el.innerHTML;
	aPr = aPr.without(id + '-' + nick);
	updateCounterPr();
}

function mouseOver(e){
	el = e.element();
	el.setStyle({color:'red', textDecoration:'line-through'});
}

function mouseOut(e){
	el = e.element();
	el.setStyle({color:'#34ADEF', textDecoration:'none'});
}

function getList(uID){
	$('sr_dv').innerHTML = "";
//	if ($F('sr').strip().empty()) {
//		$('sr_dv').hide();
//	}
//	else{
		$('sr_dv').style.visibility="visible";
		$('sr').value = $F('sr').strip();
		
		url = 'filtru_prieteni.php' + '?r='+Math.random();
		i = new Element("img", {src:url_+ "templates/images/ajax-loader.gif"});
		$('sr_dv').appendChild(i);
		new Ajax.Request(url,{
			method:'post',
			parameters:{id:uID, str:$F('sr')},
			onSuccess: function(t){
				R = t.responseText.evalJSON();
				i.remove();
				R.items.each(function(pair) {
					e = new Element("div",{id:pair.id});
					e.setStyle({cursor:'hand', cursor:'pointer', padding:'3px'});
					e.innerHTML = pair.nick;
					e.observe('click', respondToClick);
					e.observe('mouseover', respondToMouseOver);
					e.observe('mouseout', respondToMouseOut);
					$('sr_dv').appendChild(e);
				});
			},
			onFailure: function(){ 
				//alert(url); 
			}
		});
	//}	
}

function respondToClick(e){
	el = e.element();
	addUser(el.id, el.innerHTML);
	updateCounterPr();
	//$(el.id).remove();
}

function respondToMouseOver(e){
	el = e.element();
	el.className="listOver";
}

function respondToMouseOut(e){
	el = e.element();
	el.className="listOut";
}

function showMessage(txt){
	$('msg_txt').innerHTML=txt;
	Effect.SlideDown('msg',{ duration: 0.3 });
	var p = new PeriodicalExecuter(function(){
		Effect.SlideUp('msg',{ duration: 0.3 })
		p.stop();
	},2);
}

function hideMsg(){
	$('msg').hide();
}

function sterge_mesaje(){
	$('frm_st').submit();
}

var prieten = 0;

function add_prieten(id,uID,vID){
	if(!prieten){
		url = url_ + "cererePrietenie.php";
		new Ajax.Request(url,{
			method:'post',
			parameters:{uID:uID, vID:vID},
			onSuccess: function fDataPrieten(){
					prieten = 1;
					$('img_pr').src= url_ + "templates/images/p_n.gif";
					showMessage("A fost trimisa o cerere de prietenie");
			},
			onFailure: function(){ alert('connection lost..'); }
		});
		//n1.txt = "<strong>A fost trimisa o cerere de prietenie !</strong>";
		//n1.image_off = "<img src='http://www.businessworkshop.ro/mat/templates/images/p_n.gif'/>";
		//n1.sendData();
	}	
}

function blockUser(userID, userBlocatID, block){
	url = url_ + "blocareUser.php" + "?r="+Math.random();
	new Ajax.Request(url,{
		method:'post',
		parameters:{userID:userID, userBlocatID:userBlocatID, block:block},
		onSuccess: function fBlockUser(t){
			resp = t.responseText;
			//alert(resp);
			if(block && block==resp){
				$('txt_block').onclick = null;
				showMessage("Utilizatorul a fost blocat !");
				$('txt_block').src= url_ + "templates/images/unblock.gif";
				$('txt_block').title="deblocheaza utilizator";
				$('txt_block').observe('click', function(){
					blockUser(userID, userBlocatID, 0);
				});
				$('txt_blk').innerHTML = "deblocheaza utilizator";
			}else if(!block && block==resp){
				$('txt_block').onclick = null;
				showMessage("Utilizatorul a fost deblocat !");
				$('txt_block').src= url_ + "templates/images/block.gif";
				$('txt_block').title="blocheaza utilizator";
				$('txt_block').observe('click', function(){
					blockUser(userID, userBlocatID, 1);
				});
				$('txt_blk').innerHTML = "blocheaza utilizator";
			}else {}
		},
		onFailure: function(){ showMessage("Eroare la conectare cu serverul !"); }
	});
}

function verify_yahoo_form(){
	if($F('yahoo_user') && $F('yahoo_user')) $('frm_yahoo').submit();
	else showMessage("Completati toate campurile");
}






/* ----- HTML Select ----- */

function resetAllSelects()
{
	uls=document.getElementsByTagName("ul");
	for(i=0;i<uls.length;i++)
	{
		if(uls[i].className=="HTMLoptions" && uls[i].style.display!="none")
		{
			if(uls[i].parentNode.className=="HTMLselectOpened")
			{
				uls[i].parentNode.className="HTMLselect"
			}
			uls[i].style.display="none";
		}
	}
}

function scrollToLetter(letter)
{
	if(document.getElementsByTagName("body")[0].innerHTML.indexOf('class="HTMLselectOpened"')>-1)
	{
		var found=false;
		var lis=new Array();
		uls=document.getElementsByTagName("ul");
		for(i=0;i<uls.length;i++)
		{
			if(uls[i].className=="HTMLoptions" && uls[i].style.display!="none")
			{
				if(uls[i].parentNode.className=="HTMLselectOpened")
				{
					lis=uls[i].getElementsByTagName("li");
					break;
				}
			}
		}
		for(j=0;j<lis.length;j++)
		{
			if(found==false)
			{
				if(lis[j].getElementsByTagName("a").length>0)
				{
					liNodes=lis[j].getElementsByTagName("a");
					
					if(liNodes[0].innerHTML.indexOf(letter)==0)
					{
						lis[j].scrollIntoView(true);
						found=true;
					}
				}
				else if(lis[j].innerHTML.indexOf(letter)==0)
				{
					uls[i].parentNode.scrollTo(lis[j]);
					found=true;
				}
			}
		}
	}
}

function expandSelect(HTMLselect)
{
	
	if(HTMLselect.className!="HTMLselectOpened")
	{
		resetAllSelects();
	}
	Hselect=HTMLselect;
	Hnodes=Hselect.childNodes;
	if(Hselect.className=="HTMLselect")
	{
		Hselect.className="HTMLselectOpened";
		for(i=0;i<Hnodes.length;i++)
		{
			if(Hnodes[i].className=="HTMLoptions")
			{
				Hnodes[i].style.display="block";
				Hnodes[i].style.height="140px";
				Hnodes[i].style.overflow="auto";
			}
		}
	}
	else
	{
		Hselect.className="HTMLselect";
		for(i=0;i<Hnodes.length;i++)
		{
			if(Hnodes[i].className=="HTMLoptions")
			{
				Hnodes[i].style.display="none";
			}
		}
	}
}

function selectOption(option)
{
	Hselect=option.parentNode.parentNode;
	Hnodes=Hselect.childNodes;
	for(i=0;i<Hnodes.length;i++)
	{
		if(Hnodes[i].className=="HTMLselected")
		{
			Hnodes[i].innerHTML=option.innerHTML;
			expandSelect(Hselect);
		}
	}
}

function showDropdown(drop)
{
	dropdown=document.getElementById(drop);
	Hselect=dropdown.parentNode;
	
	dd=document.createElement("div");
	dd.innerHTML=dropdown.innerHTML;
	dd.className="HTMLselect";
	dd.style.width=dropdown.style.width;
	dd.id=dropdown.id;
	
	Hnodes=Hselect.childNodes;
	for(i=0;i<Hnodes.length;i++)
	{
		if(Hnodes[i].style)
		{
			Hnodes[i].style.display="none";
		}
	}
	
	Hselect.appendChild(dd);
	Hselect.removeChild(dropdown);
}

/* ----- End HTML Select ----- */