function showHelp(varIDHelp)
	{
	 obj = document.getElementById(varIDHelp);
     if (obj.style.display == 'block')  obj.style.display = 'none';
     else  obj.style.display = 'block';
	}


function emptyElement(varIDHelp)
	{
		document.getElementById('general').innerHTML = '';

	}


function check_form2() {
	var error = 0;
	var error_message = "S-a produs o EROARE in timpul inregistrarii dvs!\nVa rugam sa efectuati urmatoarele corectii:\n\n";

	var old_password = document.account_edit.old_password.value;
	var password     = document.account_edit.password.value;
	var confirmation = document.account_edit.confirmation.value;

	if (password != confirmation) {
		error_message = error_message + "* 'Parola' si 'Confirmare' trebuie sa fie aceleasi si sa aibe cel putin 5 caractere.\n";
		error = 1;
	}

	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}
}

/* Pop up */
function MM_openBrWindow(theURL,winName,features) {
	window.open(theURL,winName,features);
}

function toggle( targetId ){
	if (document.getElementById){
		target = document.getElementById( targetId );
		if (target.style.display == "block"){
			target.style.display = "none";
		}
		else {
			target.style.display = "block";
		}
	}
}

function toggleStyle( targetId, parinte ){
	if (document.getElementById){
		target = document.getElementById( targetId );
		if (target.style.display == "block"){
			target.style.display = "none";
			document.getElementById(parinte).style.borderWidth="0";
			document.getElementById(parinte).style.backgroundColor="white";
		}
		else {
			target.style.display = "block";
			document.getElementById(parinte).style.borderColor="#999999";
			document.getElementById(parinte).style.borderWidth="1px";
			document.getElementById(parinte).style.borderStyle="solid";
			document.getElementById(parinte).style.backgroundColor="#fffee5";
		}
	}
}

function toggleM( targetId, secondTargetId ){
	if (document.getElementById){
		target = document.getElementById( targetId );
		target2 = document.getElementById( secondTargetId );
		if (target.style.display == "block"){
			target2.style.display = "block";
			target.style.display = "none";
		}
		else {
			target.style.display = "block";
			target2.style.display = "none";
		}
	}
}

var timerafiseaza=null, timersorteaza=null;

function setState(which, state) {
	document.getElementById(which).style.display = state;
	if (self["timer"+which]!=null) clearTimeout(self["timer"+which]);
}

function toggleTimed( targetId, state ) {
	var states = new Array("none", "block");
	if (document.getElementById(targetId).style.display==states[state] && self["timer"+targetId]!=null)
		clearTimeout(self["timer"+targetId]);
	else {
		if (state==0)
			self["timer"+targetId]=setTimeout("setState('"+targetId+"', '"+states[state]+"')", 350);
		else
			setState(targetId, states[state]);
	}
}

function refresh_costs() {
	cost_transport = document.getElementById('costtransport').innerHTML.substring(19);
	cost_ramburs = document.getElementById('costramburs').innerHTML.substring(16);
	document.getElementById('costtotal').innerHTML = 'Total costuri expeditie: ' + (parseFloat(cost_transport) + parseFloat(cost_ramburs)) + ' RON';
}

function set_text(element, value)
{
	target = document.getElementById(element);
	target.innerHTML = value;

	refresh_costs();
}

function verificaModPlata(what) {
	var lft = new Array("transport1", "transport2", "transport3");
	var rgt = new Array("numerar", "op", "card", "inrate");
	var found = false;
	var msg = "";
	for (i=0; i<lft.length; i++) {
		if (document.getElementById(lft[i]) && document.getElementById(lft[i]).checked) {
			found = true;
			break;
		}
	}
	if (!found) {
		msg += "- Nu ati ales modalitatea de transport!";
	}
	found = false;
	for (i=0; i<rgt.length; i++) {
		if (document.getElementById(rgt[i]) && document.getElementById(rgt[i]).checked) {
			found = true;
			break;
		}
	}
	if (!found) {
		msg += "\n- Nu ati ales modalitatea de plata!";
	}
	if (what==1) {
		if (msg!="") {
			window.alert(msg);
			return false;
		}
		else {
			return true;
		}
	}
	else if (what==2 && msg!="") {
		document.checkoutform.action="/checkout#fact";
	}
	else if (what==2 && msg=="") {
		document.checkoutform.action="/confirmare";
	}
	return true;
}

function goSub() {
	document.checkoutform.submit();
}

