//document.observe('dom:loaded', page_loaded, false);
var rating_wrappers = new Array();
var SliderText;
var observer_initialized = false;
var date = new Date();
//function page_loaded(evt) {
//    var counter = 0;
//    $$('div.slider div.ratingWrapper').each(function(rating_wrapper) {
//        RatingWrapper.track_interaction(rating_wrapper);
//        counter += 1;
//    }.bind(this));
//    if (counter > 0) RatingWrapper.reset_observer();
//};

var RatingWrapper = {
    //Constants
    scale: 15,
    maxScale: 150, //10 * RatingWrapper.scale 
    offsetLeft: 21,
    //Functions
    initSliders: function() {
      $$('div.slider div.ratingWrapper').each(function(rating_wrapper) {
            RatingWrapper.track_interaction(rating_wrapper);
          }.bind(this));
    },
    updateSlider: function(wrapper) {
      if(wrapper.currentMousePosition != wrapper.previousMousePosition){
        wrapper.previousMousePosition = wrapper.currentMousePosition;
        RatingBar.calculate_position(wrapper, 'move', wrapper.currentMousePosition, wrapper.cum_pos);
      }
      var delay = function() { RatingWrapper.updateSlider(wrapper); };
      wrapper.updateTimeout = window.setTimeout(delay, 200);      
      wrapper.updateTimer = true;
    },
    mouse_movement: function(e) {
        Event.stop(e);
        date = new Date();
        this.waiting = date.getTime();
        if (this.m_out == undefined) {
            this.m_out_handler = RatingWrapper.mouse_out.bindAsEventListener(this);
            Event.observe(this, 'mouseout', this.m_out_handler);
            this.m_out = true;
        }
        this.currentMousePosition = Event.pointerX(e);
        if(!this.updateTimer){
          RatingWrapper.updateSlider(this);
        }
    },
    mouse_click: function(e) {
        Event.stop(e);
        mouse_x = Event.pointerX(e);
        /*Enable the following lines to disalble rating after clicken
                  Event.stopObserving(this.r_bar, 'click', this.m_click_handler);
                  this.m_click = undefined;
                  Event.stopObserving(this.r_bar, 'mousemove', this.m_movement_handler);
                  this.m_movement = undefined;
                  Event.stopObserving(this, 'mouseout', this.m_out_handler);
                  this.m_out = undefined;
                  */
        RatingBar.calculate_position(this, 'click', mouse_x, this.cum_pos);
    },
    mouse_out: function(e) {
        eo = Event.element(e);
        if (this == eo){
          if(this.updateTimer){
            clearTimeout(this.updateTimeout);
            clearInterval(this.updateTimeout);
            this.updateTimer = false;
          }
          RatingWrapper.reset_bar(this);
          Event.stopObserving(this, 'mouseout', this.m_out_handler);
          this.m_out = undefined;
          if(this.m_click == undefined){
            this.m_click_handler = RatingWrapper.mouse_click.bindAsEventListener(this);
            this.m_click = true;
            Event.observe(this.r_bar, 'click', this.m_click_handler); 
          }
          if(this.m_movement == undefined){
            this.m_movement_handler = RatingWrapper.mouse_movement.bindAsEventListener(this);
            this.m_movement = true;
            Event.observe(this.r_bar, 'mousemove', this.m_movement_handler);
          }
        }
    },
    display_rating_numerical: function(display, rating) {
        display.update(RatingWrapper.round_number(rating));
    },
    display_slider_text: function(text, rating) {
        var roundedRating = RatingWrapper.round_number(rating);
        var index = 0;
        if(roundedRating <= 4){
          index = 0;
        } else if (roundedRating <= 6){
          index = 1;
        } else if(roundedRating <= 7){
          index = 2;
        } else if(roundedRating <= 9){
          index = 3;
        } else {
          index = 4;
        }
        text.update(SliderText[index]);
    },
    set_display_style: function(display, rating) {
        var roundedRating = RatingWrapper.round_number(rating);
        if(roundedRating == 5.5){
          roundedRating = 5;
        } else {
          roundedRating = Math.round(roundedRating);
        }
        var position = 48 * roundedRating - 480;
        var backgroundPosition = '0px ' + position + 'px';
        if(roundedRating <= 2 || roundedRating >= 8.5){
            display.setStyle({
                backgroundPosition: backgroundPosition,
                color: '#fff'
              });
        } else {
            display.setStyle({
                    backgroundPosition: backgroundPosition,
                    color: '#000'
                });
        }
    },
    set_display_style_small: function(display, rating) {
        var roundedRating = RatingWrapper.round_number(rating);
        if(roundedRating == 5.5){
          roundedRating = 5;
        } else {
          roundedRating = Math.round(roundedRating);
        }
        var position = 28 * roundedRating - 280;
        var backgroundPosition = '0px ' + position + 'px';
        if(roundedRating <= 2 || roundedRating >= 8.5){
            display.setStyle({
                backgroundPosition: backgroundPosition,
                color: '#fff'
              });
        } else {
            display.setStyle({
                    backgroundPosition: backgroundPosition,
                    color: '#000'
                });
        }
    },
    round_number: function(number) {
    		//Correction for deleted negative margin
    		number = number - RatingWrapper.offsetLeft;
        if (number > RatingWrapper.maxScale) number = RatingWrapper.maxScale;
        if (number < 0) number = 0;
        return (Math.round(number * 2 / RatingWrapper.scale)) / 2.0;
    },
    reset_bar: function(wrapper) {
          if (wrapper.observedElement != undefined) {
            var rating = wrapper.form.ratingValue.value / 10;
            var position = rating * RatingWrapper.scale + RatingWrapper.offsetLeft;
            RatingBar.position(wrapper.c_bar, position);
            if(wrapper.showDisplay){
              RatingWrapper.display_rating_numerical(wrapper.rn, position);
              RatingWrapper.set_display_style(wrapper.mark, position);
            }
            if(wrapper.showDisplaySmall){
              RatingWrapper.display_rating_numerical(wrapper.displaySmall, position);
              RatingWrapper.set_display_style_small(wrapper.displaySmall, position);
            }
            RatingWrapper.display_slider_text(wrapper.sliderText, position);
            wrapper.r_bar.removeClassName('hatesMovie');
            wrapper.r_bar.removeClassName('lovesMovie');
            if (rating <= 0) wrapper.r_bar.addClassName('hatesMovie');
            if (rating >= 10) wrapper.r_bar.addClassName('lovesMovie');
          }           
    },
    reset_bar_timer: function() {
        var ob_date = new Date();
        if (rating_wrappers.length > 0){
          var wrapper = $(rating_wrappers[0]);
          if (wrapper != null && wrapper.waiting < ob_date.getTime() - 2000) {
            RatingWrapper.reset_bar(wrapper);
          }
        }
        setTimeout(RatingWrapper.reset_bar_timer, 800);
    },
    reset_rating_wrappers: function() {
       if (rating_wrappers.length > 0) {
            var wrapper = $(rating_wrappers[0]);
            if(wrapper != null){
              //Check if ratingWrapper is still on the website, it may disappeared durin an AJAX call
              RatingWrapper.reset_bar(wrapper);
              wrapper.observedElement = undefined;
              wrapper.waiting = false;
              Event.stopObserving(wrapper, 'mouseout', wrapper.m_out_handler);
              wrapper.m_out = undefined;
              
              Event.stopObserving(wrapper.r_bar, 'click', wrapper.m_click_handler);
              wrapper.m_click = undefined;
              Event.stopObserving(wrapper.r_bar, 'mousemove', wrapper.m_movement_handler);
              wrapper.m_movement = undefined;
            }
            rating_wrappers.pop();
        } 
    },    
    track_interaction: function(wrapperId, onTooltip, form, displaySmall, displayBig) {
        var wrapper = $(wrapperId);
        if(wrapper == null){
          return;
        }
        
        wrapper.onmouseover = function() {
            if (wrapper.observedElement == undefined) {
                wrapper.observedElement = true;
                if (rating_wrappers.length > 0) {
                   RatingWrapper.reset_rating_wrappers();
                }
                
				if(typeof(displayBig) == "string"){
					wrapper.showDisplay = true;
					wrapper.mark = $(displayBig);
					wrapper.rn = wrapper.mark.select('div.rating')[0];
				} else if(!((typeof(onTooltip) == 'boolean') && onTooltip)){ 
					wrapper.showDisplay = true;
					wrapper.mark = $(wrapper.parentNode).select('div.slider-box-content-right')[0];
					wrapper.rn = $(wrapper.parentNode).select('div.slider-box-content-right div.rating')[0];
				} else {
					wrapper.showDisplay = false;
				}
				                
                if(typeof(form) == 'string'){
                  wrapper.form = $(form);
                } else {
                  wrapper.form = $(wrapper.parentNode).getElementsByTagName('form')[0];
                }
                
                if(typeof(displaySmall) == 'string'){
                  wrapper.displaySmall = $(displaySmall);
                  wrapper.showDisplaySmall = true;
                }
                
                wrapper.cum_pos = Element.cumulativeOffset(wrapper)[0];
                wrapper.r_bar = $(wrapper).select('.ratingBar')[0];
                wrapper.c_bar = $(wrapper.r_bar).select('.coloredBar')[0];
                wrapper.sliderText = $(wrapper.parentNode).select('span.slider-txt-dynamic')[0];
                wrapper.m_click_handler = RatingWrapper.mouse_click.bindAsEventListener(wrapper);
                Event.observe(wrapper.r_bar, 'click', wrapper.m_click_handler);
                wrapper.m_movement_handler = RatingWrapper.mouse_movement.bindAsEventListener(wrapper);
                Event.observe(wrapper.r_bar, 'mousemove', wrapper.m_movement_handler);
                
                wrapper.currentMousePostion = 0,
                wrapper.previousMousePosition = 0,
                wrapper.updateTimer = false,
                
                rating_wrappers.push(wrapperId);
            }
        };
        
        if(!observer_initialized){
            observer_initialized = true;
            setTimeout(RatingWrapper.reset_bar_timer, 800);
        }
   }
};

