


/// ////////////////////////////////////////////////////////////////////////////////

            
/*
http://cache-www2.pronto.com/combine.php?type=javascript&amp;hash=1404543188&amp;files=lists.js%2Clibrary.js%2Crollover.js%2Cjquery-1-2-1.js%2Cjquery-plugins.js%2Cautocomplete_init.js%2Ccommunity%2Fstar_rating.js%2Ccommunity%2Flight_box.js%2Ccommunity%2Flight_box_element_utils.js%2Ccommunity%2Flight_box_vars.js%2Ctracking%2Fvoltage.js%2CptmPopup.js
*/
var imgRowHeight = 15, imgRowWidth= 15;

///////////////////////////////////////////////////////////

var Rating = Class.create();

Rating.prototype = {
    initialize: function(element) {
    
        this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
        this.overlayDuration = LightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration
        
        if (! $('roverlay') ) {
            $$('body div#content')[0].appendChild(Builder.node('div',{id:'roverlay'}))
            this.overlay = $('roverlay');
            this.overlay.hide();
        }
        else
            this.overlay = $('roverlay');        
    
    
        this.className = 'Rating';
        this.starContainer = $(element);
        this.starContainerId = this.starContainer.readAttribute('id');
        this.product_id = this.starContainer.readAttribute('id');
        this.product_type = this.starContainer.down('input[name="product_type"]').value;
        
        this.category_id = this.starContainer.down('input[name="category_id"]').value;
        
        this.starImage = this.starContainer.getElementsBySelector('img.ratingImage').first();
        
        var starPos = $(this.starImage).readAttribute('style');
        //this.initialStarStates[starContainerId] = {starPos: starPos, ratings: this.getInitialRating(starPos)};
        this.initialStarState = {starPos: starPos, ratings: this.getInitialRating(starPos)};

            function getRatingProp(prop) {
                var rating = parseFloat( $(this.starContainerId + "_" + prop).getValue() );
                return isNaN(rating) ? 0 : rating;
            }
            //  var starType =  $(this.starContainerId + "_star_type").getValue();
            var ratings = new Object();
            
            /*
            if ( $(this.starContainerId + "_current_user_has_reviewed_it").getValue()  == "true") {
                itemProperties.setCurrentUserHasReview(this.starContainerId, true);
            }
            */
    
            Event.observe(this.starContainer, 'mouseout', this.drawInitialRating.bind(this));
            this.starContainer.onmouseout  = function () {return false;}
               
            Event.observe(this.starImage, 'mousemove', this.hoverStars.bindAsEventListener(this));
            this.starImage.mousemove  = function () {return false;}
            
            Event.observe(this.starImage, 'click', this.pickStar.bindAsEventListener(this));
            this.starImage.onclick  = function () {return false;}
        
        // this.status = 'end initialize';
    },
    


    drawInitialRating: function() {
        if (this.initialStarState) {
            this.starImage.writeAttribute("style", this.initialStarState.starPos)
        }
    },
    
    hoverStars: function(e) {
        try {
            //  var state = this.initialStarState;
            var currentUserRating = this.initialStarState.ratings;  // state.ratings
            var starInfo = new Object;
                starInfo = this.getStarInfo(e);
            
            var tempVar = "" + starInfo.xScroll + "px " + starInfo.yScroll + "px"
            var tempBG = this.starImage.readAttribute('id')
            if((starInfo.rating != -1 ) || (starInfo.rating == -1 && (currentUserRating > 0)))
                document.getElementById(tempBG).style.backgroundPosition = tempVar;
            
        }
        catch(err) {
            //  console.log( err );
        }
    },
    
    showReviewForm: function(rating) {
    
        var title = __('post review');
        
        
        var formContent = 
            '<form id="reviewForm" class="reviewForm" action="" metod="post" style="width: 500px">'+
                '<input id="id" name="id" value="'+  this.product_id  +'" type="hidden">'+
                '<input id="rating" name="rating" value="'+rating+'" type="hidden">'+
                '<input name="type" value="1" type="hidden">'+
                '<input name="product_type" value="'+  this.product_type  +'" type="hidden">'+
                
                '<label>'+__('Review text')+'</label>' +
                '<textarea id="message" name="message" style="width: 99%; height: 150px;"></textarea>'+ 
//                '<input class="button" type="submit" value="'+__('Continue')+'"/>'+
                //'<a class="redButton erarr" href="javascript:$(\'reviewForm\').submit()"><b>'+__('Continue')+'</b></a>'+
                '<div class="leftButtonsContainer"><button class="redButton erarr" type="submit"><b>'+__('Continue')+'</b></button></div>'+
                
            //    '<input class="button" name="skip" type="button" value="'+__('Skip review')+'" >';
            '</form>';
                
                        
        var popup = new Popup({'html': formContent, 'title': title});
        this.popupbox = popup.domPopup;
        
        var popupForm = popup.domPopup.down('form');
        
        if (popupForm ) {
            //  popupForm.down('input[type=image]').observe('click', this.submitForm.bindAsEventListener(this));
            
	        Event.observe(popupForm, 'submit', ( function() {
				try {
					var elRating = this.popupbox.down( 'form.reviewForm input[name="rating"]' );
					var elMessage = this.popupbox.down('form.reviewForm textarea[name="message"]');
					
					var rating = 1;
					if(elRating) rating = elRating.value;
					
					var message = elMessage.value;
					if(elMessage) message = elMessage.value;
					
					var sendReview = this.sendReview.bind(this );
					if(sendReview(rating, message) )   // this.end();
					   popup.close();
				}
				catch(e) {
				   console.log( e );
				}
	            
	        } ).bind(this));
	        popupForm.onsubmit  = function () {return false;}
	        
	        
	        /*
	        var elSkip = popupForm.down('input[name="skip"]');
	        
	        Event.observe(elSkip, 'click', ( function() {
				try {
					var elRating = this.popupbox.down( 'form.reviewForm input[name="rating"]' );

					
					var rating = 1;
					if(elRating) rating = elRating.value;

					
					var skipReview = this.skipReview.bind(this );
					if(skipReview(rating) )   // this.end();
					   popup.close();
				}
				catch(e) {
				   console.log( e );
				}
	            
	        } ).bind(this));
	        popupForm.onsubmit  = function () {return false;}	  
	        */
	        
        }
        

    },
    

    pickStar: function(e ) {
    	e.stop();
//        console.log( $A(arguments) );
        var starInfoObj = new Object;
        starInfoObj = this.getStarInfo(e );
        var rating = starInfoObj.rating;
        

        var state = this.initialStarState;
        var currentUserRating = state.ratings;
        
        var starPosition = "background-position:" + starInfoObj.xScroll + "px" + " " + starInfoObj.yScroll + "px";
        
        if (rating == -1 && (currentUserRating > 0)) {
            //this.showReviewForm(rating);
            this.sendReview( rating, '');
        }else if(rating != -1){
            this.showReviewForm(rating);
            //this.sendReview(rating)
    /*
                state.starPos = starPosition;
                state.ratings = rating;
                this.drawInitialRating(this.starContainer);
    */

        }
        

    },


    getInitialRating: function (style) {

        style = (style.strip()).toLowerCase();
        var initArr = style.split(" ");
        var initYScroll = initArr[initArr.length - 1];
        
        if(initYScroll.charAt(initYScroll.length - 1) == ";")
            initYScroll = initYScroll.substring(0,initYScroll.length - 1);
        
        initYScroll = initYScroll.replace(/px/, "");
        initYScroll = parseInt(initYScroll);

        if (initYScroll.abs() < imgRowHeight)
            return -1
        else if( initYScroll.abs() <= (11 * imgRowHeight) ) 
            return parseFloat(-initYScroll - imgRowHeight) / (2 * imgRowHeight)
        else
            return 5;
    },
    
    getStarInfo: function(e ) {
        var posX = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY) {
            posX = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            posX = e.clientX;
            posy = e.clientY;
        }
        posX = posX - this.starImage.cumulativeOffset().left;
        
        var starInfo = new Object;
        
        starInfo.rating = Math.ceil( posX / imgRowWidth );
        
        var startSetStar = 11 * imgRowHeight;  // 600
        
        starInfo.xScroll = 0;
        starInfo.yScroll = -( startSetStar +  starInfo.rating * imgRowHeight);                                
        if(starInfo.rating >=6)
            starInfo.rating = -1;
            
        return starInfo;
    },
    
    
    
    
    // AJAX FUNCTION ////////////////////////////////////////////////////
    sendReview: function(rating, message) {
        var aErrors = new Array;
        
        //	if( rating>0 && message.length<=25 ) aErrors[ aErrors.size()] = __('Review message length mast be more then 25 characters.');
        
        var url = '?';
        //var pars = 'id=' + this.product_id + '&rating=' + rating + '&returl='+ encodeURIComponent(location.pathname+location.search);
        //  console.log(pars);
        

        
        if( aErrors.size() == 0 ) {
	        new Ajax.Request(url, //var myAjax = 
	            {
	                method: 'post', 
	                parameters:  {id: this.product_id, rating : rating, message: message, product_type: this.product_type},  //  pars, 
	                onComplete: this.showResponse.bind(this)
	                //onFailure: function() { console.log(arguments) },
	                //onException: function() { console.log(arguments) },
	                //onSuccess: function(transport) {
			        //    if (transport.responseText.match(/href="http:\/\/prototypejs.org/))
			        //      $('notice').update('Yes').setStyle({ background: '#dfd' });
			        //    else
			        //      $('notice').update('No').setStyle({ background: '#fdd' });
			        //}
			          
	            });
            return true;
        } else 
            alert(aErrors.join("\n"));
            
        return false;
    },
    
    
    skipReview: function(rating) {
    	
    	var url = '?';
    	
        if( rating > 0 ) {
	        new Ajax.Request(url, //var myAjax = 
	            {
	                method: 'post', 
	                parameters:  {id: this.product_id, rating : rating},  //  pars, 
	                onComplete: this.showResponse.bind(this)
			          
	            });
            return true;
        } else 
            alert( 'Incorrect rating.' );
            
        return false;
    },
    
    showResponse: function(originalRequest) {
        if(originalRequest.responseJSON && originalRequest.responseJSON['posted_rating'] < 0  ) {
            var rX2 = Math.round(originalRequest.responseJSON['summ']*2);
            
            var elCount = this.starContainer.down('.ratings_count');
                elCount.innerHTML = originalRequest.responseJSON['cnt'];
            /*
            <?if(IS_DEBUG) {?>
            var elRating = this.starContainer.getElementsBySelector('.rating').first();
                elRating.innerHTML = rX2 / 2;
            <?}?>
            */
            
            var startSetStar = 1 * imgRowHeight;  // 600
            pos = -( startSetStar +  rX2 * imgRowHeight);  
            
    
            this.initialStarState.starPos = "background-position: 0pt " + pos + "px;";
            this.initialStarState.ratings = originalRequest.responseJSON['posted_rating'];
            this.drawInitialRating();
            
        }else if(originalRequest.responseJSON && originalRequest.responseJSON['posted_rating'] >= 0 ) {
            var rX2 = Math.round(originalRequest.responseJSON['summ']*2);
            
            var elCount = this.starContainer.down('.ratings_count');
                elCount.innerHTML = originalRequest.responseJSON['cnt'] ;
            /*   
            <?if(IS_DEBUG) {?>
            var elRating = this.starContainer.getElementsBySelector('.rating').first();
                elRating.innerHTML = rX2 / 2;
            <?}?>
            */
/*
    $raiting = round( $value['rating']['summ']*2, 0) / 2 ;
    $cnt = $value['rating']['cnt'];
    $stars = $raiting*100 + 50;
*/
            var startSetStar = 1 * imgRowHeight;  // 600
            pos = -( startSetStar +  rX2 * imgRowHeight);  
    
            this.initialStarState.starPos = "background-position: 0pt " + pos + "px;";
            this.initialStarState.ratings = originalRequest.responseJSON['posted_rating'];
            this.drawInitialRating();
            
            var COUNTRY = "";
	        if(r = (/^(?:\/?)([a-z].)\/.*/).exec( window.location.pathname ) ) {
	            COUNTRY = r[1];
	        };
            //var goURL = (COUNTRY? '/'+COUNTRY:'' )+'/product/?id='+this.product_id+'#'+originalRequest.responseJSON['anchor'];
	        if(originalRequest.responseJSON['message']!='') {
	        	var controller = 'software';
	        	if(originalRequest.responseJSON['product_type']=='accessory')
	        		controller = 'accessories';
	        	
	        	var goURL = (LOCALE? '/'+LOCALE:'' )+ '/' + controller + '/' +
	        	    this.category_id + '/'+this.product_id+'/#'+originalRequest.responseJSON['anchor'];

	        	
	        	window.location.href = goURL;
	        }
	        
        
        }else if(originalRequest.headerJSON && originalRequest.headerJSON['type'] == 'form') {
            
            
            var title= originalRequest.headerJSON['title'];
            var text = originalRequest.responseText;
            
            new Popup({'html': originalRequest.responseText, 'title': title});

        }
    },
    
    //////////////////////// FOR LIGHHT BOX ///////////////////////////////////////////////////////////

    getPageSize: function() {            
        var xScroll, yScroll;
        
        if (window.innerHeight && window.scrollMaxY) {  
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
        
        var windowWidth, windowHeight;
        
        if (self.innerHeight) { // all except Explorer
            if(document.documentElement.clientWidth){
                windowWidth = document.documentElement.clientWidth; 
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }   
        
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else { 
            pageHeight = yScroll;
        }
    
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){  
            pageWidth = xScroll;        
        } else {
            pageWidth = windowWidth;
        }

        return [pageWidth,pageHeight];
    },
    
    end: function() {
        //this.disableKeyboardNav();
        this.popupbox.hide();
        this.popupbox.remove();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
        //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    }

}