function calculateCosts(c_curier,c_roexpres,c_ramburs) {

	 cost_livrare		= 0;
	 cost_ramburs	= 0;

	document.getElementById('ramburs_text').className 			= '';
    	document.getElementById('ramburs_value').className 			= '';

	document.getElementById('ramburs_text').innerHTML			='';
	document.getElementById('ramburs_value').innerHTML			= '';

	val_cost_cos				= document.getElementById('cost_cos').value;
	val_cost_cos_tva			= document.getElementById('cost_cos_tva').value;

	val_cost_cos				= val_cost_cos.replace('.', '');
	val_cost_cos				= val_cost_cos.replace(',', '.');
	val_cost_cos_tva			= val_cost_cos_tva.replace('.', '');
	val_cost_cos_tva			= val_cost_cos_tva.replace(',', '.');

	t1		= document.getElementById('transport1');
	t2		= document.getElementById('transport2');
	t3		= document.getElementById('transport3');

	c1		= document.getElementById('numerar');
	c2		= document.getElementById('op');
	c3		= document.getElementById('card');
	c4		= document.getElementById('inrate');


    if (t1 && t1.checked == true) {
        	cost_livrare	= 0;
		cost_ramburs	= 0;
    }

	if (t2 && t2.checked == true) {
	   if (parseFloat(val_cost_cos)<500) {
		 cost_livrare	= c_curier;
	   }
		cost_ramburs	= 0;
    }

	if (t3 && t3.checked == true) {
        if (parseFloat(val_cost_cos)<1000) {
		 cost_livrare	= c_roexpres;
	   }
	   if (c1 && c1.checked == true) {
	     cost_ramburs	= c_ramburs;
	   }
    }

    var cost_total = parseFloat(val_cost_cos_tva)  + parseFloat(cost_ramburs) + parseFloat(cost_livrare);

	var nf = new NumberFormat();
	nf.setInputDecimal('.');
	nf.setPlaces(2);
	nf.setSeparators(true,'.',',');


	if (cost_ramburs>0) {
		nf.setNumber(cost_ramburs);
		cost_ramburs = nf.toFormatted();

	    document.getElementById('ramburs_value').className 			= 'sep';
		document.getElementById('ramburs_text').className 			= 'sep';
		document.getElementById('ramburs_text').innerHTML			='Costuri ramburs:<span>Taxa de ramburs este perceputa de firma de curierat pentru returul banilor.</span>';
		document.getElementById('ramburs_value').innerHTML			= cost_ramburs + ' RON';
	}

	nf.setNumber(cost_livrare);
	cost_livrare = nf.toFormatted();



	nf.setNumber(cost_total);
	cost_total = nf.toFormatted();

	document.getElementById('c_transport').innerHTML				= cost_livrare + ' RON';
	document.getElementById('cost_total').innerHTML				= cost_total + ' RON';
}

function setFieldsPlataLivrare() {

	if (document.getElementById('numerar') && document.getElementById('numerar').checked == true) {
     document.getElementById('plata_1').value	= 6;
    }
    if (document.getElementById('op') && document.getElementById('op').checked == true) {
     document.getElementById('plata_1').value	= 1;
    }
    if (document.getElementById('card') && document.getElementById('card').checked == true) {
     document.getElementById('plata_1').value	= 5;
    }
    if (document.getElementById('inrate') && document.getElementById('inrate').checked == true) {
     document.getElementById('plata_1').value	= 4;
    }

	document.getElementById('serie_buletin_1').value = document.getElementById('serie_buletin').value;
	document.getElementById('numar_buletin_1').value = document.getElementById('numar_buletin').value;
	document.getElementById('ora_livrare_1').value = document.getElementById('ora_livrare').value;
	document.getElementById('comments_1').value = document.getElementById('comments').value;
}

function calculateRamburs(c_ramburs,transport,cost_livrare) {

	 cost_ramburs	= 0;

	document.getElementById('ramburs_text').className 			= '';
    	document.getElementById('ramburs_value').className 			= '';

	document.getElementById('ramburs_text').innerHTML			='';
	document.getElementById('ramburs_value').innerHTML			= '';

	val_cost_cos				= document.getElementById('cost_cos').value;
	val_cost_cos_tva			= document.getElementById('cost_cos_tva').value;

	val_cost_cos				= val_cost_cos.replace('.', '');
	val_cost_cos				= val_cost_cos.replace(',', '.');
	val_cost_cos_tva			= val_cost_cos_tva.replace('.', '');
	val_cost_cos_tva			= val_cost_cos_tva.replace(',', '.');


	c1		= document.getElementById('numerar');
	c2		= document.getElementById('op');
	c3		= document.getElementById('card');
	c4		= document.getElementById('inrate');



	if (transport == 'roexpres') {
	   if (c1 && c1.checked == true) {
	     cost_ramburs	= c_ramburs;
	   }
    }

    var cost_total = parseFloat(val_cost_cos_tva)  + parseFloat(cost_ramburs) + parseFloat(cost_livrare);

	var nf = new NumberFormat();
	nf.setInputDecimal('.');
	nf.setPlaces(2);
	nf.setSeparators(true,'.',',');


	if (cost_ramburs>0) {
		nf.setNumber(cost_ramburs);
		cost_ramburs = nf.toFormatted();

	    document.getElementById('ramburs_value').className 			= 'sep';
		document.getElementById('ramburs_text').className 			= 'sep';
		document.getElementById('ramburs_text').innerHTML			='Costuri ramburs:<span>Taxa de ramburs este perceputa de firma de curierat pentru returul banilor.</span>';
		document.getElementById('ramburs_value').innerHTML			= cost_ramburs + ' RON';
	}


	nf.setNumber(cost_total);
	cost_total = nf.toFormatted();

	document.getElementById('cost_total').innerHTML				= cost_total + ' RON';
}

