// JavaScript Document
// created by Smart Web Concept - copyright www.smartwebconcept.ro

// testare incarcare fisier js
//alert("S-a incarcat fisierul cu scripturi!!!");

// script schimbare ordine afisare
function schimba_afisarea(){
	document.afisare_oferte.submit();	
}

// functie pentru selectarea tarii din harta pt formularul de cautare
function filter(url,par,val){
	var loc=url+"?"+par+"="+val;
	window.open(loc,'_self');
}	

function empty_input(elm,txt){
	if (document.getElementById(elm).value==txt){
		document.getElementById(elm).value="";
	}
}

function fill_input(id,txt){
	if (document.getElementById(id).value==""){
		document.getElementById(id).value=txt;
	}
}

function mesaj_text(mesaj){
	window.alert(mesaj)	;
}

function schimba_img(id,img){
	document.getElementById(id).src=img;	
}

function preload_img(imagine,w,h){
	if (document.images){
		if(w!=0 && h!=0){
			var img=new Image(w,h);
		}
		else{
			var img=new Image();
		}
		img.src=imagine;	
	}
	
}

function img_principala(img){
	document.getElementById("main_img").src=img;
}

///////////// start validare formulare

// functie validare formular

function validareFormularCuRestrictii() { //v4.0
// err_text='The following error(s) occurred:';
// err_email_format=' must contain an e-mail address.';
// err_number_format=' must contain a number.';
// err_number_range_min=' must contain a number between ';
// err_number_range_max=' and ';
// err_checkbox=' must be checked';
// err_selectbox=' must be choosen';
// err_minLimits=' must be longer than ';
// err_maxLimits=' must be shorter than ';
// err_required_field=' is required.';
//alert('S-a apelat functia de validare a formularului!!');alert('test');
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',selected_index,args=validareFormularCuRestrictii.arguments;
    for (i=0; i<(args.length-3); i+=4) {
		test=args[i+3]; 
		lm=args[i+1]; 
		lM=args[i+2];
		val=document.getElementById(args[i]);
		var checkbox=validare_checkbox(args[i]);
		var selectbox=validare_select(args[i],args[i+3]);
		if(!checkbox){
			nm=labels(args[i]);
			errors += '- '+nm+err_checkbox+'\n';
		}
		if(!selectbox){
			nm=labels(args[i]);
			errors += '- '+nm+err_selectbox+'\n';
		}
      	if (val) { 
			nm=val.name; 
			// start my code
			nm=labels(args[i]);
			// validare select
			//selected_index=val.selectedIndex;
			//var optiune_invalida=test.slice(1);
			//if (selected_index==optiune_invalida){
			//	errors += '- '+nm+err_required_field+'\n';
			//}
			// end my code
			
			if ((val=val.value)!="") {// pentru validarea select-ului trebuie ca optiunea invalida sa aiba value="" sau se foloseste validarea selectului cu functia validare_select()
        		if(lm!=""){
					if(val.length<lm){
						errors += '- '+nm+err_minLimits+lm+'\n';
						//errors += '- '+nm+err_minLimits+'\n';
					}
				}
				if(lM!=""){
					if(val.length>lM){
						errors += '- '+nm+err_maxLimits+lM+'\n';
						//errors += '- '+nm+err_maxLimits+'\n';
					}
				}
				
				if (test.indexOf('isEmail')!=-1) { 
					p=val.indexOf('@');
          			if (p<1 || p==(val.length-1)) errors+='- '+nm+err_email_format+'\n';
        		} 
				else if (test!='R') { 
					if(test.indexOf('|')==-1){// nu e pentru validarea select-ului
						num = parseFloat(val);
						if (isNaN(val)) errors+='- '+nm+err_number_format+'\n';
						if (test.indexOf('inRange') != -1) { 
							p=test.indexOf(':');
							min=test.substring(8,p); 
							max=test.substring(p+1);
							if (num<min || max<num) errors+='- '+nm+err_number_range_min+min+err_number_range_max+max+'.\n';
						}	
					} 
				} 
			} 
			else if (test.charAt(0) == 'R') errors += '- '+nm+err_required_field+'\n';
		}
    } if (errors) alert(err_text+'\n'+errors);
	// valoarea returnata
    document.valoareReturnata = (errors == '');
  } 
}

