// rok
var COOKIE_EXPIRATION = new Date(365*24*60*60*1000 + new Date().getTime());
var LOOK = 1;
var FUNCTIONS = 2;
var QUALITY = 3;

function activatePhoneRating(iFeature, iPhoneId) {
	var iUserRating = getCookie("PHONE_RATING_" + iFeature + "_" + iPhoneId);
	if(iUserRating)  {
		var oStar = document.getElementById("ocena" + iFeature + "-" + iUserRating);
		setUserRating(oStar, iUserRating, iFeature);
	}
	else {
		for(var i=1; i<=10; i++) {
			var oStar = document.getElementById("ocena" + iFeature + "-" + i);
			oStar.iRating = i;
			oStar.iPhoneId = iPhoneId;
			oStar.iFeature = iFeature;
			addEventHandler(oStar, "click", ratePhone);
			addEventHandler(oStar, "click", preventDefaultEvent);			
		}
	}
}


function setUserRating(oSelectedStar, iRating, iFeature) {
	for(var i=1; i<=10; i++) {
		var oStar = document.getElementById("ocena" + iFeature + "-" + i);
		addEventHandler(oStar, "click", preventDefaultEvent);
		if(i > iRating) {
			oStar.className = "";
		}
		else if(i == iRating)
			oSelectedStar.className = "oceniono" + iRating;
		oStar.style.cursor = "default";
		removeEventHandler(oStar, "click", ratePhone);
	}
//	oSelectedStar.parentNode.parentNode.style.cursor = "default";
}

// wysyła asynchroniczne żądanie protokołem HTTP korzystając z obiektu XMLHttpRequest
function ratePhone(oEvent) {
  
  var oEventSrc = getEventSrc(oEvent);
	
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
  	xmlHttp.open("GET", "phoneRate.php?phone_id=" + oEventSrc.iPhoneId + "&rating=" + oEventSrc.iRating + '&feature=' + oEventSrc.iFeature, true);  
  	xmlHttp.onreadystatechange = getRatingResults;
  	xmlHttp.send(null);

	// ustaw wyglad gwiazdek
	setUserRating(oEventSrc, oEventSrc.iRating, oEventSrc.iFeature);
	// ustaw ciasteczko
	setCookie("PHONE_RATING_" + oEventSrc.iFeature + "_" + oEventSrc.iPhoneId, oEventSrc.iRating, COOKIE_EXPIRATION);
  }
  else
    // jeśli połączenie jest zajęte, ponawia próbę po 1 sekundzie
    setTimeout('ratePhone(oEvent)', 1000);
}

// wykonywana automatycznie po otrzymaniu odpowiedzi z serwera
function getRatingResults() 
{
  // kontynuuje jedynie jeśli transakcja została zakończona
  if (xmlHttp.readyState == 4)  {
    // status 200 oznacza pomyślne ukończenie transakcji
    if (xmlHttp.status == 200)  {

		var sResponse = xmlHttp.responseText;
		var arResponse = sResponse.split("\n");
	  	if(arResponse[1].indexOf("ERROR") == -1) {
			oCurrentRating = document.getElementById("ocena"+arResponse[0]);
			oCurrentRating.innerHTML = arResponse[2];
			oRatingsNumber = document.getElementById("liczbaGlosow"+arResponse[0]);
			oRatingsNumber.innerHTML = arResponse[1];
		}
	} 
  }
}