var cntcup=1;

function adaugaCupon() {
	var wrappingBut = document.createElement('input');
	wrappingBut.type = "text";
	wrappingBut.name = "cod_cupon["+cntcup+"]";
	cntcup++;
	wrappingBut.value = "";
	wrappingBut.className = "casuta";
	wrappingBut.style.display = "block";
	wrappingBut.style.margin = "4px 0";
	document.getElementById("cupoane").appendChild(wrappingBut);
}

/* Verificare input
*****************************************************************/

function checkValid(id, msg, regula) {
	var prefix = "* ";
	var suffix = "\n";

	if (!document.getElementById(id))
		return "";

	switch(regula) {
		case 'required':
						if (document.getElementById(id).value=="")
							return prefix+msg+suffix;
						break;
		case 'select':
						if (document.getElementById(id).options[document.getElementById(id).selectedIndex].value=="")
							return prefix+msg+suffix;
						break;
		case 'numeric':
						var validch = "0123456789.";
						var isNumber=true;
						var ch;
						var val = document.getElementById(id).value;

						for (i=0; i<val.length && isNumber == true; i++) {
							ch = val.charAt(i);
							if (validch.indexOf(ch) == -1)
								return prefix+msg+suffix;
						}
						break;
		case 'email':
						var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
						if (!filter.test(document.getElementById(id).value.replace(new RegExp("[\\s]+$", "g"), "")))
							return prefix+msg+suffix;
						break;
		case 'integer':
						var filter=/^\d{0,9}$/;
						if (!filter.test(document.getElementById(id).value))
							return prefix+msg+suffix;
						break;
		case 'limitpercent':
						if (document.getElementById(id).value<0 || document.getElementById(id).value>100)
							return prefix+msg+suffix;
						break;
		case 'limitpercentrate':
						if (document.getElementById(id).value<6 || document.getElementById(id).value>60)
							return prefix+msg+suffix;
						break;
	}
	return "";
}

function checkIdentical(id1, id2, msg) {

	var prefix = "* ";
	var suffix = "\n";

	if (document.getElementById(id1).value != document.getElementById(id2).value)
	return prefix+msg+suffix
	else
	return ''

}

function checkLength(id, min, max, msg) {

	var prefix = "* ";
	var suffix = "\n";

	if (document.getElementById(id).value.length < min || document.getElementById(id).value.length > max )
	return prefix+msg+suffix
	else
	return ''

}

function checkRadio(form_name,radio_name,msg)
{

	var radio_choice = false;
	var prefix = "* ";
	var suffix = "\n";
	radio_obj = eval('document.'+form_name+'.'+radio_name);

	if (radio_obj.checked) {
		radio_choice = true;
	} else {
		for (counter = 0; counter < radio_obj.length; counter++)
		{

			if (radio_obj[counter].checked) {
				radio_choice = true;
				break;
			}
		}
	}

	if (!radio_choice) {
		return prefix+msg+suffix;
	}
	    return '';
}