// --------------- afisare label in mesajul de eroare
function labels(eticheta){
	//alert(eticheta);
	nm1=document.getElementsByTagName("label");
	nm3=eticheta; // daca nu e definit un label pentru camp, returneaza id-ul campului
	var nm="";
		for(j=0;j<nm1.length;j++){
			//var nm=nm+nm1[j].htmlFor+" - ";
			if(nm1[j].htmlFor==eticheta){
				nm=nm1[j].innerHTML;
				nm2=nm.indexOf('<');
				if(nm2==-1){
					nm3=nm;
				}
				else{
					nm3=nm.substr(0,nm2);
				}
			}
		}
	nm3=nm3+" -> ";
	return nm3;
}

// --------------- validare checkbox-uri
function validare_checkbox(id){
	var box=document.getElementById(id);
	if(box.type=="checkbox"){
		if (box.checked == false)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else{
		return true;
	}
}

// --------------- validare select-uri
function validare_select(id,conditie){
	var selectid=document.getElementById(id);
	if(selectid.type=="select-one"){
		if(conditie.indexOf('R')==-1){
			return true;
		}
		else{
			poz_r=conditie.indexOf('|');
			val_implicita=conditie.substring(poz_r+1);
			if(selectid.value==val_implicita){
				return false;
			}
			else{
				return true;	
			}
		}	
	}
	else{
		return true;	
	}
}

///////////// end validare formulare

// start functii pentru meniu


var timeout	= 800;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.display = 'none';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.display = 'block';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.display = 'none';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 


// end functii pentru meniu

// start abonare newsletter

function CheckMultiple1(frm, name) {
				for (var i=0; i < frm.length; i++)
				{
					fldObj = frm.elements[i];
					fldId = fldObj.id;
					if (fldId) {
						var fieldnamecheck=fldObj.id.indexOf(name);
						if (fieldnamecheck != -1) {
							if (fldObj.checked) {
								return true;
							}
						}
					}
				}
				return false;
			}
		function CheckForm1(f) {
			if (f.email.value == "") {
				//alert("Please enter your email address.");
				// start my code 
				alert("Email - "+err_required_field);
				// end my code
				f.email.focus();
				return false;
			}
		
				return true;
			};

// end abonare newsletter

// start AJAX section

// functie ce asteapta rezultatul inainte de a permite continuarea executiei
// primul parametrul este url-ul de executat, ce va contine si un parametru ce va permite ca in fisierul url sa se aleaga ce cod sa fie executat
// al doilea parametru este id-ul elementului al carui continut va fi inlocuit de rezultatul functiei
// returneaza rezultatul furnizat de url pentru parametrul code_chooser, rezultat ce va contine cod HTML
function ajax_div(url,id_continut){
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.open("GET",url,false);
	xmlhttp.send(null);
	
	document.getElementById(id_continut).innerHTML=xmlhttp.responseText;
	//document.write(xmlhttp.responseText);
}

// functie care va rula cererea AJAX la modificarea unei selectii intr-un camp select
// primul parametru este id-ul selctului de baza
// al doilea parametru este url-ul ce va returna rezultatul; url-ului i se va alipi valoara selectului de baza si apoi va fi apelat AJAX-ul
// al treilea parametru eate id-ul elementului ce va primi rezultatul
// al patrulea parametru este imaginea ce va fi incarcata pe perioada in care se determina rezultatul ce va fi afisat
function schimba_selectia(id_sursa,url,id_element,img_src){
	var selector=document.getElementById(id_sursa);
	var val_selectata=selector.options[selector.options.selectedIndex].value;
	url+=val_selectata;
	var img="<img src='"+img_src+"' border='0' />";
	document.getElementById(id_element).innerHTML=img;
	ajax_div(url,id_element);
}

// functie care va rula cereri AJAX la modificarea unei selectii intr-un camp select si va modifica continutul mai multor elemente in functie de valoarea selectului de baza
// primul parametru este id-ul selectului de baza
// al doilea parametru este un vector cu url-urile care vor returna rezultatele in functie de valoarea selectului de baza; fiecarui url i se va alipi valoara selectului de baza si apoi va fi apelat AJAX-ul
// al treilea parametru este un vector cu id-urile elementelor ce vor primi rezultatele apelarilor AJAX
// al patrulea parametru este un vector cu imaginile ce vor fi incarcate in elementele ce urmeaza a fi modificate pe perioada in care se vor obtine rezultatele AJAX-urilor
// observatie: parametrii 2, 3 si 4 trebuie sa aiba elementele corespunzatoare intr-o relatie de 1:1 (adica elementul 1 al parametrului 2 sa corespunda elementului 1 al parametrului 2 si elementului 1 al parametrului 3, etc.)
function schimba_selectia_n(id_sursa,arr_url,arr_id_element,arr_img_src){
    var nr_elemente=arr_id_element.length;
    for(i=0;i<nr_elemente;i++){
        schimba_selectia(id_sursa,arr_url[i],arr_id_element[i],arr_img_src[i]);
    }
}

// functie care va rula cererea AJAX la modificarea unei selectii intr-un camp select si va afisa optiunile in functie de optiunea din alt element select
// primul parametru este id-ul selectului de baza
// al doilea parametru este url-ul ce va returna rezultatul; url-ului i se va alipi valoara selectului de baza si un parametru "ref" cu valoarea selectului de referita si apoi va fi apelat AJAX-ul
// al treilea parametru eate id-ul elementului ce va primi rezultatul
// al patrulea parametru este imaginea ce va fi incarcata pe perioada in care se determina rezultatul ce va fi afisat
// al cincilea parametru este id-ul selectului in functie de care se returneaza rezultatul
function schimba_selectia_2(id_sursa,url,id_element,img_src,id_referinta){
	var selector=document.getElementById(id_sursa);
	var val_selectata=selector.options[selector.options.selectedIndex].value;
	var referinta=document.getElementById(id_referinta);
	var val_referinta=referinta.options[referinta.options.selectedIndex].value;
	url+=val_selectata+"&ref="+val_referinta;
	var img="<img src='"+img_src+"' border='0' />";
	document.getElementById(id_element).innerHTML=img;
	ajax_div(url,id_element);
}


// end AJAX section

///////////// start confirmare actiune

function confirmare_actiune(intrebare_confirmare,actiune,text_cancel){
    x=window.confirm(intrebare_confirmare);
    if(x){
        window.location=actiune;
    }
    else{
        window.alert(text_cancel)
    }
}

///////////// end confirmare actiune

///////////// start date picker

// Project: Dynamic Date Selector (DtTvB) - 2006-03-16
// Script featured on JavaScript Kit- http://www.javascriptkit.com
// Code begin...
// mdificat de Smart Web Concept SRL - www.smartwebconcept.ro (Tudor Popescu)

// Set the initial date.
var ds_i_date = new Date();
ds_c_month = ds_i_date.getMonth() + 1;
ds_c_year = ds_i_date.getFullYear();

// Get Element By Id
function ds_getel(id) {
	return document.getElementById(id);
}

// Get the left and the top of the element.
function ds_getleft(el) {
	var tmp = el.offsetLeft;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetLeft;
		el = el.offsetParent;
	}
	return tmp;
}
function ds_gettop(el) {
	var tmp = el.offsetTop;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetTop;
		el = el.offsetParent;
	}
	return tmp;
}

