var errors = new Array();
errors['email']			= 'Va rugam sa introduceti o adresa de email valida';
errors['address']		= 'Va rugam sa introduceti o adresa valida';
errors['county']		= 'Va rugam sa introduceti un judet valid';
errors['city']			= 'Va rugam sa introduceti un oras valid';
errors['email_bis']		= 'Va rugam sa repetati adresa de email';
errors['firstname']		= 'Va rugam sa introduceti un nume valid';
errors['lastname']		= 'Va rugam sa introduceti un prenume valid';
errors['email_not_matching']	= 'Adresele de mail date nu sunt identice';
errors['password']		= 'Va rugam sa folositi o parola mai lunga de 6 caractere';
errors['password_not_matching']	= 'Parolele introduse nu sunt identice';
errors['phone']			= 'Va rugam sa introduceti un numar de telefon valid';
errors['terms']			= 'Pentru a va putea crea un cont, trebuie sa fiti de acord cu termenii si conditiile';

function putCity2(){
	var countyVal = jQuery('#county').val();
	if( 10 <= countyVal && countyVal <= 15 ) {
		jQuery('#cityseldiv').hide();
		jQuery('.cityseldiv').hide();
		jQuery('.cityseldivother').hide();
	} else {
		jQuery('#cityseldiv').show();
		jQuery('.cityseldiv').show();
		jQuery('.cityseldivother').show();
		ajaxFillSelect('city_sel', 'ajax.php?type=cities&county='+countyVal,true,true);
		jQuery('#city_sel').siblings('.styled_select_mask_blue').text(jQuery('#city_sel option:selected').text());
		jQuery('#city_sel').siblings('.styled_select_mask').text(jQuery('#city_sel option:selected').text());
	}
}

function recover(cant){
	error_string='';
	if(cant==1){
		jQuery('#cant_recover').val('1');
	}
	/*for(var j=f.length-1; j>=0; j--) {
		f[j].style.backgroundColor=elemFormDefaultBackColor;
	}*/
	if(!check_email(jQuery('input[name="email"]').val())){
			error_string += errors['email'] + "\r\n";
			jQuery('input[name="email"]').addClass('text-error');
	}
	if(error_string!=""){
		alerter (error_string);
	}
	else{
		document.recover_pass.submit();
	//return true;
	}
}

/**
 *
 * @access public
 * @return void
 **/

/**
  *
  * @access public
  * @return void
  **/
 function check_number(n){
 	return !isNaN(parseFloat(n)) && isFinite(n);
 }

/**
  *
  * @access public
  * @return void
  **/
 function recoverPass(email){
 	if( check_email(email)) {
 		jQuery.post('ajax_order.php?type=recoverPass',{email: email},function(data) {
 			alert(data);
 		});
 	} else {
 		alert('Adresa de e-mail nu este valida');
 	}
 }


function checkDocQty(q1,q2,type,fieldid){
	var q1,q2,type;
	//alert(q1+" "+q2);
	if(type="<=") {
		if(parseInt(q1)>parseInt(q2)) {
			alert("Cantitatea introdusa este prea mare! Maximul admis este "+q2);
			jQuery('#'+fieldid).val(0);
			return false;
		}
	}
}

function showConfirmaAviz(nrdoc){
	jQuery('#confirmOrder'+nrdoc).toggle();
	arids=getIdsByName('pQtyInput'+nrdoc);
	for(i=0;i<arids.length;i++) {
		jQuery('#pQtyInput'+nrdoc+arids[i]).toggle();
	}
	jQuery('#showConfirmPartialButton'+id).toggle();
	jQuery('#linkConfirma'+nrdoc).toggle();
	jQuery('#linkAnuleaza'+nrdoc).toggle();
}

function ConfirmPartial(nrdoc, orderid){
	arids=getIdsByName('pQtyInput'+nrdoc);
	values=new Array();
	for(i=0;i<arids.length;i++) {
		values[i]=jQuery('#pQtyInput'+nrdoc+arids[i]).val();
	}
	jQuery.post('ajax_order.php?type=confirmPartialOrder', {'ids[]':arids, 'values[]':values, 'orderid':orderid}, function(data) {
		var results = jQuery.parseJSON(data);
		if(results['nr_doc']) {
			jQuery('#actiuni'+results['nr_doc']).html('Confirmat');
		};
		if(results['finalizata']=='yes') {
			jQuery('#orderStatus'+orderid).html(results['status']);
		}
	});
	for(i=0;i<arids.length;i++) {
		jQuery('#pQtyInput'+nrdoc+arids[i]).toggle();
	}
}