function verificaFormular(which) {
	msg_alert = "______________________________________________________\n\n"
	msg_alert += "Cererea dvs. nu a fost indeplinita din motivele de mai jos.\n";
	msg_alert += "Va rugam corectati erorile si incercati din nou:\n";
	msg_alert += "______________________________________________________\n";
	msg_alert += "\n";
	switch(which) {
		case "ajuta":
					msg = "";
					msg += checkValid("name", "Trebuie sa specificati numele dvs.", "required");
					msg += checkValid("email", "Trebuie sa specificati adresa de mail", "required");
					msg += checkValid("email", "Trebuie sa specificati o adresa de mail valida", "email");
					msg += checkValid("phone", "Trebuie sa specificati telefonul dvs.", "required");
					break;
		case "cerere_oferta":
					msg = "";
					msg += checkValid("name", "Trebuie sa specificati numele dvs.", "required");
					msg += checkValid("email", "Trebuie sa specificati adresa de mail", "required");
					msg += checkValid("email", "Trebuie sa specificati o adresa de mail valida", "email");
					msg += checkValid("phone", "Trebuie sa specificati telefonul dvs.", "required");
					break;
		case "ajutor_comanda":
					msg = "";
					msg += checkValid("nume", "Trebuie sa specificati numele dvs.", "required");
					msg += checkValid("email", "Trebuie sa specificati adresa de mail", "email");
					msg += checkValid("telefon", "Trebuie sa specificati telefonul dvs", "required");
					break;

		case "dell":
					msg = "";
					msg += checkValid("nume", "Trebuie sa specificati numele dvs.", "required");
					msg += checkValid("email", "Trebuie sa specificati adresa de mail", "required");
					msg += checkValid("email", "Trebuie sa specificati o adresa de mail corecta", "email");
					msg += checkValid("telefon", "Trebuie sa specificati telefonul dvs", "required");
					break;
		case "register":
					msg = "";
					msg += checkValid("email_address_new", "Trebuie sa specificati noua adresa de e-mail.", "required");
					msg += checkValid("email_address_new", "Trebuie sa specificati o adresa de e-mail corecta.", "email");
					msg += checkLength("name_new", 4, 30, "Trebuie sa introduceti numele asociat contului!");
					msg += checkValid("password_new", "Trebuie sa specificati o parola.", "required");
					msg += checkLength("password_new", 5, 16, "Trebuie sa specificati o parola cu o lungime intre 5 si 16 caractere!");
					msg += checkValid("password_confirmation", "Trebuie sa confirmati parola noua.", "required");
					msg += checkLength("password_confirmation", 5, 16, "Trebuie sa specificati o parola cu o lungime intre 5 si 16 caractere!");
					msg += checkIdentical("password_confirmation","password_confirmation", "Parolele nu sunt identice.");
					break;
		case "auth":
					msg = "";
					msg += checkValid("email_address", "Trebuie sa specificati noua adresa de e-mail.", "required");
					msg += checkValid("email_address", "Trebuie sa specificati o adresa de e-mail corecta.", "email");
					break;
		case "auth_comanda_express":
					msg = "";
					msg += checkValid("nume_comanda", "Trebuie sa specificati numele dvs.", "required");
					msg += checkValid("telefon_comanda", "Trebuie sa specificati telefonul dvs.", "required");
					msg += checkValid("telefon_comanda", "Numarul de telefon trebuie sa contina doar cifre.", "numeric");
					break;
		case "my_details":
					msg = "";
					msg += checkValid("name", "Trebuie sa specificati numele dvs.", "required");
					msg += checkValid("telephone1", "Trebuie sa specificati telefonul dvs", "required");
					msg += checkValid("street_address", "Trebuie sa specificati adresa dvs.", "required");
					msg += checkValid("city", "Trebuie sa specificati orasul dvs", "required");
					msg += checkValid("judet", "Trebuie sa specificati judetul dvs.", "select");
					break;
		case "company":
					msg = "";
					msg += checkValid("company_name", "Trebuie sa specificati numele firmei ", "required");
					msg += checkValid("prefcode", "Trebuie sa specificati codul fiscal", "select");
					msg += checkValid("code", "Trebuie sa specificati codul fiscal", "required");
					msg += checkValid("code", "Trebuie sa specificati codul fiscal", "numeric");
					msg += checkValid("banca", "Trebuie sa specificati banca", "required");
					msg += checkValid("cont_banca", "Trebuie sa specificati contul bancii", "required");
					msg += checkValid("J", "Trebuie sa specificati numarul de la registru comertului", "select");
					msg += checkValid("J1", "Trebuie sa specificati numarul de la registru comertului", "select");
					msg += checkValid("J2", "Trebuie sa specificati numarul de la registru comertului", "numeric");
					msg += checkValid("J3", "Trebuie sa specificati numarul de la registru comertului", "select");
					msg += checkValid("street_address", "Trebuie sa specificati adresa dvs.", "required");
					msg += checkValid("city", "Trebuie sa specificati orasul dvs", "required");
					msg += checkValid("judet", "Trebuie sa specificati judetul dvs.", "select");
					break;
		case "add_address":
					msg = "";
					msg += checkValid("street_address", "Trebuie sa specificati adresa dvs.", "required");
					msg += checkValid("city", "Trebuie sa specificati orasul dvs", "required");
					msg += checkValid("judet", "Trebuie sa specificati judetul dvs.", "select");
					break;
		case "modifica_parola":
					msg = "";
					msg += checkValid("old_password", "Trebuie sa specificati parola actuala.", "required");
					msg += checkValid("password", "Trebuie sa specificati parola noua.", "required");
					msg += checkLength("password", 5, 16, "Trebuie sa specificati o parola cu o lungime intre 5 si 16 caractere!");
					msg += checkValid("confirmation", "Trebuie sa confirmati parola noua.", "required");
					msg += checkIdentical("password","confirmation", "Parolele nu sunt identice.");
					break;
		case "activeaza_cont":
					msg = "";
					msg += checkValid("password", "Trebuie sa specificati o parola.", "required");
					msg += checkLength("password", 5, 16, "Trebuie sa specificati o parola cu o lungime intre 5 si 16 caractere!");
					msg += checkValid("confirmation", "Trebuie sa confirmati parola.", "required");
					msg += checkIdentical("password","confirmation", "Parolele nu sunt identice.");
					break;
		case "modifica_email":
					msg = "";
					msg += checkValid("email_address", "Trebuie sa specificati noua adresa de e-mail.", "required");
					msg += checkValid("email_address", "Trebuie sa specificati o adresa de e-mail corecta.", "email");
					msg += checkValid("confirmation_email_address", "Trebuie sa confirmati noua adresa de e-mail.", "email");
					msg += checkIdentical("email_address","confirmation_email_address", "Adresele de e-mail furnizate nu sunt identice.");
					break;
		case "new_email":
					msg = "";
					msg += checkValid("email_address_new", "Trebuie sa specificati noua adresa de e-mail.", "required");
					msg += checkValid("email_address_new", "Trebuie sa specificati o adresa de e-mail corecta.", "email");
					break;
		case "plata_livrare":
					msg = "";
					msg += checkRadio("checkoutform","plata", "Trebuie sa specificati o metoda de plata");
					msg += checkValid("serie_buletin", "Trebuie sa specificati seria de cartii de identitate","required");
					msg += checkValid("numar_buletin", "Trebuie sa specificati numarul cartii de identitate","numeric");
					msg += checkLength("numar_buletin", 6, 6, "Numarul cartii de identitate trebuie sa aiba 6 cifre");
					break;
		case "alege_adrese":
					msg = "";
					msg += checkRadio("date_livrare","address", "Trebuie sa specificati o adresa de livrare");
					break;
		case "alege_cumparator":
					msg = "";
					msg += checkRadio("cumparator","cumparator", "Trebuie sa specificati un cumparator");
					break;
		case "validare_date":
					msg = "";
					//msg += checkValid("serie_buletin", "Trebuie sa specificati seria de cartii de identitate","required");
					//msg += checkValid("numar_buletin", "Trebuie sa specificati numarul cartii de identitate","numeric");
					//msg += checkLength("numar_buletin", 6, 6, "Numarul cartii de identitate trebuie sa aiba 6 cifre");
					break;
		case "validare_voucher":
					msg = "";
					msg += checkValid("other_value", "Valoarea dorita trebuie sa fie numerica!", "numeric");
					if (document.getElementById('other_value').value == 0 && document.getElementById('other_value').style.display != 'none') { msg += "* Valoarea voucherului trebuie sa fie mai mare ca 0!\n"; }
					//msg += checkValid("voucher_email", "Trebuie sa specificati o adresa de email valida!", "email");
					if (document.getElementById('voucher_mesaj').value.length > 200) msg += "* Limita maxima a textului introdus este de 200 caractere!\n";
					break;
	}
	if (msg != "") {
		alert(msg_alert+msg);
		return false;
	}
	return true;
}

