/**
 * @author Mihai
 */

///////////////////////
// variabile globale //
///////////////////////

var httpObject = null;
var promoTimer = null, saveTimer = null, bestTimer = null;
//var promoTimer = 0, saveTimer = 2, bestTimer = 4;
promos = new Array();
saves = new Array();
bests = new Array();

setValue = 17;
while (promoTimer === null || saveTimer === null || bestTimer === null) {
	pick = Math.round(Math.random() * 2);
	if (pick == 0 && promoTimer === null) {
		promoTimer = setValue;
		setValue += 2;
	}
	else if (pick == 1 && saveTimer === null) {
		saveTimer = setValue;
		setValue += 2;
	}
	else if (pick == 2 && bestTimer === null) {
		bestTimer = setValue;
		setValue += 2;
	}
}

var globalTimer = 0;

//////////////////////
// functii generale //
//////////////////////

function getHTTPObject(){
	var xmlhttp;
	// Attempt to initialize xmlhttp object
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch (e) {
		// Try to use different activex object
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (E) {
			xmlhttp = false;
		}
	}
	// If not initialized, create XMLHttpRequest object
	if (!xmlhttp) {
		if (typeof XMLHttpRequest != 'undefined') {
			xmlhttp = new XMLHttpRequest();
		}
		else {
			alert("Browser-ul nu suporta scripturi AJAX. Folositi Mozilla 1.5+, Internet Explorer 5.5+ sau Opera");
			return null;
		}
	}
	return xmlhttp;
}

function $(id) {
	return document.getElementById(id);
}

function $s(id) {
	return document.getElementById(id).style;
}

function ajaxOk() {
	if (httpObject)
		return httpObject.readyState == 4 && httpObject.status == 200;
		
	return false;
}

function initializeMCE(elems) {
	tinyMCE.init({
		// General options
		mode : "exact",
		elements : elems,
		height: 300,
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,advlink,preview,searchreplace,contextmenu,paste,directionality,noneditable",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,cut,copy,paste,pastetext,pasteword,|,forecolor,backcolor,|,help",
		theme_advanced_buttons2 : "search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		theme_advanced_containers_default_class : 'content_inner',
		theme_advanced_containers_default_align : 'right',
		convert_urls : false,

		// Example content CSS (should be your site CSS)
		content_css : "/css/mce.css"
	});
}

function sendGetRequest(target, handler) {
	httpObject = getHTTPObject();
	if (httpObject != null) {
		path = target.charAt(0) == '/' ? '' : '/include/admin/';
		httpObject.open('GET', path + target, true);
		eval('httpObject.onreadystatechange = ' + handler);
		httpObject.send(null);
	}
}

function sendPostRequest(target, handler, data) {
	httpObject = getHTTPObject();
	if (httpObject != null) {
		path = target.charAt(0) == '/' ? '' : '/include/admin/';
		httpObject.open('POST', path + target, true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Connection", "close");
		eval('httpObject.onreadystatechange = ' + handler);
		httpObject.send(data);
	}
}

function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) 
				c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return false;
}

function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ';path=/';
}

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	}
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}

/* rulare promos */

function tickPromo() {
	if (globalTimer == 0 && false) {
		var theArray = promos;
		nextIndex = 1 + Math.round(Math.random() * (theArray.length - 1));
		nextIndex--;
		
		$('promo_div_promo').innerHTML = theArray[nextIndex];
		$('promo_div_promo').style.opacity = 1;
		
		theArray = saves;
		nextIndex = 1 + Math.round(Math.random() * (theArray.length - 1));
		nextIndex--;
		
		$('promo_div_save').innerHTML = theArray[nextIndex];
		$('promo_div_save').style.opacity = 1;
		
		theArray = bests;
		nextIndex = 1 + Math.round(Math.random() * (theArray.length - 1));
		nextIndex--;
		
		$('promo_div_best').innerHTML = theArray[nextIndex];
		$('promo_div_best').style.opacity = 1;
	}
	
	if (globalTimer == promoTimer)
		changePromo('promo');
	else if (globalTimer == saveTimer)
		changePromo('save');
	else if (globalTimer == bestTimer)
		changePromo('best');
		
	globalTimer++;
	
	setTimeout('tickPromo()', 1000);
}

function changePromo(promoType) {
	eval('var theArray = ' + promoType + 's;');
	
	if (theArray.length > 1) {
		nextIndex = 1 + Math.round(Math.random() * (theArray.length - 1));
		nextIndex--;
		
		if ($('promo_div_' + promoType).style.opacity != 0) 
			shiftOpacity('promo_div_' + promoType, 1000);
		setTimeout("$('promo_div_" + promoType + "').innerHTML = \"" + theArray[nextIndex] + '"', 1000);
		setTimeout("shiftOpacity('promo_div_" + promoType + "', 1000)", 1000);
		
		eval(promoType + 'Timer += 15');// + (10 + Math.round(Math.random() * 5)));
	}
}