function confirmOrderDoc(id,orderid){
 	if(confirm('Sunteti sigur ca doriti confirmarea documentului cu numarul '+id+'?')) {
 		jQuery.post('ajax_order.php?type=confirmOrderDoc', { 'id':id, 'orderid':orderid }, function(data) {
			var results = jQuery.parseJSON(data);
			if(results['finalizata']=='yes') {
				jQuery('#confirmButton'+orderid).replaceWith('Comanda confirmata.');
				jQuery('#orderStatus'+orderid).html(results['status']);

			}
			jQuery('#actiuni'+id).html('Confirmat');
			arids=getIdsByName('pQtyInput'+id);
				for(i=0;i<arids.length;i++) {
					jQuery('#pQtyInput'+id+arids[i]).toggle();
				}
			//alert(results['return']);
		});
 	}
 }

function confirmOrder(id){
	if(confirm('Sunteti sigur ca doriti confirmarea comenzii cu numarul '+id+'?')) {
		jQuery.post('ajax_order.php?type=confirmOrder', { 'id' : id }, function(data) {
			var results = jQuery.parseJSON(data);
			jQuery('#actiuni'+id).html('Comanda confirmata.');
			jQuery('#orderStatus'+id).html(results['status']);
			//alert(results['return']);
		});
	} else {

	}
}

/**
 *
 * @access public
 * @return void
 **/
function reportProblem(id){
	if(check_number(id)) {
		jQuery.post('ajax_order.php?type=reportProblem', {'id':id,'comment':jQuery('#problem'+id).val()}, function(data) {
			var results = jQuery.parseJSON(data);
			jQuery('#response'+id).html(results['return']);
			//alert(results['return']);
		});
	}
}


function genCart(val,id){
	if(check_number(jQuery("input[name=shippingMethod]:checked").val())){
		ship = jQuery("input[name=shippingMethod]:checked").val();
	}
	else{
		ship = false;
	}

	if(check_number(jQuery("input[name=shippingAddress]:checked").val())){
		ship_address=jQuery("input[name=shippingAddress]:checked").val();
	}
	else{
		ship_address=false;
	}

	if(check_number(jQuery("input[name=billingAddress]:checked").val())) {
		bill_address = jQuery("input[name=billingAddress]:checked").val();
	} else {
		bill_address = false;
	}

	if(check_number(jQuery("input[name=paymentMethod]:checked").val())) {
		pay_method = jQuery("input[name=paymentMethod]:checked").val()
	} else {
		pay_method = false;
	}

	jQuery.post('ajax_order.php?type=updateCart', { 'quantity[]' : [val], 'cart_id[]' : [id], 'shipping_method' : ship, ship_address : ship_address, bill_address : bill_address, pay_method: pay_method, nr_contract: jQuery('#nr_contract').val(), nr_comanda_interna: jQuery('#nr_comanda_interna').val(), obs: jQuery('#obs').val(), voucher: jQuery('#voucher').val() }, function(data) {
		var results = jQuery.parseJSON(data);
			for(i in results['carts']) {
				jQuery( '#qty_'+results['carts'][i]['id'] ).val( results['carts'][i]['qty'] );
				jQuery( '#total_'+results['carts'][i]['id'] ).html( results['carts'][i]['totalProdString'] );
			}
			if(results['voucher']['message']) {
				jQuery('#voucher_message').html(results['voucher']['message']);
			}
			if(check_number(val) && check_number(id)) {
				if(val == 0) {
					jQuery('#tr_'+id).remove();
				}
			}
			if(results['show_buy']==false) {
				jQuery( '#tdbuy' ).html(results['form']);
			} else {
				jQuery( '#tdbuy' ).html(results['form']);
			}
		jQuery( '#shippingMethodList' ).html( results['shippingMethodList'] );
		jQuery( '#totalPrice' ).html( results['total_price_string'] );
		bind_radio_v2();
	});
}

function showOtherCity(){
	if(jQuery('#other_city').attr('checked')) {
		jQuery('#city_sel').hide();
		jQuery('.cityseldiv').hide();
		jQuery('#city_sel').siblings('.styled_select_mask_blue').hide();
		jQuery('#other_city_sel').show();
	} else {
		jQuery('#city_sel').show();
		jQuery('.cityseldiv').show();
		jQuery('#city_sel').siblings('.styled_select_mask_blue').show();
		jQuery('#other_city_sel').hide();
	}

	//jQuery('#city_sel').toggle();
	//jQuery('#other_city_sel').toggle();
}

/**
 *
 * @access public
 * @return void
 **/
