/**
 * @author Mihai
 */

///////////////////////
// variabile globale //
///////////////////////

var httpObject = null;
var globalTimer = 0, timer = 6, lastIndex = null;
var imgArray = new Array();
//////////////////////
// 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,
		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) {
		var variables = new Array('dummy', 'random', 'bull', 'useless', 'discard');
		path = target.charAt(0) == '/' ? '' : '/include/admin/';
		path += target
		for (i = 0; i < 5; i++)
			if (path.indexOf(variables[i] + '=') == -1)
				break;
		if (i < 5)
			path += (path.indexOf('?') == -1 ? '?' : '&') + variables[i] + '=' + Math.random();
		httpObject.open('GET', path, 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);
		var variables = new Array('dummy', 'random', 'bull', 'useless', 'discard');
		for (i = 0; i < 5; i++)
			if (data.indexOf(variables[i] + '=') == -1)
				break;
		if (i < 5)
			data += (data.length == 0 ? '' : '&') + variables[i] + '=' + Math.random();
		httpObject.send(data);
	}
}

function initTooltip() {
	if (ie || ns6) 
		tipobj = document.all ? document.all["dhtmltooltip"] : document.getElementById ? document.getElementById("dhtmltooltip") : ""
	document.onmousemove = positiontip
}

/* administrare produse */

function editFromDetails(idProdus) {
	sendPostRequest('set_for_edit.php', 'function() { if (ajaxOk()) document.location.href = "/admin/produse/" }', 'id_produs=' + encodeURIComponent(idProdus));
}

function deleteFromDetails(idProdus) {
	if (confirm('Sunteti sigur ca doriti sa stergeti acest produs ?'))
		sendPostRequest('set_for_delete.php', 'function() { if (ajaxOk()) document.location.href = "/admin/produse/" }', 'id_produs=' + encodeURIComponent(idProdus));
}

/* inregistrare newsletter */

function registerNewsletter(lang) {
	if (document.formNewsletter.email.value != "adresa@email.ro" && document.formNewsletter.email.value != "")
		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();
	}
}

function start_register(e) {
	var key = getkey(e);
	if (key == 13)
		registerNewsletter();
}

/* cautare */

function doSearch() {
	if (document.search.q.value != "" && document.search.q.value != "cauta")
		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 = getkey(e);
	if (key == 13) 
		doSearch();
}

/* 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;
}

/* functii fader */
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)
}

/* schimbare imagine header */

function tickHeader() {
	if (imgArray.length > 1) {
	
		if (globalTimer == timer) 
			changeHeaderImg();
		
		globalTimer++;
		
		setTimeout('tickHeader()', 1000);
	}
}

function changeHeaderImg() {
	nextIndex = 1 + Math.round(Math.random() * (imgArray.length - 1));
	nextIndex--;
	
	if (nextIndex === lastIndex) {
		timer++;
		return;
	}
	
	if ($s('image_switcher').opacity != 0) 
		shiftOpacity('image_switcher', 1000);
	setTimeout("$s('image_switcher').backgroundImage = \"url('/img/header_switch/" + imgArray[nextIndex] + "')\"", 1000);
	setTimeout("shiftOpacity('image_switcher', 1000)", 1000);
	lastIndex = nextIndex;
	
	timer +=6;
}
