///////////////////////
// Variabile globale //
///////////////////////

// Oferte speciale
var offers; // Daca mouse-ul e in oferte sau nu
var currOffer = 2; // Oferta curenta afisata
var totalOffers; // Totalul ofertelor afisate
var timedOffers = 4000; // Intervalul de schimbare oferte
var timedOffers_bk = timedOffers; // Intervalul de schimbare oferte (backup)
var offersLive = 1;

// Functii
$(document).ready(function() {
	// Event-uri
    $(document).ready(function () {
		// Oferte speciale
		$("div.images img, div.navBg, ul.previewNav").hover(function() {
			offers = 1;
			setTimeout('showOffNav()', 100);
		}, function() {
			if(offersLive == 1) {
				offers = 0;
				setTimeout('hideOffNav()', 100);
			}
		});
		
		// Animatie oferte speciale
		playOffers();
		
		// Initializare detectare locatie
		initialize();
		
	},function(){});
});

function checkBox(item) {
	var status = $("#"+item).find("input").attr("checked");
	if(status == true) { $("#"+item).find("label").removeClass("sel"); $("#"+item).find("input").attr("checked", ""); }
	else { $("#"+item).find("label").addClass("sel"); $("#"+item).find("input").attr("checked", "checked"); }
}

function showOffNav() {
	/*if(offers == 1) {
		$("div.navBg").fadeIn();
		$("ul.previewNav").fadeIn();
	}*/
}

function hideOffNav() {
	/*if(offers == 0) {
		$("div.navBg").fadeOut();
		$("ul.previewNav").fadeOut();
	}*/
}

function changeOffer(id) {
	// Change offer
	var newX = (id-1)*676*(-1);
	if(id > totalOffers) {
		$("div.offers div.images").animate({left: newX+"px"}, {duration: 500, easing: 'easeOutQuad'}).animate({left: "0px"}, 0);
		id=1;
		// Get offer title
		var title = $(".off"+id+" img").attr("alt");
	} else {
		$("div.offers div.images").animate({left: newX+"px"}, {duration: 500, easing: 'easeOutQuad'});
		// Get offer title
		var title = $(".off"+id+" img").attr("alt");
	}
	// Set ofer title and subtitle
	$("#pCaption").fadeOut("normal", function callback() {
		$("#pCaption").html(title).fadeIn();
	});

	// Set offer # selected
	$("ul.previewNav li em").removeClass("sel");
	$("ul.previewNav li em#nv"+id).addClass("sel");
	currOffer = id;
}

function clickChangeOffer(id) {
	changeOffer(id);
	currOffer = id+1; 
	if(offersLive == 1) {
		$("span.bar").stop().animate({width: "0px"}, 0);
		playOffers();
	}
}

function playOffers() {
	// Recalculare in functie de unpause si pozitia ramasa;
	var barWidth = $("span.bar").css("width");
	barWidth = parseInt(barWidth);
	if(barWidth > 0) {
		timedOffers -= timedOffers*barWidth/100;
	}
	
	// Timer animation
	$("span.bar").animate({width: "100px"}, timedOffers, "linear", function() {
		if(currOffer <= totalOffers) {
			changeOffer(currOffer);
			currOffer++;
		} else if(currOffer > totalOffers) {
			changeOffer(totalOffers+1);
			currOffer = 2;
		}
		$("span.bar").animate({width: "0px"}, 0);
		timedOffers = timedOffers_bk;
		playOffers();
	});
}

function pauseOffers() {
	if(offersLive == 1) {
		// Pause
		offersLive = 0;
		$("img.play").show();
		$("img.pause").hide();
		$("span.bar").stop();
	} else {
		// Unpause
		offersLive = 1;
		$("img.play").hide();
		$("img.pause").show();
		playOffers();
	}
}


// Animatie meniu
var history_om;
function openMenu(key) {
	if($("ul#subMenu"+key).html() == null) return true;
	else if(history_om == key) return false;
	$("ul.menus").slideUp();
	$("ul#subMenu"+key).slideDown();
	$("a.lvl1").removeClass("sel1")
	$("a#leftNav"+key).addClass("sel1");
	history_om = key;
	return false;
}

function auto_openMenu(key) {
	$(document).ready(function() {
		if(key != null) {
			$("ul#subMenu"+key).show();
			$("a#leftNav"+key).addClass("sel1");
		} else {
			$("ul.menus:first").show();
			$("a.lvl1:first").addClass("sel1")
		}
		history_om = key;
	});
}