/*function changePromo(promoType) {
	sendGetRequest('/include/get_promo.php?type=' + promoType + '&rand=' + Math.random(), 'function() { refreshPromo("' + promoType + '") }');
}

function refreshPromo(promoType) {
	if (ajaxOk()) {
		if ($('promo_div_' + promoType).innerHTML == httpObject.responseText) return;
		if ($('promo_div_' + promoType).style.opacity != 0)
			shiftOpacity('promo_div_' + promoType, 1000);
		setTimeout("$('promo_div_" + promoType + "').innerHTML = httpObject.responseText", 1000);
		setTimeout("shiftOpacity('promo_div_" + promoType + "', 1000)", 1000);
			
		//eval (promoType + 'Timer += 15');
	}
}*/

/* inregistrare newsletter */

function registerNewsletter(lang) {
	sendPostRequest('/include/register-newsletter.php', 'newsletterStatus', 'email=' + encodeURIComponent(document.formNewsletter.email.value));
}

function newsletterStatus() {
	if (ajaxOk()) {
		alert (httpObject.responseText);
		if (httpObject.responseText.indexOf('eroare') == -1 && httpObject.responseText.indexOf('error') == -1)
			document.formNewsletter.reset();
	}
}

/* cautare */

function doSearch() {
	sendPostRequest('/include/set-search.php', 'searchStatus', 'q=' + encodeURIComponent(document.search.q.value))
}

function searchStatus() {
	if (ajaxOk())
		document.location.href = "/search/";
}

function getkey(e) {
	if (window.event) 
		return window.event.keyCode;
	else 
		if (e) 
			return e.which;
		else 
			return null;
}

function start_search(e) {
	var key;
	key = getkey(e);
	if (key == 13) 
		doSearch();
	return
}

/* dezabonare newsletter */

function confirmUnsubscribe() {
	sendPostRequest('/include/unsubscribe.php', 'unsubscribeStatus', 'email=' + encodeURIComponent(document.formUnsubscribe.unsubscriber.value));
}

function unsubscribeStatus() {
	if (ajaxOk())
		document.getElementById('unsubscribeContent').innerHTML = httpObject.responseText;
}

/* adaugare in shopping cart */

function addToCart(idProdus) {
	var oldProducts = new Array, i = 0;
	
	while ((prod = getCookie('cart[' + i + ']')) !== false) {
		oldProducts[oldProducts.length] = prod;
		setCookie('cart[' + i + ']', '', -1);
		i++;
	}
	
	oldProducts[oldProducts.length] = idProdus;
	
	i = 1;
	for (i = 0; i < oldProducts.length; i++)
		setCookie('cart[' + i + ']', oldProducts[i], 7);
	
	alert('Produsul a fost adaugat in cosul dvs.');
	updateCart();
}

function updateCart() {
	i = 0;
	
	while (getCookie('cart[' + i + ']'))
		i++;
		
	if (i == 0)
		$('cart_status').innerHTML = '';
	else
		$('cart_status').innerHTML = 'Aveti ' + i + ' produs' + (i != 1 ? 'e' : '') + ' in cos';
}

function getShoppingCart() {
	sendGetRequest('/include/get_cart.php?rand=' + Math.random(), 'displayCart');
}

function displayCart() {
	if (ajaxOk())
		$('content').innerHTML = httpObject.responseText;
}

function emptyCart() {
	if (confirm('Sunteti sigur ca doriti sa stergeti toate produsele din cos?'))
		sendGetRequest('/include/empty_cart.php?rand=' + Math.random(), 'function() { if (ajaxOk()) getShoppingCart() }');
}

function removeFromCart(idProdus) {
	if (confirm('Sunteti sigur ca doriti sa stergeti acest produs din cos?'))
		sendGetRequest('/include/remove_from_cart.php?id=' + encodeURIComponent(idProdus) + '&rand=' + Math.random(), 'function() { if (ajaxOk()) getShoppingCart() }');
}

function doCompare() {
	with (document.formCompare) {
		if (!compare_1.selectedIndex && !compare_2.selectedIndex) return false;
		
		if (compare_1.selectedIndex != compare_2.selectedIndex)
			document.location.href = "/compara/" + compare_main.value + '/' + compare_1.options[compare_1.selectedIndex].value + '/' + compare_2.options[compare_2.selectedIndex].value;
		else
			document.location.href = "/compara/" + compare_main.value + '/' + compare_1.options[compare_1.selectedIndex].value;
	}
}

