/*********************************************************************
  Copyright 2006-2009 .
  
  Auteur : Boudchicha naime -- WWW.NEW6TM.COM
           Manager@new6tm.com
***********************************************************************/
NEW6TM.UI.Vote = Class.create(NEW6TM.UI.Options, {
  options: {
    direction               : "bdLeftToRight",
    asset                   : ["asset/big.png",32],
	loaddinImg              : "asset/loading16.gif",
	loadding                : "loadding",    
    stepCount               : 10,
    stepDecimal             : 2, /* calcule 1.5 */
    rpc                     : "service/rpc",
	bgColor                 : "#DCDCDC",
	ratingColor             : "#F30",
	currentRatingColor      : "#888888"
  },
  initialize: function(element, options) {
    this.setOptions(options);
    this.element = $(element);
	
	// init value 
	this.globalNote = this.options.stepCount * this.options.stepDecimal;
	this.loadding = $(this.options.loadding);
	this.options.rpc = this.options.rpc + ".php";
	
	this.loddingImage = '<img src="asset/loading16.gif" width="16" height="16"  />';
	//Connect to Rpc , Loadding iniale value of rating;	
	(function (){this.rpcConnect({target:"read"});}).bind(this).delay(1);
	
	//Create Conponents
	this.buildComponents();
	this.styleComposite();
	
	
	$("rateStars").ObserveSpecialEvent("mouseleave", function() {this.rattingToCurrentEvent()}.bind(this));
	$("rateStars").ObserveSpecialEvent("click", function() {this.saveRattingEvent()}.bind(this));
					  
  },
  
  getWindowReference : function() {
	  this.getWindowReference =Prototype.emptyFunction;
	  if (!document._NuiWindow) {
			 var _NuiWindow = document._NuiWindow = new NEW6TM.UI.Window();
		  } 
	 this._window = document._NuiWindow; 
  },
  
  alertEx          : function(Options) {
	  this.getWindowReference();
	  (function() {
			this._window.showWindowEx(Options);
		}).bind(this).delay(1);
	  
  },
  saveRattingEvent : function() {
	  var rateValue=this.isRateTo + '/' + this.globalNote;
	  this.rpcConnect({target:"write",rateValue:rateValue});
	  
	// this.loadding.show();
	 //this.rateCaption.update();
  },
  buildRequestForLogin : function() {
	    this.buildRequestForLogin =Prototype.emptyFunction;
	    var MyBody = $$('body')[0];
		var temp = this;
        // Madding Css
		MyBody.appendChild(Builder.node('div',{id:'RequestForLogin'},Builder.node('div',{id:'_RequestForLogin'},[
									 Builder.node('h5','Entrez votre adresse Email :'),
								     Builder.node('input',{type:'text', name:'email','class':'inputText',value : '<Enter your valid mail here>'}),
									 Builder.node('img',{src:temp.options.loaddinImg ,width:"16" ,height:"16"}),
									 Builder.node('input',{type : 'button', id : 'button1',value : "Identifiez-vous"}),
									 Builder.node('br'),
									 Builder.node('span',"*"),
									 Builder.node('hr'),
									 Builder.node('p')
								])));
		$("RequestForLogin").setStyle({display : "none",position : "relative"});
		$("_RequestForLogin").setStyle({width : "400px",padding:"10px 10px",margin : "2px 2px"});
		$("_RequestForLogin").down("input.inputText").setStyle({width : '250px',margin : '0px 2px',color : '#666666'})
		                 .observe('focus',(function(event){
							   var element = Event.element(event);
							   element.setStyle({color : '#000'})
							   element.value = "";	   
										}));
		$("_RequestForLogin").down("img").hide();
		$("button1").setStyle({margin : '0px 2px'});
		$("_RequestForLogin").down("h5").setStyle({font : "12px tahoma",color : "#123",height : "12px","line-height":"12px"});
		$("_RequestForLogin").down("p").setStyle({font : "12px tahoma",color : "#123"});
		$("_RequestForLogin").down("span").setStyle({color : "#FF897A",font : "10px tahoma",height : "10px"});
		$("_RequestForLogin").down("p").update('Le site de AAHP exige une identification pour ce vote ...<br />'+
											   'Inscrire chez nous vous permetra de recevoir tout les news et avoir une bonne navigation.<br />'+
											   'Vous n\'avais pas encord inscris  <a href="inscription.php">Inscriptions</a>');
		$("button1").observe('click',(function (event){
									event.stop();		   
									emailValue = $("_RequestForLogin").down("input.inputText").value;
									if ((/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/).test(emailValue))
									   {
									      this.rpcIdent($("_RequestForLogin"),{target : "mail",mail : emailValue})}
										  else {$("_RequestForLogin").down("span").update("Syntaxe de l'émail invalide")}
									}).bind(this));
  },
  rattingEvent :  function(event) {
				var element = Event.element(event);
				var note = element.readAttribute('classnote');
				//$("test").update($("test").innerHTML + note);
				this.rateTo(note);
				this.isRateTo = note;
				var noteDix = note * 10 / this.globalNote;
				this.rateCaption.update('ratting To :<b>' + noteDix + '<\/b> / 10');
   },
   rattingToCurrentEvent : function() {
       var positionNote = '-' + this.getRatePositionByNote(this.currentRating);
	   var zeroNote  = '-' + this.getRatePositionByNote(0);
	   this.toRate.morph("left:"+positionNote, {
          duration: 0.3,
          delay: 0.1,
          afterFinish: (function() {
            this.toRate.morph("opacity:0.3", {
              duration: 0.2,
              afterFinish: (function() {
				  this.toRate.setStyle({left : zeroNote});
				  this.toRate.setOpacity(1);
				  this.rateCaption.update(this.rateCache.innerHTML);
				   }).bind(this)
			  })
	 }).bind(this)});
   },
   
  styleComposite : function() {
	  var rateDimention = this.getRateDimention();
	  this.rateDimention = rateDimention;
	  var zeroNote = '-' + rateDimention.width +'px';
	  $("rateContainer").hide().setStyle({margin : '0 0',position : 'relative'});
	  var style = {width : rateDimention.width + 'px',height : rateDimention.height + 'px' ,top : '0px'};	
	  $("rateStars").setStyle(Object.extend(Object.clone(style), {position : 'relative',overflow : 'hidden',cursor : 'pointer','z-index':'2'}));	
	  $("mapRating").setStyle(Object.extend(Object.clone(style), {position : 'absolute',background : this.options.bgColor}));	  
	  $("starsRating").setStyle(Object.extend(Object.clone(style), {position : 'absolute'}));	  
	  $("toRate").setStyle(Object.extend(Object.clone(style), {position : 'absolute',
													  background : this.options.ratingColor,left :zeroNote}));
	  $("currentRating").setStyle(Object.extend(Object.clone(style), {position : 'absolute',
													  background : this.options.currentRatingColor,left :zeroNote}));
	  $("rateCaption").setStyle(Object.extend(Object.clone(style), {'font':'12px "Courier New"','padding':'0px 5px'}));
	  $("rateMask").setStyle(Object.extend(Object.clone(style), {position : 'absolute',
								  overflow : 'hidden','z-index':'3',background : 'transparent'}));	
	  $("rateMask").hide().setOpacity(0.6);
	  $("rateCache").hide();
  },
  
  getRateDimention : function() {
	  var wnd = this.options.stepCount * this.options.asset[1];
	  var hgt = this.options.asset[1];	  
	   return {width : wnd, height : hgt};	  
  }, 
  
  getRatePositionByNote : function(note) {
	  var theNote = this.rateDimention.width - ((this.options.asset[1] / this.options.stepDecimal) * note);
	  return theNote + 'px';
  },
  
  setCurrentRating : function(note) {
	  this.currentRating = note;
	  var positionNote = '-' + this.getRatePositionByNote(note);
	  $("currentRating").setStyle({left : positionNote});
  },
  
  rateTo : function(note) {
	  var positionNote = '-' + this.getRatePositionByNote(note);
	  //new Effect.MoveBy($("toRate"), 0, positionNote, {duration:3, fps:25, from:0.0, to:1.0});
	  $("toRate").setStyle({left : positionNote});
  },
  
  buildComponents : function(){
	 var temp = this;		
	// half star
	var halfStars = $R(0,temp.options.stepCount * temp.options.stepDecimal -1).inject([], function(array, value) {
           array.push(Element.extend(Builder.node("div",{"classnote" : (value + 1)})).setStyle({ 'position'   : 'absolute',
							width      : (temp.options.asset[1] / temp.options.stepDecimal) + 'px',
							height     : temp.options.asset[1] + 'px',
							top        : '0px',
							left       : (value) * (temp.options.asset[1] / temp.options.stepDecimal) + 'px'
						}).observe("mouseover", function(event) {this.rattingEvent(event)}.bind(temp))
				);			
           return array;
      });
	// big Star	
	var bigStars =  $R(0,temp.options.stepCount - 1).inject([], function(array, value) {	
			array.push(Element.extend(Builder.node("div")).setStyle({ 'position'   : 'absolute',
							'background' :'transparent url(' + temp.options.asset[0] + ') left top no-repeat',
							width        : temp.options.asset[1] + 'px',
							height       : temp.options.asset[1] + 'px',
							top          : '0px',
							left         : (value * temp.options.asset[1]) + 'px'
						}));
		return array;
      });	
	
	this.builderComposant = Builder.node('div',{id:'rateContainer'},
								[Builder.node('div',{id:'rateStars'},
						           [Builder.node('div',{id:'mapRating'}),
									Builder.node('div',{id:'currentRating'}),									
						            Builder.node('div',{id:'toRate'}),
						            Builder.node('div',{id:'starsRating'},[].concat(bigStars,halfStars)),
									]),								 
								 Builder.node('div',{id:'rateMask'},[Builder.node('div',{id:'rateCache'})]),
								 Builder.node('div',{id:'rateCaption'})
								]
								);
	this.element.appendChild(this.builderComposant); 
   (function(){
			   var ids = 'rateContainer rateStars currentRating toRate starsRating rateCaption rateCache rateMask'; 
			   $w(ids).each(function(value){ temp[value] = $(value);/*alert(id + ')' +temp[id]);*/});
			   }).defer(); 
  },
  disabledControl : function(control){
	 
  },
  rpcIdent   : function(awoner,target) {
	    var _caller = this;
		Object.extend(target,{service : "identService"});
		new Ajax.Request(this.options.rpc, {
                     method: 'post', parameters : target,
					 onCreate: function(){
						 
					 _caller._window.enable = false;
					 awoner.down("img").show();	
					 _caller.disabledControl(awoner);
					 //_caller._window.disabledWindowContent();
				   },
	          onSuccess: function(transport) {					   
				       var responseText = transport.responseText;
					   //alert(responseText);
					   awoner.down("img").hide();
					   _caller._window.enable = true;
					   if (responseText == 'ok') {
						      _caller._window.closeWindow();
							  _caller.saveRattingEvent();
						   }  else { 
					   $("_RequestForLogin").down("span").update(responseText).show();					   
						   }
					   //_caller.updateRating(responseText);
                   },onFailure: function(transport){
					     var msg = 'Une erreur est survenue :(' + transport.status + ') Verifier votre connection';
						 alert("kkkk");
						 $("_RequestForLogin").down("span").update(msg);
						 },
				     on404: function(){
					      var msg = 'Desolé Service n\'est disponible , le serveur ne repond pas';
						 $("_RequestForLogin").down("span").update(msg); 
						 }
                    });    
	  
  },
  rpcConnect : function(target){
	    var _caller = this;
		Object.extend(target,{service : "rattingService"});
		new Ajax.Request(this.options.rpc, {
                     method: 'post', parameters : target,
					 onCreate: function(){
					 _caller.inConnect(1,'Connection en cours..')				 
				   },
	          onSuccess: function(transport) {					   
				       var responseText = transport.responseText;
					   //alert(responseText);
					   _caller.updateRating(responseText);
                   },onFailure: function(transport){
					     _caller.inConnect(1,'Une erreur est survenue :(' + transport.status + ') Verifier votre connection')
						 },
				     on404: function(){
					     _caller.inConnect(1,'Desolé Service n\'est disponible , le serveur ne repond pas')
						 }
                    });    
  },
  
  inConnect : function(state,message){	
            this.rateMask.show();
			this.loadding.update(message);
			this.rateCaption.hide();
			this.loadding.show();
  },
  
  updateRating : function(message){	
    //this.rateCache.update(message);
	this.loadding.update('Receive new ratting ....');
    var findRate = message.match(/([\d]+)\/([\d]+)/);
	if (findRate) {
		  var ratting = (findRate[2] != 0) ?  (findRate[1] / (findRate[2] * 100)) : 0;	
		  var note = Math.round(ratting * this.globalNote / 10);
		  ratting =  Math.round(ratting * 100) / 100;
	      this.setCurrentRating(note);
		  this.deferMask();
		  this.showRatting();	
	      this.rateCaption.update("Rating : <b>" + ratting + "</b>/10 ("+findRate[2]+" votes cast)");	
		  this.rateCache.update("Rating : <b>" + ratting + "</b>/10 ("+findRate[2]+"&nbsp;votes&nbsp;cast)");
	} else if (message=="erreur"){
		this.loadding.update('Login failed ....!!');
		this.buildRequestForLogin();
	           this.alertEx({
					content : "RequestForLogin",
					title   : "Identifiez-vous"
				});
          this.deferMask();
		  this.rateCaption.update(this.rateCache.innerHTML);

	}
  },
  deferMask : function() {
	  (function() {
				 this.rateMask.hide();
				 this.rateCaption.show();
		         this.loadding.hide();
       }).bind(this).delay(2);
  },
  showRatting : function() {
	  this.showRatting = Prototype.emptyFunction;
	  //this.loadding.hide();
	  this.rateContainer.insert(this.loadding);
	  this.rateContainer.show();
  }
});

Element.addMethods({
	 ObserveSpecialEvent : function(element,eventName, _handler) {		 
		if ((eventName === 'mouseenter') || (eventName === 'mouseleave'))
	    { eventName === 'mouseenter' ? eventName = 'mouseover'  : eventName = 'mouseout'; 
		  element.observe(eventName,_handlerEvent(_handler));
		} else {element.observe(eventName,_handler);}   
	 }
	});
	
function _handlerEvent(_fn) {
 function isAChildOf(_parent,_child) {
     if (_parent === _child) { return false;}
       while (_child && _child !==_parent) 
         {_child = _child.parentNode;}
        return _child === _parent;	
   }
  return function(_evt) {
    var relTarget = _evt.relatedTarget;	
	 if (this === relTarget || isAChildOf(this,relTarget)) {return ;}
	 _fn.call(this,_evt);
  }
}