var RatingBar = {
    calculate_position: function(wrapper, type_of_event, mouse_x, wrapper_pos) {
        var pointer = mouse_x - wrapper_pos;
        pointer -= 20;
        //round position to 1/2 scale
        var modulo = (pointer - RatingWrapper.offsetLeft) % (0.5 * RatingWrapper.scale);
        if (modulo < 0.25 * RatingWrapper.scale){
          pointer = pointer - modulo;
        } else {
          pointer = pointer - modulo + (0.5 * RatingWrapper.scale);
        }
        var ratingbar = wrapper.r_bar;
        var coloredbar = wrapper.c_bar;
        ratingbar.removeClassName('hatesMovie');
        ratingbar.removeClassName('lovesMovie');
        if (pointer < RatingWrapper.offsetLeft + 0.25 * RatingWrapper.scale) {
            ratingbar.addClassName('hatesMovie');
            coloredbar.setStyle({
                width: '0px'
            });
        }
        if (pointer > RatingWrapper.offsetLeft + RatingWrapper.maxScale - 0.25 * RatingWrapper.scale) {
            ratingbar.addClassName('lovesMovie');
            coloredbar.setStyle({
                width: ((RatingWrapper.offsetLeft + RatingWrapper.maxScale + 1) +'px')
            });
        }
        RatingBar.position(coloredbar, pointer);
        if(wrapper.showDisplay){
          RatingWrapper.display_rating_numerical(wrapper.rn, pointer);
          RatingWrapper.set_display_style(wrapper.mark, pointer);
        }
        if(wrapper.showDisplaySmall){
          RatingWrapper.display_rating_numerical(wrapper.displaySmall, pointer);
          RatingWrapper.set_display_style_small(wrapper.displaySmall, pointer);
        }
        RatingWrapper.display_slider_text(wrapper.sliderText, pointer);
        if (type_of_event == 'click') Rating.submit(wrapper, pointer);
    },
    position: function(coloredbar, position) {
        if (position >= 0 && position <= RatingWrapper.offsetLeft + RatingWrapper.maxScale + 15){
          if(position > RatingWrapper.offsetLeft + RatingWrapper.maxScale + 1){
            position = RatingWrapper.offsetLeft + RatingWrapper.maxScale + 1;
          }
          coloredbar.setStyle({
              width: position + 'px'
          });
        }
    }
};

