/**
 * @author Sascha
 */
var hotvoiceClass = Class.create({
    
    smallAjaxLoader:null,
    largeAjaxLoader:null,
    
    ratingValues:null,
    ratingValue:0,
    resetTimer:null,
    rated:0,
    ratingImages:null,
    
    ratingDialog:null,
    
    initialize:function()
    {
       // console.log('INIT');
        // record.php: Show suggestions
        if ($('recordSuggest') != null) {
            $('recordSuggest').observe('click', this.showVoiceSuggestions.bindAsEventListener(this))
        }
        
        if (this.smallAjaxLoader == null) {
            this.smallAjaxLoader = new Element('img', { src:'/img/ajaxloaderSmall.gif' });
            $(document.body).appendChild(this.smallAjaxLoader);
            this.smallAjaxLoader.hide();
        }
        
        if (this.largeAjaxLoader == null) {
            this.largeAjaxLoader = new Element('img', { src:'/img/ajaxloader.gif' });
            $(document.body).appendChild(this.largeAjaxLoader);
            this.largeAjaxLoader.hide();
        }
        
        if ($('myVoiceCommentLink') != null) {
            $('myVoiceCommentLink').observe('click', this.editComment.bindAsEventListener(this))
        }
        
        if ($('myVoiceDeleteLink') != null) {
            $('myVoiceDeleteLink').observe('click', this.deleteVoice.bindAsEventListener(this))
        }
        
        if ($('voiceInfo') != null) {
            $('voiceInfo').observe('click', this.showVoiceInfo.bindAsEventListener(this));
            var voiceInfoCloseLink = $('voiceInfoBox').down('a.closeLink');
            if(voiceInfoCloseLink != null) {
                voiceInfoCloseLink.observe('click', this.hideVoiceInfo.bindAsEventListener(this));
            }
        }
        
        this.initRatingStuff();
        
        this.ratingDialog = new hotvoiceDialogClass();
        this.ratingDialog.url = '/ajax/dialog.php?d=rating';
        this.ratingDialog.submitCallback = this.sendRating.bindAsEventListener(this);
    },
    
    showVoiceInfo:function(e)
    {
         Event.stop(e);
         $('voiceInfo').hide();
         new Effect.SlideDown($('voiceInfoBox'));
    },
    
    hideVoiceInfo:function(e)
    {
         Event.stop(e);
         new Effect.SlideUp($('voiceInfoBox'));
         $('voiceInfo').show();
    },
    
    initRatingStuff:function()
    {
        var images = $$('#starlist img');
    	this.ratingValues = [];
        this.ratingImages = [];
    	if(images.length > 0) {
            this.ratingCount = hv_ratingCount;
    		images.each(function(img) {
                this.ratingImages.push(img);
    			if(img.src.match(/star.png/)) {
    				this.ratingValues.push(0);
    			} else {
    				this.ratingValues.push(1);
    			}
    			if(this.rated == 0) {
    				$(img).setStyle({ cursor:'pointer'});
    				$(img).observe('mouseover', this.starHoverOn.bindAsEventListener(this));
    				$(img).observe('mouseout', this.starHoverOff.bindAsEventListener(this));
    				$(img).observe('click', this.saveRating.bindAsEventListener(this));
    			}
    		}.bind(this));
    	}

  
        
    },
    
    starHoverOn:function(e) 
	{
		if(this.resetTimer != null) {
			window.clearTimeout(this.resetTimer);
		}
		if(this.rated == 1) return;
		
		for(i=1; i<=5; i++) {
			$('star'+i).src = '/img/ico/star_deact.png';
		}
		var img = Event.element(e);
		var imgId = img.id.replace(/star/, '', img.id);
		for(i=1; i<=imgId; i++) {
			$('star'+i).src = '/img/ico/star.png';
		}
	},
	
	starHoverOff:function(e) 
	{
		if(this.rated == 1) return;
		var img = Event.element(e);
		var imgId = img.id.replace(/star/, '', img.id);
		for(i=imgId; i>0; i--) {
			$('star'+i).src = '/img/ico/star.png';
		}
		this.resetTimer = window.setTimeout(this.resetRating.bindAsEventListener(this), 1000);
	},
	
    sendRating:function()
    {
        var frm = this.ratingDialog.containerEl.down('form');
        console.log(frm);
        var sStr = frm.down('textarea').getValue();
        this.ratingDialog.hide();
        tricos.ui.hidePane();
        new Ajax.Request(
            "/ajax/saveRating.php",
            {
                parameters: 'profile='+encodeURIComponent(hv_profile)+'&rating='+this.ratingValue+'&txt='+encodeURIComponent(sStr),
                onComplete:function(req)
                {
//                    alert('Done!');
                }
            }
        );
    },
    
	saveRating:function(e)
	{
		Event.stop(e);
		if(this.rated) return false;
		
		var img = Event.element(e);
		var ratingValue = img.id.replace(/star/, '', img.id);
		this.ratingValue = ratingValue;
		this.freezeRating();
        
        
        
		this.rated=1;
		this.ratingCount++;
		var aj = new Ajax.Request (
			"/ajax/saveRating.php", 
			{
				parameters: 'profile='+encodeURIComponent(hv_profile)+'&rating='+ratingValue,
				onComplete: function (req) {
                    
                    var jsonR = req.responseJSON;
                    if (jsonR != null) {
                        if (jsonR.success == 0) {
                            tricos.ui.hidePane();
                            alert(jsonR.message);
                            return;
                        }
                    }
                    tricos.ui.showPane(null, false);
                    this.resetRating();
					$('ratingTitle').setStyle({ color:'#c40000'});
					$('ratingTitle').update('Vielen Dank!');
					if($('ratingCount') != null) $('ratingCount').update(this.ratingCount);
				//	this.pointsObj.show($('starlist'), 5);
                  
                    // Show dialog
                    this.ratingDialog.show(function() {
                        var ta = this.ratingDialog.containerEl.down('textarea');
                        ta.focus();
                    }.bind(this));    
                    
                    
				}.bind(this)
			}
		);
						
	},
	
    freezeRating:function()
	{
		this.ratingImages.each(function(img) {
			img.stopObserving('mouseover', this.starHoverOn.bindAsEventListener(this));
			img.stopObserving('mouseout', this.starHoverOff.bindAsEventListener(this));
			img.stopObserving('click', this.saveRating.bindAsEventListener(this));
			img.setStyle({ cursor:'default' });
		}.bind(this));
	},

	resetRating:function()
	{ 
       // console.log('resetRating');
		if(this.ratingImages.length > 0) {
            this.ratingImages.each(function(img) {
                //console.log(img);
                if (img.hasClassName('none')) {
                    img.src='/img/ico/star_deact.png';
                }
                if (img.hasClassName('half')) {
                    img.src='/img/ico/star_half.png';
                }
                if (img.hasClassName('full')) {
                    img.src='/img/ico/star.png';
                }
            });
            return;
			for(i=1; i<6; i++) {
                     //   console.log('resetRating i:'+i);
                
				if(this.ratingValues[i-1] == 0) {
					$('star'+i).src='/img/ico/star_deact.png';
				} else {
					$('star'+i).src='/img/ico/star.png';
				}
			}
		}
	},
    
    showVoiceSuggestions:function(e)
    {
        var el = Event.element(e);
        Event.stop(e);
        el.hide();
        this.showSmallAjaxLoaderBefore(el);
        new Ajax.Updater($('voiceSuggestionBox'), '/ajax/voiceSuggestions.php', {
         /*   insertion: 'after', */
           onSuccess:function()
           {
               this.hideSmallAjaxLoader();
               new Effect.Appear('voiceSuggestionBox');
              // $('voiceSuggestionBox').show();
           }.bind(this)
        });
    },
    
    
    deleteVoice:function(e)
    {
        var el = Event.element(e);
        Event.stop(e);
        if (window.confirm('Soll die Aufnahme wirklich unwiderruflich gelöscht werden?\nDamit wird auch Deine Profilseite gelöscht, bis Du eine neue Aufnahme durchführst.')) {
            this.showSmallAjaxLoaderBefore(el);
            el.hide();
            new Ajax.Request('/ajax/deleteVoice.php', {               
               onComplete:function(req) {
                   this.hideSmallAjaxLoader();
                   el.show();
                   top.location.href = '/loggedin_index.php';
               }.bind(this)
            });
        }
    },
    
    editComment:function(e)
    {
        var el= Event.element(e);
        Event.stop(e);  
        this.showSmallAjaxLoaderBefore(el);
        el.hide();
        if ($('myComment') != null) {
            $('myComment').hide();
        }
        if ($('editCommentNote') != null) {
            $('editCommentNote').hide();
        }
        new Ajax.Updater($('editCommentBox'), '/ajax/editComment.php', {
         /*   insertion: 'after', */
           onComplete:function()
           {
               this.hideSmallAjaxLoader();
               
               var frm = $('editCommentBox').down('form');
               var textFld = frm.down('textarea');
               var saveBt = frm.down('button.save');
               var cancelBt = frm.down('button.cancel');
               var currentText = $('myComment');
               
               new Effect.Appear('editCommentBox', {
                   afterFinish:function() {
                       textFld.focus();
                   }
               });
               
               frm.observe('submit', function(e) { Event.stop(e); });
               
               cancelBt.observe('click', function(e) {
                   Event.stop(e);
                   new Effect.SlideUp($('editCommentBox'));
                   if ($('editCommentNote') != null) {
                       new Effect.Appear($('editCommentNote'));
                   } else {
                       new Effect.Appear($('myComment'));
                   }
                   new Effect.Appear(el);
               });
               
               saveBt.observe('click', function(e) {
                  Event.stop(e);
                  this.showSmallAjaxLoaderBefore(saveBt);
                  saveBt.disabled = true;
                  cancelBt.disabled = true;
                  textFld.disabled = true;
                  saveBt.blur();
                  new Ajax.Request('/ajax/editComment.php', {
                     parameters:
                     {
                         comment:textFld.getValue(),
                         action:'save'
                     },
                     onComplete:function(req)
                     {
                         saveBt.disabled = false;
                         cancelBt.disabled = false;
                         textFld.disabled = false;
                         this.hideSmallAjaxLoader();
                         new Effect.SlideUp($('editCommentBox'));
                         if ($('editCommentNote') != null) {
                               new Effect.Appear($('editCommentNote'));
                           } else {
                               $('myComment').update(req.responseText);
                               new Effect.Appear($('myComment'));
                           }
                           new Effect.Appear(el);
                     }.bind(this)
                  });
               }.bindAsEventListener(this));
                      
           }.bind(this)
        });
    },
    
    showSmallAjaxLoaderBefore:function(el)
    {
        Element.insert(el, { before: this.smallAjaxLoader });
        this.smallAjaxLoader.show();
    },
    
    hideSmallAjaxLoader:function()
    {
        this.smallAjaxLoader.hide();
    }
});

var hotvoice;
Event.observe(window, 'load', function() {
    hotvoice = new hotvoiceClass();
});