function valideazaCos() {
	result = true;
	for (i=1; i<=100; i++) {
		if (checkValid("cproduct"+i, "0", "required") != "") {
			alert("Trebuie sa specificati cantitatile produselor");
			result = false;
			break;
		}
		else if (checkValid("cproduct"+i, "0", "integer") != "") {
			alert("Cantitatile produselor trebuie sa fie numerice");
			result = false;
			break;
		}
	}
	return result;
}

function verificaConsumabile() {
	total = document.getElementById('totalcons').value;
	msg = "";
	found = false;
	for (i=1; i<=total; i++) {
		msg += checkValid("cons"+i, "Cantitatea dorita trebuie sa fie numerica", "numeric");
		break;
	}
	if (msg=="") {
		for (i=1; i<=total; i++) {
			if (document.getElementById('cons'+i).value != "") {
				found = true;
				break;
			}
		}
		if (found) {
			return true;
		}
		else {
			window.alert("Trebuie sa introduceti cel putin o cantitate dorita.");
			return false;
		}
	}
	else {

		window.alert(msg);
		return false;
	}
}

/* base64 encode/decode */

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/=";

function encode64(inp) {
	var out = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;
	do {
		chr1 = inp.charCodeAt(i++);
		chr2 = inp.charCodeAt(i++);
		chr3 = inp.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		}
		else if (isNaN(chr3)) {
			enc4 = 64;
		}

		out = out + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);

		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";

	}
	while (i < inp.length);
	return out;
}

function decode64(inp) {
	var out = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;

	var base64test = /[^A-Za-z0-9\+\/\=]/g;

	if (base64test.exec(inp)) {
		alert("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, ?+?, ?/?, and ?=?\n" + "Expect errors in decoding.");
	}
	inp = inp.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	do {

		enc1 = keyStr.indexOf(inp.charAt(i++));
		enc2 = keyStr.indexOf(inp.charAt(i++));
		enc3 = keyStr.indexOf(inp.charAt(i++));
		enc4 = keyStr.indexOf(inp.charAt(i++));

		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		out = out + String.fromCharCode(chr1);

		if (enc3 != 64) {
			out = out + String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			out = out + String.fromCharCode(chr3);
		}

		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";

	}
	while (i < inp.length);

	return out;
}