/* formular de comanda */

function doOrder() {
	if (!getCookie('cart[0]')) alert ('Cosul dvs. de produse este gol !');
	else document.location.href = '/order';
}

function togglePers(tipPers) {
	otherTip = tipPers == 'pf' ? 'pj' : 'pf';
	$('contact_' + tipPers).style.display = 'block';
	$('contact_' + otherTip).style.display = 'none';
}

function submitOrder(tipPers) {
	var params = new Array();
	
	if (tipPers == 'pf') {
		with (document.formDoOrder) {
			if (nume.value == '' || adresa.value == '' || telefon.value == '' || email.value == '') {
				alert('Toate campurile sunt obligatorii !');
				return false;
			}
			
			params[params.length] = 'nume=' + encodeURIComponent(nume.value);
			params[params.length] = 'adresa=' + encodeURIComponent(adresa.value);
			params[params.length] = 'telefon=' + encodeURIComponent(telefon.value);
			params[params.length] = 'email=' + encodeURIComponent(email.value);
			params[params.length] = 'mod_plata=' + encodeURIComponent(mod_plata.options[mod_plata.selectedIndex].value);
			params[params.length] = 'tip=pf';
		}
	}
	else {
		with (document.formDoOrderFirma) {
			if (firma.value == '' || cui.value == '' || j.value == '' || nume.value == '' || adresa.value == '' || telefon.value == '' || email.value == '') {
				alert('Toate campurile sunt obligatorii !');
				return false;
			}
			
			params[params.length] = 'nume=' + encodeURIComponent(nume.value);
			params[params.length] = 'adresa=' + encodeURIComponent(adresa.value);
			params[params.length] = 'telefon=' + encodeURIComponent(telefon.value);
			params[params.length] = 'email=' + encodeURIComponent(email.value);
			params[params.length] = 'firma=' + encodeURIComponent(firma.value);
			params[params.length] = 'cui=' + encodeURIComponent(cui.value);
			params[params.length] = 'j=' + encodeURIComponent(j.value);
			params[params.length] = 'mod_plata=' + encodeURIComponent(mod_plata.options[mod_plata.selectedIndex].value);
			params[params.length] = 'tip=pj';
		}
	}
	sendPostRequest('/include/send_order.php', 'orderStatus', params.join('&'));
}

function orderStatus() {
	if (ajaxOk()) {
		alert(httpObject.responseText);
		if (httpObject.responseText.indexOf('eroare') == -1)
			document.location.href = '/shopping-cart';
	}
}

/* formular de contact */

function sendMessage() {
	with (document.formContact) {
		if (nume.value == '' || email.value == '' || subiect.value == '' || mesaj.value == '') {
			alert('Toate campurile sunt obligatorii !');
			return false;
		}
		
		var params = new Array();
		params[params.length] = 'nume=' + encodeURIComponent(nume.value);
		params[params.length] = 'email=' + encodeURIComponent(email.value);
		params[params.length] = 'subiect=' + encodeURIComponent(subiect.value);
		params[params.length] = 'mesaj=' + encodeURIComponent(mesaj.value);
		
		sendPostRequest('/include/send_contact.php', 'contactStatus', params.join('&'));
	}
}

function contactStatus() {
	if (ajaxOk()) {
		alert(httpObject.responseText);
		if (httpObject.responseText.indexOf('eroare') == -1)
			document.formContact.reset();
	}
}

/* raportare eroare */

function sendReporting() {
	with (document.formReporting) {
		if (mesaj.value == '') {
			alert('Mesajul dvs. este gol !');
			mesaj.focus();
			return;
		}
		sendPostRequest('/include/send_reporting.php', 'reportingStatus', 'mesaj=' + encodeURIComponent(mesaj.value) + '&uri=' + encodeURIComponent(uri.value));
	}
}

function reportingStatus() {
	if (ajaxOk()) {
		alert(httpObject.responseText);
		if (httpObject.responseText.indexOf('eroare') == -1)
			document.formReporting.reset();
	}
}

/* rating produse */

function rate(idProdus, nota) {
	sendPostRequest('/include/rate_produs.php', 'ratingStatus', 'id=' + encodeURIComponent(idProdus) + '&nota=' + encodeURIComponent(nota));
}

function ratingStatus() {
	if (ajaxOk()) {
		newRating = parseFloat(httpObject.responseText);
		if (isNaN(newRating))
			alert(httpObject.responseText);
		else {
			alert('Va multumim pentru nota !');
			$('current_rating').style.width = (25* newRating) + 'px';
		}
	}
}

