var NUMBER_OF_STARS = 5;
var status;

function init_starRating() {
	// find all divs
    var ratings = $$('div');

	ratings.each(function(i) {
		// for each div skip all who hasnt a class = rating
		if (i.className	!= 'rating') return
		// get the score value
		var rating = i.firstChild.nodeValue;
		//remove the score value
		i.removeChild(i.firstChild);
		// make sure the value is in the right interval
		if (rating > NUMBER_OF_STARS || rating < 0) return
		// loop through the interval
		$R(1,NUMBER_OF_STARS).each(function(j) {
			// create image element
			var star = new Element('img');
			// set on pic if score value is greater and sett classname = on, then decrease
			if (rating >= 1) {
                star.setAttribute('src', '/gfx/rating-sun_20px-on.png');
                star.className = 'on';
                rating--;
	        } else {
				star.className = 'off';
				star.setAttribute('src', '/gfx/rating-sun_20px-off.png');
            }
			// get the id of our div and strip first 7 characters "rating_0". thats the score type
            var ratingType = i.identify().substr(7);
			// add an id attribute to our created image element. star_"type"_"score" star_0_5
            star.writeAttribute('id', 'star_'+ratingType+'_'+j);
			// add mouse handler functions
            star.onmouseover = new Function("evt", "displayHover("+ratingType+", "+j+");");
            star.onmouseout = new Function("evt", "displayNormal("+ratingType+", "+j+");");
			// add image element to DOM
			i.appendChild(star);
		});
    });



	/*// add click event handler to all immidiate descendants of our div with the class rating, i.e our star elements.
    $$('.rating').each(function(n){
		n.immediateDescendants().each(function(c){
			Event.observe(c, 'click', submitRating);
		});
	});
*/

	// add click event handler to all immidiate descendants of our div with the class rating, i.e our star elements.
    $$('.rating').each(function(n){
		n.immediateDescendants().each(function(c){
			Event.observe(c, 'click', createHiddenInputFields );
		});
	});
}

function createHiddenInputFields(evt)
{
	// strip first 5 chars from img id star_0_5 = 0_5
	var tmp = Event.element(evt).getAttribute('id').substr(5);

	var cid = $$('[id*=camping_]')[0].getAttribute('id').substr(8);
	// start at first char end end at index of "_" gives us 0 from 0_5
	var type = tmp.substr(0, tmp.indexOf('_'));
	// get the 5
	var score = tmp.substr(tmp.indexOf('_')+1);

	displayAfterClick( type, score );

	var newInputField = new Element( 'input', {
		type: 'hidden',
		value: score,
		name: 'scoretype' + type,
		id: 'scoretype' + type
	});

	var oldInputField = $( 'scoretype' + type );

	if( oldInputField )
		oldInputField.replace( newInputField );
	else
		$( 'reply_form' ).insert( newInputField );

	var newCampingIdInputField = new Element( 'input', {
		type: 'hidden',
		value: cid,
		name: 'campingId',
		id: 'campingId'
	});

	var oldCampingIdInputField = $( 'campingId' );

	if( oldCampingIdInputField )
		oldCampingIdInputField.replace( newCampingIdInputField );
	else
		$( 'reply_form' ).insert( newCampingIdInputField );
}

// if we hover over a star this executes, loops through the inter val e.g 1-3 and changes the
// src attribute for that element. we could use different hover pic here.
function displayHover(type, score) {
	// loop through all range
	$R(1,NUMBER_OF_STARS).each(function(i) {
		if (i <= score)
			$('star_'+type+'_'+i).setAttribute('src', '/gfx/rating-sun_20px-on.png');
		else
			$('star_'+type+'_'+i).setAttribute('src', '/gfx/rating-sun_20px-off.png');
	});
}
// mouseout, we restore the original state of the images
function displayNormal(type, score) {
	$R(1,NUMBER_OF_STARS).each(function(i) {
		//get the class name, on or off. this only changes in init_starRating
		status = $('star_'+type+'_'+i).className;
		$('star_'+type+'_'+i).setAttribute('src', '/gfx/rating-sun_20px-'+status+'.png');
	});
}

//change the classname to get right pic after hover off (displaynormal() ).
function displayAfterClick(type, score) {
	$R(1,NUMBER_OF_STARS).each(function(i) {
		if(i <= score)
			$('star_'+type+'_'+i).className = 'on';
		else
			$('star_'+type+'_'+i).className = 'off';
	});
}
// evt = the image we clicked on
function submitRating(evt) {
	// strip first 5 chars from img id star_0_5 = 0_5
	var tmp = Event.element(evt).getAttribute('id').substr(5);

//	var cid = Event.element(evt).ancestors()[1].getAttribute('id').substr(8);
	var cid = $$('[id*=camping_]')[0].getAttribute('id').substr(8)
	// start at first char end end at index of "_" gives us 0 from 0_5
	var type = tmp.substr(0, tmp.indexOf('_'));
	// get the 5
	var score = tmp.substr(tmp.indexOf('_')+1);

	var uid = $$('[id*=uid_]')[0].getAttribute('id').substr(4)
	
	new Ajax.Request('rate.php', {
		method:'get',
		parameters: {userId: uid, companyId: cid, type: type, score: score},
		onSuccess: function(transport) {
			var response = transport.responseText || "nothing returned";
//			alert("Success! " + response);
		},
		onFailure: function() {
			alert("Error...");
		}
	});

	// only on success
	displayAfterClick(type,score);

	$('saveInfo_'+type).update("<b>Sparad</b>");

//	$('starRatingFeedback_1').update("cid = "+cid+" type = "+type+" score = "+score);
}