// Output Element - id-ul elementului este 'ds_calclass'
//var ds_oe = ds_getel('ds_calclass');
var ds_oe;
// Container - id-ul container-ului este 'ds_conclass'
//var ds_ce = ds_getel('ds_conclass');
var ds_ce;

// Output Buffering
var ds_ob = '';
function ds_ob_clean() {
	ds_ob = '';
}
function ds_ob_flush() {
	ds_oe.innerHTML = ds_ob;
	ds_ob_clean();
}
function ds_echo(t) {
	ds_ob += t;
}

var ds_element; // Text Element...

var ds_monthnames = [
'Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie',
'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'
]; // You can translate it for your language.

var ds_daynames = [
'Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Sa'
]; // You can translate it for your language.

var close_txt="Inchide";

// Calendar template
function ds_template_main_above(t) {
	return '<table cellpadding="3" cellspacing="1" class="ds_tbl">'
	     + '<tr>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_py();">&lt;&lt;</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_pm();">&lt;</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_hi();" colspan="3">['+close_txt+']</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_nm();">&gt;</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_ny();">&gt;&gt;</td>'
		 + '</tr>'
	     + '<tr>'
		 + '<td colspan="7" class="ds_head">' + t + '</td>'
		 + '</tr>'
		 + '<tr>';
}

function ds_template_day_row(t) {
	return '<td class="ds_subhead">' + t + '</td>';
	// Define width in CSS, XHTML 1.0 Strict doesn't have width property for it.
}