function returnBuy(){
	var error_string='';

	if(!check_number(jQuery("input[name=paymentMethod]:checked").val())) {
		error_string +='Va rugam sa alegeti un mod de plata.\r\n';
	}
	if(!check_number(jQuery("input[name=shippingAddress]:checked").val())) {
		error_string +='Va rugam specificati adresa de livrare.\r\n';
	}
	if(!check_number(jQuery("input[name=billingAddress]:checked").val())) {
		error_string +='Va rugam specificati adresa de facturare.\r\n';
	}
	if(!check_number(jQuery("input[name=shippingMethod]:checked").val())) {
		error_string +='Va rugam specificati metoda de livrare.\r\n';
	}

	if (error_string!="") {
		alerter(error_string);
		return false;
	} else {
		return true;
	}
}

/**
*@return bool
*@description checks address
*/
function addAddress(prepend){
	jQuery('input.text-error').each(function(){
		jQuery(this).removeClass('text-error');
	});
	jQuery('span.styled_select_mask.text-error').each(function(){
		jQuery(this).removeClass('text-error');
	});
	var error_string='';
	if(jQuery('#tlivr').attr('checked') || jQuery('#t').val()=='ship'){
		if (!check_name(jQuery(prepend+'input[name="firstname"]').val())){
			error_string += errors['firstname'] + "\r\n";
			jQuery(prepend+'input[name="firstname"]').addClass('text-error');
		}
		if (!check_name(jQuery(prepend+'input[name="lastname"]').val())){
			error_string += errors['lastname'] + "\r\n";
			jQuery(prepend+'input[name="lastname"]').addClass('text-error');
		}

		if (!check_phone(jQuery(prepend+'input[name="phone"]').val())){
			error_string += errors['phone'] + "\r\n";
			jQuery(prepend+'input[name="phone"]').addClass('text-error');
		}
		if (parseInt(jQuery('input[name="address1"]').val().length)<4){
			error_string += errors['address'] + "\r\n";
			jQuery('input[name="address1"]').addClass('text-error');
		}
		countyid=parseInt(jQuery('#county option:selected').val());
		if (countyid==0){
			error_string += errors['county'] + "\r\n";
			jQuery('select[name="county"]').addClass('text-error');
			jQuery('select[name="county"]').siblings('.styled_select_mask').addClass('text-error');
		}
		if(!(countyid>=10 && countyid<=15)){
			if(parseInt(jQuery('#city_sel option:selected').val())==0){
				error_string += errors['city'] + "\r\n";
				jQuery('select[name="city"]').addClass('text-error');
				jQuery('select[name="city"]').siblings('.styled_select_mask').addClass('text-error');
			}
		}

		if(jQuery('input[name=other_city]').is(':visible')){
			if(parseInt(jQuery('input[name=other_city]').val().length)<3){
				error_string += errors['city'] + "\r\n";
				jQuery('input[name=other_city]').addClass('text-error');
			}
		}
	}
	else if(jQuery('#tfact').attr('checked') || jQuery('#t').val()=='bill'){
		if(jQuery('#pfizica').attr('checked')){
			if(!check_name(jQuery('input[name="ffirstname"]').val())){
				error_string += errors['firstname'] + "\r\n";
				jQuery('input[name="ffirstname"]').addClass('text-error');
			}
			if(!check_name(jQuery('input[name="flastname"]').val())){
				error_string += errors['lastname'] + "\r\n";
				jQuery('input[name="flastname"]').addClass('text-error');
			}
			if(jQuery('input[name="serie_bi"]').val().length!=0 && jQuery('input[name="serie_bi"]').val().length!=2){
				error_string += 'Este necesar sa specificati o serie valida a buletinului.' + "\r\n";
				jQuery('input[name="serie_bi"]').addClass('text-error');
			}
			if(jQuery('input[name="nr_bi"]').val().length!=0 && jQuery('input[name="nr_bi"]').val().length!=6){
				error_string += 'Este necesar sa specificati un numar valid al buletinului.' + "\r\n";
				jQuery('input[name="nr_bi"]').addClass('text-error');
			}
			if(jQuery('input[name="CNP"]').val().length!=0 && !check_cnp(jQuery('input[name="CNP"]').val())){
				error_string += 'Este necesar sa precizati un cod numeric personal valid.' + "\r\n";
				jQuery('input[name="CNP"]').addClass('text-error');
			}
		}
		else if(jQuery('#pjuridica').attr('checked')){
			if(!check_name(jQuery('input[name="company"]').val())){
				error_string += "Va rugam sa completati campul Nume firma\r\n";
				jQuery('input[name="company"]').addClass('text-error');
			}
			if(jQuery('input[name="nr_reg_c"]').val().length<=4){
				error_string += "Va rugam sa completati campul Numarul registrul comertului\r\n";
				jQuery('input[name="nr_reg_c"]').addClass('text-error');
			}
			if(jQuery('input[name="CUI"]').val()!=''){
				if(!check_cui( jQuery( 'input[name="CUI"]' ).val() ) ) {
					error_string += "Campul CUI nu este completat corect!\r\n";
					jQuery('input[name="CUI"]').addClass('text-error');
				}
			}
			else{
				error_string += "Va rugam sa completati campul CUI\r\n";
				jQuery('input[name="CUI"]').addClass('text-error');
			}
			if(jQuery('input[name="IBAN"]').val().length<13){
				if(jQuery('input[name="IBAN"]').val()=='')
					error_string += "Va rugam sa completati campul IBAN\r\n";
				else
					error_string += "Campul IBAN nu este completat corect\r\n";
				jQuery('input[name="IBAN"]').addClass('text-error');
			}
			if(jQuery('input[name="banca"]').val().length<2){
				error_string += "Va rugam sa completati campul Banca\r\n";
				jQuery('input[name="banca"]').addClass('text-error');
			}
		} else {
			error_string +="Trebuie sa alegeti tipul de persoana\r\n";
		}
	} else {
		error_string+="Trebuie sa selectati tipul adresei";
	}
	if(error_string!="") {
		alerter(error_string);
		return false;
	} else {
		return true;
	}
}