var Rating = {
    submit: function(wrapper, rating) {
        var card = wrapper.parentNode;
        var form = wrapper.form;
        rating = RatingWrapper.round_number(rating);
        //wrapper.c_bar.title = rating;
        //card.getElementsByClassName('rating')[0].title = rating;
        form.ratingValue.value = (rating * 10);
        form.onsubmit();
    }
};

function submitRatingEPG(form, url){
	var contentId = form.contentid.value;
    showLoader();
	new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
      					onSuccess: function(transport){
      						blindPossible = true;
							if((typeof(currentProgramId) == 'string') && (currentProgramId == ('epgProgram' + contentId))){
								var ratingValue = form.ratingValue.value;
								if(ratingValue > 95){
									currentProgramColor = '#ff6801';
								} else if(ratingValue > 85){
									currentProgramColor = '#ff7c02';
								} else if(ratingValue > 75){
									currentProgramColor = '#ff9e06';
								} else if(ratingValue > 65){
									currentProgramColor = '#ffb911';
								} else if(ratingValue >= 60){
									currentProgramColor = '#ffd13a';
								} else {
									currentProgramColor = '#e6e6e6';
								}
							}
						},
      					onComplete: function(){
							hideLoader();
						}
      			});
	return false;
}

function submitRatingList(form, url){
    showLoader();
	new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
	  					onSuccess: function(transport){
						},
      					onComplete: function(){
							hideLoader();
						}
      			});
	return false;
}