function ds_template_new_week() {
	return '</tr><tr>';
}

function ds_template_blank_cell(colspan) {
	return '<td colspan="' + colspan + '"></td>'
}

function ds_template_day(d, m, y) {
	return '<td class="ds_cell" onclick="ds_onclick(' + d + ',' + m + ',' + y + ')">' + d + '</td>';
	// Define width the day row.
}

// start my code
function ds_template_day_today(d, m, y) {
	return '<td class="ds_cell_today" onclick="ds_onclick(' + d + ',' + m + ',' + y + ')">' + d + '</td>';
	// Define width the day row.
        // defineste ziua curenta
}
// end my code

function ds_template_main_below() {
	return '</tr>'
	     + '</table>';
}

// This one draws calendar...
function ds_draw_calendar(m, y) {
	// First clean the output buffer.
	ds_ob_clean();
	// Here we go, do the header
	ds_echo (ds_template_main_above(ds_monthnames[m - 1] + ' ' + y));
	for (i = 0; i < 7; i ++) {
		ds_echo (ds_template_day_row(ds_daynames[i]));
	}
	// Make a date object.
	var ds_dc_date = new Date();
	ds_dc_date.setMonth(m - 1);
	ds_dc_date.setFullYear(y);
	ds_dc_date.setDate(1);
	if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
		days = 31;
	} else if (m == 4 || m == 6 || m == 9 || m == 11) {
		days = 30;
	} else {
		days = (y % 4 == 0) ? 29 : 28;
	}
	var first_day = ds_dc_date.getDay();
	var first_loop = 1;
	// Start the first week
	ds_echo (ds_template_new_week());
	// If sunday is not the first day of the month, make a blank cell...
	if (first_day != 0) {
		ds_echo (ds_template_blank_cell(first_day));
	}
	var j = first_day;
	for (i = 0; i < days; i ++) {
		// Today is sunday, make a new week.
		// If this sunday is the first day of the month,
		// we've made a new row for you already.
		if (j == 0 && !first_loop) {
			// New week!!
			ds_echo (ds_template_new_week());
		}
		// Make a row of that day!
                // start my code
                var azi=new Date();
                var astazi=azi.getDate();
                if((i+1)==astazi){
                    // se evidentiaza ziua curenta
                    ds_echo (ds_template_day_today(i + 1, m, y));
                }
                else{
                    ds_echo (ds_template_day(i + 1, m, y));
                }
                // end my code

		// This is not first loop anymore...
		first_loop = 0;
		// What is the next day?
		j ++;
		j %= 7;
	}
	// Do the footer
	ds_echo (ds_template_main_below());
	// And let's display..
	ds_ob_flush();
	// Scroll it into view.
	// ds_ce.scrollIntoView(); // nu se mai scroll-eaza pana la campul cu data calendaristica
}

// A function to show the calendar.
// When user click on the date, it will set the content of t.
function ds_sh(t) {
	// Set the element to set...
	ds_element = t;
	// Make a new date, and set the current month and year.
	var ds_sh_date = new Date();
	ds_c_month = ds_sh_date.getMonth() + 1;
	ds_c_year = ds_sh_date.getFullYear();
	// Draw the calendar
	ds_draw_calendar(ds_c_month, ds_c_year);
	// To change the position properly, we must show it first.
	ds_ce.style.display = '';
	// Move the calendar container!
	the_left = ds_getleft(t);
	the_top = ds_gettop(t) + t.offsetHeight;
	ds_ce.style.left = the_left + 'px';
	ds_ce.style.top = the_top + 'px';
	// Scroll it into view.
	//ds_ce.scrollIntoView(); // nu se mai scroll-eaza pana la campul cu data calendaristica
}

// Hide the calendar.
function ds_hi() {
	ds_ce.style.display = 'none';
}