function ajaxMatrix(content,line_separator,field_separator){
	var matrix=content.split(line_separator);
	for(i=0;i<matrix.length;i++)
		matrix[i]=matrix[i].split(field_separator);
	return matrix;
}

var ajaxSelectsLoaded=new Array();
function ajaxFillSelect(selId,link,reset,reload){
	if(ajaxSelectsLoaded[selId] && !reload){
		alert('List already loaded');
		return;
	}

	ajaxSelectsLoaded[selId]=true;
	matrix=ajaxMatrix(getFile(link),'\r\n','\t');
	selectBox=$(selId);
	if(reset)
		selectBox.options.length=0;
	offset=selectBox.options.length;

	for(i=0;i<matrix.length;i++)
		selectBox.options[i+offset]=new Option(matrix[i][1],matrix[i][0]);
}


function mmin(a,b){
	if(a<b)
		return a;
	else
		return b;
}

function mmax(a,b){
	if(a>b)
		return a;
	else
		return b;
}

function reload(url){
	window.opener.focus();
	window.opener.location.href=url;
	window.close();
}

function SetCookie(cookieName,cookieValue,nDays){
	var today = new Date();
	var expire = new Date();
	if(nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)+";expires="+expire.toGMTString()+";path=/";
}

function popDetails(id,pagen,w,h){
	if(!w)
		w=400;
    if(!h)
    	h=600;
	scr=window.open(base_href+"details/"+id,'pagen',"width="+w+",height="+h+",scrollbars=1,status=yes,menubar=no,resizable=1");
	//scr.moveTo(screen.width/2-250,screen.height/2-275);
	if(scr){
		scr.focus();
	}
}

function checkEnter(event){
	if(event.which==13)
		return true;
	else
		return false;
}