/* galerie poze */
function gal_open_centered(url) {
	w = 700;
	h = 650;
	sw = screen.width;
	sh = screen.height;
	l = (sw - w) / 2;
	t = (sh - h) / 2;
	window.open(url, 'Galerie', 'width='+w+',height='+h+',top='+t+',left='+l+',scrollbars=no,resizable=no');
}

function gal_open_emagia(url) {
	w = 627;
	h = 650;
	sw = screen.width;
	sh = screen.height;
	l = (sw - w) / 2;
	t = (sh - h) / 2;
	window.open(url, 'Galerie', 'width='+w+',height='+h+',top='+t+',left='+l+',scrollbars=no,resizable=no');
}

function showPic (whichpic) {
	if (document.getElementById) {
		document.getElementById('placeholder').src = whichpic.href.replace('thumbs', 'big');
		if (whichpic.title) {
			document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
		} else {
			document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
		}
		return false;
	} else {
		return true;
	}
}
/* galerie poze ends*/


// BEGIN functions for the homepage main banner
var divs = new Array("containerz","containerz1","containerz2")
var divs2 = new Array();
var currentDiv = 0;
// homepage main banner
//check which divs contain a commercial
function checkDivs() {
	for(i=0;i<divs.length;i++) {
		if (navigator.appName == 'Microsoft Internet Explorer') {
			if (document.getElementById(divs[i]).childNodes.length == 6) {
				divs2[divs2.length] = divs[i];
			}
		} else {
			if (document.getElementById(divs[i]).childNodes.length == 9) {
				divs2[divs2.length] = divs[i];
			}
		}
	}
	spitOutLinks();

}

// homepage main banner
//spit out the links according to the number of active ones
function spitOutLinks() {
	for (i=0;i<divs2.length;i++) {
		document.write(' <div class="pad-top" id="link' + i + '" onclick="javascript: selectedShow(\'' + i + '\');">test1</div>');
	}
	first();
}

// homepage main banner
//get the alternate text from the image and print out
function first() {
	for (i=0;i<divs2.length;i++) {

		if (document.getElementById(divs2[i])) {
			if (navigator.appName == 'Microsoft Internet Explorer') {
				var el = document.getElementById(divs2[i]).childNodes[2].childNodes[0].alt;
				//var thumb = document.getElementById(divs2[i]).childNodes[2].childNodes[0].src;
			}
			else {
				var el = document.getElementById(divs2[i]).childNodes[3].childNodes[0].alt;
				//var thumb = document.getElementById(divs2[i]).childNodes[3].childNodes[0].src;
			}
			//var image = "<div class=\"image_pos\"><image width=\"40px\" height=\"40px\" src='"+thumb.slice(0,thumb.lastIndexOf("/"))+"/thumbs"+thumb.slice(thumb.lastIndexOf("/"))+"' /></div>";
			document.getElementById('link'+i).innerHTML = /*image+*/"<div class=\"text_pos\">"+el+"</div>";
		}
	}

	if (document.getElementById(divs2[0])) {
		document.getElementById(divs2[0]).style.display = 'block';
		document.getElementById("link0").className = 'pad-top pad-top2';
	}else{
		document.getElementById(divs2[0]).style.display = 'none';
		document.getElementById('link'+i).className = 'pad-top';
	}

	timer = window.setInterval("cycle()",5000);
	cycle();
}

// homepage main banner
function cycle() {
	if(divs2.length==0) {
		return;
	}
	if (currentDiv == '') {
		currentDiv = 0;
	}

	if (currentDiv == divs2.length) {
		currentDiv = 0
	}

	for (i=0;i<divs2.length;i++) {
		if (document.getElementById(divs[i])) {
			document.getElementById(divs[i]).style.display = 'none';
			document.getElementById('link'+i).className = 'pad-top';
		}
	}
	try{
	if (document.getElementById(divs[currentDiv])) {
		document.getElementById(divs[currentDiv]).style.display = 'block';
		try {
			document.getElementById('link'+currentDiv).className = 'pad-top pad-top2';
		} catch(err) {
			//error processing stripped
		}
	}} catch(err) {
		//error processing stripped
	}
	currentDiv++
}

// homepage main banner
function selectedShow(id) {

	window.clearInterval(timer);

	for (i=0;i<divs2.length;i++) {
		if (document.getElementById(divs[i])) {
			document.getElementById(divs[i]).style.display = 'none';
			document.getElementById('link'+i).className = 'pad-top';
		}
	}
	if (document.getElementById(divs[id])) {
		document.getElementById(divs[id]).style.display = 'block';
		document.getElementById('link'+id).className = 'pad-top pad-top2';
	}
}

