var WiziComments = function(params){
    this.initializer(params);
}


WiziComments.WID_ACTION_CONTAINER = 'wizi-action-container';
WiziComments.WID_BTN_VALID_COM = 'wizi-btn-valid-com';
WiziComments.WID_FB_CHK = 'wizi-chk-fb';
WiziComments.WID_TWITTER_CHK = 'wizi-chk-twitter';
WiziComments.that = false;
WiziComments.T = false;
WiziComments.prototype = {
    editing: false,
    
    initializer: function(params){
        if (params.callback && typeof(params.callback) == 'function') {
            this._callback = params.callback;
        }
        
        this._textArea = $(params.textArea);
        this._textCheck = this._textArea.val();
        this._textArea.after('<input type="hidden" name="com[nospam]" value="nospam" />')
        var ok = this._textArea.wrap('<div class="wizi-boundingBox" />');
        this.boundingBox = this._textArea.parent().parent();
        if (document.location.href.search('#facebook_ok') != -1) {
            this.boundingBox.find('.' + WiziComments.WID_FB_CHK).attr('checked', 'checked');
        }
        this._textArea.css({
            height: 20,
            overflow: 'hidden',
            resize: 'none',
            autocomplete: "off"
            //            width: 600
        });
        $('.' + WiziComments.WID_ACTION_CONTAINER).hide();
        
        $("[placeholder]").focus(function() {
            var input = $(this);
            if (input.val() == input.attr("placeholder")) {
                input.val("");
                input.removeClass("placeholder");
            }
        }).blur(function() {
            var input = $(this);
            if (input.val() == "" || input.val() == input.attr("placeholder")) {
                input.addClass("placeholder");
                input.val(input.attr("placeholder"));
            }
        }).blur();
        
        $("[placeholder]").parents("form").submit(function() {
            $(this).find("[placeholder]").each(function() {
                var input = $(this);
                if (input.val() == input.attr("placeholder")) {
                input.val("");
                }
            })
        });
    },
    
    render: function(){
        this.renderUI();
        this.bindUI();
        this.star_notation();
        this._bindOther();
        return this;
    },
    
    renderUI: function(){
        twttr.anywhere(function(_T){
            WiziComments.T = _T;
            twttr.anywhere.signOut();
        });
    },
    
    _afterEditingChange: function(e){
    
        var tabSplit, value;
        value = this._textArea.val();
        tabSplit = value.split("\n");
        if (this._textArea.val()) {
            if (tabSplit.length > 4) {
                this._textArea.css('height', 20 + (tabSplit.length - 1) * 15);
            }
            else {
                this._textArea.css('height', 80);
            }
        }
    },
    
    _twitter: function(e){
        //debugger;
        var _this = this;
        /*var debug = $('#' + WiziComments.WID_TWITTER_CHK);
        debugger;*/
        if ($('#' + WiziComments.WID_TWITTER_CHK)[0].checked == false) {
            $('#' + WiziComments.WID_TWITTER_CHK).removeAttr("checked");
        } else {
            $('#' + WiziComments.WID_TWITTER_CHK).removeAttr("checked");
            var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=800,height=500";
            var win = window.open("/callback_twitter.php", 'FB', strWindowFeatures);
            var timer = setInterval(function(){
                if (win.closed) {
                    clearInterval(timer);
                    $.getJSON('/callback_twitter.php', {
                        action: 'getLogin'
                    },function(data){
                        if(data)
                            $('#' + WiziComments.WID_TWITTER_CHK).attr("checked", "checked");
                    })
    
                }
            }, 500);
        }
    },
    
    _connectFB: function(e){
		var _this = this;
        if ($('#' + WiziComments.WID_FB_CHK)[0].checked == false) {
			$('#' + WiziComments.WID_FB_CHK).removeAttr("checked");
        } else {
            $('#' + WiziComments.WID_FB_CHK).removeAttr("checked");
			var isConnected = function(callback){
				$.getJSON('/callback_facebook.php', {
					action: 'getLogin'
				}, function(data){
					console.log(data);
					if (callback) {
						callback(data.isConnected);
					}
				});
			}
			var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=600,height=327";
			var win = window.open("/callback_facebook.php", 'FB', strWindowFeatures);
			var timer = setInterval(function(){
				if (win.closed) {
					clearInterval(timer);
					isConnected(function(connected){
						if (connected) 
							$('#' + WiziComments.WID_FB_CHK).attr("checked", "checked");
					})
				}
			}, 500);
		}
    },
    
    /*_validCom: function(e){
        var value = this._textArea.attr("value").split("\n"), _this = this;
        if (this.boundingBox.find('.wizijs-textarea').val()) {
            //console.log(this.boundingBox.find('#wizi-txt-nom').val());
            if (this.boundingBox.find('.' + WiziComments.WID_FB_CHK).attr('checked')) {
                FB.api('/me/feed', 'post', {
                    message: this._textArea.attr("value")
                }, function(response){
                    if (!response || response.error) {
                        alert('Error occured');
                        //console.log(response);
                    }
                    else {
                        //console.log('Post ID: ' + response.id);
                    }
                });
            }
            if (this.boundingBox.find('.' + WiziComments.WID_TWITTER_CHK).attr('checked')) {
                if (WiziComments.T.isConnected) 
                    WiziComments.T.Status.update(this._textArea.val());
            }
            i = -1;
            while (value[++i]) {
                value[i] = value[i].concat('<br />');
            }
            
            if (this._callback) {
                twttr.anywhere.signOut();
                this.boundingBox.find('.' + WiziComments.WID_TWITTER_CHK).removeAttr('checked');
                this.boundingBox.find('.' + WiziComments.WID_FB_CHK).removeAttr('checked');
                this._callback.call(this, value, this.boundingBox.parent().find('ul.wizijs-notes-echelle input:checked').val(), this.boundingBox.find('.wizi-action-container .textNomArea').val(), this.boundingBox.find('.wizi-action-container .textEmailArea').val());
                //                this.boundingBox.find('.wizi-action-container .textNomArea').attr('value', '');
                //                this.boundingBox.find('.wizi-action-container .textEmailArea').attr('value', '');
                //				this.boundingBox.parent().find('ul.wizijs-notes-echelle input:checked').removeAttr('checked');
                //				$("ul.wizijs-notes-echelle li").removeClass("note-checked");
                //				$("ul.wizijs-notes-echelle li").removeClass("note-off");
                //				$("ul.wizijs-notes-echelle li").addClass("note-off");
            }
            this._hideContain.call(_this);
        }
        
    },*/
    
    _valueChange: function(){
        var _this = this;
        
        if (this.timeoutID) {
            clearTimeout(this.timeoutID);
            delete _this.timeoutID;
        }
        if (!this.intervalID) {
            this.intervalID = setInterval(function(){
                _this._checkValue.call(_this);
            }, 1000);
        }
        this.timeoutID = setTimeout(function(){
            clearInterval(_this.intervalID);
            delete _this.timeoutID;
            delete _this.intervalID;
        }, 1000);
    },
    
    _hideContain: function(){
        if (!this._textArea.val()) {
            this.boundingBox.find('.' + WiziComments.WID_ACTION_CONTAINER).hide();
            this._textArea.css({
                height: 20
            });
        }
    },
    
    _showContain: function(){
        var tabSplit, value;
        if (!this.editing) {
            this.editing = true;
            //this._bindOther();
        }
        $('.' + WiziComments.WID_ACTION_CONTAINER).show();
        value = this._textArea.val();
        tabSplit = value.split("\n");
        if (tabSplit.length > 4) {
            this._textArea.css('height', 20 + (tabSplit.length - 1) * 15);
        }
        else {
            this._textArea.css('height', 80);
        }
    },
    
    _checkValue: function(){
        if (this._textCheck != this._textArea.val()) {
            this._textCheck = this._textArea.val();
            this._afterEditingChange();
        }
    },
    
    bindUI: function(){
        var _this = this;
        
        this._textArea.bind('paste blur focus keyup mousedown', function(){
            _this._valueChange.call(_this);
        });
        this._textArea.bind('focus', function(){
            _this._showContain.call(_this);
        });
        $("ul.wizijs-notes-echelle input").click(function(){
            _this._showContain.call(_this);
        })
        $('.wizijs-lire-avis').click(function(e){
            e.preventDefault();
            if($('#a-commentaires').length > 0) {
                $('#a-commentaires').click();
            }
            $('html, body').animate({
                scrollTop: $('#commentaires').offset().top + 'px'
            }, 800);
        });
        $('.wizijs-btn-ajout-com').click(function(e){
            e.preventDefault();
            $('#a-commentaires').click();
            $('html, body').animate({
                scrollTop: $('.wizijs-comment').offset().top + 'px'
            }, 800);
            $('.wizijs-textarea').focus();
        });
        
        
    },
    
    _bindOther: function(){
        var _this = this;
        
//        this.boundingBox.find('.' + WiziComments.WID_BTN_VALID_COM).bind('click', function(){
//            _this._validCom.call(_this);
//        });
        $('#' + WiziComments.WID_FB_CHK).bind('click', function(){
            _this._connectFB.call(_this);
        });
        $('#' + WiziComments.WID_TWITTER_CHK).bind('click', function(){
            _this._twitter.call(_this);
        });
    },
    
    star_notation: function(){
        //		$('ul.wizijs-notes-echelle input:checked').removeAttr('checked');
        //$("ul.wizijs-notes-echelle li").removeClass("note-checked");
        $("ul.wizijs-notes-echelle li").removeClass("note-off");
        $("ul.wizijs-notes-echelle li").addClass("note-off");
        //$("ul.wizijs-notes-echelle").addClass("js");
        //$("ul.wizijs-notes-echelle li").addClass("note-off");
        $("ul.wizijs-notes-echelle li").mouseover(function(){
            $(this).nextAll("li").addClass("note-off");
            $(this).prevAll("li").removeClass("note-off");
            $(this).removeClass("note-off");
            //debugger;
        });
        $("ul.wizijs-notes-echelle").mouseout(function(){
            $(this).children("li").addClass("note-off");
            $(this).find("li input:checked").parent().parent().trigger("mouseover");
        });
        $("ul.wizijs-notes-echelle li input:checked").parent().parent().trigger("mouseover");
        $("ul.wizijs-notes-echelle input").focus(function(){
            $(this).parent("li").nextAll("li").addClass("note-off");
            $(this).parent("li").prevAll("li").removeClass("note-off");
            $(this).parent("li").removeClass("note-off");
        }).blur(function(){
            if ($(this).parents("ul.wizijs-notes-echelle").find("li input:checked").length == 0) {
                $(this).parents("ul.wizijs-notes-echelle").find("li").addClass("note-off");
            }
        });
        $("ul.wizijs-notes-echelle input").focus(function(){
            $(this).parents("ul.wizijs-notes-echelle").find("li").removeClass("note-focus");
            $(this).parent("li").addClass("note-focus");
        }).blur(function(){
            $(this).parents("ul.wizijs-notes-echelle").find("li").removeClass("note-focus");
        }).click(function(){
            $(this).parents("ul.wizijs-notes-echelle").find("li").removeClass("note-checked");
            $(this).parent().parent().addClass("note-checked");
        });
        $("ul.wizijs-notes-echelle input:checked").parent("li").trigger("mouseover");
        $("ul.wizijs-notes-echelle input:checked").trigger("click");
    }
}