function getCookie(name){
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if(begin == -1){
		begin = dc.indexOf(prefix);
		if(begin != 0)
			return null;
	}
	else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if(end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function is_empty(s,n){
	if((s == null) || (s.length == 0) || (s.length < n)){
		return true;
	}
	else
		return false;
}

function check_enter(event){
	if(event.which==13)
		return true;
	else
		return false;
}

function check_iban(nr){
	nr=nr.replace(/\s/g, '');
	nr=nr.replace(/-/, '');
	if(nr.length!=24)
		return false;
	return true;
}

function check_cui(CIF){
	CIF=CIF.replace(/RO/, '').replace(/ro/, '').replace(/rO/, '').replace(/Ro/, '');

	NrCifre=CIF.length;
	CifraControl=CIF.substring(NrCifre-1,NrCifre);
	CIF=CIF.substring(0,NrCifre-1);
	while(CIF.length<9){
		CIF='0'+CIF;
	}
	SUMA=CIF.charAt(0)*7+CIF.charAt(1)*5+CIF.charAt(2)*3+CIF.charAt(3)*2+CIF.charAt(4)*1+CIF.charAt(5)*7+CIF.charAt(6)*5+CIF.charAt(7)*3+CIF.charAt(8)*2;
	SUMA=SUMA*10;
	REST=SUMA%11;
	if(REST==10)
		$rest=0;

	if(REST == CifraControl)
		return true;
	else
		return false;
}

function check_cnp(nr){
	if(nr.length!=13 || !reInteger.test(nr))
		return false;

	var tmp=nr.substr(0,1);
	if(tmp>6 && tmp!=9)
		return false;

	tmp=nr.substr(3,2);
	if(tmp<1 || tmp>12)
		return false;

	tmp=nr.substr(5,2);
	if(tmp<1 || tmp>31)
		return false;

	var control=0;
	var c="279146358279";
	for(var i=0; i<c.length; i++)
		control+=c.substr(i,1)*nr.substr(i,1);
	control=control%11;
	if(control==10)
		control=1;

	if(control!=nr.substr(12,1))
		return false;

	return true;
}


// BOI = Beginning Of Input
// EOI = End Of Input
// BOI, followed by one or more whitespace characters, followed by EOI.
var reWhitespace = /^s+$/

// BOI, followed by one lower or uppercase English letter, followed by EOI.
var reLetter = /^[a-zA-Z]$/

// BOI, followed by one or more lower or uppercase English letters,
// followed by EOI.
var reAlphabetic = /^[a-zA-Z]+$/

// BOI, followed by one or more lower or uppercase English letters
// or digits, followed by EOI.
var reAlphanumeric = /^[a-zA-Z0-9]+$/

// BOI, followed by one digit, followed by EOI.
var reDigit = /^d/

// BOI, followed by one lower or uppercase English letter
// or digit, followed by EOI.
var reLetterOrDigit = /^([a-zA-Z]|d)$/

// BOI, followed by one or more digits, followed by EOI.
var reInteger = /^[0-9]+$/

// BOI, followed by one of these two patterns:
// (a) one or more digits, followed by ., followed by zero or more digits
// (b) zero or more digits, followed by ., followed by one or more digits
// ... followed by EOI.
var reFloat = /^((d+(.d*)?)|((d*.)?d+))$/

// BOI, followed by one or more characters, followed by @,
// followed by one or more characters, followed by .,
// followed by one or more characters, followed by EOI.
var reEmail = /^.+@.+\..+$/

var reNamed="@-=[];,/\\~!#$%^&*()_+{}:\"<>?|1234567890"
var reName="@=[];,/\\~!#$%^*()_+{}:\"<>?|"
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// whitespace characters as defined by this sample code
var whitespace = " \t\n\r";

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";

// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";

// U.S. phone numbers have 10 digits.
// They are formatted as 123 456 7890 or (123) 456-7890.
var digitsInUSPhoneNumber = 10;

// non-digit characters which are allowed in ZIP Codes
var ZIPCodeDelimiters = "-";

// characters which are allowed in ZIP Code
var validZIPCodeChars = digits + ZIPCodeDelimiters

// U.S. ZIP codes have 5 or 9 digits.
// They are formatted as 12345 or 12345-6789.
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9

// non-digit characters which are allowed in credit card numbers
var creditCardDelimiters = " "

function check_email(a){	// verifica o adresa de e-mail, a=valoarea adresei, nume=numele campului
	if(is_empty(a,4))
		return false;
	else if(!reEmail.test(a))
		return false;
	else
		return true;
}

/**
* verifica sizeul unui element s
*/
function check_element(s, size) {
	if(is_empty(s,size)===true)
		return false;
	else{
		z=0;
		for(j=0; j<=reName.length-1; j++)
    		if(s.indexOf(reName.substring(j,j+1))!=-1)
			z=1;
		if(z==1)
			return false;
		return true;
	}
}

function check_name(s){ // verifica un nume, s=valoarea campului, nume=numele campului, cum va fi afisat
	// verifica daca e mai mic de "size" caractere si daca nu contine caractere invalide
	// perfecte pt un nume

	if(is_empty(s,2)===true)
		return false;
	else{
		z=0;
		for(j=0; j<=reName.length-1; j++)
    		if(s.indexOf(reName.substring(j,j+1))!=-1)
			z=1;
		if(z==1)
			return false;
		return true;
	}
}

function check_phone(s){
	// verifica un numar de telefon,
	// verifica sa contina doar anumite caractere
	// sa fie mai mare de 4 si sa nu fie nul

	if(isEmpty(s,4))
		return false;
	else{
		z=0;
		for(j=0; j<=validWorldPhoneChars.length-1; j++)
			if(validWorldPhoneChars.indexOf(s.substring(j,j+1))==-1)
				z=1;
		if(z==1)
			return false;
		else
			return true;
	}
}