var globalFilterState = false;
function openFilters() {
	if(globalFilterState == false) {
		$(".filters form, div.fCont").slideDown();
		$(".fEnd").show();
		$("#catOpener").addClass("sel");
		globalFilterState = true;
	} else {
		$(".filters form, div.fCont").slideUp();
		$(".fEnd").hide();
		$("#catOpener").removeClass("sel");
		globalFilterState = false;
	}
	return false;
}
/*
function closeFilters() {
	$("#zoomApp_bg").hide();
	$(".filters").hide();
	return false;
}
*/

function submitFilters() {
	$("form[name=filters]").submit();
	return false;
}

function cancelFilters(cat) {
	document.location = 'index.php?cat='+cat;
	return false;
}

function openZoom() {
	$("#zoomApp_bg").fadeIn("medium", function() {
		$("#zoomApp_bg").css("filter", "alpha(opacity=80)")
		$("#zoomApp").fadeIn("slow", function() {
			$("#zoomApp ul").slideDown();
		});
	});
	document.title = "Imagini cu "+$("#prodName").html();
	return false;
}

function closeZoom() {
	$("#zoomApp ul").hide();
	$("#zoomApp").fadeOut();
	$("#zoomApp_bg").fadeOut();
	document.title = $("#prodName").html();
}

function navImg(param) {
	var total = parseInt($("#zoomCount").html());
	var current = parseInt($("#current").html());
	var old = current;
	
	// Incrementare
	if(param == 'prev') current--;
	else if(param == 'next') current++;
	
	if(current > total-1) current = 0;
	else if(current < 0) current = (total-1);
	
	// Tranzitie
	$("#zImg_"+old).fadeOut('fast', function() {
		$("#zImg_"+current).fadeIn();
	});
	
	// Afisare text
	$("#zoomApp li.info span").html('Poza '+(current+1)+' din '+total);
	
	// Introducere date noi
	$("#current").html(current);
	
	return false;
}

function initialize() {
	dhtmlHistory.initialize();
	var initialLocation = dhtmlHistory.getCurrentLocation();
	dhtmlHistory.addListener(handleHistoryChange);
}

function handleHistoryChange(newLocation, historyData) {
	var productName = $("#prodName").html();
	if(newLocation == "" && productName != null) { closeZoom(); }
	if(newLocation == "" && productName == null) { closeFilters(); }
}

function isLen(str, min, max) {
	if(str.length < min || str.length > max) return false;
	else return true;
}

function verifyEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)) return true; else return false;
}

function contact() {
	// Setare verificari erori
	errors = "Urmatoarele date nu au fost introduse corect:\n\n";
	errCount = 0;
	
	// Setare campuri verificate
	fullname = 			$("input[name=fullname]").attr("value");
	email = 			$("input[name=email]").attr("value");
	message = 			$("textarea[name=message]").attr("value");
	
	// Validare campuri
	if(fullname == '') { errors += "- Numele a fost omis\n"; errCount++; }
	if(email == '') { errors += "- Email-ul nu fost completat\n"; errCount++; }
	else if(verifyEmail(email) == false) { errors += "- Adresa de e-mail nu este valida\n"; errCount++; }
	if(message == '') { errors += "- Mesajul tau lipseste\n"; errCount++; }
	
	
	// Afisare erori sau submit
	if(errCount > 0) { alert(errors); return false; }
	$("input#submit").hide();
	$("div#submitted").show();
	return true;
}

function formatPrice(price) {
    return number_format(price,2,',','.') + " Lei";
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // %        note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

var selServ = 0;
var servSubTotal = 0;
var servTva = 0;
var servTotal = 0;

function servCalc(id) {
	// Preluare date
	var cS = $("#serv_"+id).attr("checked");
	var vS = parseInt($("#serv_"+id).attr("value"));
	
	// Calculare date
	if(cS == true) {
		selServ++;
		servSubTotal += vS;
	} else {
		selServ--;
		servSubTotal -= vS;
	}
	servTva = Math.round(((servSubTotal/100)*24)*100)/100;
	servTotal = Math.round((servSubTotal+servTva)*100)/100;
	
	// Afisare date
	if(selServ == 0) $("#selServ").html("Nu s-au selectat servicii.");
	else if(selServ == 1) $("#selServ").html("S-a selectat un serviciu.");
	else $("#selServ").html("S-au selectat <b>"+selServ+"</b> servicii.");
	$("#servSubTotal").html(formatPrice(servSubTotal));
	$("#servTva").html(formatPrice(servTva));
	$("#servTotal").html(formatPrice(servTotal));
}

function qFocus() {
	qVal = $("input[name=q]").attr("value");
	if(qVal == 'Denumire sau cod produs') $("input#q").attr("value", "");
}

function qBlur() {
	qVal = $("input[name=q]").attr("value");
	if(qVal == '') $("input#q").attr("value", "Denumire sau cod produs");
}