// Moves to the next month...
function ds_nm() {
	// Increase the current month.
	ds_c_month ++;
	// We have passed December, let's go to the next year.
	// Increase the current year, and set the current month to January.
	if (ds_c_month > 12) {
		ds_c_month = 1;
		ds_c_year++;
	}
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Moves to the previous month...
function ds_pm() {
	ds_c_month = ds_c_month - 1; // Can't use dash-dash here, it will make the page invalid.
	// We have passed January, let's go back to the previous year.
	// Decrease the current year, and set the current month to December.
	if (ds_c_month < 1) {
		ds_c_month = 12;
		ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
	}
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Moves to the next year...
function ds_ny() {
	// Increase the current year.
	ds_c_year++;
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Moves to the previous year...
function ds_py() {
	// Decrease the current year.
	ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Format the date to output.
function ds_format_date(d, m, y) {
	// 2 digits month.
	m2 = '00' + m;
	m2 = m2.substr(m2.length - 2);
	// 2 digits day.
	d2 = '00' + d;
	d2 = d2.substr(d2.length - 2);
	// YYYY-MM-DD
	return y + '-' + m2 + '-' + d2;
}

// When the user clicks the day.
function ds_onclick(d, m, y) {
	// Hide the calendar.
	ds_hi();
	// Set the value of it, if we can.
	if (typeof(ds_element.value) != 'undefined') {
		ds_element.value = ds_format_date(d, m, y);
	// Maybe we want to set the HTML in it.
	} else if (typeof(ds_element.innerHTML) != 'undefined') {
		ds_element.innerHTML = ds_format_date(d, m, y);
	// I don't know how should we display it, just alert it to user.
	} else {
		alert (ds_format_date(d, m, y));
	}
}

// start my code
function calendar_init(obj,container,output_element){
    // Output Element
    ds_oe = ds_getel(output_element);
    // Container
    ds_ce = ds_getel(container);
    ds_sh(obj);
}
// end my code

// And here is the end.

///////////// end date picker

///////////// start validare 2 momente de timp consecutive

// functie pentru validarea ordinii cronologice

function validare_cronologica(iddata_start,idora_start,iddata_end,idora_end){
    var rezultat=false;
    var obj_data_start=document.getElementById(iddata_start);
    var data_start=obj_data_start.value;
    var obj_ora_start=document.getElementById(idora_start);
    var ora_start=obj_ora_start.value;
    var obj_data_end=document.getElementById(iddata_end);
    var data_end=obj_data_end.value;
    var obj_ora_end=document.getElementById(idora_end);
    var ora_end=obj_ora_end.value;
    if(data_start<data_end){
        rezultat=true;
    }
    else{
        if(data_start==data_end){
            if(ora_start<ora_end){
                rezultat=true;
            }
            else{
                rezultat=false;
            }
        }
        else{
            rezultat=false;
        }
    }

    if(!rezultat){
//        var err_chronologically="Momentele de timp nu sunt alese corect cronologic";
        alert(err_chronologically);
    }
    document.rezultat_cronologic=rezultat;
//    return rezultat;
}

///////////// end validare 2 momente de timp consecutive

///////////// start adaugare file-field in formular

function photogallery_add_filefield(formid,txt_link,field_limit){

    field_limit--;
    
    var formular=document.getElementById(formid);

    var submit_btn;

    var br_tag=document.createElement('br');

    var space=document.createTextNode(' ');

    

    // se determina input-ul de tip submit
    var inputs_arr=formular.getElementsByTagName('input'); // se determina toate input-urile
    var submit_index=0;
    for(i=0;i<inputs_arr.length;i++){
        if(inputs_arr[i].getAttribute('type')=='submit'){
            submit_btn=inputs_arr[i];
            submit_index=i;
        }
    }
    //

    // se elimina toate butoanele de tip add new field
    var anchor_arr=formular.getElementsByTagName('a');
    for(j=0;j<anchor_arr.length;j++){
        formular.removeChild(anchor_arr[j]);
    }
    //

    var input_field=document.createElement('input');
    input_field.setAttribute('type', 'file');
    input_field.setAttribute('name', 'arr_img[]');
    input_field.setAttribute('id', 'foto'+submit_index);
    
    formular.insertBefore(input_field, submit_btn); // se adauga campul
    formular.insertBefore(space, submit_btn); // se adauga un spatiu

    if(field_limit>0){
        var add_field_btn=document.createElement('a');
        var link_add_btn="javascript:photogallery_add_filefield('"+formid+"','"+txt_link+"','"+field_limit+"');";
        add_field_btn.setAttribute('href','#0');
        add_field_btn.setAttribute('onclick', link_add_btn);

        var txt_link_add_field=document.createTextNode(txt_link);
        add_field_btn.appendChild(txt_link_add_field);

        formular.insertBefore(add_field_btn, submit_btn); // se adauga butonul pentru crearea unui nou camp
    }

    formular.insertBefore(br_tag,submit_btn); // se adauna un rand nou

}

///////////// start adaugare file-field in formular