// END functions for the homepage main banner


//BEGIN FUNCTIONS FOR THE VOUCHER ORDER
function show_input_text(value)
{
	var el = document.getElementById('other_value');
	if (value == 'alta') el.style.display = 'inline';
	else
	{
		if (el.style.display == 'inline')
		{
			el.style.display = 'none';
		}
	}
}


function ofera_voucher_cadou(show, email)
{
	if (show == 'show_cadou')
	{
		document.getElementById('voucher_email').style.width = '130px';
		document.getElementById('voucher_email').style.height = '100px';
		document.getElementById('label_email').innerHTML = 'Email destinatar';
		document.getElementById('voucher_email').value = '';
		document.getElementById('show_mesaj_box').style.display = 'block';
		document.getElementById('mesaj_email').style.display = 'block';
	}
	else if (show == 'hide_cadou')
	{
		document.getElementById('voucher_email').style.width = '117px';
		document.getElementById('voucher_email').style.height = '14px';
		document.getElementById('label_email').innerHTML = 'Email';
		document.getElementById('voucher_email').value = email;
		document.getElementById('show_mesaj_box').style.display = 'none';
		document.getElementById('mesaj_email').style.display = 'none';
	}
}

//END FUNCTIONS FOR THE VOUCHER ORDER

//INCEPE SECTIUNE PT CAMPANII CEAS
function display_c(start, id)
{
	if (start != '' && start != null)
	{
		test = parseFloat(start);
		
		var end = 0
		
		var refresh=1000;
		
		if(test >= end )
		{
			mytime=setTimeout('display_ct(\''+id+'\', \''+test+'\')',refresh)
		}
		else {
			//window.location.reload();
			return false;
		}
	}
	else return;
}

function display_ct(id, time) 
{
	elTimerLocal = document.getElementById(id);
	
	if (elTimerLocal == null) return;
	
	// After deducting the days calculate the number of hours left
	var hours = Math.floor(time/3600)
	
	if (hours == 0) hours = '00';
	if (hours < 10 && hours != '00') hours = '0'+hours;
	
	// After days and hours , how many minutes are left 
	var minutes = Math.floor((time - (hours *3600 ))/60)
	
	if (minutes == 0) minutes = '00';
	if (minutes < 10 && minutes != '00') minutes = '0'+minutes;
	
	// Finally how many seconds left after removing days, hours and minutes. 
	var secs = Math.floor((time - (hours *3600 ) - (minutes*60)))

	if (secs == 0) secs = '00';
	if (secs < 10 && secs != '00') secs = '0'+secs;
	
	var x = hours + ":"  + minutes + ":"  + secs;
	
	elTimerLocal.innerHTML = x;
	
	test2 = time - 1;
	
	tt = display_c(test2, id);
 }

//END SECTIUNE

// functii pt produse conectabile
function getNewProducts(e, replace)
{
	url = e.href;
	
	if (replace == 1) 
	{
		$('.element-categorii-conectabile').removeClass('selectat');
		$(e.parentNode.parentNode).addClass('selectat');
	}

	$('#produse-conectabile').load(url);
}

//end functii produse conectabile.

function returnHelp(e, type)
{
	switch(type)
	{
		case 'getNext':
			$('help-interconectare').removeClass('hidden').addClass('visible');
			//elem = e.getNext();
			//elem.removeClass('hidden').addClass('visible');	
			break;
	}
}


function hideHelp(e, type)
{
	switch(type)
	{
		case 'getNext':
			$('help-interconectare').removeClass('visible').addClass('hidden');
			//elem = e.getNext();
			//elem.removeClass('visible').addClass('hidden');	
			break;
	}
	
}



function update_campanie(type, desc, current_pos)
{
	url = 'ajax/update-campanie/'+type+'/'+desc+'/'+current_pos;
	$('#'+type).load(url);
}

function swpr2(val) {
    $('a.pagini-options-group').css('display', 'inline');
    $('a.spgx' + val).css('display','none');
    
    $('a[rel^="cpgx"], span[rel^="cpgx"]').css('display', 'none');
    if (val == 1) {
        $('a[rel^="cpgx"]:lt(9)').css('display', 'inline')
    } else {
        $('a[rel^="cpgx'+(val-1)+'"]:gt(1)').css('display', 'inline'); //primul va fi din grupul 1-10 si trebuie lasat ascuns
    }
}

var liveBoxHeight = 47;
function inchideLiveBox(isIE6)
{
	if( isIE6 ) {
		liveBoxHeight = 16;
		moveLiveBox();
	} else
		$('#liveBox').css('bottom', '-31px');

	$('#imgButonInchide').attr('src', '/imagini/layout/live-promo/deschide.gif');
	document.getElementById('divButonInchide').onclick = function(){
		deschideLiveBox(isIE6)};
	$.cookie('live_box', '0', {path: '/'});
}