$(function(){

    //		$('.btn-ajouter').click(function (e) {
    //            $('html, body').animate({scrollTop:$('#textComArea').position().top+'px'}, 800);
    ////			debugger;
    //			//$('.textComArea').focus();
    //			
    //        });
    $('.wizijs-comment textarea').each(function(i, node){
        var test = new WiziComments({
            textArea: node,
            callback: function(com, note, nom, email){
                this.boundingBox.parent().find('.coms').append('<p>' + com + 'note: ' + note + '  nom: ' + nom + '  email:' + email + '</p>');
            }
        }).render();
    });
});

//----------------------------- avis_boutique ------------------------------
$(window).load(function(){
	if (document.location.href.search('compte/avis.html') != -1){
		$('#wizi-txt-commentaire').focus();
	}
	
	if (document.location.href.search('#addCom') == -1 && document.location.href.search('#wizi-com') == -1 ){
		$('#a-description').click();
	}
	else{
		$('#a-commentaires').click();
		if (document.location.href.search('#addCom') != -1) { //On ajoute un commentaire
			$('#wizi-btn-ajout-com').click();
		}
		else { //On souhaite voir un commentaire spécifique
			var _idCom = document.location.href.split('#');
			$('html, body').animate({
				scrollTop: ($('#'+_idCom[1]).offset().top) + 'px'
			}, 800);
			$('#wizi-txt-commentaire').focus();
		}
	}
});