function submitRatingTip(form, url, divId, day, tipUrl)
{
    new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
      			onSuccess: function(transport){changeDay(divId, day, tipUrl)}
     			});
	return false;
}

// Does the same as 
function submitRatingAndReload(form, url, reloadDivId, reloadFunction)
{
    showLoader();
    	new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
                        onSuccess: function(transport){reloadDiv(reloadDivId, reloadFunction)},
      			onComplete: function(){hideLoader();}
      			});
	return false;
    /*
	new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
						onSuccess: function(transport){reloadDiv(reloadDivId, reloadFunction)},
      			onComplete: function(){hideLoaderOnDiv(reloadDivId);}
      			});
	return false;    */
}

function reloadDiv(reloadDivId, reloadFunction)
{
    //alert(reloadFunction);
    new Ajax.Updater(reloadDivId, reloadFunction, {asynchronous:true, evalScripts:true,onComplete: function(){}});
}

function submitRating(form, url){
    showLoader();
	new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
      			onComplete: function(){hideLoader();}
      			});
	return false;
}

function submitRatingNowNext(form, url, updateelementId, updateurl, params){
    showLoader();
	new Ajax.Request(url, {asynchronous:true, 
						evalScripts:true, 
						method:'post', 
						parameters:Form.serialize(form),
						onSuccess: function(){updateElement(updateelementId, updateurl, params);},
      			onComplete: function(){hideLoader();}
      			});
	return false;
}