function deschideLiveBox(isIE6)
{
	if( isIE6 ) {
		liveBoxHeight = 47;
		moveLiveBox();
	} else
		$('#liveBox').css('bottom', '0px');

	$('#imgButonInchide').attr('src', '/imagini/layout/live-promo/inchide.gif');
	document.getElementById('divButonInchide').onclick =  function(){
		inchideLiveBox(isIE6)};
	$.cookie('live_box', '1', {path: '/'});
}

function moveLiveBox()
{
	var s = window.pageYOffset ||
    	document.body.scrollTop ||
    	document.documentElement.scrollTop;

	var h = window.innerHeight ||
		document.documentElement.clientHeight ||
		document.body.clientHeight;
	
	$('#liveBox').css('top', Math.min(document.body.clientHeight, h + s - liveBoxHeight));
}

function PromoBanner(divname, boxWidth, catid, zone, initial_promo_nr)
{
	this.divname = divname;
	this.boxWidth = boxWidth;
	this.catid = catid;
	this.zone = zone;
	this.initial_promo_nr = initial_promo_nr;

	this.nextBox = 4;
	this.currentBox = 3;
	this.boxRotationSpeed =  1000;
	this.boxNumbers = 10000/this.boxWidth;
	this.step = 0;
	this.click = 0;

	this.rotate = function(action)
	{
		if (this.initial_promo_nr < 3)
			return;
			
		if( action == "inc" ) this.currentBox++;
		else this.currentBox--;
	
		if(this.currentBox > this.boxNumbers) { this.currentBox--; return; }
		if(this.currentBox < 3) { this.currentBox = 3; return; }
	
		$('#'+this.divname).animate({"left": ((action == "inc") ? "-=" : "+=") + this.boxWidth + "px"}, this.boxRotationSpeed);
	
		if(this.currentBox  == this.nextBox)
		{
			var IDs = "";
			$('#'+this.divname).children().each(function(){ IDs+=this.id+"-"; });
			IDs = IDs.slice(0,-1);
			
			var self = this;
	
			$.ajax({
				url : "/get_promo_product?ids="+IDs+"&zone="+this.zone+"&catid="+this.catid,
				success: function(html){
					if(html.length <= 1000) self.boxNumbers = self.nextBox-1;
					else {$('#'+self.divname).append(html);}
				}
			});
			
			this.nextBox++;
		}
	};
	
	this.rotate_all = function(action){
		
		if (this.initial_promo_nr < 3)
			return;
		
		if(this.step == 0 && action == 'inc') {
			var IDs = "";
			$('#'+this.divname).children().each(function(){ IDs+=this.id+"-"; });
			IDs = IDs.slice(0,-1);
			var self = this;
			$.ajax({
				url : "/get_promo_product_all?ids="+IDs+"&zone="+this.zone+"&catid="+this.catid,
				success: function(html){
					if(html.length <= 1000) 
						self.boxNumbers = self.nextBox-1;
					else {
						$('#'+self.divname).append(html);
					}
				}
			});
			$('#'+this.divname).animate({"left": ((action == "inc") ? "-=" : "+=") + this.boxWidth + "px"}, this.boxRotationSpeed);
			this.step++;
			return;
		}
		
		var nr_children = $('#'+this.divname).children("div").length;
		
		
		if(this.step > 0){
			if(this.currentBox > 2 && this.currentBox < nr_children){
				if( action == "inc" ) this.currentBox++;
				else this.currentBox--;
				$('#'+this.divname).animate({"left": ((action == "inc") ? "-=" : "+=") + this.boxWidth + "px"}, this.boxRotationSpeed);
			} else if (this.currentBox == 2 && action == 'inc') {
				this.currentBox++;
				$('#'+this.divname).animate({"left": ((action == "inc") ? "-=" : "+=") + this.boxWidth + "px"}, this.boxRotationSpeed);
			} else if(this.currentBox == nr_children && action == 'dec') {
				this.currentBox--;
				$('#'+this.divname).animate({"left": ((action == "inc") ? "-=" : "+=") + this.boxWidth + "px"}, this.boxRotationSpeed);
			}
			
		}
	}
}

///////////////////////////////////////////////////////////////////////////////

$(document).ready(function () {
	$('#termenLivrareID').change( function() { 
		var city_id = 0;
	    $("#termenLivrareID option:selected").each(function () {
	    	city_id = parseInt($(this).val());
	    });
	    $.cookie('liv_city', city_id, { expires: 1000, path: '/', domain: '.emag.ro' });
	    updateInfoStoc(city_id);
	});
});

function updateInfoStoc(city_id)
{	
	$('.delivery_times_div').hide();
	$('#delivery_times_div_' + city_id).show();
}

